@maiaos/node 0.1.0-canary.72 → 0.1.0-canary.74

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.
@@ -235,7 +235,7 @@ DO UPDATE SET count = count + excluded.count`,Tfo="DELETE FROM integration_autho
235
235
  plan_bytes, created_at, created_at_ms, expires_at, expires_at_ms
236
236
  ) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(...n)},ggo=(e,t)=>{let r=_$(e,t);if(r!==void 0)return r;throw f("storage_corrupt","The integration plan was not persisted.")},ygo=(e,t)=>{let r=`integration.plan.${t.integration}`,n=pgo(t),o=_$(e,n.planId);if(o!==void 0)return mgo(o,n),{method:r,plan:qxe(o,t.integration)};hgo(e,t.recordedAt,n);let i=ggo(e,n.planId);return{method:r,plan:qxe(i,t.integration)}},Jlt=(e,t)=>Xy(e,{...t,method:`integration.plan.${t.integration}`},()=>ygo(e,t)),Ylt=(e,t)=>{let r=Np(t.planId,"The integration plan identifier"),n=_$(e,r);if(n?.integration===t.integration)return qxe(n,t.integration)}});var T$=q(()=>{"use strict";QTr();E$();oIr();aIr();BT();Hlt()});import{lstat as Sgo,realpath as Ego}from"node:fs/promises";var cIr,dIr,zxe,lIr=q(()=>{"use strict";F();z();cIr=()=>f("repository_invalid","The repository authority changed at the process launch boundary."),dIr=s.fn("ProcessResourceManager.verifyDirectory")(function*(e,t){let[r,n]=yield*s.tryPromise({catch:cIr,try:()=>Promise.all([Ego(e),Sgo(e,{bigint:!0})])}),o=typeof process.getuid!="function"||n.uid===BigInt(process.getuid());if(r!==e||!n.isDirectory()||n.isSymbolicLink()||!o||n.dev!==BigInt(t.device)||n.ino!==BigInt(t.inode))return yield*s.fail(cIr())}),zxe=s.fn("ProcessResourceManager.verifyLaunchAuthority")(function*(e){if(e.owner.kind!=="interactive-terminal"&&e.owner.kind!=="execution-command")return;let t=e.repositoryAuthority;if(e.workingDirectory!==t?.rootPath)return yield*s.fail(f("repository_invalid","The managed process repository authority is unavailable."));yield*dIr(t.rootPath,{device:t.rootDevice,inode:t.rootInode}),yield*dIr(t.gitCommonDirectory,{device:t.gitCommonDevice,inode:t.gitCommonInode})})});import{userInfo as Rgo}from"node:os";var _go,vgo,fIr,uIr,Tgo,pIr,Igo,mIr,xgo,Zlt,eZ,tZ,Qlt=q(()=>{"use strict";Qi();F();z();_go=16,vgo=2,fIr=(e,t)=>{if(e.uid!==t.uid&&e.uid!==0)return"foreign_owner";if((e.mode&vgo)!==0)return"writable_by_others";if((e.mode&_go)!==0)return e.gid===t.privateGroupId?void 0:"writable_by_others"},uIr=e=>e.split(`
237
237
  `).filter(t=>t.length>0).map(t=>t.split(":")),Tgo=/^\d+$/u,pIr=(e,t)=>e!==void 0&&Tgo.test(e)&&Number(e)===t,Igo=e=>{if(e.user.length===0)return;let t=uIr(e.group).filter(i=>pIr(i[2],e.gid)),r=t[0],n=r?.[3]??"";return t.length!==1||r?.[0]!==e.user||n!==""&&n!==e.user||uIr(e.passwd).some(i=>pIr(i[3],e.gid)&&i[0]!==e.user)?void 0:e.gid},mIr=(e,t)=>e.readFileString(t).pipe(s.option),xgo=s.fnUntraced(function*(e){let t=yield*s.try(()=>Rgo().username).pipe(s.option),r=yield*ve.FileSystem,n=yield*mIr(r,"/etc/passwd"),o=yield*mIr(r,"/etc/group");if(B.isNone(t)||B.isNone(n)||B.isNone(o))return{};let i=Igo({gid:e,group:o.value,passwd:n.value,user:t.value});return i===void 0?{}:{privateGroupId:i}}),Zlt=s.gen(function*(){if(typeof process.geteuid!="function"||typeof process.getegid!="function")return yield*s.fail(f("configuration_invalid","The vouch policy needs POSIX user ids, which this platform lacks."));let e=process.geteuid();return{...yield*xgo(process.getegid()),uid:e}}).pipe(s.provide(Rr)),eZ=["private_gid() {",' [ -n "$3" ] && [ -n "$4" ] || return 1',` u="$3" g="$4" awk -F: '$3 ~ /^[0-9]+$/ && $3 == ENVIRON["g"] + 0 { n++; if ($1 != ENVIRON["u"] "" || ($4 != "" && $4 != ENVIRON["u"] "")) bad = 1 } END { exit (n == 1 && !bad) ? 0 : 1 }' "$2" || return 1`,` u="$3" g="$4" awk -F: '$4 ~ /^[0-9]+$/ && $4 == ENVIRON["g"] + 0 && $1 != ENVIRON["u"] "" { bad = 1 } END { exit bad ? 1 : 0 }' "$1" || return 1`,` printf '%s' "$4"`,"}"].join(`
238
- `),tZ='user_writes_only() { { [ "$1" = "$uid" ] || [ "$1" = 0 ]; } && [ $(( 0$3 & 002 )) -eq 0 ] && { [ $(( 0$3 & 020 )) -eq 0 ] || { [ -n "$upg" ] && [ "$2" = "$upg" ]; }; }; }'});import{createHash as Ago,timingSafeEqual as bgo}from"node:crypto";import{closeSync as Cgo,constants as rZ,fstatSync as yIr,lstatSync as kgo,openSync as wgo,statfsSync as Ngo}from"node:fs";import{lstat as Vxe,open as SIr}from"node:fs/promises";import{isAbsolute as eut,resolve as tut}from"node:path";var Pgo,Ogo,EIr,Lgo,Dgo,Mgo,RIr,hIr,Kxe,qT,_Ir,vL,Ugo,Fgo,Hgo,Bgo,nZ,qgo,jgo,Wgo,$go,Ggo,zgo,rut,Vgo,gIr,Kgo,Xgo,vIr,nut,TIr,Jgo,Ygo,IIr,Zgo,Qgo,xIr,eyo,tyo,ryo,nyo,oyo,iyo,syo,Ah,AIr,ayo,cyo,oZ,iZ,Xxe,bIr=q(()=>{"use strict";Z();F();z();Qlt();Pgo=256*1024*1024,Ogo=64*1024,EIr=/^[0-9a-f]{64}$/u,Lgo=64,Dgo=4095,Mgo=new Set([de.antigravity,de.claudeCode,de.grokCli,de.maiaAgent,de.pi,"codex"]),RIr=e=>{switch(e){case de.antigravity:return["antigravity-session"];case de.claudeCode:return["claude-code-session"];case de.grokCli:return["grok-cli-session"];case de.maiaAgent:return["maia-agent-session"];case de.pi:return["pi-session"];case"codex":return["codex-probe","codex-session"];case"pi-rpc":return["pi-rpc-probe","pi-rpc-session"];case"skills":return["skills-listing"];case"git":case"security":case"systemd-creds":case"terminal":return[]}},hIr="skills-listing-1",Kxe=e=>({adapter:"skills",adapterVersion:e.version,executablePath:e.interpreterPath,ownerKinds:["skills-listing"],sandboxPolicyRevision:hIr,sha256:e.interpreterSha256,vouchPolicyRevision:hIr}),qT=()=>f("transport_failed","The requested executable is not admitted by the vouch policy."),_Ir=e=>({changedAtNanoseconds:e.ctimeNs,device:e.dev,inode:e.ino,modifiedAtNanoseconds:e.mtimeNs,size:e.size}),vL=(e,t)=>e.ctimeNs===t.changedAtNanoseconds&&e.dev===t.device&&e.ino===t.inode&&e.mtimeNs===t.modifiedAtNanoseconds&&e.size===t.size,Ugo=e=>e.uid===0n?e.nlink>0n:e.nlink===1n,Fgo=e=>`0${(Number(e.mode)&Dgo).toString(8)}`,Hgo=({adapter:e,path:t},r)=>{if(r.isSymbolicLink())return`${t}: a symbolic link; fix: approve the file it points to.`;if(!r.isFile())return`${t}: not a regular file.`;if(r.size===0n)return`${t}: an empty file.`;if(!Mgo.has(e)&&r.size>BigInt(Pgo))return`${t}: ${r.size.toString()} bytes, over the 256 MiB limit.`},Bgo=(e,t,r)=>{let n=Hgo(e,t);if(n!==void 0)return n;let{path:o}=e,i=Fgo(t),a=fIr({gid:Number(t.gid),mode:Number(t.mode),uid:Number(t.uid)},r);if(a==="foreign_owner")return`${o}: mode ${i}, owner uid ${t.uid.toString()}, not this user (${String(r.uid)}) or root; fix: install it as this user.`;if(a==="writable_by_others")return`${o}: mode ${i}, gid ${t.gid.toString()}, writable by others or a shared group; fix: chmod go-w on it.`;if(!Ugo(t))return`${o}: ${t.nlink.toString()} hard links; fix: approve a copy with one link.`;if((Number(t.mode)&Lgo)===0)return`${o}: mode ${i}, not executable by its owner; fix: chmod u+x on it.`},nZ=(e,t,r)=>{let n=Bgo(e,t,r);if(n!==void 0)throw f("configuration_invalid",`The vouch policy refuses ${n}`)},qgo=(e,t)=>{let r=Buffer.from(t,"hex");return e.byteLength===r.byteLength&&bgo(e,r)},jgo=(e,t)=>{switch(e.adapter){case"git":return t==="git-inspection";case"security":case"systemd-creds":return t==="secret-store";case"terminal":return t==="interactive-terminal";case de.antigravity:case de.claudeCode:case de.grokCli:case de.maiaAgent:case de.pi:case"codex":case"pi-rpc":case"skills":return RIr(e.adapter).includes(t)}},Wgo=e=>e.selectedTier==="cooperative_multi_pgid"||e.selectedTier==="hard_containment",$go=(e,t)=>{switch(e.adapter){case"git":return t.selectedTier==="vouched_runtime"||t.selectedTier==="hard_containment";case"security":return t.selectedTier==="vouched_runtime";case"skills":case"systemd-creds":return t.selectedTier==="hard_containment";case"terminal":return t.selectedTier==="local_user_interactive_terminal";case de.antigravity:case de.claudeCode:case de.grokCli:case de.maiaAgent:case de.pi:case"codex":return Wgo(t);case"pi-rpc":return t.selectedTier==="cooperative_pi_rpc_conversation"}},Ggo=(e,t)=>{let r=t.find(n=>n.executablePath===e.executable&&n.ownerKinds.includes(e.owner.kind));if(r===void 0||!jgo(r,e.owner.kind)||!$go(r,e)||!eut(r.executablePath)||tut(r.executablePath)!==r.executablePath||!EIr.test(r.sha256)||r.adapterVersion.length===0||r.sandboxPolicyRevision.length===0||r.adapter==="pi-rpc"&&(r.conversationPolicyRevision===void 0||r.conversationPolicyRevision.length===0)||r.vouchPolicyRevision.length===0)throw qT();return r},zgo=e=>{nZ(e,e.openedMetadata,e.user);let t=_Ir(e.openedMetadata);if(!vL(e.pathMetadata,t)||!vL(e.currentMetadata,t)||!qgo(e.digest,e.expectedDigest))throw qT();return t},rut=new Map,Vgo=new Set([16914836n,1481003842n,2435016766n,61267n]),gIr=new Map,Kgo=()=>{try{let e=wgo("/proc/self/exe",rZ.O_RDONLY);try{return[yIr(e,{bigint:!0})]}finally{Cgo(e)}}catch{return[]}},Xgo=()=>{if(process.platform!=="linux")return[];let[e]=Kgo();if(e===void 0)return[];try{let{type:t}=Ngo("/proc/self/exe",{bigint:!0});return[{filesystemType:t,identity:e}]}catch{return[]}},vIr=()=>{let e=gIr.get("exe");if(e!==void 0)return[e];let t=Xgo(),[r]=t;return r!==void 0&&gIr.set("exe",r),t},nut=e=>[e.dev,e.ino,e.size,e.mode,e.uid,e.ctimeNs,e.mtimeNs].join(":"),TIr=e=>e.platform==="linux"&&e.adapter==="skills"&&e.running.some(({filesystemType:t,identity:r})=>Vgo.has(t)&&e.metadata.dev===r.dev&&e.metadata.ino===r.ino),Jgo=e=>TIr(e)&&e.remembered===nut(e.metadata),Ygo=(e,t,r)=>TIr({adapter:e,metadata:t,platform:process.platform,running:r}),IIr=({executablePath:e,sha256:t})=>`${e}\0${t}`,Zgo=(e,t)=>{let{expectation:r,handle:n,pathMetadata:o,signal:i}=e;return Jgo({adapter:r.adapter,metadata:o,platform:process.platform,remembered:rut.get(IIr(r))??"",running:t})?Promise.resolve(Buffer.from(r.sha256,"hex")):xIr(n,o.size,i)},Qgo=async e=>{let{expectation:t,handle:r,pathMetadata:n,user:o}=e,i=await Zgo(e,vIr()),a=await r.stat({bigint:!0}),c=zgo({adapter:t.adapter,currentMetadata:await Vxe(t.executablePath,{bigint:!0}),digest:i,expectedDigest:t.sha256,openedMetadata:a,path:t.executablePath,pathMetadata:n,user:o});return t.adapter==="skills"&&rut.set(IIr(t),nut(a)),c},xIr=async(e,t,r)=>{let n=Ago("sha256"),o=Buffer.allocUnsafe(Ogo),i=Number(t),a=async c=>{if(c>=i)return;r.throwIfAborted();let{bytesRead:l}=await e.read(o,0,Math.min(o.byteLength,i-c),c);if(l<=0)throw qT();n.update(o.subarray(0,l)),await a(c+l)};return await a(0),r.throwIfAborted(),n.digest()},eyo=async(e,t)=>{let[r,n]=await Promise.all([e.handle.stat({bigint:!0}),Vxe(e.path,{bigint:!0})]);if(!vL(r,t)||!vL(n,t))throw qT()},tyo=(e,t,r)=>({device:t.device.toString(),inode:t.inode.toString(),path:e,sha256:r.toString("hex"),sizeBytes:t.size.toString()}),ryo=async e=>{let t=await e.handle.stat({bigint:!0});nZ(e,t,e.user);let r=_Ir(t);if(!vL(e.pathMetadata,r))throw qT();let n=await xIr(e.handle,t.size,e.signal);return await eyo(e,r),Ygo(e.adapter,t,vIr())&&rut.set(`${e.path}\0${n.toString("hex")}`,nut(t)),tyo(e.path,r,n)},nyo=async(e,t,r)=>{let{path:n}=e;if(!eut(n)||tut(n)!==n)throw qT();let o=await Vxe(n,{bigint:!0});nZ(e,o,t);let i=await SIr(n,rZ.O_RDONLY|rZ.O_NOFOLLOW);try{return await ryo({...e,handle:i,pathMetadata:o,signal:r,user:t})}finally{await i.close()}},oyo=e=>({adapter:e.adapter,path:e.executablePath}),iyo=async(e,t,r)=>{let n=await Vxe(e.executablePath,{bigint:!0});nZ(oyo(e),n,t);let o=await SIr(e.executablePath,rZ.O_RDONLY|rZ.O_NOFOLLOW);try{let i=await Qgo({expectation:e,handle:o,pathMetadata:n,signal:r,user:t});return{handle:o,identity:i}}catch(i){throw await o.close(),i}},syo=(e,t,r)=>({adapter:e.adapter,adapterVersion:e.adapterVersion,descriptor:t.handle.fd,identity:t.identity,path:e.executablePath,sandboxPolicyRevision:e.sandboxPolicyRevision,sha256:e.sha256,user:r,vouchPolicyRevision:e.vouchPolicyRevision}),Ah=s.fn("DarwinVouch.inspectTarget")(function*(e,t){let r=yield*Zlt;return yield*s.tryPromise({catch:n=>Le(n,"transport_failed","The requested executable is not admitted by the vouch policy."),try:n=>nyo({adapter:t,path:e},r,n)})}),AIr=s.fnUntraced(function*(e){let t=yield*Zlt,r=yield*s.acquireRelease(s.tryPromise({catch:n=>Le(n,"transport_failed","The requested executable is not admitted by the vouch policy."),try:n=>iyo(e,t,n)}),({handle:n})=>s.promise(()=>n.close()).pipe(s.ignore));return syo(e,r,t)}),ayo=e=>{let t=RIr(e.adapter);return e.ownerKinds.length>0&&e.ownerKinds.every(r=>t.includes(r))},cyo=e=>ayo(e)&&eut(e.executablePath)&&tut(e.executablePath)===e.executablePath&&EIr.test(e.sha256)&&e.adapterVersion.length>0&&e.sandboxPolicyRevision.length>0&&(e.adapter!=="pi-rpc"||e.conversationPolicyRevision!==void 0&&e.conversationPolicyRevision.length>0)&&e.vouchPolicyRevision.length>0,oZ=s.fnUntraced(function*(e){return cyo(e)?yield*AIr(e):yield*s.fail(qT())}),iZ=e=>{try{let t=yIr(e.descriptor,{bigint:!0}),r=kgo(e.path,{bigint:!0});if(!vL(t,e.identity)||!vL(r,e.identity))throw qT();nZ(e,t,e.user)}catch(t){throw Le(t,"transport_failed","The requested executable is not admitted by the vouch policy.")}},Xxe=s.fnUntraced(function*(e,t){let r=yield*s.try({catch:()=>qT(),try:()=>Ggo(e,t)});return yield*AIr(r)})});import{createHash as dyo,randomUUID as lyo}from"node:crypto";var out,CIr,sC,iut,Jxe,Yxe,kIr=q(()=>{"use strict";F();z();out=new WeakMap,CIr=()=>f("authentication_failed","The Invocation attachment launch authorization is invalid."),sC=e=>`process_${dyo("sha256").update(JSON.stringify({commandId:e.commandId,kind:e.kind,sessionId:e.sessionId,taskId:e.taskId,terminalId:e.terminalId,workspaceId:e.workspaceId})).digest("hex")}`,iut=e=>{let t=sC(e.owner),r=Object.freeze({attachmentId:e.attachmentId,...e.parentProcessOwnerId===void 0?{}:{parentProcessOwnerId:e.parentProcessOwnerId},processOwnerId:t,slotId:`invocation-slot-${lyo().replaceAll("-","")}`});return out.set(r,{lease:e.lease,processOwnerId:t,state:"available"}),r},Jxe=(e,t)=>{let r=out.get(e),n=sC(t);return r?.state!=="available"||r.processOwnerId!==n||e.processOwnerId!==n?s.fail(CIr()):s.void},Yxe=s.fn("ProcessResourceManager.consumeInvocationAttachmentLease")(function*(e,t){let r=out.get(e),n=sC(t);return r?.state!=="available"||r.processOwnerId!==n?yield*s.fail(CIr()):(r.state="consumed",r.lease)})});import{mkdtemp as uyo,open as pyo,rmdir as wIr,unlink as NIr}from"node:fs/promises";import{tmpdir as myo}from"node:os";import{join as PIr}from"node:path";var fyo,OIr,sut,aut,hyo,cut,LIr=q(()=>{"use strict";F();z();fyo=32,OIr=e=>Le(e,"transport_failed","The protected Invocation attachment handle could not be created."),sut=()=>{},aut=e=>e.close().catch(sut),hyo=async e=>{let t=Buffer.from(e),r=await uyo(PIr(myo(),"maia-ic1-")),n=PIr(r,"attachment");try{let o=await pyo(n,"wx+",384);try{return await o.write(t,0,t.byteLength,0),await NIr(n),await wIr(r),o}catch(i){throw await aut(o),i}}finally{t.fill(0),await NIr(n).catch(sut),await wIr(r).catch(sut)}},cut=s.fn("ProcessResourceManager.openInvocationAttachmentNativeLease")(function*(e){return e.byteLength!==fyo?yield*s.fail(OIr(new Error("credential size invalid"))):yield*s.acquireRelease(s.tryPromise({catch:OIr,try:()=>hyo(e)}),t=>s.promise(()=>aut(t)).pipe(s.asVoid)).pipe(s.map(t=>({close:s.promise(()=>aut(t)).pipe(s.asVoid),descriptor:t.fd})))})});import{createHash as BIr}from"node:crypto";import{closeSync as qIr,constants as DIr,existsSync as gyo,fstatSync as mut,lstatSync as yyo,openSync as Syo,readdirSync as Eyo,readFileSync as Ryo,readSync as _yo,realpathSync as jIr}from"node:fs";import{builtinModules as MIr}from"node:module";import{dirname as lut,isAbsolute as WIr,join as aC,relative as vyo,resolve as $Ir,sep as fut}from"node:path";var Qxe,eAe,Tyo,UIr,Iyo,xyo,hut,GIr,FIr,zIr,cC,I$,is,VIr,KIr,Ayo,tAe,byo,nAe,IL,sZ,Cyo,kyo,oAe,rAe,XIr,JIr,YIr,gut,wyo,Nyo,Pyo,ZIr,Oyo,QIr,uut,exr,TL,Lyo,Dyo,Myo,Uyo,Fyo,txr,Hyo,Byo,qyo,jyo,Wyo,$yo,rxr,Gyo,zyo,Vyo,Kyo,Xyo,iAe,put,dut,HIr,sAe,yut,Jyo,Yyo,Sut,Zxe,aZ,nxr=q(()=>{"use strict";z();Qxe="@maiaos/agent",eAe="dist/managed-worker/main.js",Tyo="maia-agent-worker",UIr=["README.md","dist"],Iyo="dist/managed-worker/main.meta.json",xyo=["bin","engines","exports","files","imports","name","piConfig","type"],hut="package.json",GIr="24.22.1",FIr=/^[0-9a-f]{64}$/u,zIr=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,cC=Object.freeze({maximumFileBytes:32*1024*1024,maximumFiles:4096,maximumInterpreterBytes:256*1024*1024,maximumPathBytes:4096,maximumTotalBytes:64*1024*1024}),I$=()=>f("transport_failed","The packaged managed Pi worker artifact is invalid."),is=()=>{throw I$()},VIr=e=>{try{return e()}catch(t){if(t instanceof lt)throw t;return is()}},KIr=e=>BIr("sha256").update(e).digest("hex"),Ayo=e=>e.length>0&&!e.includes("\0")&&Buffer.byteLength(e,"utf8")<=cC.maximumPathBytes&&WIr(e)&&$Ir(e)===e,tAe=e=>Ayo(e)?e:is(),byo=e=>e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":is(),nAe=e=>Object.freeze({changedAtNanoseconds:e.ctimeNs,device:e.dev,groupId:e.gid,inode:e.ino,linkCount:e.nlink,mode:Number(e.mode),modifiedAtNanoseconds:e.mtimeNs,size:e.size,type:byo(e),userId:e.uid}),IL=e=>nAe(yyo(e,{bigint:!0})),sZ=(e,t)=>e.changedAtNanoseconds===t.changedAtNanoseconds&&e.device===t.device&&e.groupId===t.groupId&&e.inode===t.inode&&e.linkCount===t.linkCount&&e.mode===t.mode&&e.modifiedAtNanoseconds===t.modifiedAtNanoseconds&&e.size===t.size&&e.type===t.type&&e.userId===t.userId,Cyo=(e,t)=>{let r=IL(e),n=typeof process.getuid=="function"?process.getuid():void 0,o=n===void 0||r.userId===0n||r.userId===BigInt(n);return sZ(t,r)&&o&&(t.mode&18)===0},kyo={package:"A path of the managed Pi worker package is writable by group or others; reinstall under umask 022 or remove group and other write access.",runtime:"The Node.js runtime is writable by group or others; use a Node.js installation that only you or root can write."},oAe=(e,t,r="package")=>{if(!Cyo(e,t))throw(t.mode&18)===0?I$():f("path_invalid",kyo[r])},rAe=(e,t,{allowSelectedSymlink:r,kind:n="package"})=>{let o=tAe(e),i=IL(o);if(i.type!==t&&!(r&&i.type==="symlink"))return is();let a=tAe(jIr.native(o)),c=IL(a);return c.type!==t?is():(oAe(a,c,n),Object.freeze({nofollow:Object.freeze({identity:i,path:o}),realpath:Object.freeze({identity:c,path:a})}))},XIr=(e,t,r)=>{let n=IL(e);return n.type!=="file"||n.linkCount!==1n||n.size<0n||n.size>BigInt(t)?is():(oAe(e,n,r),n)},JIr=e=>{let t=nAe(mut(e.descriptor,{bigint:!0}));(!sZ(e.before,e.opened)||e.byteCount!==Number(e.opened.size)||!sZ(e.opened,t)||!sZ(e.opened,IL(e.path)))&&is()},YIr=e=>Syo(e,DIr.O_RDONLY|(process.platform==="win32"?0:DIr.O_NOFOLLOW)),gut=(e,t,r="package")=>{let n=XIr(e,t,r),o=YIr(e);try{let i=nAe(mut(o,{bigint:!0})),a=Ryo(o),c=a.byteLength;return JIr({before:n,byteCount:c,descriptor:o,opened:i,path:e}),Object.freeze({bytes:a,identity:i,sha256:KIr(a)})}finally{qIr(o)}},wyo=1024*1024,Nyo=(e,t,r=wyo)=>{let n=BIr("sha256"),o=Buffer.allocUnsafe(r);return{byteCount:Array.from({length:Math.ceil(t/r)+1},(c,l)=>l*r).reduce((c,l)=>{let u=_yo(e,o,0,r,l);return c+u>t?is():(n.update(o.subarray(0,u)),c+u)},0),sha256:n.digest("hex")}},Pyo=(e,t,r)=>{let n=XIr(e,t,r),o=YIr(e);try{let i=nAe(mut(o,{bigint:!0})),{byteCount:a,sha256:c}=Nyo(o,Number(i.size));return JIr({before:n,byteCount:a,descriptor:o,opened:i,path:e}),Object.freeze({identity:i,sha256:c})}finally{qIr(o)}},ZIr=e=>{let t=e.split(fut).join("/"),r=t.split("/");return t.length===0||t.startsWith("/")||t.includes("\\")||t.includes("\0")||r.some(n=>n.length===0||n==="."||n==="..")?is():t},Oyo=(e,t)=>{let r=vyo(e,t);return r===""||r===".."||r.startsWith(`..${fut}`)||WIr(r)?is():ZIr(r)},QIr=(e,t,r)=>{e.observations.push({identity:r,path:t}),e.observations.length>cC.maximumFiles*2&&is()},uut=(e,t,r)=>{let n=gut(t,cC.maximumFileBytes);QIr(r,t,n.identity),r.totalBytes+=n.bytes.byteLength,(r.entries.length>=cC.maximumFiles||r.totalBytes>cC.maximumTotalBytes)&&is(),r.entries.push(Object.freeze({byteCount:n.bytes.byteLength,executable:(n.identity.mode&73)!==0,relativePath:Oyo(e,t),sha256:n.sha256}))},exr=(e,t,r)=>{let n=IL(t);n.type!=="directory"&&is(),oAe(t,n),QIr(r,t,n),Eyo(t).toSorted().forEach(o=>{ZIr(o);let i=aC(t,o),a=IL(i);a.type==="directory"?exr(e,i,r):a.type==="file"?uut(e,i,r):is()})},TL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lyo=e=>Array.isArray(e),Dyo=new Set([...MIr,...MIr.map(e=>`node:${e}`)]),Myo=e=>{let t=gut(aC(e,Iyo),cC.maximumFileBytes).bytes.toString("utf8"),r=JSON.parse(t);if(!TL(r))throw I$();let n=Reflect.get(r,"outputs");if(!TL(n))throw I$();Object.values(n).flatMap(a=>{if(!TL(a))throw I$();let c=Reflect.get(a,"imports");if(!Lyo(c))throw I$();return c}).some(a=>!TL(a)||typeof a.path!="string"||typeof a.external!="boolean"||a.external&&!Dyo.has(a.path))&&is()},Uyo=e=>{if(!TL(e)||!TL(e.exports)||!TL(e.bin))return is();let t=e.files;return e.name!==Qxe||typeof e.version!="string"||!zIr.test(e.version)||e.exports["./managed-worker"]!==`./${eAe}`||e.bin[Tyo]!==`./${eAe}`||!Array.isArray(t)||t.length!==UIr.length||!UIr.every(r=>t.includes(r))?is():{loading:Object.fromEntries(xyo.map(r=>[r,e[r]])),name:Qxe,version:e.version}},Fyo=e=>Uyo(JSON.parse(gut(aC(e,hut),cC.maximumFileBytes).bytes.toString("utf8"))),txr=(e,t)=>e===t||lut(e)===e?is():gyo(aC(e,"package.json"))?e:txr(lut(e),t),Hyo=e=>txr(lut(e),$Ir(e,fut)),Byo=e=>{e.forEach(({identity:t,path:r})=>{oAe(r,t)})},qyo=(e,t)=>e.relativePath<t.relativePath?-1:e.relativePath>t.relativePath?1:0,jyo=(e,t)=>KIr(JSON.stringify({entries:e.filter(({relativePath:r})=>r!==hut),manifest:t.loading})),Wyo=e=>{let t={entries:[],observations:[],totalBytes:0};uut(e,aC(e,hut),t),uut(e,aC(e,"README.md"),t),exr(e,aC(e,"dist"),t);let r=Object.freeze(t.entries.toSorted(qyo)),n=Fyo(e);Myo(e),Byo(t.observations);let o=Object.freeze([...t.observations]);return Object.freeze({entries:r,observations:o,packageClosureSha256:jyo(r,n),packageName:n.name,packageVersion:n.version})},$yo=e=>{if(process.versions.node!==GIr)return is();let t=rAe(e,"file",{allowSelectedSymlink:!0,kind:"runtime"}),r=rAe(process.execPath,"file",{allowSelectedSymlink:!0,kind:"runtime"});if(t.realpath.path!==r.realpath.path)return is();let n=Pyo(t.realpath.path,cC.maximumInterpreterBytes,"runtime");return sZ(n.identity,t.realpath.identity)?{binding:t,sha256:n.sha256}:is()},rxr=e=>e.packageName===Qxe&&zIr.test(e.packageVersion)&&FIr.test(e.entrySha256)&&FIr.test(e.packageClosureSha256),Gyo=e=>{let t=tAe(e),r=rAe(t,"file",{allowSelectedSymlink:!0}),n=tAe(jIr.native(Hyo(r.realpath.path))),o=rAe(n,"directory",{allowSelectedSymlink:!1}),i=aC(n,...eAe.split("/"));if(r.realpath.path!==i)return is();let a=Wyo(n),c=a.entries.find(({relativePath:l})=>l===eAe);return c===void 0?is():{closure:a,entry:r,entryRecord:c,packageRoot:o,packageRootPath:n,selectedEntryPath:t}},zyo=e=>({entrySha256:e.entryRecord.sha256,packageClosureSha256:e.closure.packageClosureSha256,packageName:e.closure.packageName,packageVersion:e.closure.packageVersion}),Vyo=(e,t)=>e.entrySha256===t.entrySha256&&e.packageClosureSha256===t.packageClosureSha256&&e.packageName===t.packageName&&e.packageVersion===t.packageVersion,Kyo=(e,t)=>{(!rxr(e)||t!==void 0&&!Vyo(e,t))&&is()},Xyo=e=>Object.freeze({...e.releaseIdentity,closurePhysicalIdentities:e.inspected.closure.observations,entries:e.inspected.closure.entries,entryPath:e.inspected.entry.realpath.path,entryPhysicalIdentity:e.inspected.entry,interpreterPath:e.interpreter.binding.realpath.path,interpreterPhysicalIdentity:e.interpreter.binding,interpreterSha256:e.interpreter.sha256,interpreterVersion:GIr,packageRootPath:e.inspected.packageRootPath,packageRootPhysicalIdentity:e.inspected.packageRoot,selectedEntryPath:e.inspected.selectedEntryPath,selectedInterpreterPath:e.selectedInterpreterPath}),iAe=e=>VIr(()=>{let t=Gyo(e.entryPath),r=zyo(t);Kyo(r,e.expectedRelease);let n=e.interpreterPath??process.execPath,o=$yo(n);return Xyo({inspected:t,interpreter:o,releaseIdentity:r,selectedInterpreterPath:n})}),put=e=>({...e,changedAtNanoseconds:e.changedAtNanoseconds.toString(),device:e.device.toString(),groupId:e.groupId.toString(),inode:e.inode.toString(),linkCount:e.linkCount.toString(),modifiedAtNanoseconds:e.modifiedAtNanoseconds.toString(),size:e.size.toString(),userId:e.userId.toString()}),dut=e=>({nofollow:{identity:put(e.nofollow.identity),path:e.nofollow.path},realpath:{identity:put(e.realpath.identity),path:e.realpath.path}}),HIr=e=>JSON.stringify({...e,closurePhysicalIdentities:e.closurePhysicalIdentities.map(({identity:t,path:r})=>({identity:put(t),path:r})),entryPhysicalIdentity:dut(e.entryPhysicalIdentity),interpreterPhysicalIdentity:dut(e.interpreterPhysicalIdentity),packageRootPhysicalIdentity:dut(e.packageRootPhysicalIdentity)}),sAe=e=>{VIr(()=>{let t=iAe({entryPath:e.selectedEntryPath,expectedRelease:{entrySha256:e.entrySha256,packageClosureSha256:e.packageClosureSha256,packageName:e.packageName,packageVersion:e.packageVersion},interpreterPath:e.selectedInterpreterPath});if(HIr(t)!==HIr(e))return is()})},yut=e=>Object.freeze({entrySha256:e.entrySha256,packageClosureSha256:e.packageClosureSha256,packageName:e.packageName,packageVersion:e.packageVersion}),Jyo=["MAIA_NODE_MANAGED_PI_WORKER_CLOSURE_SHA256","MAIA_NODE_MANAGED_PI_WORKER_ENTRY_SHA256","MAIA_NODE_MANAGED_PI_WORKER_PACKAGE_NAME","MAIA_NODE_MANAGED_PI_WORKER_PACKAGE_VERSION"],Yyo=e=>JSON.stringify(e)??"undefined",Sut=e=>Object.fromEntries(Jyo.map((t,r)=>[t,Yyo([e?.packageClosureSha256,e?.entrySha256,e?.packageName,e?.packageVersion][r])])),Zxe=e=>{try{return e()}catch(t){if(t instanceof ReferenceError)return;throw t}},aZ=()=>{let e=[Zxe(()=>"46c90bb11a15acec3441bd4212bf416ff5280cf60a769d2ecbac4ae5b6e53a28"),Zxe(()=>"7174f15101ef045ba1a60eaa433881fb8df4e5381c5d58cca41470d68271852a"),Zxe(()=>"@maiaos/agent"),Zxe(()=>"0.1.0-canary.72")];if(e.every(a=>a===void 0))return;let[t,r,n,o]=e,i={entrySha256:r,packageClosureSha256:t,packageName:n,packageVersion:o};return typeof r!="string"||typeof t!="string"||n!==Qxe||typeof o!="string"||!rxr(i)?is():Object.freeze(i)}});import{isAbsolute as Zyo,resolve as Qyo}from"node:path";var oxr,eSo,tSo,cZ,rSo,nSo,oSo,aAe,ixr=q(()=>{"use strict";os();oxr=([e],[t])=>e<t?-1:e>t?1:0,eSo=(e,t)=>{let r=Object.entries(e).toSorted(oxr),n=Object.entries(t).toSorted(oxr);return r.length===n.length&&r.every(([o,i],a)=>n[a]?.[0]===o&&n[a]?.[1]===i)},tSo=(e,t)=>e.kind===t.kind&&e.commandId===t.commandId&&e.sessionId===t.sessionId&&e.taskId===t.taskId&&e.terminalId===t.terminalId&&e.workspaceId===t.workspaceId,cZ=(e,t)=>e.executable===t.executable&&e.workingDirectory===t.workingDirectory&&e.standardInput===t.standardInput&&e.arguments_.length===t.arguments_.length&&e.arguments_.every((r,n)=>t.arguments_[n]===r)&&eSo(e.environment,t.environment)&&tSo(e.owner,t.owner)&&e.limits.maximumCpuTimeMilliseconds===t.limits.maximumCpuTimeMilliseconds&&e.limits.maximumMemoryBytes===t.limits.maximumMemoryBytes&&e.limits.maximumProcessCount===t.limits.maximumProcessCount&&e.limits.maximumWallTimeMilliseconds===t.limits.maximumWallTimeMilliseconds&&e.streamLimits.maximumDataChunkBytes===t.streamLimits.maximumDataChunkBytes&&e.streamLimits.maximumPendingInputBytes===t.streamLimits.maximumPendingInputBytes&&e.streamLimits.maximumPendingOutputBytes===t.streamLimits.maximumPendingOutputBytes&&e.interactiveTerminal===void 0&&t.interactiveTerminal===void 0&&e.repositoryAuthority===void 0&&t.repositoryAuthority===void 0,rSo=e=>e.interpreterVersion==="24.22.1"&&e.packageName==="@maiaos/agent"&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(e.packageVersion)&&[e.entryPath,e.interpreterPath].every(t=>Zyo(t)&&Qyo(t)===t)&&[e.entrySha256,e.interpreterSha256,e.packageClosureSha256].every(t=>/^[0-9a-f]{64}$/u.test(t)),nSo=e=>{let t=Object.keys(e).toSorted();return t.length===2&&t[0]==="LANG"&&t[1]==="LC_ALL"&&e.LANG==="C"&&e.LC_ALL==="C"},oSo=(e,t)=>{let r=Xm(e.launchRequest);return r.state==="valid"&&t.owner.kind==="pi-managed-session"&&t.owner.commandId!==void 0&&t.owner.sessionId!==void 0&&t.owner.workspaceId!==void 0&&rSo(e.artifact)&&e.artifact.interpreterPath===t.executable&&t.arguments_.length===1&&t.arguments_[0]===e.artifact.entryPath&&t.standardInput==="pipe"&&nSo(t.environment)&&cZ(r.request,t)},aAe=(e,t)=>{if(e.owner.kind!=="pi-managed-session")return;let r=t?.managedPi;return r!==void 0&&oSo(r,e)?r:void 0}});import{dirname as sxr,isAbsolute as axr,join as dZ,normalize as iSo,relative as sSo,resolve as aSo,sep as cSo}from"node:path";var lZ,CR,Dl,dSo,lSo,Ko,or,uSo,pSo,mSo,fSo,bh,cAe,uZ,Eut,hSo,gSo,ySo,SSo,ESo,RSo,_So,vSo,x$,Rut=q(()=>{"use strict";F();lZ="24.22.1",CR="1.0.0",Dl={exitDrainDeadline:"1 second",maximumInputRecordBytes:64*1024,maximumMessageEndRecords:16,maximumOutputRecordBytes:1024*1024,maximumOutputRecordsPerChunk:4096,maximumOutstandingRequests:8,maximumPendingInputBytes:128*1024,maximumPendingInputRecords:8,maximumPromptBytes:48*1024,maximumRequestIdBytes:128,maximumStderrBytes:64*1024,maximumStdoutBytes:16*1024*1024,requestDeadline:"10 seconds"},dSo=d.Literals(["command_rejected","cleanup_unknown","input_limit_exceeded","invalid_request","lifecycle_invalid","output_limit_exceeded","prompt_acceptance_unknown","protocol_invalid","request_outcome_unknown","runtime_exited","saturated","transport_failed"]),lSo=d.TaggedError,Ko=class extends lSo("@maiaos/node/pi-rpc-failure")("PiRpcFailure",{message:d.String,reason:dSo}){},or=(e,t)=>new Ko({message:t,reason:e}),uSo=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u,pSo=/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/u,mSo=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,fSo=/^[0-9a-f]{64}$/u,bh=e=>{throw or("invalid_request",e)},cAe=(e,t,r)=>e.length===0||e.includes("\0")||Buffer.byteLength(e,"utf8")>r?bh(`The Pi RPC ${t} is invalid.`):e,uZ=(e,t)=>(cAe(e,t,4096),!axr(e)||iSo(e)!==e||aSo(e)!==e?bh(`The Pi RPC ${t} must be an absolute normalized path.`):e),Eut=(e,t)=>fSo.test(e)?e:bh(`The Pi RPC ${t} must be a lowercase SHA-256.`),hSo=e=>(cAe(e,"session id",128),uSo.test(e)?e:bh("The Pi RPC session id is invalid.")),gSo=(e,t)=>{let r=sSo(e,t);return r.length>0&&r!==".."&&!r.startsWith(`..${cSo}`)&&!axr(r)},ySo=e=>e.interpreterVersion!==lZ?bh(`Pi RPC requires the exact Node ${lZ} interpreter.`):(uZ(e.interpreterPath,"interpreter path"),uZ(e.entryPath,"entry path"),Eut(e.interpreterSha256,"interpreter digest"),Eut(e.entrySha256,"entry digest"),Eut(e.packageClosureSha256,"package-closure digest"),cAe(e.packageName,"package name",214),cAe(e.packageVersion,"package version",128),pSo.test(e.packageName)?mSo.test(e.packageVersion)?Object.freeze({...e}):bh("The Pi RPC package version is invalid."):bh("The Pi RPC package name is invalid.")),SSo=(e,t)=>{let r=dZ(e,"harness","pi-rpc",t);return{agentDirectory:dZ(r,"agent"),homeDirectory:dZ(r,"home"),sessionDirectory:dZ(r,"sessions"),temporaryDirectory:dZ(r,"tmp")}},ESo=(e,t,r)=>{if(e.kind==="fresh"&&e.sessionFile===void 0)return{kind:"fresh",sessionId:r};if(e.sessionFile===void 0)return bh("The Pi RPC session file is missing.");let n=uZ(e.sessionFile,e.kind==="fresh"?"prepared fresh session file":"resume session file");return(sxr(n)!==t.sessionDirectory||!gSo(t.sessionDirectory,n)||!n.endsWith(".jsonl"))&&bh("The Pi RPC resume file must be an exact file in its node-private session directory."),{kind:e.kind,sessionFile:n,sessionId:r}},RSo=(e,t,r)=>{let n;if(t.kind==="fresh"&&t.sessionFile===void 0)n=["--session-id",t.sessionId];else{if(t.sessionFile===void 0)return bh("The Pi RPC session file is missing.");n=["--session",t.sessionFile]}return Object.freeze([e.entryPath,"--mode","rpc","--session-dir",r,...n,"--no-tools","--no-extensions","--no-skills","--no-prompt-templates","--no-themes","--no-context-files","--no-approve","--offline"])},_So=e=>Object.freeze({HOME:e.homeDirectory,LANG:"C",LC_ALL:"C",NO_COLOR:"1",NODE_DISABLE_COMPILE_CACHE:"1",PI_CODING_AGENT_DIR:e.agentDirectory,PI_CODING_AGENT_SESSION_DIR:e.sessionDirectory,PI_OFFLINE:"1",PI_TELEMETRY:"0",TMPDIR:e.temporaryDirectory}),vSo=e=>{let t=uZ(e.nodePrivateRoot,"node-private root");sxr(t)===t&&bh("The Pi RPC node-private root cannot be a filesystem root.");let r=uZ(e.workingDirectory,"working directory"),n=hSo(e.activation.sessionId),o=SSo(t,n);return{activation:ESo(e.activation,o,n),paths:o,workingDirectory:r}},x$=e=>{let t=ySo(e.artifact),{activation:r,paths:n,workingDirectory:o}=vSo(e);return r.sessionFile!==void 0&&t.packageVersion!==CR&&bh(`Pi RPC persistent sessions require the exact ${CR} package format.`),Object.freeze({activation:r,...n,arguments_:RSo(t,r,n.sessionDirectory),artifact:t,environment:_So(n),executable:t.interpreterPath,workingDirectory:o})}});var A$,_ut=q(()=>{"use strict";A$=(e,t)=>e===t?0:e<t?-1:1});import{createHash as TSo}from"node:crypto";import{closeSync as ISo,constants as cxr,existsSync as xSo,fstatSync as dxr,lstatSync as uxr,openSync as ASo,readdirSync as pxr,readFileSync as bSo,realpathSync as Aut}from"node:fs";import{dirname as vut,isAbsolute as mxr,join as but,normalize as CSo,relative as kSo,resolve as Cut,sep as Tut}from"node:path";var wSo,NSo,PSo,jT,OSo,LSo,fxr,Wi,DSo,hxr,dAe,MSo,Iut,xL,kR,lAe,xut,USo,uAe,kut,wut,gxr,FSo,lxr,yxr,HSo,BSo,qSo,jSo,WSo,Sxr,Exr,$So,GSo,zSo,VSo,KSo,XSo,JSo,YSo,ZSo,QSo,WT,Rxr=q(()=>{"use strict";F();Rut();_ut();wSo="@earendil-works/pi-coding-agent",NSo=/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/u,PSo=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,jT=Object.freeze({maximumExcludedBinEntries:256,maximumFileBytes:16*1024*1024,maximumFiles:16384,maximumFilesystemEntries:16384,maximumInterpreterBytes:256*1024*1024,maximumManifestBytes:8*1024*1024,maximumPathBytes:4096,maximumTotalBytes:256*1024*1024}),OSo=d.Struct({bin:d.Struct({pi:d.String}),name:d.String,version:d.String}),LSo=d.decodeUnknownSync(d.fromJsonString(OSo)),fxr=()=>or("invalid_request","The selected Pi RPC artifact is invalid."),Wi=()=>{throw fxr()},DSo=e=>{try{return e()}catch(t){throw t instanceof Ko?t:fxr()}},hxr=e=>TSo("sha256").update(e).digest("hex"),dAe=e=>e.length===0||e.includes("\0")||Buffer.byteLength(e,"utf8")>jT.maximumPathBytes||!mxr(e)||CSo(e)!==e||Cut(e)!==e?Wi():e,MSo=e=>e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":Wi(),Iut=e=>Object.freeze({changedAtNanoseconds:e.ctimeNs,device:e.dev,inode:e.ino,linkCount:e.nlink,mode:Number(e.mode),modifiedAtNanoseconds:e.mtimeNs,size:e.size,type:MSo(e)}),xL=(e,t)=>e.changedAtNanoseconds===t.changedAtNanoseconds&&e.device===t.device&&e.inode===t.inode&&e.linkCount===t.linkCount&&e.mode===t.mode&&e.modifiedAtNanoseconds===t.modifiedAtNanoseconds&&e.size===t.size&&e.type===t.type,kR=e=>Iut(uxr(e,{bigint:!0})),lAe=(e,t,r)=>{let n=dAe(e),o=kR(n);if(o.type!==t&&!(r&&o.type==="symlink"))return Wi();let i=dAe(Aut.native(n)),a=kR(i);return a.type!==t?Wi():Object.freeze({nofollow:Object.freeze({identity:o,path:n}),realpath:Object.freeze({identity:a,path:i})})},xut=e=>{let t=kR(e.nofollow.path),r=dAe(Aut.native(e.nofollow.path)),n=kR(e.realpath.path);(r!==e.realpath.path||!xL(t,e.nofollow.identity)||!xL(n,e.realpath.identity))&&Wi()},USo=e=>Buffer.from(e,"utf8").some(t=>t<=31||t===127),uAe=e=>{let t=e.split("/");return e.length===0||e.includes("\\")||e.startsWith("/")||Buffer.byteLength(e,"utf8")>jT.maximumPathBytes||USo(e)||t.some(r=>r.length===0||r==="."||r==="..")?Wi():e},kut=(e,t)=>{let r=kSo(e,t);return r.length===0||r===".."||r.startsWith(`..${Tut}`)||mxr(r)?Wi():uAe(r.split(Tut).join("/"))},wut=(e,t,r)=>{gxr(e),e.observed.push({identity:r,path:t})},gxr=e=>{e.filesystemEntryCount+=1,e.filesystemEntryCount>jT.maximumFilesystemEntries&&Wi()},FSo=e=>{e.excludedBinEntryCount+=1,e.excludedBinEntryCount>jT.maximumExcludedBinEntries&&Wi()},lxr=(e,t)=>{(e.type!=="file"||e.linkCount!==1n||e.size<0n||e.size>BigInt(t))&&Wi()},yxr=(e,t)=>{let r=kR(e);lxr(r,t);let n=ASo(e,cxr.O_RDONLY|cxr.O_NOFOLLOW);try{let o=Iut(dxr(n,{bigint:!0}));lxr(o,t),xL(r,o)||Wi();let i=bSo(n),a=Iut(dxr(n,{bigint:!0})),c=kR(e);return(i.byteLength!==Number(o.size)||!xL(o,a)||!xL(o,c))&&Wi(),{bytes:i,identity:o,sha256:hxr(i)}}finally{ISo(n)}},HSo=(e,t)=>A$(e.relativePath,t.relativePath),BSo=(e,t,r)=>{t==="package.json"&&(e.state.packageManifestText=new TextDecoder("utf-8",{fatal:!0}).decode(r.bytes)),t===e.entryRelativePath&&(e.state.entrySha256=r.sha256)},qSo=(e,t,r)=>{e.entries.push(Object.freeze({byteCount:r.bytes.byteLength,executable:(r.identity.mode&73)!==0,relativePath:t,sha256:r.sha256}))},jSo=(e,t)=>{let r=kut(e.root,t),n=yxr(t,jT.maximumFileBytes);wut(e.state,t,n.identity),e.state.fileCount+=1,e.state.totalBytes+=n.bytes.byteLength,(e.state.fileCount>jT.maximumFiles||e.state.totalBytes>jT.maximumTotalBytes)&&Wi(),qSo(e.state,r,n),BSo(e,r,n)},WSo=(e,t)=>{let r=kut(e,t);return r==="node_modules/.bin"||r.startsWith("node_modules/")&&r.endsWith("/node_modules/.bin")},Sxr=(e,t)=>{let r=kR(t);r.type!=="directory"&&Wi(),wut(e,t,r),pxr(t).forEach(n=>{uAe(n);let o=but(t,n),i=uxr(o,{bigint:!0});i.isDirectory()&&!i.isSymbolicLink()?Sxr(e,o):(gxr(e),FSo(e))})},Exr=(e,t)=>{let r=kR(t);r.type!=="directory"&&Wi(),wut(e.state,t,r),pxr(t).sort().forEach(o=>{uAe(o);let i=but(t,o),a=kR(i);a.type==="directory"?WSo(e.root,i)?Sxr(e.state,i):Exr(e,i):a.type==="file"?jSo(e,i):Wi()})},$So=e=>{e.forEach(t=>{xL(kR(t.path),t.identity)||Wi()})},GSo=()=>({entries:[],entrySha256:void 0,excludedBinEntryCount:0,fileCount:0,filesystemEntryCount:0,observed:[],packageManifestText:void 0,totalBytes:0}),zSo=e=>{let t=Cut(e,Tut),r=n=>xSo(but(n,"package.json"))?n:n===t||vut(n)===n?Wi():r(vut(n));return r(vut(e))},VSo=(e,t,r)=>{if(e===void 0)return Wi();let n=LSo(e);if(n.name!==wSo||!NSo.test(n.name)||!PSo.test(n.version))return Wi();let o=uAe(n.bin.pi.startsWith("./")?n.bin.pi.slice(2):n.bin.pi);return Cut(t,o)!==r?Wi():{name:n.name,version:n.version}},KSo=e=>{let t=JSON.stringify(e.map(({byteCount:n,executable:o,relativePath:i,sha256:a})=>({byteCount:n,executable:o,relativePath:i,sha256:a}))),r=Buffer.byteLength(t,"utf8");return r>jT.maximumManifestBytes&&Wi(),{bytes:r,sha256:hxr(t)}},XSo=e=>Object.freeze(e.entries.sort(HSo).map((t,r)=>Object.freeze({...t,ordinal:r}))),JSo=(e,t)=>{let r=kut(e,t),n=GSo();Exr({entryRelativePath:r,root:e,state:n},e),$So(n.observed);let o=XSo(n),i=VSo(n.packageManifestText,e,t);if(n.entrySha256===void 0)return Wi();let a=KSo(o);return{entries:o,entrySha256:n.entrySha256,excludedBinEntryCount:n.excludedBinEntryCount,fileCount:n.fileCount,manifestBytes:a.bytes,packageClosureSha256:a.sha256,packageName:i.name,packageVersion:i.version,totalBytes:n.totalBytes}},YSo=e=>Object.freeze({closureSha256:e.closure.packageClosureSha256,entries:e.closure.entries,entryPath:e.entry.realpath.path,entryPhysicalIdentity:e.entry,entrySha256:e.closure.entrySha256,excludedBinEntryCount:e.closure.excludedBinEntryCount,fileCount:e.closure.fileCount,interpreterPath:e.interpreter.binding.realpath.path,interpreterPhysicalIdentity:e.interpreter.binding,interpreterSha256:e.interpreter.sha256,interpreterVersion:lZ,manifestBytes:e.closure.manifestBytes,packageClosureSha256:e.closure.packageClosureSha256,packageName:e.closure.packageName,packageRootPath:e.packageRootPath,packageRootPhysicalIdentity:e.packageRoot,packageVersion:e.closure.packageVersion,totalBytes:e.closure.totalBytes}),ZSo=e=>{process.versions.node!==lZ&&Wi();let t=lAe(e,"file",!0),r=lAe(process.execPath,"file",!0);t.realpath.path!==r.realpath.path&&Wi();let n=yxr(t.realpath.path,jT.maximumInterpreterBytes);return xL(n.identity,t.realpath.identity)||Wi(),xut(t),{binding:t,sha256:n.sha256}},QSo=e=>{let t=ZSo(e.interpreterPath),r=lAe(e.piExecutablePath,"file",!0),n=dAe(Aut.native(zSo(r.realpath.path))),o=lAe(n,"directory",!1);o.realpath.path!==n&&Wi();let i=JSo(n,r.realpath.path);return xut(r),xut(o),YSo({closure:i,entry:r,interpreter:t,packageRoot:o,packageRootPath:n})},WT=e=>DSo(()=>QSo(e))});var Cu=q(()=>{"use strict";Rxr();Rut();_ut()});import{dirname as eEo,isAbsolute as pZ,resolve as mZ}from"node:path";var Txr,_xr,tEo,rEo,nEo,oEo,iEo,vxr,sEo,b$,aEo,cEo,dEo,lEo,pAe,Ixr=q(()=>{"use strict";Cu();os();Txr=e=>(e.kind==="pi-rpc-probe"||e.kind==="pi-rpc-session")&&e.commandId!==void 0&&e.sessionId!==void 0,_xr=(e,t)=>e<t?-1:e>t?1:0,tEo=(e,t)=>{let r=Object.entries(e).sort(([o],[i])=>_xr(o,i)),n=Object.entries(t).sort(([o],[i])=>_xr(o,i));return r.length===n.length&&r.every(([o,i],a)=>n[a]?.[0]===o&&n[a]?.[1]===i)},rEo=(e,t)=>e.kind===t.kind&&e.commandId===t.commandId&&e.sessionId===t.sessionId&&e.taskId===t.taskId&&e.terminalId===t.terminalId&&e.workspaceId===t.workspaceId,nEo=(e,t)=>e.executable===t.executable&&e.workingDirectory===t.workingDirectory&&e.standardInput===t.standardInput&&e.arguments_.length===t.arguments_.length&&e.arguments_.every((r,n)=>t.arguments_[n]===r)&&tEo(e.environment,t.environment)&&rEo(e.owner,t.owner)&&e.limits.maximumCpuTimeMilliseconds===t.limits.maximumCpuTimeMilliseconds&&e.limits.maximumMemoryBytes===t.limits.maximumMemoryBytes&&e.limits.maximumProcessCount===t.limits.maximumProcessCount&&e.limits.maximumWallTimeMilliseconds===t.limits.maximumWallTimeMilliseconds&&e.streamLimits.maximumDataChunkBytes===t.streamLimits.maximumDataChunkBytes&&e.streamLimits.maximumPendingInputBytes===t.streamLimits.maximumPendingInputBytes&&e.streamLimits.maximumPendingOutputBytes===t.streamLimits.maximumPendingOutputBytes&&e.interactiveTerminal===void 0&&t.interactiveTerminal===void 0&&e.repositoryAuthority===void 0&&t.repositoryAuthority===void 0,oEo=e=>{let t=e.nativeSession.activation,r=t.sessionFile===void 0?["--session-id",e.nativeSession.id]:["--session",t.sessionFile];return[e.artifact.entryPath,"--mode","rpc","--session-dir",e.nativeSession.directory,...r,"--no-tools","--no-extensions","--no-skills","--no-prompt-templates","--no-themes","--no-context-files","--no-approve","--offline"]},iEo=(e,t)=>e.length===t.length&&e.every((r,n)=>t[n]===r),vxr=new Set(["HOME","LANG","LC_ALL","NODE_DISABLE_COMPILE_CACHE","NO_COLOR","PI_CODING_AGENT_DIR","PI_CODING_AGENT_SESSION_DIR","PI_OFFLINE","PI_TELEMETRY","TMPDIR"]),sEo=(e,t)=>{let r=e.environment,n=Object.keys(r);return n.length===vxr.size&&n.every(o=>vxr.has(o))&&r.LANG==="C"&&r.LC_ALL==="C"&&r.NODE_DISABLE_COMPILE_CACHE==="1"&&r.NO_COLOR==="1"&&r.PI_CODING_AGENT_SESSION_DIR===t&&r.PI_OFFLINE==="1"&&r.PI_TELEMETRY==="0"&&[r.HOME,r.PI_CODING_AGENT_DIR,r.TMPDIR].every(o=>o!==void 0&&pZ(o)&&mZ(o)===o)},b$=e=>e.length>0&&!e.includes("\0")&&Buffer.byteLength(e,"utf8")<=128,aEo=e=>e.interpreterVersion==="24.22.1"&&pZ(e.interpreterPath)&&mZ(e.interpreterPath)===e.interpreterPath&&pZ(e.entryPath)&&mZ(e.entryPath)===e.entryPath&&[e.interpreterSha256,e.entrySha256,e.packageClosureSha256].every(t=>/^[0-9a-f]{64}$/u.test(t))&&/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/u.test(e.packageName)&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(e.packageVersion),cEo=e=>pZ(e.directory)&&mZ(e.directory)===e.directory&&/^(?:[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)$/u.test(e.id)&&(e.activation.sessionFile===void 0||pZ(e.activation.sessionFile)&&mZ(e.activation.sessionFile)===e.activation.sessionFile&&eEo(e.activation.sessionFile)===e.directory),dEo=e=>{let{artifact:t,authorizationRevision:r,fenceId:n,nativeSession:o,permitId:i,policy:a}=e;return b$(r)&&b$(n)&&b$(i)&&aEo(t)&&cEo(o)&&b$(a.adapterVersion)&&b$(a.conversationPolicyRevision)&&b$(a.vouchPolicyRevision)},lEo=(e,t)=>{let r=Xm(e.launchRequest);return r.state==="valid"&&Txr(t.owner)&&dEo(e)&&(t.owner.kind!=="pi-rpc-session"||e.nativeSession.activation.sessionFile!==void 0&&e.artifact.packageVersion===CR)&&e.launchRequest.owner.kind===t.owner.kind&&e.launchRequest.owner.commandId===t.owner.commandId&&e.launchRequest.owner.sessionId===t.owner.sessionId&&e.artifact.interpreterPath===t.executable&&iEo(t.arguments_,oEo(e))&&sEo(t,e.nativeSession.directory)&&nEo(r.request,t)},pAe=(e,t)=>{if(!Txr(e.owner))return;let r=t?.piRpc;return r!==void 0&&lEo(r,e)?r:void 0}});import{createHash as Axr}from"node:crypto";import{lstatSync as uEo}from"node:fs";import{dirname as C$,isAbsolute as pEo,join as dC,relative as bxr,sep as xxr}from"node:path";import{fileURLToPath as mEo}from"node:url";var k$,Nut,fEo,hEo,AL,Ch,gEo,yEo,mAe,$T,SEo,Put,Cxr,kxr,EEo,REo,_Eo,vEo,wxr,TEo,Nxr,Pxr,IEo,xEo,AEo,bEo,CEo,Oxr,fAe,hAe,Lxr=q(()=>{"use strict";F();z();k$="1.7.0",Nut=Object.freeze({maximumEntries:4096,maximumFileBytes:8*1024*1024,maximumTotalBytes:16*1024*1024}),fEo=/\.(?:c?js|mjs|json)$/u,hEo=d.fromJsonString(d.Struct({bin:d.optionalKey(d.Unknown),dependencies:d.optionalKey(d.Record(d.String,d.Unknown)),name:d.optionalKey(d.Unknown),version:d.optionalKey(d.Unknown)})),AL=()=>f("transport_failed","The bundled Skills CLI does not match the package this Node was built with."),Ch=s.fail(AL()),gEo=e=>{let t=process.getuid?.();return(t===void 0||Number(e.uid)===t||Number(e.uid)===0)&&(Number(e.mode)&18)===0},yEo=e=>e.isFile()?"file":e.isDirectory()?"directory":void 0,mAe=(e,t)=>s.try({catch:AL,try:()=>{let r=uEo(e,{bigint:!0}),n=yEo(r);if(n===void 0||t!==void 0&&n!==t||!gEo(r))throw AL();return{kind:n,size:r.size}}}),$T=(e,t)=>{let r=bxr(e,t);return r!==""&&!r.startsWith("..")&&!pEo(r)},SEo=1024*1024,Put=(e,t)=>{let r=dC(t,"package.json");return mAe(r,"file").pipe(s.filterOrFail(({size:n})=>n<=BigInt(SEo),AL),s.flatMap(()=>e.readFileString(r)),s.flatMap(d.decodeUnknownEffect(hEo)))},Cxr=(e,t,r=t)=>e.fs.readDirectory(r).pipe(s.flatMap(n=>(e.closure.entries+=n.length,e.closure.entries>Nut.maximumEntries?Ch:s.forEach(n,o=>{let i=dC(r,o);return o==="node_modules"&&r===t?s.succeed([]):mAe(i).pipe(s.flatMap(({kind:a})=>a==="directory"?Cxr(e,t,i):s.succeed([i])))}))),s.map(n=>n.flat())),kxr=(e,t,r)=>e.realPath(dC(t,"node_modules",r)).pipe(s.catch(()=>{let n=C$(t);return n===t?Ch:kxr(e,n,r)})),EEo=(e,t,r)=>s.gen(function*(){let{closure:n,fs:o}=e,{size:i}=yield*mAe(r,"file");if(n.total+=Number(i),i>BigInt(Nut.maximumFileBytes)||n.total>Nut.maximumTotalBytes)return yield*Ch;let a=yield*o.readFile(r);return n.hash.update(`${bxr(t,r)}\0${String(a.byteLength)}\0`),n.hash.update(Axr("sha256").update(a).digest()),r}),REo=e=>Object.keys(e.dependencies??{}).toSorted(),_Eo=(e,t)=>Cxr(e,t).pipe(s.flatMap(r=>s.forEach(r.toSorted().filter(n=>fEo.test(n)),n=>EEo(e,t,n)))),vEo=(e,t)=>s.gen(function*(){let{closure:r,fs:n,prefix:o}=e;if(!$T(o,t))return yield*Ch;r.seen.add(t),yield*mAe(t,"directory");let i=yield*Put(n,t);return r.hash.update(`${String(i.name)}@${String(i.version)}\0`),i}),wxr=(e,t)=>s.gen(function*(){if(e.closure.seen.has(t))return[];let r=yield*vEo(e,t),n=yield*_Eo(e,t),o=yield*s.forEach(REo(r),i=>kxr(e.fs,t,i).pipe(s.flatMap(a=>wxr(e,a))));return[...n,...o.flat()]}),TEo="@maiaos/node",Nxr=(e,t)=>Put(e,t).pipe(s.flatMap(r=>r.name===TEo?s.succeed(t):Ch),s.catch(()=>{let r=C$(t);return r===t?Ch:Nxr(e,r)})),Pxr=(e,t)=>e.exists(dC(t,"pnpm-workspace.yaml")).pipe(s.flatMap(r=>{let n=C$(t);return r?s.succeed(t):n===t?Ch:Pxr(e,n)}),s.mapError(AL)),IEo=(e,t)=>s.gen(function*(){let r=yield*Nxr(e,C$(t)),n=r.indexOf(`${xxr}node_modules${xxr}`),o=n>0?r.slice(0,n):yield*Pxr(e,r);return{modules:n>0?C$(C$(r)):dC(r,"node_modules"),own:r,prefix:o}}),xEo=(e,t)=>{let{bin:r}=t,n=typeof r=="string"?r:r?.skills,o=typeof n=="string"?dC(e,n):"";return $T(e,o)?s.succeed(o):Ch},AEo=(e,t)=>wxr(e,t).pipe(s.map(r=>({files:r,sha256:e.closure.hash.digest("hex")}))),bEo=(e,t)=>s.gen(function*(){let{modules:r,own:n,prefix:o}=yield*IEo(e,yield*e.realPath(mEo(t.fromUrl))),i=yield*e.realPath(dC(n,"node_modules","skills")).pipe(s.catch(()=>e.realPath(dC(r,"skills")))),a=yield*Put(e,i);return a.name!=="skills"||a.version!==k$?yield*Ch:$T(o,i)?{entryPath:yield*e.realPath(yield*xEo(i,a)),prefix:o,root:i}:yield*Ch}),CEo=(e,t)=>({closure:{entries:0,hash:Axr("sha256"),seen:new Set,total:0},fs:e,prefix:t}),Oxr=e=>s.gen(function*(){let t=yield*ve.FileSystem,{entryPath:r,prefix:n,root:o}=yield*bEo(t,e),i=CEo(t,n),{files:a,sha256:c}=yield*AEo(i,o);return(yield*s.forEach(a,u=>t.realPath(u))).includes(r)?{closureSha256:c,entryPath:r,files:a,fromUrl:e.fromUrl,interpreterPath:yield*t.realPath(e.interpreterPath??process.execPath),packageRoot:o,version:k$}:yield*Ch}),fAe=e=>Oxr(e).pipe(s.mapError(AL)),hAe=e=>Oxr({fromUrl:e.fromUrl,interpreterPath:e.interpreterPath}).pipe(s.mapError(AL),s.flatMap(t=>t.closureSha256===e.closureSha256&&t.entryPath===e.entryPath&&t.interpreterPath===e.interpreterPath&&t.packageRoot===e.packageRoot&&t.files.join("\0")===e.files.join("\0")?s.void:Ch))});var lC,kEo,bL,GT,gAe,w$,Dxr=q(()=>{"use strict";Z();T$();lC=Object.freeze(S$.map(({integration:e})=>e)),kEo=e=>bu(e).ownerKinds,bL=e=>lC.find(t=>kEo(t).includes(e)),GT=(e,t)=>{switch(t){case de.antigravity:return e?.antigravity;case de.claudeCode:return e?.claudeCode;case"codex":return e?.codex;case de.grokCli:return e?.grokCli;case de.maiaAgent:return e?.maiaAgent;case de.pi:return e?.pi}},gAe=(e,t)=>{let r=Object.freeze(t);switch(e){case de.antigravity:return Object.freeze({antigravity:r});case de.claudeCode:return Object.freeze({claudeCode:r});case"codex":return Object.freeze({codex:r});case de.grokCli:return Object.freeze({grokCli:r});case de.maiaAgent:return Object.freeze({maiaAgent:r});case de.pi:return Object.freeze({pi:r})}},w$=e=>lC.flatMap(t=>{let r=GT(e,t);return r===void 0?[]:[r]})});var Mxr={};Nn(Mxr,{PRIVATE_GROUP_SHELL_FUNCTION:()=>eZ,SKILLS_PACKAGE_VERSION:()=>k$,USER_WRITES_ONLY_SHELL_FUNCTION:()=>tZ,consumeInvocationAttachmentNativeLease:()=>Yxe,embeddedManagedPiWorkerDefines:()=>Sut,insideDirectory:()=>$T,inspectDarwinVouchedTarget:()=>Ah,inspectManagedPiWorkerArtifact:()=>iAe,inspectSkillsFiles:()=>fAe,invocationAttachmentProcessOwnerId:()=>sC,issueInvocationAttachmentLaunchAuthorization:()=>iut,managedPiAuthorizationForRequest:()=>aAe,openDarwinVouchedTarget:()=>Xxe,openInvocationAttachmentNativeLease:()=>cut,piRpcAuthorizationForRequest:()=>pAe,readEmbeddedManagedPiWorkerReleaseIdentity:()=>aZ,releaseIdentityOf:()=>yut,requireInvocationAttachmentLaunchAuthorization:()=>Jxe,retainDarwinVouchedAuthorizationTarget:()=>oZ,sameRequest:()=>cZ,skillsVouchTarget:()=>Kxe,suppliedVendorLaunchAuthorizations:()=>w$,vendorIntegrationForOwner:()=>bL,vendorLaunchAuthorization:()=>GT,vendorLaunchAuthorizationGrant:()=>gAe,vendorLaunchIntegrations:()=>lC,verifyProcessLaunchAuthority:()=>zxe,verifyResolvedManagedPiWorkerArtifact:()=>sAe,verifyRetainedDarwinVouchedTargetPath:()=>iZ,verifySkillsPackage:()=>hAe});var wR=q(()=>{"use strict";lIr();bIr();kIr();LIr();nxr();ixr();Ixr();Qlt();Lxr();Dxr()});var ZT=sm((ruc,Ubr)=>{"use strict";var Dbr=["nodebuffer","arraybuffer","fragments"],Mbr=typeof Blob<"u";Mbr&&Dbr.push("blob");Ubr.exports={BINARY_TYPES:Dbr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Mbr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var BZ=sm((nuc,ZAe)=>{"use strict";var{EMPTY_BUFFER:PIo}=ZT(),jpt=Buffer[Symbol.species];function OIo(e,t){if(e.length===0)return PIo;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return n<t?new jpt(r.buffer,r.byteOffset,n):r}function Fbr(e,t,r,n,o){for(let i=0;i<o;i++)r[n+i]=e[i]^t[i&3]}function Hbr(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function LIo(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function Wpt(e){if(Wpt.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new jpt(e):ArrayBuffer.isView(e)?t=new jpt(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),Wpt.readOnly=!1),t}ZAe.exports={concat:OIo,mask:Fbr,toArrayBuffer:LIo,toBuffer:Wpt,unmask:Hbr};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=Ha("bufferutil");ZAe.exports.mask=function(t,r,n,o,i){i<48?Fbr(t,r,n,o,i):e.mask(t,r,n,o,i)},ZAe.exports.unmask=function(t,r){t.length<32?Hbr(t,r):e.unmask(t,r)}}catch{}});var jbr=sm((ouc,qbr)=>{"use strict";var Bbr=Symbol("kDone"),$pt=Symbol("kRun"),Gpt=class{constructor(t){this[Bbr]=()=>{this.pending--,this[$pt]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[$pt]()}[$pt](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[Bbr])}}};qbr.exports=Gpt});var V$=sm((iuc,zbr)=>{"use strict";var qZ=Ha("zlib"),Wbr=BZ(),DIo=jbr(),{kStatusCode:$br}=ZT(),MIo=Buffer[Symbol.species],UIo=Buffer.from([0,0,255,255]),ebe=Symbol("permessage-deflate"),QT=Symbol("total-length"),G$=Symbol("callback"),gC=Symbol("buffers"),z$=Symbol("error"),QAe,zpt=class{constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!QAe){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;QAe=new DIo(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[G$];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,n=t.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&(typeof o.client_max_window_bits=="number"?r.clientMaxWindowBits>o.client_max_window_bits:!o.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),t}decompress(t,r,n){QAe.add(o=>{this._decompress(t,r,(i,a)=>{o(),n(i,a)})})}compress(t,r,n){QAe.add(o=>{this._compress(t,r,(i,a)=>{o(),n(i,a)})})}_decompress(t,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?qZ.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=qZ.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[ebe]=this,this._inflate[QT]=0,this._inflate[gC]=[],this._inflate.on("error",HIo),this._inflate.on("data",Gbr)}this._inflate[G$]=n,this._inflate.write(t),r&&this._inflate.write(UIo),this._inflate.flush(()=>{let i=this._inflate[z$];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=Wbr.concat(this._inflate[gC],this._inflate[QT]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[QT]=0,this._inflate[gC]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(t,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?qZ.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=qZ.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[QT]=0,this._deflate[gC]=[],this._deflate.on("data",FIo)}this._deflate[G$]=n,this._deflate.write(t),this._deflate.flush(qZ.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Wbr.concat(this._deflate[gC],this._deflate[QT]);r&&(i=new MIo(i.buffer,i.byteOffset,i.length-4)),this._deflate[G$]=null,this._deflate[QT]=0,this._deflate[gC]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};zbr.exports=zpt;function FIo(e){this[gC].push(e),this[QT]+=e.length}function Gbr(e){if(this[QT]+=e.length,this[ebe]._maxPayload<1||this[QT]<=this[ebe]._maxPayload){this[gC].push(e);return}this[z$]=new RangeError("Max payload size exceeded"),this[z$].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[z$][$br]=1009,this.removeListener("data",Gbr),this.reset()}function HIo(e){if(this[ebe]._inflate=null,this[z$]){this[G$](this[z$]);return}e[$br]=1007,this[G$](e)}});var K$=sm((suc,tbe)=>{"use strict";var{isUtf8:Vbr}=Ha("buffer"),{hasBlob:BIo}=ZT(),qIo=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function jIo(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Vpt(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function WIo(e){return BIo&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}tbe.exports={isBlob:WIo,isValidStatusCode:jIo,isValidUTF8:Vpt,tokenChars:qIo};if(Vbr)tbe.exports.isValidUTF8=function(e){return e.length<24?Vpt(e):Vbr(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=Ha("utf-8-validate");tbe.exports.isValidUTF8=function(t){return t.length<32?Vpt(t):e(t)}}catch{}});var Zpt=sm((auc,eCr)=>{"use strict";var{Writable:$Io}=Ha("stream"),Kbr=V$(),{BINARY_TYPES:GIo,EMPTY_BUFFER:Xbr,kStatusCode:zIo,kWebSocket:VIo}=ZT(),{concat:Kpt,toArrayBuffer:KIo,unmask:XIo}=BZ(),{isValidStatusCode:JIo,isValidUTF8:Jbr}=K$(),rbe=Buffer[Symbol.species],Ph=0,Ybr=1,Zbr=2,Qbr=3,Xpt=4,Jpt=5,nbe=6,Ypt=class extends $Io{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||GIo[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[VIo]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ph}_write(t,r,n){if(this._opcode===8&&this._state==Ph)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(n)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new rbe(n.buffer,n.byteOffset+t,n.length-t),new rbe(n.buffer,n.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let n=this._buffers[0],o=r.length-t;t>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,t),o),this._buffers[0]=new rbe(n.buffer,n.byteOffset+t,n.length-t)),t-=n.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case Ph:this.getInfo(t);break;case Ybr:this.getPayloadLength16(t);break;case Zbr:this.getPayloadLength64(t);break;case Qbr:this.getMask();break;case Xpt:this.getData(t);break;case Jpt:case nbe:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[Kbr.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=Ybr:this._payloadLength===127?this._state=Zbr:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=Qbr:this._state=Xpt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Xpt}getData(t){let r=Xbr;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&XIo(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(n);return}if(this._compressed){this._state=Jpt,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[Kbr.extensionName].decompress(t,this._fin,(o,i)=>{if(o)return r(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(i)}this.dataMessage(r),this._state===Ph&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=Ph;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Kpt(n,r):this._binaryType==="arraybuffer"?o=KIo(Kpt(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Ph):(this._state=nbe,setImmediate(()=>{this.emit("message",o,!0),this._state=Ph,this.startLoop(t)}))}else{let o=Kpt(n,r);if(!this._skipUTF8Validation&&!Jbr(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._state===Jpt||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Ph):(this._state=nbe,setImmediate(()=>{this.emit("message",o,!1),this._state=Ph,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,Xbr),this.end();else{let n=t.readUInt16BE(0);if(!JIo(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let o=new rbe(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Jbr(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=Ph;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=Ph):(this._state=nbe,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=Ph,this.startLoop(r)}))}createError(t,r,n,o,i){this._loop=!1,this._errored=!0;let a=new t(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=i,a[zIo]=o,a}};eCr.exports=Ypt});var tmt=sm((duc,nCr)=>{"use strict";var{Duplex:cuc}=Ha("stream"),{randomFillSync:YIo}=Ha("crypto"),{types:{isUint8Array:ZIo}}=Ha("util"),tCr=V$(),{EMPTY_BUFFER:QIo,kWebSocket:exo,NOOP:txo}=ZT(),{isBlob:X$,isValidStatusCode:rxo}=K$(),{mask:rCr,toBuffer:BL}=BZ(),Oh=Symbol("kByteLength"),nxo=Buffer.alloc(4),obe=8*1024,qL,J$=obe,Zy=0,oxo=1,ixo=2,Qpt=class e{constructor(t,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Zy,this.onerror=txo,this[exo]=void 0}static frame(t,r){let n,o=!1,i=2,a=!1;r.mask&&(n=r.maskBuffer||nxo,r.generateMask?r.generateMask(n):(J$===obe&&(qL===void 0&&(qL=Buffer.alloc(obe)),YIo(qL,0,obe),J$=0),n[0]=qL[J$++],n[1]=qL[J$++],n[2]=qL[J$++],n[3]=qL[J$++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof t=="string"?(!r.mask||a)&&r[Oh]!==void 0?c=r[Oh]:(t=Buffer.from(t),c=t.length):(c=t.length,o=r.mask&&r.readOnly&&!a);let l=c;c>=65536?(i+=8,l=127):c>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(o?c+i:i);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(c,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(c,4,6)),r.mask?(u[1]|=128,u[i-4]=n[0],u[i-3]=n[1],u[i-2]=n[2],u[i-1]=n[3],a?[u,t]:o?(rCr(t,n,u,i,c),[u]):(rCr(t,n,t,0,c),[u,t])):[u,t]}close(t,r,n,o){let i;if(t===void 0)i=QIo;else{if(typeof t!="number"||!rxo(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(t,0),typeof r=="string")i.write(r,2);else if(ZIo(r))i.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[Oh]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Zy?this.enqueue([this.dispatch,i,!1,a,o]):this.sendFrame(e.frame(i,a),o)}ping(t,r,n){let o,i;if(typeof t=="string"?(o=Buffer.byteLength(t),i=!1):X$(t)?(o=t.size,i=!1):(t=BL(t),o=t.length,i=BL.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Oh]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};X$(t)?this._state!==Zy?this.enqueue([this.getBlobData,t,!1,a,n]):this.getBlobData(t,!1,a,n):this._state!==Zy?this.enqueue([this.dispatch,t,!1,a,n]):this.sendFrame(e.frame(t,a),n)}pong(t,r,n){let o,i;if(typeof t=="string"?(o=Buffer.byteLength(t),i=!1):X$(t)?(o=t.size,i=!1):(t=BL(t),o=t.length,i=BL.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Oh]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};X$(t)?this._state!==Zy?this.enqueue([this.getBlobData,t,!1,a,n]):this.getBlobData(t,!1,a,n):this._state!==Zy?this.enqueue([this.dispatch,t,!1,a,n]):this.sendFrame(e.frame(t,a),n)}send(t,r,n){let o=this._extensions[tCr.extensionName],i=r.binary?2:1,a=r.compress,c,l;typeof t=="string"?(c=Buffer.byteLength(t),l=!1):X$(t)?(c=t.size,l=!1):(t=BL(t),c=t.length,l=BL.readOnly),this._firstFragment?(this._firstFragment=!1,a&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=o._threshold),this._compress=a):(a=!1,i=0),r.fin&&(this._firstFragment=!0);let u={[Oh]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:a};X$(t)?this._state!==Zy?this.enqueue([this.getBlobData,t,this._compress,u,n]):this.getBlobData(t,this._compress,u,n):this._state!==Zy?this.enqueue([this.dispatch,t,this._compress,u,n]):this.dispatch(t,this._compress,u,n)}getBlobData(t,r,n,o){this._bufferedBytes+=n[Oh],this._state=ixo,t.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(emt,this,c,o);return}this._bufferedBytes-=n[Oh];let a=BL(i);r?this.dispatch(a,r,n,o):(this._state=Zy,this.sendFrame(e.frame(a,n),o),this.dequeue())}).catch(i=>{process.nextTick(sxo,this,i,o)})}dispatch(t,r,n,o){if(!r){this.sendFrame(e.frame(t,n),o);return}let i=this._extensions[tCr.extensionName];this._bufferedBytes+=n[Oh],this._state=oxo,i.compress(t,n.fin,(a,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");emt(this,l,o);return}this._bufferedBytes-=n[Oh],this._state=Zy,n.readOnly=!1,this.sendFrame(e.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===Zy&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][Oh],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][Oh],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};nCr.exports=Qpt;function emt(e,t,r){typeof r=="function"&&r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],i=o[o.length-1];typeof i=="function"&&i(t)}}function sxo(e,t,r){emt(e,t,r),e.onerror(t)}});var pCr=sm((luc,uCr)=>{"use strict";var{kForOnEventAttribute:jZ,kListener:rmt}=ZT(),oCr=Symbol("kCode"),iCr=Symbol("kData"),sCr=Symbol("kError"),aCr=Symbol("kMessage"),cCr=Symbol("kReason"),Y$=Symbol("kTarget"),dCr=Symbol("kType"),lCr=Symbol("kWasClean"),eI=class{constructor(t){this[Y$]=null,this[dCr]=t}get target(){return this[Y$]}get type(){return this[dCr]}};Object.defineProperty(eI.prototype,"target",{enumerable:!0});Object.defineProperty(eI.prototype,"type",{enumerable:!0});var jL=class extends eI{constructor(t,r={}){super(t),this[oCr]=r.code===void 0?0:r.code,this[cCr]=r.reason===void 0?"":r.reason,this[lCr]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[oCr]}get reason(){return this[cCr]}get wasClean(){return this[lCr]}};Object.defineProperty(jL.prototype,"code",{enumerable:!0});Object.defineProperty(jL.prototype,"reason",{enumerable:!0});Object.defineProperty(jL.prototype,"wasClean",{enumerable:!0});var Z$=class extends eI{constructor(t,r={}){super(t),this[sCr]=r.error===void 0?null:r.error,this[aCr]=r.message===void 0?"":r.message}get error(){return this[sCr]}get message(){return this[aCr]}};Object.defineProperty(Z$.prototype,"error",{enumerable:!0});Object.defineProperty(Z$.prototype,"message",{enumerable:!0});var WZ=class extends eI{constructor(t,r={}){super(t),this[iCr]=r.data===void 0?null:r.data}get data(){return this[iCr]}};Object.defineProperty(WZ.prototype,"data",{enumerable:!0});var axo={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[jZ]&&o[rmt]===t&&!o[jZ])return;let n;if(e==="message")n=function(i,a){let c=new WZ("message",{data:a?i:i.toString()});c[Y$]=this,ibe(t,this,c)};else if(e==="close")n=function(i,a){let c=new jL("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Y$]=this,ibe(t,this,c)};else if(e==="error")n=function(i){let a=new Z$("error",{error:i,message:i.message});a[Y$]=this,ibe(t,this,a)};else if(e==="open")n=function(){let i=new eI("open");i[Y$]=this,ibe(t,this,i)};else return;n[jZ]=!!r[jZ],n[rmt]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[rmt]===t&&!r[jZ]){this.removeListener(e,r);break}}};uCr.exports={CloseEvent:jL,ErrorEvent:Z$,Event:eI,EventTarget:axo,MessageEvent:WZ};function ibe(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var sbe=sm((uuc,mCr)=>{"use strict";var{tokenChars:$Z}=K$();function FR(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function cxo(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,i=!1,a,c,l=-1,u=-1,p=-1,h=0;for(;h<e.length;h++)if(u=e.charCodeAt(h),a===void 0)if(p===-1&&$Z[u]===1)l===-1&&(l=h);else if(h!==0&&(u===32||u===9))p===-1&&l!==-1&&(p=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);p===-1&&(p=h);let S=e.slice(l,p);u===44?(FR(t,S,r),r=Object.create(null)):a=S,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(c===void 0)if(p===-1&&$Z[u]===1)l===-1&&(l=h);else if(u===32||u===9)p===-1&&l!==-1&&(p=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);p===-1&&(p=h),FR(r,e.slice(l,p),!0),u===44&&(FR(t,a,r),r=Object.create(null),a=void 0),l=p=-1}else if(u===61&&l!==-1&&p===-1)c=e.slice(l,h),l=p=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(o){if($Z[u]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);l===-1?l=h:n||(n=!0),o=!1}else if(i)if($Z[u]===1)l===-1&&(l=h);else if(u===34&&l!==-1)i=!1,p=h;else if(u===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(u===34&&e.charCodeAt(h-1)===61)i=!0;else if(p===-1&&$Z[u]===1)l===-1&&(l=h);else if(l!==-1&&(u===32||u===9))p===-1&&(p=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);p===-1&&(p=h);let S=e.slice(l,p);n&&(S=S.replace(/\\/g,""),n=!1),FR(r,c,S),u===44&&(FR(t,a,r),r=Object.create(null),a=void 0),c=void 0,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=h);let g=e.slice(l,p);return a===void 0?FR(t,g,r):(c===void 0?FR(r,g,!0):n?FR(r,c,g.replace(/\\/g,"")):FR(r,c,g),FR(t,a,r)),t}function dxo(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(n=>[t].concat(Object.keys(n).map(o=>{let i=n[o];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?o:`${o}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}mCr.exports={format:dxo,parse:cxo}});var lbe=sm((fuc,xCr)=>{"use strict";var lxo=Ha("events"),uxo=Ha("https"),pxo=Ha("http"),gCr=Ha("net"),mxo=Ha("tls"),{randomBytes:fxo,createHash:hxo}=Ha("crypto"),{Duplex:puc,Readable:muc}=Ha("stream"),{URL:nmt}=Ha("url"),yC=V$(),gxo=Zpt(),yxo=tmt(),{isBlob:Sxo}=K$(),{BINARY_TYPES:fCr,CLOSE_TIMEOUT:Exo,EMPTY_BUFFER:abe,GUID:Rxo,kForOnEventAttribute:omt,kListener:_xo,kStatusCode:vxo,kWebSocket:pd,NOOP:yCr}=ZT(),{EventTarget:{addEventListener:Txo,removeEventListener:Ixo}}=pCr(),{format:xxo,parse:Axo}=sbe(),{toBuffer:bxo}=BZ(),SCr=Symbol("kAborted"),imt=[8,13],tI=["CONNECTING","OPEN","CLOSING","CLOSED"],Cxo=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ws=class e extends lxo{constructor(t,r,n){super(),this._binaryType=fCr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=abe,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?!n||n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]):r=[r]),ECr(this,t,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){fCr.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){let o=new gxo({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new yxo(t,this._extensions,n.generateMask);this._receiver=o,this._sender=i,this._socket=t,o[pd]=this,i[pd]=this,t[pd]=this,o.on("conclude",Nxo),o.on("drain",Pxo),o.on("error",Oxo),o.on("message",Lxo),o.on("ping",Dxo),o.on("pong",Mxo),i.onerror=Uxo,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",vCr),t.on("data",dbe),t.on("end",TCr),t.on("error",ICr),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[yC.extensionName]&&this._extensions[yC.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Zm(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(t,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=e.CLOSING,_Cr(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){smt(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||abe,r,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){smt(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||abe,r,n)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){smt(this,t,n);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[yC.extensionName]||(o.compress=!1),this._sender.send(t||abe,o,n)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Zm(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ws,"CONNECTING",{enumerable:!0,value:tI.indexOf("CONNECTING")});Object.defineProperty(Ws.prototype,"CONNECTING",{enumerable:!0,value:tI.indexOf("CONNECTING")});Object.defineProperty(Ws,"OPEN",{enumerable:!0,value:tI.indexOf("OPEN")});Object.defineProperty(Ws.prototype,"OPEN",{enumerable:!0,value:tI.indexOf("OPEN")});Object.defineProperty(Ws,"CLOSING",{enumerable:!0,value:tI.indexOf("CLOSING")});Object.defineProperty(Ws.prototype,"CLOSING",{enumerable:!0,value:tI.indexOf("CLOSING")});Object.defineProperty(Ws,"CLOSED",{enumerable:!0,value:tI.indexOf("CLOSED")});Object.defineProperty(Ws.prototype,"CLOSED",{enumerable:!0,value:tI.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(Ws.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(Ws.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[omt])return t[_xo];return null},set(t){for(let r of this.listeners(e))if(r[omt]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[omt]:!0})}})});Ws.prototype.addEventListener=Txo;Ws.prototype.removeEventListener=Ixo;xCr.exports=Ws;function ECr(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Exo,protocolVersion:imt[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!imt.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${imt.join(", ")})`);let i;if(t instanceof nmt)i=t;else try{i=new nmt(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),e._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!a&&!c?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let v=new SyntaxError(l);if(e._redirects===0)throw v;cbe(e,v);return}let u=a?443:80,p=fxo(16).toString("base64"),h=a?uxo.request:pxo.request,g=new Set,S;if(o.createConnection=o.createConnection||(a?wxo:kxo),o.defaultPort=o.defaultPort||u,o.port=i.port||u,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(S=new yC({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=xxo({[yC.extensionName]:S.offer()})),r.length){for(let v of r){if(typeof v!="string"||!Cxo.test(v)||g.has(v))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(v)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),c){let v=o.path.split(":");o.socketPath=v[0],o.path=v[1]}let E;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=a,e._originalHostOrSocketPath=c?o.socketPath:i.host;let v=n&&n.headers;if(n={...n,headers:{}},v)for(let[T,x]of Object.entries(v))n.headers[T.toLowerCase()]=x}else if(e.listenerCount("redirect")===0){let v=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:i.host===e._originalHostOrSocketPath;(!v||e._originalSecure&&!a)&&(delete o.headers.authorization,delete o.headers.cookie,v||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=e._req=h(o),e._redirects&&e.emit("redirect",e.url,E)}else E=e._req=h(o);o.timeout&&E.on("timeout",()=>{Zm(e,E,"Opening handshake has timed out")}),E.on("error",v=>{E===null||E[SCr]||(E=e._req=null,cbe(e,v))}),E.on("response",v=>{let T=v.headers.location,x=v.statusCode;if(T&&o.followRedirects&&x>=300&&x<400){if(++e._redirects>o.maxRedirects){Zm(e,E,"Maximum redirects exceeded");return}E.abort();let w;try{w=new nmt(T,t)}catch{let N=new SyntaxError(`Invalid URL: ${T}`);cbe(e,N);return}ECr(e,w,r,n)}else e.emit("unexpected-response",E,v)||Zm(e,E,`Unexpected server response: ${v.statusCode}`)}),E.on("upgrade",(v,T,x)=>{if(e.emit("upgrade",v),e.readyState!==Ws.CONNECTING)return;E=e._req=null;let w=v.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){Zm(e,T,"Invalid Upgrade header");return}let D=hxo("sha1").update(p+Rxo).digest("base64");if(v.headers["sec-websocket-accept"]!==D){Zm(e,T,"Invalid Sec-WebSocket-Accept header");return}let N=v.headers["sec-websocket-protocol"],A;if(N!==void 0?g.size?g.has(N)||(A="Server sent an invalid subprotocol"):A="Server sent a subprotocol but none was requested":g.size&&(A="Server sent no subprotocol"),A){Zm(e,T,A);return}N&&(e._protocol=N);let k=v.headers["sec-websocket-extensions"];if(k!==void 0){if(!S){Zm(e,T,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let b;try{b=Axo(k)}catch{Zm(e,T,"Invalid Sec-WebSocket-Extensions header");return}let L=Object.keys(b);if(L.length!==1||L[0]!==yC.extensionName){Zm(e,T,"Server indicated an extension that was not requested");return}try{S.accept(b[yC.extensionName])}catch{Zm(e,T,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[yC.extensionName]=S}e.setSocket(T,x,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,e):E.end()}function cbe(e,t){e._readyState=Ws.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function kxo(e){return e.path=e.socketPath,gCr.connect(e)}function wxo(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=gCr.isIP(e.host)?"":e.host),mxo.connect(e)}function Zm(e,t,r){e._readyState=Ws.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Zm),t.setHeader?(t[SCr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(cbe,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function smt(e,t,r){if(t){let n=Sxo(t)?t.size:bxo(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${e.readyState} (${tI[e.readyState]})`);process.nextTick(r,n)}}function Nxo(e,t){let r=this[pd];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[pd]!==void 0&&(r._socket.removeListener("data",dbe),process.nextTick(RCr,r._socket),e===1005?r.close():r.close(e,t))}function Pxo(){let e=this[pd];e.isPaused||e._socket.resume()}function Oxo(e){let t=this[pd];t._socket[pd]!==void 0&&(t._socket.removeListener("data",dbe),process.nextTick(RCr,t._socket),t.close(e[vxo])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function hCr(){this[pd].emitClose()}function Lxo(e,t){this[pd].emit("message",e,t)}function Dxo(e){let t=this[pd];t._autoPong&&t.pong(e,!this._isServer,yCr),t.emit("ping",e)}function Mxo(e){this[pd].emit("pong",e)}function RCr(e){e.resume()}function Uxo(e){let t=this[pd];t.readyState!==Ws.CLOSED&&(t.readyState===Ws.OPEN&&(t._readyState=Ws.CLOSING,_Cr(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function _Cr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function vCr(){let e=this[pd];if(this.removeListener("close",vCr),this.removeListener("data",dbe),this.removeListener("end",TCr),e._readyState=Ws.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[pd]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",hCr),e._receiver.on("finish",hCr))}function dbe(e){this[pd]._receiver.write(e)||this.pause()}function TCr(){let e=this[pd];e._readyState=Ws.CLOSING,e._receiver.end(),this.end()}function ICr(){let e=this[pd];this.removeListener("error",ICr),this.on("error",yCr),e&&(e._readyState=Ws.CLOSING,this.destroy())}});var kCr=sm((guc,CCr)=>{"use strict";var huc=lbe(),{Duplex:Fxo}=Ha("stream");function ACr(e){e.emit("close")}function Hxo(){!this.destroyed&&this._writableState.finished&&this.destroy()}function bCr(e){this.removeListener("error",bCr),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Bxo(e,t){let r=!0,n=new Fxo({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||e.pause()}),e.once("error",function(i){n.destroyed||(r=!1,n.destroy(i))}),e.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(o,i){if(e.readyState===e.CLOSED){i(o),process.nextTick(ACr,n);return}let a=!1;e.once("error",function(l){a=!0,i(l)}),e.once("close",function(){a||i(o),process.nextTick(ACr,n)}),r&&e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){n._final(o)});return}e._socket!==null&&(e._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",function(){o()}),e.close()))},n._read=function(){e.isPaused&&e.resume()},n._write=function(o,i,a){if(e.readyState===e.CONNECTING){e.once("open",function(){n._write(o,i,a)});return}e.send(o,a)},n.on("end",Hxo),n.on("error",bCr),n}CCr.exports=Bxo});var amt=sm((yuc,wCr)=>{"use strict";var{tokenChars:qxo}=K$();function jxo(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let a=e.charCodeAt(o);if(n===-1&&qxo[a]===1)r===-1&&(r=o);else if(o!==0&&(a===32||a===9))n===-1&&r!==-1&&(n=o);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=e.slice(r,n);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=e.slice(r,o);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}wCr.exports={parse:jxo}});var UCr=sm((Euc,MCr)=>{"use strict";var Wxo=Ha("events"),ube=Ha("http"),{Duplex:Suc}=Ha("stream"),{createHash:$xo}=Ha("crypto"),NCr=sbe(),WL=V$(),Gxo=amt(),zxo=lbe(),{CLOSE_TIMEOUT:Vxo,GUID:Kxo,kWebSocket:Xxo}=ZT(),Jxo=/^[+/0-9A-Za-z]{22}==$/,PCr=0,OCr=1,DCr=2,cmt=class extends Wxo{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Vxo,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:zxo,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=ube.createServer((n,o)=>{let i=ube.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Yxo(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,a)=>{this.handleUpgrade(o,i,a,n)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=PCr}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===DCr){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(GZ,this);return}if(t&&this.once("close",t),this._state!==OCr)if(this._state=OCr,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(GZ,this):process.nextTick(GZ,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{GZ(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,n,o){r.on("error",LCr);let i=t.headers["sec-websocket-key"],a=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){$L(this,t,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){$L(this,t,r,400,"Invalid Upgrade header");return}if(i===void 0||!Jxo.test(i)){$L(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){$L(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){zZ(r,400);return}let l=t.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=Gxo.parse(l)}catch{$L(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let p=t.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&p!==void 0){let g=new WL({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=NCr.parse(p);S[WL.extensionName]&&(g.accept(S[WL.extensionName]),h[WL.extensionName]=g)}catch{$L(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(g,(S,E,v,T)=>{if(!S)return zZ(r,E||401,v,T);this.completeUpgrade(h,i,u,t,r,n,o)});return}if(!this.options.verifyClient(g))return zZ(r,401)}this.completeUpgrade(h,i,u,t,r,n,o)}completeUpgrade(t,r,n,o,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[Xxo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>PCr)return zZ(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$xo("sha1").update(r+Kxo).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let h=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;h&&(u.push(`Sec-WebSocket-Protocol: ${h}`),p._protocol=h)}if(t[WL.extensionName]){let h=t[WL.extensionName].params,g=NCr.format({[WL.extensionName]:[h]});u.push(`Sec-WebSocket-Extensions: ${g}`),p._extensions=t}this.emit("headers",u,o),i.write(u.concat(`\r
238
+ `),tZ='user_writes_only() { { [ "$1" = "$uid" ] || [ "$1" = 0 ]; } && [ $(( 0$3 & 002 )) -eq 0 ] && { [ $(( 0$3 & 020 )) -eq 0 ] || { [ -n "$upg" ] && [ "$2" = "$upg" ]; }; }; }'});import{createHash as Ago,timingSafeEqual as bgo}from"node:crypto";import{closeSync as Cgo,constants as rZ,fstatSync as yIr,lstatSync as kgo,openSync as wgo,statfsSync as Ngo}from"node:fs";import{lstat as Vxe,open as SIr}from"node:fs/promises";import{isAbsolute as eut,resolve as tut}from"node:path";var Pgo,Ogo,EIr,Lgo,Dgo,Mgo,RIr,hIr,Kxe,qT,_Ir,vL,Ugo,Fgo,Hgo,Bgo,nZ,qgo,jgo,Wgo,$go,Ggo,zgo,rut,Vgo,gIr,Kgo,Xgo,vIr,nut,TIr,Jgo,Ygo,IIr,Zgo,Qgo,xIr,eyo,tyo,ryo,nyo,oyo,iyo,syo,Ah,AIr,ayo,cyo,oZ,iZ,Xxe,bIr=q(()=>{"use strict";Z();F();z();Qlt();Pgo=256*1024*1024,Ogo=64*1024,EIr=/^[0-9a-f]{64}$/u,Lgo=64,Dgo=4095,Mgo=new Set([de.antigravity,de.claudeCode,de.grokCli,de.maiaAgent,de.pi,"codex"]),RIr=e=>{switch(e){case de.antigravity:return["antigravity-session"];case de.claudeCode:return["claude-code-session"];case de.grokCli:return["grok-cli-session"];case de.maiaAgent:return["maia-agent-session"];case de.pi:return["pi-session"];case"codex":return["codex-probe","codex-session"];case"pi-rpc":return["pi-rpc-probe","pi-rpc-session"];case"skills":return["skills-listing"];case"git":case"security":case"systemd-creds":case"terminal":return[]}},hIr="skills-listing-1",Kxe=e=>({adapter:"skills",adapterVersion:e.version,executablePath:e.interpreterPath,ownerKinds:["skills-listing"],sandboxPolicyRevision:hIr,sha256:e.interpreterSha256,vouchPolicyRevision:hIr}),qT=()=>f("transport_failed","The requested executable is not admitted by the vouch policy."),_Ir=e=>({changedAtNanoseconds:e.ctimeNs,device:e.dev,inode:e.ino,modifiedAtNanoseconds:e.mtimeNs,size:e.size}),vL=(e,t)=>e.ctimeNs===t.changedAtNanoseconds&&e.dev===t.device&&e.ino===t.inode&&e.mtimeNs===t.modifiedAtNanoseconds&&e.size===t.size,Ugo=e=>e.uid===0n?e.nlink>0n:e.nlink===1n,Fgo=e=>`0${(Number(e.mode)&Dgo).toString(8)}`,Hgo=({adapter:e,path:t},r)=>{if(r.isSymbolicLink())return`${t}: a symbolic link; fix: approve the file it points to.`;if(!r.isFile())return`${t}: not a regular file.`;if(r.size===0n)return`${t}: an empty file.`;if(!Mgo.has(e)&&r.size>BigInt(Pgo))return`${t}: ${r.size.toString()} bytes, over the 256 MiB limit.`},Bgo=(e,t,r)=>{let n=Hgo(e,t);if(n!==void 0)return n;let{path:o}=e,i=Fgo(t),a=fIr({gid:Number(t.gid),mode:Number(t.mode),uid:Number(t.uid)},r);if(a==="foreign_owner")return`${o}: mode ${i}, owner uid ${t.uid.toString()}, not this user (${String(r.uid)}) or root; fix: install it as this user.`;if(a==="writable_by_others")return`${o}: mode ${i}, gid ${t.gid.toString()}, writable by others or a shared group; fix: chmod go-w on it.`;if(!Ugo(t))return`${o}: ${t.nlink.toString()} hard links; fix: approve a copy with one link.`;if((Number(t.mode)&Lgo)===0)return`${o}: mode ${i}, not executable by its owner; fix: chmod u+x on it.`},nZ=(e,t,r)=>{let n=Bgo(e,t,r);if(n!==void 0)throw f("configuration_invalid",`The vouch policy refuses ${n}`)},qgo=(e,t)=>{let r=Buffer.from(t,"hex");return e.byteLength===r.byteLength&&bgo(e,r)},jgo=(e,t)=>{switch(e.adapter){case"git":return t==="git-inspection";case"security":case"systemd-creds":return t==="secret-store";case"terminal":return t==="interactive-terminal";case de.antigravity:case de.claudeCode:case de.grokCli:case de.maiaAgent:case de.pi:case"codex":case"pi-rpc":case"skills":return RIr(e.adapter).includes(t)}},Wgo=e=>e.selectedTier==="cooperative_multi_pgid"||e.selectedTier==="hard_containment",$go=(e,t)=>{switch(e.adapter){case"git":return t.selectedTier==="vouched_runtime"||t.selectedTier==="hard_containment";case"security":return t.selectedTier==="vouched_runtime";case"skills":case"systemd-creds":return t.selectedTier==="hard_containment";case"terminal":return t.selectedTier==="local_user_interactive_terminal";case de.antigravity:case de.claudeCode:case de.grokCli:case de.maiaAgent:case de.pi:case"codex":return Wgo(t);case"pi-rpc":return t.selectedTier==="cooperative_pi_rpc_conversation"}},Ggo=(e,t)=>{let r=t.find(n=>n.executablePath===e.executable&&n.ownerKinds.includes(e.owner.kind));if(r===void 0||!jgo(r,e.owner.kind)||!$go(r,e)||!eut(r.executablePath)||tut(r.executablePath)!==r.executablePath||!EIr.test(r.sha256)||r.adapterVersion.length===0||r.sandboxPolicyRevision.length===0||r.adapter==="pi-rpc"&&(r.conversationPolicyRevision===void 0||r.conversationPolicyRevision.length===0)||r.vouchPolicyRevision.length===0)throw qT();return r},zgo=e=>{nZ(e,e.openedMetadata,e.user);let t=_Ir(e.openedMetadata);if(!vL(e.pathMetadata,t)||!vL(e.currentMetadata,t)||!qgo(e.digest,e.expectedDigest))throw qT();return t},rut=new Map,Vgo=new Set([16914836n,1481003842n,2435016766n,61267n]),gIr=new Map,Kgo=()=>{try{let e=wgo("/proc/self/exe",rZ.O_RDONLY);try{return[yIr(e,{bigint:!0})]}finally{Cgo(e)}}catch{return[]}},Xgo=()=>{if(process.platform!=="linux")return[];let[e]=Kgo();if(e===void 0)return[];try{let{type:t}=Ngo("/proc/self/exe",{bigint:!0});return[{filesystemType:t,identity:e}]}catch{return[]}},vIr=()=>{let e=gIr.get("exe");if(e!==void 0)return[e];let t=Xgo(),[r]=t;return r!==void 0&&gIr.set("exe",r),t},nut=e=>[e.dev,e.ino,e.size,e.mode,e.uid,e.ctimeNs,e.mtimeNs].join(":"),TIr=e=>e.platform==="linux"&&e.adapter==="skills"&&e.running.some(({filesystemType:t,identity:r})=>Vgo.has(t)&&e.metadata.dev===r.dev&&e.metadata.ino===r.ino),Jgo=e=>TIr(e)&&e.remembered===nut(e.metadata),Ygo=(e,t,r)=>TIr({adapter:e,metadata:t,platform:process.platform,running:r}),IIr=({executablePath:e,sha256:t})=>`${e}\0${t}`,Zgo=(e,t)=>{let{expectation:r,handle:n,pathMetadata:o,signal:i}=e;return Jgo({adapter:r.adapter,metadata:o,platform:process.platform,remembered:rut.get(IIr(r))??"",running:t})?Promise.resolve(Buffer.from(r.sha256,"hex")):xIr(n,o.size,i)},Qgo=async e=>{let{expectation:t,handle:r,pathMetadata:n,user:o}=e,i=await Zgo(e,vIr()),a=await r.stat({bigint:!0}),c=zgo({adapter:t.adapter,currentMetadata:await Vxe(t.executablePath,{bigint:!0}),digest:i,expectedDigest:t.sha256,openedMetadata:a,path:t.executablePath,pathMetadata:n,user:o});return t.adapter==="skills"&&rut.set(IIr(t),nut(a)),c},xIr=async(e,t,r)=>{let n=Ago("sha256"),o=Buffer.allocUnsafe(Ogo),i=Number(t),a=async c=>{if(c>=i)return;r.throwIfAborted();let{bytesRead:l}=await e.read(o,0,Math.min(o.byteLength,i-c),c);if(l<=0)throw qT();n.update(o.subarray(0,l)),await a(c+l)};return await a(0),r.throwIfAborted(),n.digest()},eyo=async(e,t)=>{let[r,n]=await Promise.all([e.handle.stat({bigint:!0}),Vxe(e.path,{bigint:!0})]);if(!vL(r,t)||!vL(n,t))throw qT()},tyo=(e,t,r)=>({device:t.device.toString(),inode:t.inode.toString(),path:e,sha256:r.toString("hex"),sizeBytes:t.size.toString()}),ryo=async e=>{let t=await e.handle.stat({bigint:!0});nZ(e,t,e.user);let r=_Ir(t);if(!vL(e.pathMetadata,r))throw qT();let n=await xIr(e.handle,t.size,e.signal);return await eyo(e,r),Ygo(e.adapter,t,vIr())&&rut.set(`${e.path}\0${n.toString("hex")}`,nut(t)),tyo(e.path,r,n)},nyo=async(e,t,r)=>{let{path:n}=e;if(!eut(n)||tut(n)!==n)throw qT();let o=await Vxe(n,{bigint:!0});nZ(e,o,t);let i=await SIr(n,rZ.O_RDONLY|rZ.O_NOFOLLOW);try{return await ryo({...e,handle:i,pathMetadata:o,signal:r,user:t})}finally{await i.close()}},oyo=e=>({adapter:e.adapter,path:e.executablePath}),iyo=async(e,t,r)=>{let n=await Vxe(e.executablePath,{bigint:!0});nZ(oyo(e),n,t);let o=await SIr(e.executablePath,rZ.O_RDONLY|rZ.O_NOFOLLOW);try{let i=await Qgo({expectation:e,handle:o,pathMetadata:n,signal:r,user:t});return{handle:o,identity:i}}catch(i){throw await o.close(),i}},syo=(e,t,r)=>({adapter:e.adapter,adapterVersion:e.adapterVersion,descriptor:t.handle.fd,identity:t.identity,path:e.executablePath,sandboxPolicyRevision:e.sandboxPolicyRevision,sha256:e.sha256,user:r,vouchPolicyRevision:e.vouchPolicyRevision}),Ah=s.fn("DarwinVouch.inspectTarget")(function*(e,t){let r=yield*Zlt;return yield*s.tryPromise({catch:n=>Le(n,"transport_failed","The requested executable is not admitted by the vouch policy."),try:n=>nyo({adapter:t,path:e},r,n)})}),AIr=s.fnUntraced(function*(e){let t=yield*Zlt,r=yield*s.acquireRelease(s.tryPromise({catch:n=>Le(n,"transport_failed","The requested executable is not admitted by the vouch policy."),try:n=>iyo(e,t,n)}),({handle:n})=>s.promise(()=>n.close()).pipe(s.ignore));return syo(e,r,t)}),ayo=e=>{let t=RIr(e.adapter);return e.ownerKinds.length>0&&e.ownerKinds.every(r=>t.includes(r))},cyo=e=>ayo(e)&&eut(e.executablePath)&&tut(e.executablePath)===e.executablePath&&EIr.test(e.sha256)&&e.adapterVersion.length>0&&e.sandboxPolicyRevision.length>0&&(e.adapter!=="pi-rpc"||e.conversationPolicyRevision!==void 0&&e.conversationPolicyRevision.length>0)&&e.vouchPolicyRevision.length>0,oZ=s.fnUntraced(function*(e){return cyo(e)?yield*AIr(e):yield*s.fail(qT())}),iZ=e=>{try{let t=yIr(e.descriptor,{bigint:!0}),r=kgo(e.path,{bigint:!0});if(!vL(t,e.identity)||!vL(r,e.identity))throw qT();nZ(e,t,e.user)}catch(t){throw Le(t,"transport_failed","The requested executable is not admitted by the vouch policy.")}},Xxe=s.fnUntraced(function*(e,t){let r=yield*s.try({catch:()=>qT(),try:()=>Ggo(e,t)});return yield*AIr(r)})});import{createHash as dyo,randomUUID as lyo}from"node:crypto";var out,CIr,sC,iut,Jxe,Yxe,kIr=q(()=>{"use strict";F();z();out=new WeakMap,CIr=()=>f("authentication_failed","The Invocation attachment launch authorization is invalid."),sC=e=>`process_${dyo("sha256").update(JSON.stringify({commandId:e.commandId,kind:e.kind,sessionId:e.sessionId,taskId:e.taskId,terminalId:e.terminalId,workspaceId:e.workspaceId})).digest("hex")}`,iut=e=>{let t=sC(e.owner),r=Object.freeze({attachmentId:e.attachmentId,...e.parentProcessOwnerId===void 0?{}:{parentProcessOwnerId:e.parentProcessOwnerId},processOwnerId:t,slotId:`invocation-slot-${lyo().replaceAll("-","")}`});return out.set(r,{lease:e.lease,processOwnerId:t,state:"available"}),r},Jxe=(e,t)=>{let r=out.get(e),n=sC(t);return r?.state!=="available"||r.processOwnerId!==n||e.processOwnerId!==n?s.fail(CIr()):s.void},Yxe=s.fn("ProcessResourceManager.consumeInvocationAttachmentLease")(function*(e,t){let r=out.get(e),n=sC(t);return r?.state!=="available"||r.processOwnerId!==n?yield*s.fail(CIr()):(r.state="consumed",r.lease)})});import{mkdtemp as uyo,open as pyo,rmdir as wIr,unlink as NIr}from"node:fs/promises";import{tmpdir as myo}from"node:os";import{join as PIr}from"node:path";var fyo,OIr,sut,aut,hyo,cut,LIr=q(()=>{"use strict";F();z();fyo=32,OIr=e=>Le(e,"transport_failed","The protected Invocation attachment handle could not be created."),sut=()=>{},aut=e=>e.close().catch(sut),hyo=async e=>{let t=Buffer.from(e),r=await uyo(PIr(myo(),"maia-ic1-")),n=PIr(r,"attachment");try{let o=await pyo(n,"wx+",384);try{return await o.write(t,0,t.byteLength,0),await NIr(n),await wIr(r),o}catch(i){throw await aut(o),i}}finally{t.fill(0),await NIr(n).catch(sut),await wIr(r).catch(sut)}},cut=s.fn("ProcessResourceManager.openInvocationAttachmentNativeLease")(function*(e){return e.byteLength!==fyo?yield*s.fail(OIr(new Error("credential size invalid"))):yield*s.acquireRelease(s.tryPromise({catch:OIr,try:()=>hyo(e)}),t=>s.promise(()=>aut(t)).pipe(s.asVoid)).pipe(s.map(t=>({close:s.promise(()=>aut(t)).pipe(s.asVoid),descriptor:t.fd})))})});import{createHash as BIr}from"node:crypto";import{closeSync as qIr,constants as DIr,existsSync as gyo,fstatSync as mut,lstatSync as yyo,openSync as Syo,readdirSync as Eyo,readFileSync as Ryo,readSync as _yo,realpathSync as jIr}from"node:fs";import{builtinModules as MIr}from"node:module";import{dirname as lut,isAbsolute as WIr,join as aC,relative as vyo,resolve as $Ir,sep as fut}from"node:path";var Qxe,eAe,Tyo,UIr,Iyo,xyo,hut,GIr,FIr,zIr,cC,I$,is,VIr,KIr,Ayo,tAe,byo,nAe,IL,sZ,Cyo,kyo,oAe,rAe,XIr,JIr,YIr,gut,wyo,Nyo,Pyo,ZIr,Oyo,QIr,uut,exr,TL,Lyo,Dyo,Myo,Uyo,Fyo,txr,Hyo,Byo,qyo,jyo,Wyo,$yo,rxr,Gyo,zyo,Vyo,Kyo,Xyo,iAe,put,dut,HIr,sAe,yut,Jyo,Yyo,Sut,Zxe,aZ,nxr=q(()=>{"use strict";z();Qxe="@maiaos/agent",eAe="dist/managed-worker/main.js",Tyo="maia-agent-worker",UIr=["README.md","dist"],Iyo="dist/managed-worker/main.meta.json",xyo=["bin","engines","exports","files","imports","name","piConfig","type"],hut="package.json",GIr="24.22.1",FIr=/^[0-9a-f]{64}$/u,zIr=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,cC=Object.freeze({maximumFileBytes:32*1024*1024,maximumFiles:4096,maximumInterpreterBytes:256*1024*1024,maximumPathBytes:4096,maximumTotalBytes:64*1024*1024}),I$=()=>f("transport_failed","The packaged managed Pi worker artifact is invalid."),is=()=>{throw I$()},VIr=e=>{try{return e()}catch(t){if(t instanceof lt)throw t;return is()}},KIr=e=>BIr("sha256").update(e).digest("hex"),Ayo=e=>e.length>0&&!e.includes("\0")&&Buffer.byteLength(e,"utf8")<=cC.maximumPathBytes&&WIr(e)&&$Ir(e)===e,tAe=e=>Ayo(e)?e:is(),byo=e=>e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":is(),nAe=e=>Object.freeze({changedAtNanoseconds:e.ctimeNs,device:e.dev,groupId:e.gid,inode:e.ino,linkCount:e.nlink,mode:Number(e.mode),modifiedAtNanoseconds:e.mtimeNs,size:e.size,type:byo(e),userId:e.uid}),IL=e=>nAe(yyo(e,{bigint:!0})),sZ=(e,t)=>e.changedAtNanoseconds===t.changedAtNanoseconds&&e.device===t.device&&e.groupId===t.groupId&&e.inode===t.inode&&e.linkCount===t.linkCount&&e.mode===t.mode&&e.modifiedAtNanoseconds===t.modifiedAtNanoseconds&&e.size===t.size&&e.type===t.type&&e.userId===t.userId,Cyo=(e,t)=>{let r=IL(e),n=typeof process.getuid=="function"?process.getuid():void 0,o=n===void 0||r.userId===0n||r.userId===BigInt(n);return sZ(t,r)&&o&&(t.mode&18)===0},kyo={package:"A path of the managed Pi worker package is writable by group or others; reinstall under umask 022 or remove group and other write access.",runtime:"The Node.js runtime is writable by group or others; use a Node.js installation that only you or root can write."},oAe=(e,t,r="package")=>{if(!Cyo(e,t))throw(t.mode&18)===0?I$():f("path_invalid",kyo[r])},rAe=(e,t,{allowSelectedSymlink:r,kind:n="package"})=>{let o=tAe(e),i=IL(o);if(i.type!==t&&!(r&&i.type==="symlink"))return is();let a=tAe(jIr.native(o)),c=IL(a);return c.type!==t?is():(oAe(a,c,n),Object.freeze({nofollow:Object.freeze({identity:i,path:o}),realpath:Object.freeze({identity:c,path:a})}))},XIr=(e,t,r)=>{let n=IL(e);return n.type!=="file"||n.linkCount!==1n||n.size<0n||n.size>BigInt(t)?is():(oAe(e,n,r),n)},JIr=e=>{let t=nAe(mut(e.descriptor,{bigint:!0}));(!sZ(e.before,e.opened)||e.byteCount!==Number(e.opened.size)||!sZ(e.opened,t)||!sZ(e.opened,IL(e.path)))&&is()},YIr=e=>Syo(e,DIr.O_RDONLY|(process.platform==="win32"?0:DIr.O_NOFOLLOW)),gut=(e,t,r="package")=>{let n=XIr(e,t,r),o=YIr(e);try{let i=nAe(mut(o,{bigint:!0})),a=Ryo(o),c=a.byteLength;return JIr({before:n,byteCount:c,descriptor:o,opened:i,path:e}),Object.freeze({bytes:a,identity:i,sha256:KIr(a)})}finally{qIr(o)}},wyo=1024*1024,Nyo=(e,t,r=wyo)=>{let n=BIr("sha256"),o=Buffer.allocUnsafe(r);return{byteCount:Array.from({length:Math.ceil(t/r)+1},(c,l)=>l*r).reduce((c,l)=>{let u=_yo(e,o,0,r,l);return c+u>t?is():(n.update(o.subarray(0,u)),c+u)},0),sha256:n.digest("hex")}},Pyo=(e,t,r)=>{let n=XIr(e,t,r),o=YIr(e);try{let i=nAe(mut(o,{bigint:!0})),{byteCount:a,sha256:c}=Nyo(o,Number(i.size));return JIr({before:n,byteCount:a,descriptor:o,opened:i,path:e}),Object.freeze({identity:i,sha256:c})}finally{qIr(o)}},ZIr=e=>{let t=e.split(fut).join("/"),r=t.split("/");return t.length===0||t.startsWith("/")||t.includes("\\")||t.includes("\0")||r.some(n=>n.length===0||n==="."||n==="..")?is():t},Oyo=(e,t)=>{let r=vyo(e,t);return r===""||r===".."||r.startsWith(`..${fut}`)||WIr(r)?is():ZIr(r)},QIr=(e,t,r)=>{e.observations.push({identity:r,path:t}),e.observations.length>cC.maximumFiles*2&&is()},uut=(e,t,r)=>{let n=gut(t,cC.maximumFileBytes);QIr(r,t,n.identity),r.totalBytes+=n.bytes.byteLength,(r.entries.length>=cC.maximumFiles||r.totalBytes>cC.maximumTotalBytes)&&is(),r.entries.push(Object.freeze({byteCount:n.bytes.byteLength,executable:(n.identity.mode&73)!==0,relativePath:Oyo(e,t),sha256:n.sha256}))},exr=(e,t,r)=>{let n=IL(t);n.type!=="directory"&&is(),oAe(t,n),QIr(r,t,n),Eyo(t).toSorted().forEach(o=>{ZIr(o);let i=aC(t,o),a=IL(i);a.type==="directory"?exr(e,i,r):a.type==="file"?uut(e,i,r):is()})},TL=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lyo=e=>Array.isArray(e),Dyo=new Set([...MIr,...MIr.map(e=>`node:${e}`)]),Myo=e=>{let t=gut(aC(e,Iyo),cC.maximumFileBytes).bytes.toString("utf8"),r=JSON.parse(t);if(!TL(r))throw I$();let n=Reflect.get(r,"outputs");if(!TL(n))throw I$();Object.values(n).flatMap(a=>{if(!TL(a))throw I$();let c=Reflect.get(a,"imports");if(!Lyo(c))throw I$();return c}).some(a=>!TL(a)||typeof a.path!="string"||typeof a.external!="boolean"||a.external&&!Dyo.has(a.path))&&is()},Uyo=e=>{if(!TL(e)||!TL(e.exports)||!TL(e.bin))return is();let t=e.files;return e.name!==Qxe||typeof e.version!="string"||!zIr.test(e.version)||e.exports["./managed-worker"]!==`./${eAe}`||e.bin[Tyo]!==`./${eAe}`||!Array.isArray(t)||t.length!==UIr.length||!UIr.every(r=>t.includes(r))?is():{loading:Object.fromEntries(xyo.map(r=>[r,e[r]])),name:Qxe,version:e.version}},Fyo=e=>Uyo(JSON.parse(gut(aC(e,hut),cC.maximumFileBytes).bytes.toString("utf8"))),txr=(e,t)=>e===t||lut(e)===e?is():gyo(aC(e,"package.json"))?e:txr(lut(e),t),Hyo=e=>txr(lut(e),$Ir(e,fut)),Byo=e=>{e.forEach(({identity:t,path:r})=>{oAe(r,t)})},qyo=(e,t)=>e.relativePath<t.relativePath?-1:e.relativePath>t.relativePath?1:0,jyo=(e,t)=>KIr(JSON.stringify({entries:e.filter(({relativePath:r})=>r!==hut),manifest:t.loading})),Wyo=e=>{let t={entries:[],observations:[],totalBytes:0};uut(e,aC(e,hut),t),uut(e,aC(e,"README.md"),t),exr(e,aC(e,"dist"),t);let r=Object.freeze(t.entries.toSorted(qyo)),n=Fyo(e);Myo(e),Byo(t.observations);let o=Object.freeze([...t.observations]);return Object.freeze({entries:r,observations:o,packageClosureSha256:jyo(r,n),packageName:n.name,packageVersion:n.version})},$yo=e=>{if(process.versions.node!==GIr)return is();let t=rAe(e,"file",{allowSelectedSymlink:!0,kind:"runtime"}),r=rAe(process.execPath,"file",{allowSelectedSymlink:!0,kind:"runtime"});if(t.realpath.path!==r.realpath.path)return is();let n=Pyo(t.realpath.path,cC.maximumInterpreterBytes,"runtime");return sZ(n.identity,t.realpath.identity)?{binding:t,sha256:n.sha256}:is()},rxr=e=>e.packageName===Qxe&&zIr.test(e.packageVersion)&&FIr.test(e.entrySha256)&&FIr.test(e.packageClosureSha256),Gyo=e=>{let t=tAe(e),r=rAe(t,"file",{allowSelectedSymlink:!0}),n=tAe(jIr.native(Hyo(r.realpath.path))),o=rAe(n,"directory",{allowSelectedSymlink:!1}),i=aC(n,...eAe.split("/"));if(r.realpath.path!==i)return is();let a=Wyo(n),c=a.entries.find(({relativePath:l})=>l===eAe);return c===void 0?is():{closure:a,entry:r,entryRecord:c,packageRoot:o,packageRootPath:n,selectedEntryPath:t}},zyo=e=>({entrySha256:e.entryRecord.sha256,packageClosureSha256:e.closure.packageClosureSha256,packageName:e.closure.packageName,packageVersion:e.closure.packageVersion}),Vyo=(e,t)=>e.entrySha256===t.entrySha256&&e.packageClosureSha256===t.packageClosureSha256&&e.packageName===t.packageName&&e.packageVersion===t.packageVersion,Kyo=(e,t)=>{(!rxr(e)||t!==void 0&&!Vyo(e,t))&&is()},Xyo=e=>Object.freeze({...e.releaseIdentity,closurePhysicalIdentities:e.inspected.closure.observations,entries:e.inspected.closure.entries,entryPath:e.inspected.entry.realpath.path,entryPhysicalIdentity:e.inspected.entry,interpreterPath:e.interpreter.binding.realpath.path,interpreterPhysicalIdentity:e.interpreter.binding,interpreterSha256:e.interpreter.sha256,interpreterVersion:GIr,packageRootPath:e.inspected.packageRootPath,packageRootPhysicalIdentity:e.inspected.packageRoot,selectedEntryPath:e.inspected.selectedEntryPath,selectedInterpreterPath:e.selectedInterpreterPath}),iAe=e=>VIr(()=>{let t=Gyo(e.entryPath),r=zyo(t);Kyo(r,e.expectedRelease);let n=e.interpreterPath??process.execPath,o=$yo(n);return Xyo({inspected:t,interpreter:o,releaseIdentity:r,selectedInterpreterPath:n})}),put=e=>({...e,changedAtNanoseconds:e.changedAtNanoseconds.toString(),device:e.device.toString(),groupId:e.groupId.toString(),inode:e.inode.toString(),linkCount:e.linkCount.toString(),modifiedAtNanoseconds:e.modifiedAtNanoseconds.toString(),size:e.size.toString(),userId:e.userId.toString()}),dut=e=>({nofollow:{identity:put(e.nofollow.identity),path:e.nofollow.path},realpath:{identity:put(e.realpath.identity),path:e.realpath.path}}),HIr=e=>JSON.stringify({...e,closurePhysicalIdentities:e.closurePhysicalIdentities.map(({identity:t,path:r})=>({identity:put(t),path:r})),entryPhysicalIdentity:dut(e.entryPhysicalIdentity),interpreterPhysicalIdentity:dut(e.interpreterPhysicalIdentity),packageRootPhysicalIdentity:dut(e.packageRootPhysicalIdentity)}),sAe=e=>{VIr(()=>{let t=iAe({entryPath:e.selectedEntryPath,expectedRelease:{entrySha256:e.entrySha256,packageClosureSha256:e.packageClosureSha256,packageName:e.packageName,packageVersion:e.packageVersion},interpreterPath:e.selectedInterpreterPath});if(HIr(t)!==HIr(e))return is()})},yut=e=>Object.freeze({entrySha256:e.entrySha256,packageClosureSha256:e.packageClosureSha256,packageName:e.packageName,packageVersion:e.packageVersion}),Jyo=["MAIA_NODE_MANAGED_PI_WORKER_CLOSURE_SHA256","MAIA_NODE_MANAGED_PI_WORKER_ENTRY_SHA256","MAIA_NODE_MANAGED_PI_WORKER_PACKAGE_NAME","MAIA_NODE_MANAGED_PI_WORKER_PACKAGE_VERSION"],Yyo=e=>JSON.stringify(e)??"undefined",Sut=e=>Object.fromEntries(Jyo.map((t,r)=>[t,Yyo([e?.packageClosureSha256,e?.entrySha256,e?.packageName,e?.packageVersion][r])])),Zxe=e=>{try{return e()}catch(t){if(t instanceof ReferenceError)return;throw t}},aZ=()=>{let e=[Zxe(()=>"46c90bb11a15acec3441bd4212bf416ff5280cf60a769d2ecbac4ae5b6e53a28"),Zxe(()=>"7174f15101ef045ba1a60eaa433881fb8df4e5381c5d58cca41470d68271852a"),Zxe(()=>"@maiaos/agent"),Zxe(()=>"0.1.0-canary.74")];if(e.every(a=>a===void 0))return;let[t,r,n,o]=e,i={entrySha256:r,packageClosureSha256:t,packageName:n,packageVersion:o};return typeof r!="string"||typeof t!="string"||n!==Qxe||typeof o!="string"||!rxr(i)?is():Object.freeze(i)}});import{isAbsolute as Zyo,resolve as Qyo}from"node:path";var oxr,eSo,tSo,cZ,rSo,nSo,oSo,aAe,ixr=q(()=>{"use strict";os();oxr=([e],[t])=>e<t?-1:e>t?1:0,eSo=(e,t)=>{let r=Object.entries(e).toSorted(oxr),n=Object.entries(t).toSorted(oxr);return r.length===n.length&&r.every(([o,i],a)=>n[a]?.[0]===o&&n[a]?.[1]===i)},tSo=(e,t)=>e.kind===t.kind&&e.commandId===t.commandId&&e.sessionId===t.sessionId&&e.taskId===t.taskId&&e.terminalId===t.terminalId&&e.workspaceId===t.workspaceId,cZ=(e,t)=>e.executable===t.executable&&e.workingDirectory===t.workingDirectory&&e.standardInput===t.standardInput&&e.arguments_.length===t.arguments_.length&&e.arguments_.every((r,n)=>t.arguments_[n]===r)&&eSo(e.environment,t.environment)&&tSo(e.owner,t.owner)&&e.limits.maximumCpuTimeMilliseconds===t.limits.maximumCpuTimeMilliseconds&&e.limits.maximumMemoryBytes===t.limits.maximumMemoryBytes&&e.limits.maximumProcessCount===t.limits.maximumProcessCount&&e.limits.maximumWallTimeMilliseconds===t.limits.maximumWallTimeMilliseconds&&e.streamLimits.maximumDataChunkBytes===t.streamLimits.maximumDataChunkBytes&&e.streamLimits.maximumPendingInputBytes===t.streamLimits.maximumPendingInputBytes&&e.streamLimits.maximumPendingOutputBytes===t.streamLimits.maximumPendingOutputBytes&&e.interactiveTerminal===void 0&&t.interactiveTerminal===void 0&&e.repositoryAuthority===void 0&&t.repositoryAuthority===void 0,rSo=e=>e.interpreterVersion==="24.22.1"&&e.packageName==="@maiaos/agent"&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(e.packageVersion)&&[e.entryPath,e.interpreterPath].every(t=>Zyo(t)&&Qyo(t)===t)&&[e.entrySha256,e.interpreterSha256,e.packageClosureSha256].every(t=>/^[0-9a-f]{64}$/u.test(t)),nSo=e=>{let t=Object.keys(e).toSorted();return t.length===2&&t[0]==="LANG"&&t[1]==="LC_ALL"&&e.LANG==="C"&&e.LC_ALL==="C"},oSo=(e,t)=>{let r=Xm(e.launchRequest);return r.state==="valid"&&t.owner.kind==="pi-managed-session"&&t.owner.commandId!==void 0&&t.owner.sessionId!==void 0&&t.owner.workspaceId!==void 0&&rSo(e.artifact)&&e.artifact.interpreterPath===t.executable&&t.arguments_.length===1&&t.arguments_[0]===e.artifact.entryPath&&t.standardInput==="pipe"&&nSo(t.environment)&&cZ(r.request,t)},aAe=(e,t)=>{if(e.owner.kind!=="pi-managed-session")return;let r=t?.managedPi;return r!==void 0&&oSo(r,e)?r:void 0}});import{dirname as sxr,isAbsolute as axr,join as dZ,normalize as iSo,relative as sSo,resolve as aSo,sep as cSo}from"node:path";var lZ,CR,Dl,dSo,lSo,Ko,or,uSo,pSo,mSo,fSo,bh,cAe,uZ,Eut,hSo,gSo,ySo,SSo,ESo,RSo,_So,vSo,x$,Rut=q(()=>{"use strict";F();lZ="24.22.1",CR="1.0.0",Dl={exitDrainDeadline:"1 second",maximumInputRecordBytes:64*1024,maximumMessageEndRecords:16,maximumOutputRecordBytes:1024*1024,maximumOutputRecordsPerChunk:4096,maximumOutstandingRequests:8,maximumPendingInputBytes:128*1024,maximumPendingInputRecords:8,maximumPromptBytes:48*1024,maximumRequestIdBytes:128,maximumStderrBytes:64*1024,maximumStdoutBytes:16*1024*1024,requestDeadline:"10 seconds"},dSo=d.Literals(["command_rejected","cleanup_unknown","input_limit_exceeded","invalid_request","lifecycle_invalid","output_limit_exceeded","prompt_acceptance_unknown","protocol_invalid","request_outcome_unknown","runtime_exited","saturated","transport_failed"]),lSo=d.TaggedError,Ko=class extends lSo("@maiaos/node/pi-rpc-failure")("PiRpcFailure",{message:d.String,reason:dSo}){},or=(e,t)=>new Ko({message:t,reason:e}),uSo=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/u,pSo=/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/u,mSo=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,fSo=/^[0-9a-f]{64}$/u,bh=e=>{throw or("invalid_request",e)},cAe=(e,t,r)=>e.length===0||e.includes("\0")||Buffer.byteLength(e,"utf8")>r?bh(`The Pi RPC ${t} is invalid.`):e,uZ=(e,t)=>(cAe(e,t,4096),!axr(e)||iSo(e)!==e||aSo(e)!==e?bh(`The Pi RPC ${t} must be an absolute normalized path.`):e),Eut=(e,t)=>fSo.test(e)?e:bh(`The Pi RPC ${t} must be a lowercase SHA-256.`),hSo=e=>(cAe(e,"session id",128),uSo.test(e)?e:bh("The Pi RPC session id is invalid.")),gSo=(e,t)=>{let r=sSo(e,t);return r.length>0&&r!==".."&&!r.startsWith(`..${cSo}`)&&!axr(r)},ySo=e=>e.interpreterVersion!==lZ?bh(`Pi RPC requires the exact Node ${lZ} interpreter.`):(uZ(e.interpreterPath,"interpreter path"),uZ(e.entryPath,"entry path"),Eut(e.interpreterSha256,"interpreter digest"),Eut(e.entrySha256,"entry digest"),Eut(e.packageClosureSha256,"package-closure digest"),cAe(e.packageName,"package name",214),cAe(e.packageVersion,"package version",128),pSo.test(e.packageName)?mSo.test(e.packageVersion)?Object.freeze({...e}):bh("The Pi RPC package version is invalid."):bh("The Pi RPC package name is invalid.")),SSo=(e,t)=>{let r=dZ(e,"harness","pi-rpc",t);return{agentDirectory:dZ(r,"agent"),homeDirectory:dZ(r,"home"),sessionDirectory:dZ(r,"sessions"),temporaryDirectory:dZ(r,"tmp")}},ESo=(e,t,r)=>{if(e.kind==="fresh"&&e.sessionFile===void 0)return{kind:"fresh",sessionId:r};if(e.sessionFile===void 0)return bh("The Pi RPC session file is missing.");let n=uZ(e.sessionFile,e.kind==="fresh"?"prepared fresh session file":"resume session file");return(sxr(n)!==t.sessionDirectory||!gSo(t.sessionDirectory,n)||!n.endsWith(".jsonl"))&&bh("The Pi RPC resume file must be an exact file in its node-private session directory."),{kind:e.kind,sessionFile:n,sessionId:r}},RSo=(e,t,r)=>{let n;if(t.kind==="fresh"&&t.sessionFile===void 0)n=["--session-id",t.sessionId];else{if(t.sessionFile===void 0)return bh("The Pi RPC session file is missing.");n=["--session",t.sessionFile]}return Object.freeze([e.entryPath,"--mode","rpc","--session-dir",r,...n,"--no-tools","--no-extensions","--no-skills","--no-prompt-templates","--no-themes","--no-context-files","--no-approve","--offline"])},_So=e=>Object.freeze({HOME:e.homeDirectory,LANG:"C",LC_ALL:"C",NO_COLOR:"1",NODE_DISABLE_COMPILE_CACHE:"1",PI_CODING_AGENT_DIR:e.agentDirectory,PI_CODING_AGENT_SESSION_DIR:e.sessionDirectory,PI_OFFLINE:"1",PI_TELEMETRY:"0",TMPDIR:e.temporaryDirectory}),vSo=e=>{let t=uZ(e.nodePrivateRoot,"node-private root");sxr(t)===t&&bh("The Pi RPC node-private root cannot be a filesystem root.");let r=uZ(e.workingDirectory,"working directory"),n=hSo(e.activation.sessionId),o=SSo(t,n);return{activation:ESo(e.activation,o,n),paths:o,workingDirectory:r}},x$=e=>{let t=ySo(e.artifact),{activation:r,paths:n,workingDirectory:o}=vSo(e);return r.sessionFile!==void 0&&t.packageVersion!==CR&&bh(`Pi RPC persistent sessions require the exact ${CR} package format.`),Object.freeze({activation:r,...n,arguments_:RSo(t,r,n.sessionDirectory),artifact:t,environment:_So(n),executable:t.interpreterPath,workingDirectory:o})}});var A$,_ut=q(()=>{"use strict";A$=(e,t)=>e===t?0:e<t?-1:1});import{createHash as TSo}from"node:crypto";import{closeSync as ISo,constants as cxr,existsSync as xSo,fstatSync as dxr,lstatSync as uxr,openSync as ASo,readdirSync as pxr,readFileSync as bSo,realpathSync as Aut}from"node:fs";import{dirname as vut,isAbsolute as mxr,join as but,normalize as CSo,relative as kSo,resolve as Cut,sep as Tut}from"node:path";var wSo,NSo,PSo,jT,OSo,LSo,fxr,Wi,DSo,hxr,dAe,MSo,Iut,xL,kR,lAe,xut,USo,uAe,kut,wut,gxr,FSo,lxr,yxr,HSo,BSo,qSo,jSo,WSo,Sxr,Exr,$So,GSo,zSo,VSo,KSo,XSo,JSo,YSo,ZSo,QSo,WT,Rxr=q(()=>{"use strict";F();Rut();_ut();wSo="@earendil-works/pi-coding-agent",NSo=/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/u,PSo=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,jT=Object.freeze({maximumExcludedBinEntries:256,maximumFileBytes:16*1024*1024,maximumFiles:16384,maximumFilesystemEntries:16384,maximumInterpreterBytes:256*1024*1024,maximumManifestBytes:8*1024*1024,maximumPathBytes:4096,maximumTotalBytes:256*1024*1024}),OSo=d.Struct({bin:d.Struct({pi:d.String}),name:d.String,version:d.String}),LSo=d.decodeUnknownSync(d.fromJsonString(OSo)),fxr=()=>or("invalid_request","The selected Pi RPC artifact is invalid."),Wi=()=>{throw fxr()},DSo=e=>{try{return e()}catch(t){throw t instanceof Ko?t:fxr()}},hxr=e=>TSo("sha256").update(e).digest("hex"),dAe=e=>e.length===0||e.includes("\0")||Buffer.byteLength(e,"utf8")>jT.maximumPathBytes||!mxr(e)||CSo(e)!==e||Cut(e)!==e?Wi():e,MSo=e=>e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":Wi(),Iut=e=>Object.freeze({changedAtNanoseconds:e.ctimeNs,device:e.dev,inode:e.ino,linkCount:e.nlink,mode:Number(e.mode),modifiedAtNanoseconds:e.mtimeNs,size:e.size,type:MSo(e)}),xL=(e,t)=>e.changedAtNanoseconds===t.changedAtNanoseconds&&e.device===t.device&&e.inode===t.inode&&e.linkCount===t.linkCount&&e.mode===t.mode&&e.modifiedAtNanoseconds===t.modifiedAtNanoseconds&&e.size===t.size&&e.type===t.type,kR=e=>Iut(uxr(e,{bigint:!0})),lAe=(e,t,r)=>{let n=dAe(e),o=kR(n);if(o.type!==t&&!(r&&o.type==="symlink"))return Wi();let i=dAe(Aut.native(n)),a=kR(i);return a.type!==t?Wi():Object.freeze({nofollow:Object.freeze({identity:o,path:n}),realpath:Object.freeze({identity:a,path:i})})},xut=e=>{let t=kR(e.nofollow.path),r=dAe(Aut.native(e.nofollow.path)),n=kR(e.realpath.path);(r!==e.realpath.path||!xL(t,e.nofollow.identity)||!xL(n,e.realpath.identity))&&Wi()},USo=e=>Buffer.from(e,"utf8").some(t=>t<=31||t===127),uAe=e=>{let t=e.split("/");return e.length===0||e.includes("\\")||e.startsWith("/")||Buffer.byteLength(e,"utf8")>jT.maximumPathBytes||USo(e)||t.some(r=>r.length===0||r==="."||r==="..")?Wi():e},kut=(e,t)=>{let r=kSo(e,t);return r.length===0||r===".."||r.startsWith(`..${Tut}`)||mxr(r)?Wi():uAe(r.split(Tut).join("/"))},wut=(e,t,r)=>{gxr(e),e.observed.push({identity:r,path:t})},gxr=e=>{e.filesystemEntryCount+=1,e.filesystemEntryCount>jT.maximumFilesystemEntries&&Wi()},FSo=e=>{e.excludedBinEntryCount+=1,e.excludedBinEntryCount>jT.maximumExcludedBinEntries&&Wi()},lxr=(e,t)=>{(e.type!=="file"||e.linkCount!==1n||e.size<0n||e.size>BigInt(t))&&Wi()},yxr=(e,t)=>{let r=kR(e);lxr(r,t);let n=ASo(e,cxr.O_RDONLY|cxr.O_NOFOLLOW);try{let o=Iut(dxr(n,{bigint:!0}));lxr(o,t),xL(r,o)||Wi();let i=bSo(n),a=Iut(dxr(n,{bigint:!0})),c=kR(e);return(i.byteLength!==Number(o.size)||!xL(o,a)||!xL(o,c))&&Wi(),{bytes:i,identity:o,sha256:hxr(i)}}finally{ISo(n)}},HSo=(e,t)=>A$(e.relativePath,t.relativePath),BSo=(e,t,r)=>{t==="package.json"&&(e.state.packageManifestText=new TextDecoder("utf-8",{fatal:!0}).decode(r.bytes)),t===e.entryRelativePath&&(e.state.entrySha256=r.sha256)},qSo=(e,t,r)=>{e.entries.push(Object.freeze({byteCount:r.bytes.byteLength,executable:(r.identity.mode&73)!==0,relativePath:t,sha256:r.sha256}))},jSo=(e,t)=>{let r=kut(e.root,t),n=yxr(t,jT.maximumFileBytes);wut(e.state,t,n.identity),e.state.fileCount+=1,e.state.totalBytes+=n.bytes.byteLength,(e.state.fileCount>jT.maximumFiles||e.state.totalBytes>jT.maximumTotalBytes)&&Wi(),qSo(e.state,r,n),BSo(e,r,n)},WSo=(e,t)=>{let r=kut(e,t);return r==="node_modules/.bin"||r.startsWith("node_modules/")&&r.endsWith("/node_modules/.bin")},Sxr=(e,t)=>{let r=kR(t);r.type!=="directory"&&Wi(),wut(e,t,r),pxr(t).forEach(n=>{uAe(n);let o=but(t,n),i=uxr(o,{bigint:!0});i.isDirectory()&&!i.isSymbolicLink()?Sxr(e,o):(gxr(e),FSo(e))})},Exr=(e,t)=>{let r=kR(t);r.type!=="directory"&&Wi(),wut(e.state,t,r),pxr(t).sort().forEach(o=>{uAe(o);let i=but(t,o),a=kR(i);a.type==="directory"?WSo(e.root,i)?Sxr(e.state,i):Exr(e,i):a.type==="file"?jSo(e,i):Wi()})},$So=e=>{e.forEach(t=>{xL(kR(t.path),t.identity)||Wi()})},GSo=()=>({entries:[],entrySha256:void 0,excludedBinEntryCount:0,fileCount:0,filesystemEntryCount:0,observed:[],packageManifestText:void 0,totalBytes:0}),zSo=e=>{let t=Cut(e,Tut),r=n=>xSo(but(n,"package.json"))?n:n===t||vut(n)===n?Wi():r(vut(n));return r(vut(e))},VSo=(e,t,r)=>{if(e===void 0)return Wi();let n=LSo(e);if(n.name!==wSo||!NSo.test(n.name)||!PSo.test(n.version))return Wi();let o=uAe(n.bin.pi.startsWith("./")?n.bin.pi.slice(2):n.bin.pi);return Cut(t,o)!==r?Wi():{name:n.name,version:n.version}},KSo=e=>{let t=JSON.stringify(e.map(({byteCount:n,executable:o,relativePath:i,sha256:a})=>({byteCount:n,executable:o,relativePath:i,sha256:a}))),r=Buffer.byteLength(t,"utf8");return r>jT.maximumManifestBytes&&Wi(),{bytes:r,sha256:hxr(t)}},XSo=e=>Object.freeze(e.entries.sort(HSo).map((t,r)=>Object.freeze({...t,ordinal:r}))),JSo=(e,t)=>{let r=kut(e,t),n=GSo();Exr({entryRelativePath:r,root:e,state:n},e),$So(n.observed);let o=XSo(n),i=VSo(n.packageManifestText,e,t);if(n.entrySha256===void 0)return Wi();let a=KSo(o);return{entries:o,entrySha256:n.entrySha256,excludedBinEntryCount:n.excludedBinEntryCount,fileCount:n.fileCount,manifestBytes:a.bytes,packageClosureSha256:a.sha256,packageName:i.name,packageVersion:i.version,totalBytes:n.totalBytes}},YSo=e=>Object.freeze({closureSha256:e.closure.packageClosureSha256,entries:e.closure.entries,entryPath:e.entry.realpath.path,entryPhysicalIdentity:e.entry,entrySha256:e.closure.entrySha256,excludedBinEntryCount:e.closure.excludedBinEntryCount,fileCount:e.closure.fileCount,interpreterPath:e.interpreter.binding.realpath.path,interpreterPhysicalIdentity:e.interpreter.binding,interpreterSha256:e.interpreter.sha256,interpreterVersion:lZ,manifestBytes:e.closure.manifestBytes,packageClosureSha256:e.closure.packageClosureSha256,packageName:e.closure.packageName,packageRootPath:e.packageRootPath,packageRootPhysicalIdentity:e.packageRoot,packageVersion:e.closure.packageVersion,totalBytes:e.closure.totalBytes}),ZSo=e=>{process.versions.node!==lZ&&Wi();let t=lAe(e,"file",!0),r=lAe(process.execPath,"file",!0);t.realpath.path!==r.realpath.path&&Wi();let n=yxr(t.realpath.path,jT.maximumInterpreterBytes);return xL(n.identity,t.realpath.identity)||Wi(),xut(t),{binding:t,sha256:n.sha256}},QSo=e=>{let t=ZSo(e.interpreterPath),r=lAe(e.piExecutablePath,"file",!0),n=dAe(Aut.native(zSo(r.realpath.path))),o=lAe(n,"directory",!1);o.realpath.path!==n&&Wi();let i=JSo(n,r.realpath.path);return xut(r),xut(o),YSo({closure:i,entry:r,interpreter:t,packageRoot:o,packageRootPath:n})},WT=e=>DSo(()=>QSo(e))});var Cu=q(()=>{"use strict";Rxr();Rut();_ut()});import{dirname as eEo,isAbsolute as pZ,resolve as mZ}from"node:path";var Txr,_xr,tEo,rEo,nEo,oEo,iEo,vxr,sEo,b$,aEo,cEo,dEo,lEo,pAe,Ixr=q(()=>{"use strict";Cu();os();Txr=e=>(e.kind==="pi-rpc-probe"||e.kind==="pi-rpc-session")&&e.commandId!==void 0&&e.sessionId!==void 0,_xr=(e,t)=>e<t?-1:e>t?1:0,tEo=(e,t)=>{let r=Object.entries(e).sort(([o],[i])=>_xr(o,i)),n=Object.entries(t).sort(([o],[i])=>_xr(o,i));return r.length===n.length&&r.every(([o,i],a)=>n[a]?.[0]===o&&n[a]?.[1]===i)},rEo=(e,t)=>e.kind===t.kind&&e.commandId===t.commandId&&e.sessionId===t.sessionId&&e.taskId===t.taskId&&e.terminalId===t.terminalId&&e.workspaceId===t.workspaceId,nEo=(e,t)=>e.executable===t.executable&&e.workingDirectory===t.workingDirectory&&e.standardInput===t.standardInput&&e.arguments_.length===t.arguments_.length&&e.arguments_.every((r,n)=>t.arguments_[n]===r)&&tEo(e.environment,t.environment)&&rEo(e.owner,t.owner)&&e.limits.maximumCpuTimeMilliseconds===t.limits.maximumCpuTimeMilliseconds&&e.limits.maximumMemoryBytes===t.limits.maximumMemoryBytes&&e.limits.maximumProcessCount===t.limits.maximumProcessCount&&e.limits.maximumWallTimeMilliseconds===t.limits.maximumWallTimeMilliseconds&&e.streamLimits.maximumDataChunkBytes===t.streamLimits.maximumDataChunkBytes&&e.streamLimits.maximumPendingInputBytes===t.streamLimits.maximumPendingInputBytes&&e.streamLimits.maximumPendingOutputBytes===t.streamLimits.maximumPendingOutputBytes&&e.interactiveTerminal===void 0&&t.interactiveTerminal===void 0&&e.repositoryAuthority===void 0&&t.repositoryAuthority===void 0,oEo=e=>{let t=e.nativeSession.activation,r=t.sessionFile===void 0?["--session-id",e.nativeSession.id]:["--session",t.sessionFile];return[e.artifact.entryPath,"--mode","rpc","--session-dir",e.nativeSession.directory,...r,"--no-tools","--no-extensions","--no-skills","--no-prompt-templates","--no-themes","--no-context-files","--no-approve","--offline"]},iEo=(e,t)=>e.length===t.length&&e.every((r,n)=>t[n]===r),vxr=new Set(["HOME","LANG","LC_ALL","NODE_DISABLE_COMPILE_CACHE","NO_COLOR","PI_CODING_AGENT_DIR","PI_CODING_AGENT_SESSION_DIR","PI_OFFLINE","PI_TELEMETRY","TMPDIR"]),sEo=(e,t)=>{let r=e.environment,n=Object.keys(r);return n.length===vxr.size&&n.every(o=>vxr.has(o))&&r.LANG==="C"&&r.LC_ALL==="C"&&r.NODE_DISABLE_COMPILE_CACHE==="1"&&r.NO_COLOR==="1"&&r.PI_CODING_AGENT_SESSION_DIR===t&&r.PI_OFFLINE==="1"&&r.PI_TELEMETRY==="0"&&[r.HOME,r.PI_CODING_AGENT_DIR,r.TMPDIR].every(o=>o!==void 0&&pZ(o)&&mZ(o)===o)},b$=e=>e.length>0&&!e.includes("\0")&&Buffer.byteLength(e,"utf8")<=128,aEo=e=>e.interpreterVersion==="24.22.1"&&pZ(e.interpreterPath)&&mZ(e.interpreterPath)===e.interpreterPath&&pZ(e.entryPath)&&mZ(e.entryPath)===e.entryPath&&[e.interpreterSha256,e.entrySha256,e.packageClosureSha256].every(t=>/^[0-9a-f]{64}$/u.test(t))&&/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/u.test(e.packageName)&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(e.packageVersion),cEo=e=>pZ(e.directory)&&mZ(e.directory)===e.directory&&/^(?:[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)$/u.test(e.id)&&(e.activation.sessionFile===void 0||pZ(e.activation.sessionFile)&&mZ(e.activation.sessionFile)===e.activation.sessionFile&&eEo(e.activation.sessionFile)===e.directory),dEo=e=>{let{artifact:t,authorizationRevision:r,fenceId:n,nativeSession:o,permitId:i,policy:a}=e;return b$(r)&&b$(n)&&b$(i)&&aEo(t)&&cEo(o)&&b$(a.adapterVersion)&&b$(a.conversationPolicyRevision)&&b$(a.vouchPolicyRevision)},lEo=(e,t)=>{let r=Xm(e.launchRequest);return r.state==="valid"&&Txr(t.owner)&&dEo(e)&&(t.owner.kind!=="pi-rpc-session"||e.nativeSession.activation.sessionFile!==void 0&&e.artifact.packageVersion===CR)&&e.launchRequest.owner.kind===t.owner.kind&&e.launchRequest.owner.commandId===t.owner.commandId&&e.launchRequest.owner.sessionId===t.owner.sessionId&&e.artifact.interpreterPath===t.executable&&iEo(t.arguments_,oEo(e))&&sEo(t,e.nativeSession.directory)&&nEo(r.request,t)},pAe=(e,t)=>{if(!Txr(e.owner))return;let r=t?.piRpc;return r!==void 0&&lEo(r,e)?r:void 0}});import{createHash as Axr}from"node:crypto";import{lstatSync as uEo}from"node:fs";import{dirname as C$,isAbsolute as pEo,join as dC,relative as bxr,sep as xxr}from"node:path";import{fileURLToPath as mEo}from"node:url";var k$,Nut,fEo,hEo,AL,Ch,gEo,yEo,mAe,$T,SEo,Put,Cxr,kxr,EEo,REo,_Eo,vEo,wxr,TEo,Nxr,Pxr,IEo,xEo,AEo,bEo,CEo,Oxr,fAe,hAe,Lxr=q(()=>{"use strict";F();z();k$="1.7.0",Nut=Object.freeze({maximumEntries:4096,maximumFileBytes:8*1024*1024,maximumTotalBytes:16*1024*1024}),fEo=/\.(?:c?js|mjs|json)$/u,hEo=d.fromJsonString(d.Struct({bin:d.optionalKey(d.Unknown),dependencies:d.optionalKey(d.Record(d.String,d.Unknown)),name:d.optionalKey(d.Unknown),version:d.optionalKey(d.Unknown)})),AL=()=>f("transport_failed","The bundled Skills CLI does not match the package this Node was built with."),Ch=s.fail(AL()),gEo=e=>{let t=process.getuid?.();return(t===void 0||Number(e.uid)===t||Number(e.uid)===0)&&(Number(e.mode)&18)===0},yEo=e=>e.isFile()?"file":e.isDirectory()?"directory":void 0,mAe=(e,t)=>s.try({catch:AL,try:()=>{let r=uEo(e,{bigint:!0}),n=yEo(r);if(n===void 0||t!==void 0&&n!==t||!gEo(r))throw AL();return{kind:n,size:r.size}}}),$T=(e,t)=>{let r=bxr(e,t);return r!==""&&!r.startsWith("..")&&!pEo(r)},SEo=1024*1024,Put=(e,t)=>{let r=dC(t,"package.json");return mAe(r,"file").pipe(s.filterOrFail(({size:n})=>n<=BigInt(SEo),AL),s.flatMap(()=>e.readFileString(r)),s.flatMap(d.decodeUnknownEffect(hEo)))},Cxr=(e,t,r=t)=>e.fs.readDirectory(r).pipe(s.flatMap(n=>(e.closure.entries+=n.length,e.closure.entries>Nut.maximumEntries?Ch:s.forEach(n,o=>{let i=dC(r,o);return o==="node_modules"&&r===t?s.succeed([]):mAe(i).pipe(s.flatMap(({kind:a})=>a==="directory"?Cxr(e,t,i):s.succeed([i])))}))),s.map(n=>n.flat())),kxr=(e,t,r)=>e.realPath(dC(t,"node_modules",r)).pipe(s.catch(()=>{let n=C$(t);return n===t?Ch:kxr(e,n,r)})),EEo=(e,t,r)=>s.gen(function*(){let{closure:n,fs:o}=e,{size:i}=yield*mAe(r,"file");if(n.total+=Number(i),i>BigInt(Nut.maximumFileBytes)||n.total>Nut.maximumTotalBytes)return yield*Ch;let a=yield*o.readFile(r);return n.hash.update(`${bxr(t,r)}\0${String(a.byteLength)}\0`),n.hash.update(Axr("sha256").update(a).digest()),r}),REo=e=>Object.keys(e.dependencies??{}).toSorted(),_Eo=(e,t)=>Cxr(e,t).pipe(s.flatMap(r=>s.forEach(r.toSorted().filter(n=>fEo.test(n)),n=>EEo(e,t,n)))),vEo=(e,t)=>s.gen(function*(){let{closure:r,fs:n,prefix:o}=e;if(!$T(o,t))return yield*Ch;r.seen.add(t),yield*mAe(t,"directory");let i=yield*Put(n,t);return r.hash.update(`${String(i.name)}@${String(i.version)}\0`),i}),wxr=(e,t)=>s.gen(function*(){if(e.closure.seen.has(t))return[];let r=yield*vEo(e,t),n=yield*_Eo(e,t),o=yield*s.forEach(REo(r),i=>kxr(e.fs,t,i).pipe(s.flatMap(a=>wxr(e,a))));return[...n,...o.flat()]}),TEo="@maiaos/node",Nxr=(e,t)=>Put(e,t).pipe(s.flatMap(r=>r.name===TEo?s.succeed(t):Ch),s.catch(()=>{let r=C$(t);return r===t?Ch:Nxr(e,r)})),Pxr=(e,t)=>e.exists(dC(t,"pnpm-workspace.yaml")).pipe(s.flatMap(r=>{let n=C$(t);return r?s.succeed(t):n===t?Ch:Pxr(e,n)}),s.mapError(AL)),IEo=(e,t)=>s.gen(function*(){let r=yield*Nxr(e,C$(t)),n=r.indexOf(`${xxr}node_modules${xxr}`),o=n>0?r.slice(0,n):yield*Pxr(e,r);return{modules:n>0?C$(C$(r)):dC(r,"node_modules"),own:r,prefix:o}}),xEo=(e,t)=>{let{bin:r}=t,n=typeof r=="string"?r:r?.skills,o=typeof n=="string"?dC(e,n):"";return $T(e,o)?s.succeed(o):Ch},AEo=(e,t)=>wxr(e,t).pipe(s.map(r=>({files:r,sha256:e.closure.hash.digest("hex")}))),bEo=(e,t)=>s.gen(function*(){let{modules:r,own:n,prefix:o}=yield*IEo(e,yield*e.realPath(mEo(t.fromUrl))),i=yield*e.realPath(dC(n,"node_modules","skills")).pipe(s.catch(()=>e.realPath(dC(r,"skills")))),a=yield*Put(e,i);return a.name!=="skills"||a.version!==k$?yield*Ch:$T(o,i)?{entryPath:yield*e.realPath(yield*xEo(i,a)),prefix:o,root:i}:yield*Ch}),CEo=(e,t)=>({closure:{entries:0,hash:Axr("sha256"),seen:new Set,total:0},fs:e,prefix:t}),Oxr=e=>s.gen(function*(){let t=yield*ve.FileSystem,{entryPath:r,prefix:n,root:o}=yield*bEo(t,e),i=CEo(t,n),{files:a,sha256:c}=yield*AEo(i,o);return(yield*s.forEach(a,u=>t.realPath(u))).includes(r)?{closureSha256:c,entryPath:r,files:a,fromUrl:e.fromUrl,interpreterPath:yield*t.realPath(e.interpreterPath??process.execPath),packageRoot:o,version:k$}:yield*Ch}),fAe=e=>Oxr(e).pipe(s.mapError(AL)),hAe=e=>Oxr({fromUrl:e.fromUrl,interpreterPath:e.interpreterPath}).pipe(s.mapError(AL),s.flatMap(t=>t.closureSha256===e.closureSha256&&t.entryPath===e.entryPath&&t.interpreterPath===e.interpreterPath&&t.packageRoot===e.packageRoot&&t.files.join("\0")===e.files.join("\0")?s.void:Ch))});var lC,kEo,bL,GT,gAe,w$,Dxr=q(()=>{"use strict";Z();T$();lC=Object.freeze(S$.map(({integration:e})=>e)),kEo=e=>bu(e).ownerKinds,bL=e=>lC.find(t=>kEo(t).includes(e)),GT=(e,t)=>{switch(t){case de.antigravity:return e?.antigravity;case de.claudeCode:return e?.claudeCode;case"codex":return e?.codex;case de.grokCli:return e?.grokCli;case de.maiaAgent:return e?.maiaAgent;case de.pi:return e?.pi}},gAe=(e,t)=>{let r=Object.freeze(t);switch(e){case de.antigravity:return Object.freeze({antigravity:r});case de.claudeCode:return Object.freeze({claudeCode:r});case"codex":return Object.freeze({codex:r});case de.grokCli:return Object.freeze({grokCli:r});case de.maiaAgent:return Object.freeze({maiaAgent:r});case de.pi:return Object.freeze({pi:r})}},w$=e=>lC.flatMap(t=>{let r=GT(e,t);return r===void 0?[]:[r]})});var Mxr={};Nn(Mxr,{PRIVATE_GROUP_SHELL_FUNCTION:()=>eZ,SKILLS_PACKAGE_VERSION:()=>k$,USER_WRITES_ONLY_SHELL_FUNCTION:()=>tZ,consumeInvocationAttachmentNativeLease:()=>Yxe,embeddedManagedPiWorkerDefines:()=>Sut,insideDirectory:()=>$T,inspectDarwinVouchedTarget:()=>Ah,inspectManagedPiWorkerArtifact:()=>iAe,inspectSkillsFiles:()=>fAe,invocationAttachmentProcessOwnerId:()=>sC,issueInvocationAttachmentLaunchAuthorization:()=>iut,managedPiAuthorizationForRequest:()=>aAe,openDarwinVouchedTarget:()=>Xxe,openInvocationAttachmentNativeLease:()=>cut,piRpcAuthorizationForRequest:()=>pAe,readEmbeddedManagedPiWorkerReleaseIdentity:()=>aZ,releaseIdentityOf:()=>yut,requireInvocationAttachmentLaunchAuthorization:()=>Jxe,retainDarwinVouchedAuthorizationTarget:()=>oZ,sameRequest:()=>cZ,skillsVouchTarget:()=>Kxe,suppliedVendorLaunchAuthorizations:()=>w$,vendorIntegrationForOwner:()=>bL,vendorLaunchAuthorization:()=>GT,vendorLaunchAuthorizationGrant:()=>gAe,vendorLaunchIntegrations:()=>lC,verifyProcessLaunchAuthority:()=>zxe,verifyResolvedManagedPiWorkerArtifact:()=>sAe,verifyRetainedDarwinVouchedTargetPath:()=>iZ,verifySkillsPackage:()=>hAe});var wR=q(()=>{"use strict";lIr();bIr();kIr();LIr();nxr();ixr();Ixr();Qlt();Lxr();Dxr()});var ZT=sm((ruc,Ubr)=>{"use strict";var Dbr=["nodebuffer","arraybuffer","fragments"],Mbr=typeof Blob<"u";Mbr&&Dbr.push("blob");Ubr.exports={BINARY_TYPES:Dbr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Mbr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var BZ=sm((nuc,ZAe)=>{"use strict";var{EMPTY_BUFFER:PIo}=ZT(),jpt=Buffer[Symbol.species];function OIo(e,t){if(e.length===0)return PIo;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),n=0;for(let o=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return n<t?new jpt(r.buffer,r.byteOffset,n):r}function Fbr(e,t,r,n,o){for(let i=0;i<o;i++)r[n+i]=e[i]^t[i&3]}function Hbr(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function LIo(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function Wpt(e){if(Wpt.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new jpt(e):ArrayBuffer.isView(e)?t=new jpt(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),Wpt.readOnly=!1),t}ZAe.exports={concat:OIo,mask:Fbr,toArrayBuffer:LIo,toBuffer:Wpt,unmask:Hbr};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=Ha("bufferutil");ZAe.exports.mask=function(t,r,n,o,i){i<48?Fbr(t,r,n,o,i):e.mask(t,r,n,o,i)},ZAe.exports.unmask=function(t,r){t.length<32?Hbr(t,r):e.unmask(t,r)}}catch{}});var jbr=sm((ouc,qbr)=>{"use strict";var Bbr=Symbol("kDone"),$pt=Symbol("kRun"),Gpt=class{constructor(t){this[Bbr]=()=>{this.pending--,this[$pt]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[$pt]()}[$pt](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[Bbr])}}};qbr.exports=Gpt});var V$=sm((iuc,zbr)=>{"use strict";var qZ=Ha("zlib"),Wbr=BZ(),DIo=jbr(),{kStatusCode:$br}=ZT(),MIo=Buffer[Symbol.species],UIo=Buffer.from([0,0,255,255]),ebe=Symbol("permessage-deflate"),QT=Symbol("total-length"),G$=Symbol("callback"),gC=Symbol("buffers"),z$=Symbol("error"),QAe,zpt=class{constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!QAe){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;QAe=new DIo(r)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[G$];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,n=t.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&(typeof o.client_max_window_bits=="number"?r.clientMaxWindowBits>o.client_max_window_bits:!o.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let i=+o;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),t}decompress(t,r,n){QAe.add(o=>{this._decompress(t,r,(i,a)=>{o(),n(i,a)})})}compress(t,r,n){QAe.add(o=>{this._compress(t,r,(i,a)=>{o(),n(i,a)})})}_decompress(t,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?qZ.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=qZ.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[ebe]=this,this._inflate[QT]=0,this._inflate[gC]=[],this._inflate.on("error",HIo),this._inflate.on("data",Gbr)}this._inflate[G$]=n,this._inflate.write(t),r&&this._inflate.write(UIo),this._inflate.flush(()=>{let i=this._inflate[z$];if(i){this._inflate.close(),this._inflate=null,n(i);return}let a=Wbr.concat(this._inflate[gC],this._inflate[QT]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[QT]=0,this._inflate[gC]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(t,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let i=`${o}_max_window_bits`,a=typeof this.params[i]!="number"?qZ.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=qZ.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[QT]=0,this._deflate[gC]=[],this._deflate.on("data",FIo)}this._deflate[G$]=n,this._deflate.write(t),this._deflate.flush(qZ.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Wbr.concat(this._deflate[gC],this._deflate[QT]);r&&(i=new MIo(i.buffer,i.byteOffset,i.length-4)),this._deflate[G$]=null,this._deflate[QT]=0,this._deflate[gC]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};zbr.exports=zpt;function FIo(e){this[gC].push(e),this[QT]+=e.length}function Gbr(e){if(this[QT]+=e.length,this[ebe]._maxPayload<1||this[QT]<=this[ebe]._maxPayload){this[gC].push(e);return}this[z$]=new RangeError("Max payload size exceeded"),this[z$].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[z$][$br]=1009,this.removeListener("data",Gbr),this.reset()}function HIo(e){if(this[ebe]._inflate=null,this[z$]){this[G$](this[z$]);return}e[$br]=1007,this[G$](e)}});var K$=sm((suc,tbe)=>{"use strict";var{isUtf8:Vbr}=Ha("buffer"),{hasBlob:BIo}=ZT(),qIo=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function jIo(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Vpt(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function WIo(e){return BIo&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}tbe.exports={isBlob:WIo,isValidStatusCode:jIo,isValidUTF8:Vpt,tokenChars:qIo};if(Vbr)tbe.exports.isValidUTF8=function(e){return e.length<24?Vpt(e):Vbr(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=Ha("utf-8-validate");tbe.exports.isValidUTF8=function(t){return t.length<32?Vpt(t):e(t)}}catch{}});var Zpt=sm((auc,eCr)=>{"use strict";var{Writable:$Io}=Ha("stream"),Kbr=V$(),{BINARY_TYPES:GIo,EMPTY_BUFFER:Xbr,kStatusCode:zIo,kWebSocket:VIo}=ZT(),{concat:Kpt,toArrayBuffer:KIo,unmask:XIo}=BZ(),{isValidStatusCode:JIo,isValidUTF8:Jbr}=K$(),rbe=Buffer[Symbol.species],Ph=0,Ybr=1,Zbr=2,Qbr=3,Xpt=4,Jpt=5,nbe=6,Ypt=class extends $Io{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||GIo[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[VIo]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ph}_write(t,r,n){if(this._opcode===8&&this._state==Ph)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(n)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new rbe(n.buffer,n.byteOffset+t,n.length-t),new rbe(n.buffer,n.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let n=this._buffers[0],o=r.length-t;t>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,t),o),this._buffers[0]=new rbe(n.buffer,n.byteOffset+t,n.length-t)),t-=n.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case Ph:this.getInfo(t);break;case Ybr:this.getPayloadLength16(t);break;case Zbr:this.getPayloadLength64(t);break;case Qbr:this.getMask();break;case Xpt:this.getData(t);break;case Jpt:case nbe:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[Kbr.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(o);return}this._payloadLength===126?this._state=Ybr:this._payloadLength===127?this._state=Zbr:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=Qbr:this._state=Xpt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Xpt}getData(t){let r=Xbr;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&XIo(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(n);return}if(this._compressed){this._state=Jpt,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[Kbr.extensionName].decompress(t,this._fin,(o,i)=>{if(o)return r(o);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(i)}this.dataMessage(r),this._state===Ph&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=Ph;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=Kpt(n,r):this._binaryType==="arraybuffer"?o=KIo(Kpt(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=Ph):(this._state=nbe,setImmediate(()=>{this.emit("message",o,!0),this._state=Ph,this.startLoop(t)}))}else{let o=Kpt(n,r);if(!this._skipUTF8Validation&&!Jbr(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._state===Jpt||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=Ph):(this._state=nbe,setImmediate(()=>{this.emit("message",o,!1),this._state=Ph,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,Xbr),this.end();else{let n=t.readUInt16BE(0);if(!JIo(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(i);return}let o=new rbe(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Jbr(o)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(i);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=Ph;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=Ph):(this._state=nbe,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=Ph,this.startLoop(r)}))}createError(t,r,n,o,i){this._loop=!1,this._errored=!0;let a=new t(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=i,a[zIo]=o,a}};eCr.exports=Ypt});var tmt=sm((duc,nCr)=>{"use strict";var{Duplex:cuc}=Ha("stream"),{randomFillSync:YIo}=Ha("crypto"),{types:{isUint8Array:ZIo}}=Ha("util"),tCr=V$(),{EMPTY_BUFFER:QIo,kWebSocket:exo,NOOP:txo}=ZT(),{isBlob:X$,isValidStatusCode:rxo}=K$(),{mask:rCr,toBuffer:BL}=BZ(),Oh=Symbol("kByteLength"),nxo=Buffer.alloc(4),obe=8*1024,qL,J$=obe,Zy=0,oxo=1,ixo=2,Qpt=class e{constructor(t,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Zy,this.onerror=txo,this[exo]=void 0}static frame(t,r){let n,o=!1,i=2,a=!1;r.mask&&(n=r.maskBuffer||nxo,r.generateMask?r.generateMask(n):(J$===obe&&(qL===void 0&&(qL=Buffer.alloc(obe)),YIo(qL,0,obe),J$=0),n[0]=qL[J$++],n[1]=qL[J$++],n[2]=qL[J$++],n[3]=qL[J$++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof t=="string"?(!r.mask||a)&&r[Oh]!==void 0?c=r[Oh]:(t=Buffer.from(t),c=t.length):(c=t.length,o=r.mask&&r.readOnly&&!a);let l=c;c>=65536?(i+=8,l=127):c>125&&(i+=2,l=126);let u=Buffer.allocUnsafe(o?c+i:i);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=l,l===126?u.writeUInt16BE(c,2):l===127&&(u[2]=u[3]=0,u.writeUIntBE(c,4,6)),r.mask?(u[1]|=128,u[i-4]=n[0],u[i-3]=n[1],u[i-2]=n[2],u[i-1]=n[3],a?[u,t]:o?(rCr(t,n,u,i,c),[u]):(rCr(t,n,t,0,c),[u,t])):[u,t]}close(t,r,n,o){let i;if(t===void 0)i=QIo;else{if(typeof t!="number"||!rxo(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(t,0);else{let c=Buffer.byteLength(r);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(t,0),typeof r=="string")i.write(r,2);else if(ZIo(r))i.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let a={[Oh]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Zy?this.enqueue([this.dispatch,i,!1,a,o]):this.sendFrame(e.frame(i,a),o)}ping(t,r,n){let o,i;if(typeof t=="string"?(o=Buffer.byteLength(t),i=!1):X$(t)?(o=t.size,i=!1):(t=BL(t),o=t.length,i=BL.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Oh]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};X$(t)?this._state!==Zy?this.enqueue([this.getBlobData,t,!1,a,n]):this.getBlobData(t,!1,a,n):this._state!==Zy?this.enqueue([this.dispatch,t,!1,a,n]):this.sendFrame(e.frame(t,a),n)}pong(t,r,n){let o,i;if(typeof t=="string"?(o=Buffer.byteLength(t),i=!1):X$(t)?(o=t.size,i=!1):(t=BL(t),o=t.length,i=BL.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Oh]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};X$(t)?this._state!==Zy?this.enqueue([this.getBlobData,t,!1,a,n]):this.getBlobData(t,!1,a,n):this._state!==Zy?this.enqueue([this.dispatch,t,!1,a,n]):this.sendFrame(e.frame(t,a),n)}send(t,r,n){let o=this._extensions[tCr.extensionName],i=r.binary?2:1,a=r.compress,c,l;typeof t=="string"?(c=Buffer.byteLength(t),l=!1):X$(t)?(c=t.size,l=!1):(t=BL(t),c=t.length,l=BL.readOnly),this._firstFragment?(this._firstFragment=!1,a&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=c>=o._threshold),this._compress=a):(a=!1,i=0),r.fin&&(this._firstFragment=!0);let u={[Oh]:c,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:a};X$(t)?this._state!==Zy?this.enqueue([this.getBlobData,t,this._compress,u,n]):this.getBlobData(t,this._compress,u,n):this._state!==Zy?this.enqueue([this.dispatch,t,this._compress,u,n]):this.dispatch(t,this._compress,u,n)}getBlobData(t,r,n,o){this._bufferedBytes+=n[Oh],this._state=ixo,t.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(emt,this,c,o);return}this._bufferedBytes-=n[Oh];let a=BL(i);r?this.dispatch(a,r,n,o):(this._state=Zy,this.sendFrame(e.frame(a,n),o),this.dequeue())}).catch(i=>{process.nextTick(sxo,this,i,o)})}dispatch(t,r,n,o){if(!r){this.sendFrame(e.frame(t,n),o);return}let i=this._extensions[tCr.extensionName];this._bufferedBytes+=n[Oh],this._state=oxo,i.compress(t,n.fin,(a,c)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");emt(this,l,o);return}this._bufferedBytes-=n[Oh],this._state=Zy,n.readOnly=!1,this.sendFrame(e.frame(c,n),o),this.dequeue()})}dequeue(){for(;this._state===Zy&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][Oh],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][Oh],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};nCr.exports=Qpt;function emt(e,t,r){typeof r=="function"&&r(t);for(let n=0;n<e._queue.length;n++){let o=e._queue[n],i=o[o.length-1];typeof i=="function"&&i(t)}}function sxo(e,t,r){emt(e,t,r),e.onerror(t)}});var pCr=sm((luc,uCr)=>{"use strict";var{kForOnEventAttribute:jZ,kListener:rmt}=ZT(),oCr=Symbol("kCode"),iCr=Symbol("kData"),sCr=Symbol("kError"),aCr=Symbol("kMessage"),cCr=Symbol("kReason"),Y$=Symbol("kTarget"),dCr=Symbol("kType"),lCr=Symbol("kWasClean"),eI=class{constructor(t){this[Y$]=null,this[dCr]=t}get target(){return this[Y$]}get type(){return this[dCr]}};Object.defineProperty(eI.prototype,"target",{enumerable:!0});Object.defineProperty(eI.prototype,"type",{enumerable:!0});var jL=class extends eI{constructor(t,r={}){super(t),this[oCr]=r.code===void 0?0:r.code,this[cCr]=r.reason===void 0?"":r.reason,this[lCr]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[oCr]}get reason(){return this[cCr]}get wasClean(){return this[lCr]}};Object.defineProperty(jL.prototype,"code",{enumerable:!0});Object.defineProperty(jL.prototype,"reason",{enumerable:!0});Object.defineProperty(jL.prototype,"wasClean",{enumerable:!0});var Z$=class extends eI{constructor(t,r={}){super(t),this[sCr]=r.error===void 0?null:r.error,this[aCr]=r.message===void 0?"":r.message}get error(){return this[sCr]}get message(){return this[aCr]}};Object.defineProperty(Z$.prototype,"error",{enumerable:!0});Object.defineProperty(Z$.prototype,"message",{enumerable:!0});var WZ=class extends eI{constructor(t,r={}){super(t),this[iCr]=r.data===void 0?null:r.data}get data(){return this[iCr]}};Object.defineProperty(WZ.prototype,"data",{enumerable:!0});var axo={addEventListener(e,t,r={}){for(let o of this.listeners(e))if(!r[jZ]&&o[rmt]===t&&!o[jZ])return;let n;if(e==="message")n=function(i,a){let c=new WZ("message",{data:a?i:i.toString()});c[Y$]=this,ibe(t,this,c)};else if(e==="close")n=function(i,a){let c=new jL("close",{code:i,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[Y$]=this,ibe(t,this,c)};else if(e==="error")n=function(i){let a=new Z$("error",{error:i,message:i.message});a[Y$]=this,ibe(t,this,a)};else if(e==="open")n=function(){let i=new eI("open");i[Y$]=this,ibe(t,this,i)};else return;n[jZ]=!!r[jZ],n[rmt]=t,r.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[rmt]===t&&!r[jZ]){this.removeListener(e,r);break}}};uCr.exports={CloseEvent:jL,ErrorEvent:Z$,Event:eI,EventTarget:axo,MessageEvent:WZ};function ibe(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var sbe=sm((uuc,mCr)=>{"use strict";var{tokenChars:$Z}=K$();function FR(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function cxo(e){let t=Object.create(null),r=Object.create(null),n=!1,o=!1,i=!1,a,c,l=-1,u=-1,p=-1,h=0;for(;h<e.length;h++)if(u=e.charCodeAt(h),a===void 0)if(p===-1&&$Z[u]===1)l===-1&&(l=h);else if(h!==0&&(u===32||u===9))p===-1&&l!==-1&&(p=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);p===-1&&(p=h);let S=e.slice(l,p);u===44?(FR(t,S,r),r=Object.create(null)):a=S,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);else if(c===void 0)if(p===-1&&$Z[u]===1)l===-1&&(l=h);else if(u===32||u===9)p===-1&&l!==-1&&(p=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);p===-1&&(p=h),FR(r,e.slice(l,p),!0),u===44&&(FR(t,a,r),r=Object.create(null),a=void 0),l=p=-1}else if(u===61&&l!==-1&&p===-1)c=e.slice(l,h),l=p=-1;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(o){if($Z[u]!==1)throw new SyntaxError(`Unexpected character at index ${h}`);l===-1?l=h:n||(n=!0),o=!1}else if(i)if($Z[u]===1)l===-1&&(l=h);else if(u===34&&l!==-1)i=!1,p=h;else if(u===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${h}`);else if(u===34&&e.charCodeAt(h-1)===61)i=!0;else if(p===-1&&$Z[u]===1)l===-1&&(l=h);else if(l!==-1&&(u===32||u===9))p===-1&&(p=h);else if(u===59||u===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${h}`);p===-1&&(p=h);let S=e.slice(l,p);n&&(S=S.replace(/\\/g,""),n=!1),FR(r,c,S),u===44&&(FR(t,a,r),r=Object.create(null),a=void 0),c=void 0,l=p=-1}else throw new SyntaxError(`Unexpected character at index ${h}`);if(l===-1||i||u===32||u===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=h);let g=e.slice(l,p);return a===void 0?FR(t,g,r):(c===void 0?FR(r,g,!0):n?FR(r,c,g.replace(/\\/g,"")):FR(r,c,g),FR(t,a,r)),t}function dxo(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(n=>[t].concat(Object.keys(n).map(o=>{let i=n[o];return Array.isArray(i)||(i=[i]),i.map(a=>a===!0?o:`${o}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}mCr.exports={format:dxo,parse:cxo}});var lbe=sm((fuc,xCr)=>{"use strict";var lxo=Ha("events"),uxo=Ha("https"),pxo=Ha("http"),gCr=Ha("net"),mxo=Ha("tls"),{randomBytes:fxo,createHash:hxo}=Ha("crypto"),{Duplex:puc,Readable:muc}=Ha("stream"),{URL:nmt}=Ha("url"),yC=V$(),gxo=Zpt(),yxo=tmt(),{isBlob:Sxo}=K$(),{BINARY_TYPES:fCr,CLOSE_TIMEOUT:Exo,EMPTY_BUFFER:abe,GUID:Rxo,kForOnEventAttribute:omt,kListener:_xo,kStatusCode:vxo,kWebSocket:pd,NOOP:yCr}=ZT(),{EventTarget:{addEventListener:Txo,removeEventListener:Ixo}}=pCr(),{format:xxo,parse:Axo}=sbe(),{toBuffer:bxo}=BZ(),SCr=Symbol("kAborted"),imt=[8,13],tI=["CONNECTING","OPEN","CLOSING","CLOSED"],Cxo=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ws=class e extends lxo{constructor(t,r,n){super(),this._binaryType=fCr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=abe,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?!n||n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,n.protocols===void 0?r=[]:Array.isArray(n.protocols)?r=n.protocols:r=[n.protocols]):r=[r]),ECr(this,t,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){fCr.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,n){let o=new gxo({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new yxo(t,this._extensions,n.generateMask);this._receiver=o,this._sender=i,this._socket=t,o[pd]=this,i[pd]=this,t[pd]=this,o.on("conclude",Nxo),o.on("drain",Pxo),o.on("error",Oxo),o.on("message",Lxo),o.on("ping",Dxo),o.on("pong",Mxo),i.onerror=Uxo,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",vCr),t.on("data",dbe),t.on("end",TCr),t.on("error",ICr),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[yC.extensionName]&&this._extensions[yC.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Zm(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(t,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=e.CLOSING,_Cr(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){smt(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||abe,r,n)}pong(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(n=t,t=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){smt(this,t,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||abe,r,n)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,n){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){smt(this,t,n);return}let o={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[yC.extensionName]||(o.compress=!1),this._sender.send(t||abe,o,n)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){Zm(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ws,"CONNECTING",{enumerable:!0,value:tI.indexOf("CONNECTING")});Object.defineProperty(Ws.prototype,"CONNECTING",{enumerable:!0,value:tI.indexOf("CONNECTING")});Object.defineProperty(Ws,"OPEN",{enumerable:!0,value:tI.indexOf("OPEN")});Object.defineProperty(Ws.prototype,"OPEN",{enumerable:!0,value:tI.indexOf("OPEN")});Object.defineProperty(Ws,"CLOSING",{enumerable:!0,value:tI.indexOf("CLOSING")});Object.defineProperty(Ws.prototype,"CLOSING",{enumerable:!0,value:tI.indexOf("CLOSING")});Object.defineProperty(Ws,"CLOSED",{enumerable:!0,value:tI.indexOf("CLOSED")});Object.defineProperty(Ws.prototype,"CLOSED",{enumerable:!0,value:tI.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(Ws.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(Ws.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[omt])return t[_xo];return null},set(t){for(let r of this.listeners(e))if(r[omt]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[omt]:!0})}})});Ws.prototype.addEventListener=Txo;Ws.prototype.removeEventListener=Ixo;xCr.exports=Ws;function ECr(e,t,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Exo,protocolVersion:imt[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!imt.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${imt.join(", ")})`);let i;if(t instanceof nmt)i=t;else try{i=new nmt(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),e._url=i.href;let a=i.protocol==="wss:",c=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!a&&!c?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let v=new SyntaxError(l);if(e._redirects===0)throw v;cbe(e,v);return}let u=a?443:80,p=fxo(16).toString("base64"),h=a?uxo.request:pxo.request,g=new Set,S;if(o.createConnection=o.createConnection||(a?wxo:kxo),o.defaultPort=o.defaultPort||u,o.port=i.port||u,o.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},o.path=i.pathname+i.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(S=new yC({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=xxo({[yC.extensionName]:S.offer()})),r.length){for(let v of r){if(typeof v!="string"||!Cxo.test(v)||g.has(v))throw new SyntaxError("An invalid or duplicated subprotocol was specified");g.add(v)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(i.username||i.password)&&(o.auth=`${i.username}:${i.password}`),c){let v=o.path.split(":");o.socketPath=v[0],o.path=v[1]}let E;if(o.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=a,e._originalHostOrSocketPath=c?o.socketPath:i.host;let v=n&&n.headers;if(n={...n,headers:{}},v)for(let[T,x]of Object.entries(v))n.headers[T.toLowerCase()]=x}else if(e.listenerCount("redirect")===0){let v=c?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:i.host===e._originalHostOrSocketPath;(!v||e._originalSecure&&!a)&&(delete o.headers.authorization,delete o.headers.cookie,v||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=e._req=h(o),e._redirects&&e.emit("redirect",e.url,E)}else E=e._req=h(o);o.timeout&&E.on("timeout",()=>{Zm(e,E,"Opening handshake has timed out")}),E.on("error",v=>{E===null||E[SCr]||(E=e._req=null,cbe(e,v))}),E.on("response",v=>{let T=v.headers.location,x=v.statusCode;if(T&&o.followRedirects&&x>=300&&x<400){if(++e._redirects>o.maxRedirects){Zm(e,E,"Maximum redirects exceeded");return}E.abort();let w;try{w=new nmt(T,t)}catch{let N=new SyntaxError(`Invalid URL: ${T}`);cbe(e,N);return}ECr(e,w,r,n)}else e.emit("unexpected-response",E,v)||Zm(e,E,`Unexpected server response: ${v.statusCode}`)}),E.on("upgrade",(v,T,x)=>{if(e.emit("upgrade",v),e.readyState!==Ws.CONNECTING)return;E=e._req=null;let w=v.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){Zm(e,T,"Invalid Upgrade header");return}let D=hxo("sha1").update(p+Rxo).digest("base64");if(v.headers["sec-websocket-accept"]!==D){Zm(e,T,"Invalid Sec-WebSocket-Accept header");return}let N=v.headers["sec-websocket-protocol"],A;if(N!==void 0?g.size?g.has(N)||(A="Server sent an invalid subprotocol"):A="Server sent a subprotocol but none was requested":g.size&&(A="Server sent no subprotocol"),A){Zm(e,T,A);return}N&&(e._protocol=N);let k=v.headers["sec-websocket-extensions"];if(k!==void 0){if(!S){Zm(e,T,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let b;try{b=Axo(k)}catch{Zm(e,T,"Invalid Sec-WebSocket-Extensions header");return}let L=Object.keys(b);if(L.length!==1||L[0]!==yC.extensionName){Zm(e,T,"Server indicated an extension that was not requested");return}try{S.accept(b[yC.extensionName])}catch{Zm(e,T,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[yC.extensionName]=S}e.setSocket(T,x,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,e):E.end()}function cbe(e,t){e._readyState=Ws.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function kxo(e){return e.path=e.socketPath,gCr.connect(e)}function wxo(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=gCr.isIP(e.host)?"":e.host),mxo.connect(e)}function Zm(e,t,r){e._readyState=Ws.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Zm),t.setHeader?(t[SCr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(cbe,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function smt(e,t,r){if(t){let n=Sxo(t)?t.size:bxo(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${e.readyState} (${tI[e.readyState]})`);process.nextTick(r,n)}}function Nxo(e,t){let r=this[pd];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[pd]!==void 0&&(r._socket.removeListener("data",dbe),process.nextTick(RCr,r._socket),e===1005?r.close():r.close(e,t))}function Pxo(){let e=this[pd];e.isPaused||e._socket.resume()}function Oxo(e){let t=this[pd];t._socket[pd]!==void 0&&(t._socket.removeListener("data",dbe),process.nextTick(RCr,t._socket),t.close(e[vxo])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function hCr(){this[pd].emitClose()}function Lxo(e,t){this[pd].emit("message",e,t)}function Dxo(e){let t=this[pd];t._autoPong&&t.pong(e,!this._isServer,yCr),t.emit("ping",e)}function Mxo(e){this[pd].emit("pong",e)}function RCr(e){e.resume()}function Uxo(e){let t=this[pd];t.readyState!==Ws.CLOSED&&(t.readyState===Ws.OPEN&&(t._readyState=Ws.CLOSING,_Cr(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function _Cr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function vCr(){let e=this[pd];if(this.removeListener("close",vCr),this.removeListener("data",dbe),this.removeListener("end",TCr),e._readyState=Ws.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[pd]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",hCr),e._receiver.on("finish",hCr))}function dbe(e){this[pd]._receiver.write(e)||this.pause()}function TCr(){let e=this[pd];e._readyState=Ws.CLOSING,e._receiver.end(),this.end()}function ICr(){let e=this[pd];this.removeListener("error",ICr),this.on("error",yCr),e&&(e._readyState=Ws.CLOSING,this.destroy())}});var kCr=sm((guc,CCr)=>{"use strict";var huc=lbe(),{Duplex:Fxo}=Ha("stream");function ACr(e){e.emit("close")}function Hxo(){!this.destroyed&&this._writableState.finished&&this.destroy()}function bCr(e){this.removeListener("error",bCr),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Bxo(e,t){let r=!0,n=new Fxo({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(i,a){let c=!a&&n._readableState.objectMode?i.toString():i;n.push(c)||e.pause()}),e.once("error",function(i){n.destroyed||(r=!1,n.destroy(i))}),e.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(o,i){if(e.readyState===e.CLOSED){i(o),process.nextTick(ACr,n);return}let a=!1;e.once("error",function(l){a=!0,i(l)}),e.once("close",function(){a||i(o),process.nextTick(ACr,n)}),r&&e.terminate()},n._final=function(o){if(e.readyState===e.CONNECTING){e.once("open",function(){n._final(o)});return}e._socket!==null&&(e._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(e._socket.once("finish",function(){o()}),e.close()))},n._read=function(){e.isPaused&&e.resume()},n._write=function(o,i,a){if(e.readyState===e.CONNECTING){e.once("open",function(){n._write(o,i,a)});return}e.send(o,a)},n.on("end",Hxo),n.on("error",bCr),n}CCr.exports=Bxo});var amt=sm((yuc,wCr)=>{"use strict";var{tokenChars:qxo}=K$();function jxo(e){let t=new Set,r=-1,n=-1,o=0;for(o;o<e.length;o++){let a=e.charCodeAt(o);if(n===-1&&qxo[a]===1)r===-1&&(r=o);else if(o!==0&&(a===32||a===9))n===-1&&r!==-1&&(n=o);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let c=e.slice(r,n);if(t.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);t.add(c),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=e.slice(r,o);if(t.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return t.add(i),t}wCr.exports={parse:jxo}});var UCr=sm((Euc,MCr)=>{"use strict";var Wxo=Ha("events"),ube=Ha("http"),{Duplex:Suc}=Ha("stream"),{createHash:$xo}=Ha("crypto"),NCr=sbe(),WL=V$(),Gxo=amt(),zxo=lbe(),{CLOSE_TIMEOUT:Vxo,GUID:Kxo,kWebSocket:Xxo}=ZT(),Jxo=/^[+/0-9A-Za-z]{22}==$/,PCr=0,OCr=1,DCr=2,cmt=class extends Wxo{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Vxo,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:zxo,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=ube.createServer((n,o)=>{let i=ube.STATUS_CODES[426];o.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),o.end(i)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Yxo(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,i,a)=>{this.handleUpgrade(o,i,a,n)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=PCr}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===DCr){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(GZ,this);return}if(t&&this.once("close",t),this._state!==OCr)if(this._state=OCr,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(GZ,this):process.nextTick(GZ,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{GZ(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,n,o){r.on("error",LCr);let i=t.headers["sec-websocket-key"],a=t.headers.upgrade,c=+t.headers["sec-websocket-version"];if(t.method!=="GET"){$L(this,t,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){$L(this,t,r,400,"Invalid Upgrade header");return}if(i===void 0||!Jxo.test(i)){$L(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){$L(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){zZ(r,400);return}let l=t.headers["sec-websocket-protocol"],u=new Set;if(l!==void 0)try{u=Gxo.parse(l)}catch{$L(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let p=t.headers["sec-websocket-extensions"],h={};if(this.options.perMessageDeflate&&p!==void 0){let g=new WL({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let S=NCr.parse(p);S[WL.extensionName]&&(g.accept(S[WL.extensionName]),h[WL.extensionName]=g)}catch{$L(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let g={origin:t.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(g,(S,E,v,T)=>{if(!S)return zZ(r,E||401,v,T);this.completeUpgrade(h,i,u,t,r,n,o)});return}if(!this.options.verifyClient(g))return zZ(r,401)}this.completeUpgrade(h,i,u,t,r,n,o)}completeUpgrade(t,r,n,o,i,a,c){if(!i.readable||!i.writable)return i.destroy();if(i[Xxo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>PCr)return zZ(i,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$xo("sha1").update(r+Kxo).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let h=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;h&&(u.push(`Sec-WebSocket-Protocol: ${h}`),p._protocol=h)}if(t[WL.extensionName]){let h=t[WL.extensionName].params,g=NCr.format({[WL.extensionName]:[h]});u.push(`Sec-WebSocket-Extensions: ${g}`),p._extensions=t}this.emit("headers",u,o),i.write(u.concat(`\r
239
239
  `).join(`\r
240
240
  `)),i.removeListener("error",LCr),p.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(GZ,this)})),c(p,o)}};MCr.exports=cmt;function Yxo(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function GZ(e){e._state=DCr,e.emit("close")}function LCr(){this.destroy()}function zZ(e,t,r,n){r=r||ube.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${ube.STATUS_CODES[t]}\r
241
241
  `+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
@@ -8764,7 +8764,7 @@ fund=false
8764
8764
  `),NBr=["debug","prompt-input"],kBr=[kNe,"<skills_instructions>","<multi_agent_role>"],EZo=128,PBr=(e,t)=>!B.exists(e,n=>n.exitCode===0&&kBr.every(o=>n.stdout.includes(o)))||B.isNone(t)||t.value.exitCode>=EZo?"inconclusive":t.value.exitCode===0&&kBr.every(n=>!t.value.stdout.includes(n))?"ok":"failed";F();var MBr={kind:"none"},Qz={kind:"unreadable"},r_t=e=>({endpoint:e,kind:"endpoint"}),RZo=/\b(\d+\.\d+\.\d+[0-9A-Za-z.+-]{0,40})/u,_Zo=/^[a-z0-9][a-z0-9._-]{0,63}$/u,UBr="ANTHROPIC_BASE_URL",FBr=e=>RZo.exec(e)?.[1],vZo=e=>{let t=e?.toLowerCase();return t!==void 0&&_Zo.test(t)?t:void 0},TZo=d.decodeUnknownOption(d.fromJsonString(d.Struct({authMethod:d.optional(d.String),loggedIn:d.Boolean}))),HBr=(e,t)=>{let r=TZo(t.trim());if(B.isNone(r))return{auth:"unknown"};if(r.value.loggedIn&&e===0){let n=vZo(r.value.authMethod);return n===void 0?{auth:"vendor-login"}:{accountKind:n,auth:"vendor-login"}}return!r.value.loggedIn&&e!==0?{auth:"none"}:{auth:"unknown"}},BBr=(e,t)=>e===0&&/^Logged in using ChatGPT\b/mu.test(t)?{accountKind:"chatgpt",auth:"vendor-login"}:e===0&&/^Logged in using an API key\b/mu.test(t)?{accountKind:"api-key",auth:"vendor-login"}:e!==0&&/^Not logged in\b/mu.test(t)?{auth:"none"}:{auth:"unknown"},qBr=e=>{if(e===void 0||!URL.canParse(e))return;let t=new URL(e);if(!(t.protocol!=="https:"&&t.protocol!=="http:"))return/^[A-Za-z0-9.[\]:-]{1,260}$/u.test(t.host)?t.host:void 0},IZo=e=>{let t="<url>";if(typeof e=="string"&&e.length<=2048&&/^[A-Za-z0-9:/.[\]_-]+$/u.test(e)&&URL.canParse(e)){let r=new URL(e);if(r.protocol==="https:"||r.protocol==="http:"&&/^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])$/u.test(r.hostname)){let o=r.pathname.replace(/\/+$/u,"").replace(/\/v1$/u,"");if(!o.endsWith("/")&&!o.endsWith("/v1")){let i=`${r.origin}${o}`;t=i.includes("[")||i.includes("]")?`'${i}'`:i}}}return`maia login gateway --name <name> --base-url ${t} --api-key-stdin`},xZo=d.decodeUnknownOption(d.fromJsonString(d.Struct({apiKeyHelper:d.optional(d.Unknown),env:d.optional(d.Struct({[UBr]:d.optional(d.Unknown)}))}))),jBr=e=>{let t=xZo(e);if(B.isNone(t))return Qz;let r=t.value.env?.[UBr];if(r===void 0)return MBr;let n=qBr(typeof r=="string"?r:void 0),o=t.value.apiKeyHelper;return n!==void 0&&typeof o=="string"&&o.length>0?r_t({credential:"helper",hint:IZo(r),host:n}):Qz},AZo=e=>/^"(.*)"$/u.exec(e)?.[1]??/^'(.*)'$/u.exec(e)?.[1]??e,OBr=e=>(e.match(/"[^"]*"|'[^']*'|[^.\s]+/gu)??[]).map(AZo),LBr=e=>/^"((?:[^"\\]|\\.)*)"/u.exec(e)?.[1]??/^'([^']*)'/u.exec(e)?.[1],bZo=new Set(["base_url","model_provider"]),CZo=/^(\[\[?)([^[\]]+)\]\]?\s*(?:#.*)?$/u,kZo=/^((?:"[^"]*"|'[^']*'|[A-Za-z0-9_.-])+?)\s*=\s*(.*)$/u,wZo=1e4,NZo=(e,t,r)=>{let n=t.at(-1)??"",o=t.join("\0");e.values.set(o,bZo.has(n)?r:""),n==="auth"&&/^\{.*\bcommand\s*=/u.test(r)&&e.values.set(`${o}\0command`,"")},PZo=e=>{let t=[{name:[],values:new Map}];return e.forEach(r=>{let n=r.trim(),o=CZo.exec(n);if(o?.[2]!==void 0){let c=OBr(o[2]);t.push({name:o[1]==="[["?["[[",...c]:c,values:new Map});return}let i=kZo.exec(n),a=t.at(-1);i?.[1]!==void 0&&i[2]!==void 0&&a&&NZo(a,OBr(i[1]),i[2])}),t},OZo=(e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]),DBr=(e,t)=>e.find(r=>OZo(r.name,t)),WBr=e=>{let t=e.split(/\r?\n/u);if(t.length>wZo)return Qz;let r=PZo(t),n=LBr(r[0]?.values.get("model_provider")??"");if(n===void 0||n===""||n==="openai")return r[0]?.values.has("model_provider")===!0&&n===void 0?Qz:MBr;let o=["model_providers",n],i=DBr(r,o),a=qBr(LBr(i?.values.get("base_url")??""));return a===void 0?Qz:DBr(r,[...o,"auth"])?.values.has("command")===!0||i?.values.has("auth\0command")===!0?r_t({credential:"helper",host:a}):i?.values.has("env_key")===!0?r_t({credential:"env-key",host:a}):Qz};var DZo=["HOME","LANG","LC_ALL","PATH","USER"],MZo=Ze.seconds(3),$Br=64*1024,UZo=1024*1024,FZo=8,HZo={command:"claude",config:[".claude","settings.json"],readEndpoint:jBr,status:["auth","status","--json"],statusOf:e=>HBr(e.exitCode,e.stdout)},BZo={command:"codex",config:[".codex","config.toml"],readEndpoint:WBr,status:["login","status"],statusOf:e=>BBr(e.exitCode,e.output)},XBr=["/opt/homebrew/bin","/usr/local/bin","/usr/bin"],qZo=e=>[...e.home===void 0?[]:[qp(e.home,".local","bin"),qp(e.home,".npm-global","bin"),qp(e.home,".bun","bin"),qp(e.home,".claude","local")],...e.systemDirectories],JBr=(e,t)=>e.fileSystem.stat(t).pipe(s.map(r=>r.type==="File"&&(r.mode&73)!==0),s.orElseSucceed(()=>!1)),jZo=(e,t)=>{let r=nk(e.path),n=r.state==="valid"?r.directories:[];return s.findFirst(n,o=>e.fileSystem.exists(qp(o,t)).pipe(s.orElseSucceed(()=>!1))).pipe(s.map(B.map(o=>qp(o,t))),s.flatMap(o=>B.isNone(o)?s.succeedNone:s.map(JBr(e,o.value),i=>i?o:B.none())))},WZo=(e,t)=>s.findFirst(qZo(e),r=>JBr(e,qp(r,t))).pipe(s.map(B.map(r=>qp(r,t)))),YBr=s.fn("VendorCli.locate")(function*(e,t){let r=yield*jZo(e,t),n=B.isSome(r)?r:yield*WZo(e,t);return B.map(n,o=>({onNodePath:B.isSome(r),path:o}))}),NNe=(e,t)=>ve.FileSystem.use(r=>YBr({fileSystem:r,home:e.home,path:e.path,systemDirectories:e.systemDirectories??XBr},t)),GBr=e=>e.pipe(Ge.runFold(()=>Buffer.alloc(0),(t,r)=>t.byteLength>=$Br?t:Buffer.concat([t,r]).subarray(0,$Br)),s.map(t=>t.toString("utf8"))),$Zo=(e,t,r)=>Gs(t,[...r],{cwd:e.home??"/",env:e.environment,extendEnv:!1,forceKillAfter:Ze.millis(500),stderr:"pipe",stdin:"ignore",stdout:"pipe"}),wNe=(e,t,r)=>s.gen(function*(){let n=yield*e.spawner.spawn($Zo(e,t,r)),[o,i,a]=yield*s.all([GBr(n.stdout),GBr(n.stderr),n.exitCode],{concurrency:"unbounded"});return{exitCode:Number(a),output:`${o}
8765
8765
  ${i}`,stdout:o}}).pipe(s.scoped,s.timeoutOption(e.timeout),s.orElseSucceed(()=>B.none())),zBr={kind:"none"},VBr={kind:"unreadable"},GZo=(e,t)=>{if(e.home===void 0)return s.succeed(zBr);let r=qp(e.home,...t.config);return e.fileSystem.exists(r).pipe(s.flatMap(n=>n?e.fileSystem.stat(r).pipe(s.flatMap(o=>o.type==="File"&&Number(o.size)<=UZo?s.map(e.fileSystem.readFileString(r),t.readEndpoint):s.succeed(VBr))):s.succeed(zBr)),s.orElseSucceed(()=>VBr))},zZo=(e,t)=>t.kind==="endpoint"?{...e,auth:"custom-endpoint",endpoint:t.endpoint}:t.kind==="unreadable"?{auth:"unknown"}:e,ZBr=e=>B.match(B.flatMap(e,t=>B.fromNullishOr(t.exitCode===0?FBr(t.stdout):void 0)),{onNone:()=>({}),onSome:t=>({version:t})}),KBr=(e,t,r)=>s.gen(function*(){let{home:n,overrides:o}=r,i=qp(n,".codex"),a=qp(i,"skills",kNe);yield*e.fileSystem.makeDirectory(a,{recursive:!0}),yield*e.fileSystem.writeFileString(qp(a,"SKILL.md"),wBr);let c={...e,environment:{...e.environment,CODEX_HOME:i,HOME:n},home:n};return yield*wNe(c,t,[...NBr,...o])}),VZo=(e,t)=>s.gen(function*(){let r=yield*e.fileSystem.makeTempDirectoryScoped({prefix:"maia-codex-prompt-"}),[n,o]=yield*s.all([KBr(e,t,{home:qp(r,"control"),overrides:[]}),KBr(e,t,{home:qp(r,"worker"),overrides:e.codexWorkerPromptArguments})],{concurrency:"unbounded"});return PBr(n,o)}).pipe(s.scoped,s.orElseSucceed(()=>"inconclusive")),KZo=s.fn("VendorCli.versionOnly")(function*(e,t){let r=yield*wNe(e,t.path,["--version"]);return{auth:"unknown",binary:{found:!0,...t,...ZBr(r)}}}),XZo=s.fn("VendorCli.probeBinary")(function*(e,t,{found:r,options:n}){if(n.versionOnly===!0)return yield*KZo(e,r);let[o,i,a,c]=yield*s.all([wNe(e,r.path,["--version"]),wNe(e,r.path,t.status),GZo(e,t),t.command==="codex"&&n.workerPrompt!==!1?s.map(VZo(e,r.path),B.some):s.succeedNone],{concurrency:"unbounded"}),l=B.match(i,{onNone:()=>({auth:"unknown"}),onSome:t.statusOf});return{...zZo(l,a),binary:{found:!0,...r,...ZBr(o)},...B.match(c,{onNone:()=>({}),onSome:u=>({workerPrompt:u})})}}),JZo=e=>s.fn("VendorCli.detect")(function*(t,r={}){let n=t===de.claudeCode?HZo:BZo,o=yield*YBr(e,n.command);return B.isNone(o)?{auth:"unknown",binary:{found:!1}}:yield*XZo(e,n,{found:o.value,options:r})}),YZo=e=>Object.fromEntries(DZo.flatMap(t=>{let r=e[t];return r===void 0?[]:[[t,r]]})),ZZo=(e,t)=>e.fileSystem.stream(t).pipe(Ge.runFold(()=>LZo("sha256"),(r,n)=>r.update(n)),s.map(r=>r.digest("hex"))),QZo=(e,t)=>r=>s.gen(function*(){let n=yield*e.fileSystem.stat(r),o=[B.getOrElse(n.ino,()=>-1),n.dev,String(n.size),B.match(n.mtime,{onNone:()=>"",onSome:l=>l.toISOString()})].join(":"),i=(yield*fe.get(t)).get(r);if(i?.key===o)return B.some(i.sha256);let a=yield*ZZo(e,r),c=[r,{key:o,sha256:a}];return yield*fe.update(t,l=>new Map([...l,c].slice(-FZo))),B.some(a)}).pipe(s.orElseSucceed(()=>B.none())),PNe=e=>s.gen(function*(){let t=e.environment.HOME,r={codexWorkerPromptArguments:e.codexWorkerPromptArguments,environment:YZo(e.environment),fileSystem:yield*ve.FileSystem,...t===void 0||t===""?{}:{home:t},path:e.environment.PATH??"",spawner:yield*Pa,systemDirectories:e.systemDirectories??XBr,timeout:e.timeout??MZo},n=yield*Ut.make(2),o=JZo(r),i=yield*fe.make(new Map);return{detect:(a,c)=>n.withPermits(1)(o(a,c)),sha256:QZo(r,i)}});var QBr=()=>f("authentication_failed","Connections require an authenticated operator without an Invocation attachment."),n_t=s.fn("Connection.ensureConfigRoot")(function*(e){if(!("connection"in e))return;let{configRoot:t}=e.connection;t.kind==="maia-managed"&&(yield*s.tryPromise({catch:()=>f("storage_failed","The connection config root could not be prepared."),try:()=>eQo(t.path,{mode:448,recursive:!0})}))}),ik=e=>s.fail(f("configuration_invalid",e)),tQo=(e,t)=>e.revision!==t.parameters.expectedRevision?s.fail(f("storage_conflict","The connection changed since the expected revision.",!0)):e.executor==="gateway"?ik("A gateway connection signs in with its API key: run 'maia login gateway' for a new one."):e.state!=="enabled"?ik("Enable the connection before signing in."):e.configRoot.kind!=="maia-managed"?ik("A system-default account signs in with the vendor CLI itself; Maia signs in Maia-managed roots only."):s.void,rQo=s.fn("Connection.startLogin")(function*(e,t,r){let n=yield*e.database.replayConnectionLogin(t,r);if(n!==void 0)return n;let o=yield*e.database.readConnection(r.parameters.connectionId);yield*tQo(o,r);let i=e.connectionUsage;if(i===void 0)return yield*s.fail(f("command_not_implemented","This Node cannot start vendor sign-ins."));let a=yield*i.startLogin(o,r.parameters.flow);return yield*e.database.recordConnectionLogin(t,r,a)}),tqr=(e,t,r)=>t.refresh(r).pipe(s.flatMap(n=>e.database.recordConnectionUsage(r.connectionId,n))),nQo=s.fn("Connection.showUsage")(function*(e,t,r){let n=yield*e.database.readConnection(r.parameters.connectionId);if(n.executor==="gateway")return yield*ik("A gateway connection reports no account usage; the gateway keeps its own quotas.");let o=e.connectionUsage;return r.parameters.refresh===!0&&o!==void 0&&(yield*tqr(e,o,n)),yield*e.database.executeConnectionRequest(t,r)}),oQo=(e,t)=>{let{secrets:r}=e;return r===void 0?s.fail(f("command_not_implemented","This Node has no secret store for gateway keys.")):Buffer.byteLength(t)>r.maximumBytes?ik(`The gateway API key is over the ${String(r.maximumBytes)}-byte limit of this Node's secret store.`):s.succeed(r)},iQo=(e,t,r)=>e===void 0||r===void 0?s.succeed("referenced"):e.put(r7(t),Dn.make(r)),sQo=s.fn("Connection.createGateway")(function*(e,t,r){let{apiKey:n}=r.parameters,o=n===void 0?void 0:yield*oQo(e,n),i=yield*e.database.executeConnectionRequest(t,r);if(yield*n_t(i),i.method!=="connection.gateway.create"||i.connection.configRoot.kind!=="maia-managed")return yield*s.fail(f("storage_corrupt","The gateway record has no Maia-managed root for its key."));let a=yield*iQo(o,i.connection.connectionId,n);return{...i,keyCustody:a}}),aQo=s.fn("Connection.listModels")(function*(e,t){let r=yield*e.database.readConnection(t.parameters.connectionId);if(r.executor!=="gateway")return yield*ik("A vendor account has no gateway model list; it uses the vendor's catalog.");if(r.state!=="enabled")return yield*ik("Enable the gateway connection before listing models.");let n=e.gatewayModels;if(n===void 0)return yield*s.fail(f("command_not_implemented","This Node cannot reach gateways."));let o=yield*Sz(e.secrets,r);return B.isNone(o)?yield*ik("Not a gateway connection."):yield*n.list({...o.value,connectionId:r.connectionId})}),cQo=e=>e.method==="connection.detect"||e.method.startsWith("connection.system.")||e.method.startsWith("connection.upkeep."),dQo=(e,t,r)=>{switch(r.method){case"connection.detect":return jRt(e,r.parameters);case"connection.system.confirm":return $Rt(e,t,r.parameters);case"connection.system.preview":return WRt(e,t,r.parameters);case"connection.upkeep.confirm":return YRt(e,t,r.parameters);case"connection.upkeep.preview":return JRt(e,t,r.parameters);case"connection.upkeep.refresh":return XRt(e)}},lQo=(e,t,r)=>e.systemSetup===void 0?s.fail(f("command_not_implemented","This Node cannot detect vendor CLIs.")):dQo({...e.systemSetup,database:e.database},t,r),eqr=e=>{let{connectionUsage:t,database:r,executors:n}=e;return{...n===void 0?{}:{executors:n},listExecutorConnections:r.listExecutorConnections,...t===void 0?{}:{refreshUsage:o=>tqr(e,t,o)}}},uQo=(e,t,r)=>cQo(r)?lQo(e,t,r):r.method==="connection.gateway.create"?sQo(e,t,r):r.method==="connection.executors.list"?e0r(eqr(e),r.parameters):r.method==="connection.executors.show"?t0r(eqr(e),r.parameters):r.method==="connection.models.list"?aQo(e,r):r.method==="connection.login.start"?rQo(e,t,r):r.method==="connection.usage.show"?nQo(e,t,r):e.database.executeConnectionRequest(t,r),o_t=s.fn("Connection.executeRequest")(function*(e,t,r){if(r!==void 0)return yield*s.fail(QBr());let n=yield*vn(e.profile);if(n.attachmentUsed||n.principal.kind!=="client")return yield*s.fail(QBr());let o=yield*uQo(e,n.actorId,t);return t.method==="connection.create"&&(yield*n_t(o)),o});var i_t=e=>e.method.startsWith("connection."),e2="connection",aS=JSON.parse("null");F();import{randomUUID as jQo}from"node:crypto";import{join as WQo}from"node:path";Z();import{createHash as yQo}from"node:crypto";Z();Z();F();z();var pQo=d.Struct({configRootKind:d.Literals(["maia-managed","system-default"]),configRootPath:d.NullOr(d.String),connectionId:d.String,createdAt:d.String,executor:d.Literals(Ts),gatewayBaseUrl:d.NullOr(d.String),gatewayKeyEnv:d.NullOr(d.String),limitedUntil:d.NullOr(d.String),maxConcurrentSessions:d.Number,name:d.String,revision:d.Number,sequence:d.Number,state:d.Literals(["disabled","enabled"]),updatedAt:d.String,usageJson:d.NullOr(d.String)}),mQo=d.decodeUnknownSync(pQo,{onExcessProperty:"error"}),ONe=["connections.sequence","connections.connection_id AS connectionId","connections.name","connections.executor","connections.config_root_kind AS configRootKind","connections.config_root_path AS configRootPath","connections.state","connections.max_concurrent_sessions AS maxConcurrentSessions","connections.limited_until AS limitedUntil","connections.revision","connections.created_at AS createdAt","connections.updated_at AS updatedAt","connection_usage.usage_json AS usageJson","connection_gateways.base_url AS gatewayBaseUrl","connection_gateways.key_env AS gatewayKeyEnv"].join(", "),LNe=`connections
8766
8766
  LEFT JOIN connection_usage USING (connection_id)
8767
- LEFT JOIN connection_gateways USING (connection_id)`,fQo=e=>e.gatewayBaseUrl===null?{executor:e.executor}:{executor:"gateway",gateway:{baseUrl:e.gatewayBaseUrl,...e.gatewayKeyEnv===null?{}:{keyEnv:e.gatewayKeyEnv}}},hQo=e=>Uy.parse({configRoot:e.configRootKind==="maia-managed"?{kind:"maia-managed",path:e.configRootPath}:{kind:"system-default"},connectionId:e.connectionId,createdAt:e.createdAt,...fQo(e),limitedUntil:e.limitedUntil??aS,maxConcurrentSessions:e.maxConcurrentSessions,name:e.name,revision:String(e.revision),schemaVersion:Ip,state:e.state,updatedAt:e.updatedAt,...e.usageJson===null?{}:{usage:_u.parse(JSON.parse(e.usageJson))}}),DNe=e=>{try{let t=mQo(e);return{connection:hQo(t),sequence:t.sequence}}catch{throw f("storage_corrupt","A stored connection record is invalid.")}},K7=(e,t)=>{let r=e.prepare(`SELECT ${ONe} FROM ${LNe} WHERE connection_id = ?`).get(t);return r===void 0?void 0:DNe(r)},Lu=(e,t)=>{let r=K7(e,t);if(r===void 0)throw f("resource_not_found","The connection does not exist.");return r},sk=(e,t)=>Lu(e,t).connection,s_t=e=>f("configuration_invalid",e),X7=(e,t)=>{if(e.executor==="gateway"){if(t.executor===void 0)throw s_t("A gateway connection serves any executor: name one with 'executor' (--harness).");return t.executor}if(t.executor!==void 0&&t.executor!==e.executor)throw s_t(`The connection is a ${e.executor} account, not ${t.executor}.`);if(t.model!==void 0&&!$B(e.executor))throw s_t(`The ${e.executor} executor takes no model; it uses its own default.`);return e.executor},J7=(e,t)=>{let r=sk(e,t.connectionId);if(r.state!=="enabled")throw f("storage_conflict","The executor connection is disabled.");return X7(r,t)},jD=(e,t)=>e.prepare(`SELECT ${ONe} FROM ${LNe}
8767
+ LEFT JOIN connection_gateways USING (connection_id)`,fQo=e=>e.gatewayBaseUrl===null?{executor:e.executor}:{executor:"gateway",gateway:{baseUrl:e.gatewayBaseUrl,...e.gatewayKeyEnv===null?{}:{keyEnv:e.gatewayKeyEnv}}},hQo=e=>Uy.parse({configRoot:e.configRootKind==="maia-managed"?{kind:"maia-managed",path:e.configRootPath}:{kind:"system-default"},connectionId:e.connectionId,createdAt:e.createdAt,...fQo(e),limitedUntil:e.limitedUntil??aS,maxConcurrentSessions:e.maxConcurrentSessions,name:e.name,revision:String(e.revision),schemaVersion:Ip,state:e.state,updatedAt:e.updatedAt,...e.usageJson===null?{}:{usage:_u.parse(JSON.parse(e.usageJson))}}),DNe=e=>{try{let t=mQo(e);return{connection:hQo(t),sequence:t.sequence}}catch{throw f("storage_corrupt","A stored connection record is invalid.")}},K7=(e,t)=>{let r=e.prepare(`SELECT ${ONe} FROM ${LNe} WHERE connection_id = ?`).get(t);return r===void 0?void 0:DNe(r)},Lu=(e,t)=>{let r=K7(e,t);if(r===void 0)throw f("resource_not_found","The connection does not exist.");return r},sk=(e,t)=>Lu(e,t).connection,s_t=e=>f("configuration_invalid",e),X7=(e,t)=>{if(e.executor==="gateway"){if(t.executor===void 0)throw s_t("A gateway connection serves any executor: name one with 'executor' (--harness).");return t.executor}if(t.executor!==void 0&&t.executor!==e.executor)throw s_t(`The connection is a ${e.executor} account, not ${t.executor}.`);if(t.model!==void 0&&!$B(e.executor))throw s_t(`The ${e.executor} executor takes no model; it uses its own default.`);return e.executor},J7=(e,t)=>{let r=sk(e,t.connectionId);if(r.state!=="enabled")throw f("configuration_invalid","The executor connection is disabled. Enable the connection or choose another one.");return X7(r,t)},jD=(e,t)=>e.prepare(`SELECT ${ONe} FROM ${LNe}
8768
8768
  WHERE connections.executor = ? AND connection_gateways.connection_id IS NULL
8769
8769
  ORDER BY connections.sequence`).all(t).map(r=>DNe(r).connection),gQo=e=>e===de.claudeCode?["claude","claude-system"]:["codex","codex-system"],rqr=(e,t)=>{let r=jD(e,t).find(i=>i.configRoot.kind==="system-default");if(r!==void 0)return{existing:r};let n=e.prepare("SELECT 1 FROM connections WHERE name = ?"),o=gQo(t).find(i=>n.get(i)===void 0);return o===void 0?{}:{freeName:o}};var SQo="actor_maia_node",EQo=e=>{let t=yQo("sha256").update(JSON.stringify(["maia.connection/limit/v1",e.connectionId,e.limitedUntil])).digest("hex");return{actorId:SQo,commandId:`connection.limit.${t.slice(0,48)}`,method:"connection.limit.record",requestDigest:t}},RQo=(e,t,r)=>{e.database.prepare(`UPDATE connections SET limited_until = ?, revision = revision + 1, updated_at = ?
8770
8770
  WHERE connection_id = ? AND revision = ?`).run(r,e.now,t.connectionId,Number(t.revision))},_Qo=(e,t,r)=>({...e,aggregateId:t.connectionId,aggregateType:e2,eventPayloadJson:JSON.stringify({connectionId:t.connectionId,limitedUntil:r.limitedUntil}),eventType:"connection.limit.recorded",expectedRevision:BigInt(t.revision),resultJson:JSON.stringify(r),targetId:t.connectionId,targetType:e2}),nqr=(e,t)=>{let r=EQo(t);if(Pe(e.database,r)!==void 0)return;let{connection:n}=Lu(e.database,t.connectionId),o=Uy.parse({...n,limitedUntil:t.limitedUntil,revision:(BigInt(n.revision)+1n).toString(),updatedAt:e.now});Nt({database:e.database,input:_Qo(r,n,o),mutate:()=>{RQo(e,n,t.limitedUntil)},recordedAt:e.now})};Z();import{join as oqr}from"node:path";z();import{createHash as vQo}from"node:crypto";var TQo=e=>[e.commandId,e.name,e.baseUrl,e.maxConcurrentSessions??aS,e.apiKeyEnv??aS],IQo=e=>{if(e.method==="connection.create"){let n=e.parameters;return[n.commandId,n.name,n.executor,n.configRootKind,n.maxConcurrentSessions??aS]}if(e.method==="connection.gateway.create")return TQo(e.parameters);let t=e.parameters,r=[t.commandId,t.connectionId,t.expectedRevision];switch(e.method){case"connection.capacity.set":return[...r,e.parameters.maxConcurrentSessions];case"connection.login.start":return[...r,e.parameters.flow];case"connection.state.set":return[...r,e.parameters.state]}},a_t=(e,t)=>({actorId:e,commandId:t.parameters.commandId,method:t.method,requestDigest:vQo("sha256").update(JSON.stringify(["maia.connection/command/v1",e,t.method,IQo(t)])).digest("hex")});var iqr=Bp.defaultAccountSessions,MNe=(e,t)=>{if(e.database.prepare(`SELECT 1 FROM connections WHERE name = ?
@@ -8856,7 +8856,7 @@ ${t.expiresAt}`).digest("base64url"),_si=(e,t)=>t===void 0?{expiresAt:new Date(D
8856
8856
  VALUES (?, ?, ?, NULLIF(?, ''), NULLIF(?, ''), ?)`).run(t.sessionId,t.executor.kind,t.executor.connectionId,t.executor.model??"",t.executor.effort??"",t.recordedAt)};F();z();F();z();var Sai=d.Struct({value:d.Number}),Eai=d.decodeUnknownSync(Sai),qvt=(e,t)=>Eai(e.prepare(`SELECT count(*) AS value FROM session_runtime_activations AS activation
8857
8857
  JOIN session_executor_bindings AS binding USING (session_id)
8858
8858
  WHERE binding.connection_id = ?
8859
- AND activation.status IN ('queued', 'launching', 'recovering', 'ready')`).get(t)).value,jvt=(e,t,r)=>{let n=sk(e,t.connectionId);if(n.state!=="enabled")throw f("storage_conflict","The executor connection is disabled.");if(n.limitedUntil!==null&&n.limitedUntil>r)throw ai("account",`The executor connection is limited until ${n.limitedUntil}.`);if(qvt(e,t.connectionId)>=n.maxConcurrentSessions)throw ai("account","The executor connection has no free Session slot.")};var Rai=10,mWr=(e,t)=>(e.usage?.windows??[]).filter(r=>r.kind!=="other"&&(r.resetsAt===void 0||r.resetsAt>t)),Wvt=(e,t)=>Math.max(0,...mWr(e,t).map(r=>r.usedPercent)),yPe=(e,t)=>{let{connection:r,live:n}=e;return r.state!=="enabled"?"disabled":r.usage?.unavailable?.reason==="signed_out"?"signed_out":r.limitedUntil!==null&&r.limitedUntil>t?"limited":Wvt(r,t)>=100?"exhausted":n<r.maxConcurrentSessions?void 0:"full"},_ai=(e,t)=>e===t?0:e<t?-1:1,$vt=e=>e.connection.maxConcurrentSessions-e.live-e.pending,pWr=e=>$vt(e)>0?0:1,vai=(e,t)=>e.filter(r=>yPe(r,t)===void 0).toSorted((r,n)=>pWr(r)-pWr(n)||Wvt(r.connection,t)-Wvt(n.connection,t)||$vt(n)-$vt(r)||_ai(r.connection.name,n.connection.name))[0],Tai=d.Struct({value:d.Number}),Iai=d.decodeUnknownSync(Tai),xai=e=>new Date(Date.parse(e)-Rai*6e4).toISOString(),Aai=(e,t,r)=>Iai(e.prepare(`SELECT count(*) AS value FROM session_executor_bindings AS binding
8859
+ AND activation.status IN ('queued', 'launching', 'recovering', 'ready')`).get(t)).value,jvt=(e,t,r)=>{let n=sk(e,t.connectionId);if(n.state!=="enabled")throw f("configuration_invalid","The executor connection is disabled. Enable the connection or choose another one.");if(n.limitedUntil!==null&&n.limitedUntil>r)throw ai("account",`The executor connection is limited until ${n.limitedUntil}.`);if(qvt(e,t.connectionId)>=n.maxConcurrentSessions)throw ai("account","The executor connection has no free Session slot.")};var Rai=10,mWr=(e,t)=>(e.usage?.windows??[]).filter(r=>r.kind!=="other"&&(r.resetsAt===void 0||r.resetsAt>t)),Wvt=(e,t)=>Math.max(0,...mWr(e,t).map(r=>r.usedPercent)),yPe=(e,t)=>{let{connection:r,live:n}=e;return r.state!=="enabled"?"disabled":r.usage?.unavailable?.reason==="signed_out"?"signed_out":r.limitedUntil!==null&&r.limitedUntil>t?"limited":Wvt(r,t)>=100?"exhausted":n<r.maxConcurrentSessions?void 0:"full"},_ai=(e,t)=>e===t?0:e<t?-1:1,$vt=e=>e.connection.maxConcurrentSessions-e.live-e.pending,pWr=e=>$vt(e)>0?0:1,vai=(e,t)=>e.filter(r=>yPe(r,t)===void 0).toSorted((r,n)=>pWr(r)-pWr(n)||Wvt(r.connection,t)-Wvt(n.connection,t)||$vt(n)-$vt(r)||_ai(r.connection.name,n.connection.name))[0],Tai=d.Struct({value:d.Number}),Iai=d.decodeUnknownSync(Tai),xai=e=>new Date(Date.parse(e)-Rai*6e4).toISOString(),Aai=(e,t,r)=>Iai(e.prepare(`SELECT count(*) AS value FROM session_executor_bindings AS binding
8860
8860
  JOIN sessions USING (session_id)
8861
8861
  LEFT JOIN session_runtime_activations AS activation USING (session_id)
8862
8862
  WHERE binding.connection_id = ?
@@ -11890,6 +11890,6 @@ planned and unavailable.
11890
11890
  `);return}r.stdout(yCa(e))},SCa=(e,t,r)=>{if(t){r.stderr(`${JSON.stringify({error:e,ok:!1})}
11891
11891
  `);return}r.stderr(`maia-node: ${e.message}
11892
11892
  Run 'maia-node --help' for usage.
11893
- `)},Id=e=>({code:"invalid_argument",message:e,retryable:!1}),tqe=e=>e.replaceAll(/[\p{C}]/gu,"\uFFFD"),ECa=e=>({code:"command_not_implemented",message:`Command '${tqe(e)}' is not implemented.`,retryable:!1}),uCn="The start, help and version forms accept no additional arguments.",pCn="--desktop",RCa=e=>{if(e.length>cCn)return Id(`At most ${String(cCn)} arguments are allowed.`);if(e.some(t=>t.length>dCn))return Id(`Arguments must be at most ${String(dCn)} characters.`)},mCn=()=>Id(l6),_Ca=(e,t)=>{let[r,n,o,i,...a]=e;if(r==="state")return n!=="check"?Id("Use 'maia-node state check [--profile <name>] [--json]'."):o===void 0?{command:"state-check",json:t,profile:cCa}:o!=="--profile"||a.length>0?Id("State check accepts only '--profile <name>' and '--json', each once."):i===void 0?Id("Option '--profile' requires a profile name."):z0(i)?{command:"state-check",json:t,profile:i}:mCn()},vCa=(e,t)=>Id(t?`Option '--profile' cannot come before '${tqe(e)}'; put it after the command.`:`Option '--profile' starts the Node and cannot be used with '${tqe(e)}'.`),TCa=(e,t)=>{let r=e.filter(c=>c==="--profile").length;if(r===0)return;if(r>1)return Id("Option '--profile' may be used only once.");let n=e.indexOf("--profile"),o=e[n+1];if(o===void 0)return Id("Option '--profile' requires a profile name.");if(!z0(o))return mCn();let i=e.filter((c,l)=>l!==n&&l!==n+1),a=i.find(c=>c!==pCn);return a!==void 0?vCa(a,e.indexOf(a)>n):i.length>1?Id(uCn):{command:"desktop",json:t,profile:o}},ICa=(e,t)=>{let r=_Ca(e,t)??TCa(e,t);if(r!==void 0)return r;if(e.length>1)return Id(uCn);let n=e[0];return n===void 0||n===pCn?{command:"desktop",json:t}:lCa.has(n)?{command:"help",json:t}:uCa.has(n)?{command:"version",json:t}:n.startsWith("-")?Id(`Unknown option '${tqe(n)}'.`):ECa(n)},xCa=e=>{let t=e.filter(o=>o==="--json").length;if(t>1)return Id("Option '--json' may be used only once.");let r=e.filter(o=>o===eqe).length;if(r>1)return Id(`Option '${eqe}' may be used only once.`);let n=ICa(e.filter(o=>o!=="--json"&&o!==eqe),t===1);return r===0||fCn(n)?n:n.command==="desktop"?{...n,bootstrapChannel:!0}:Id(`Option '${eqe}' may be used only when starting the Node.`)},fCn=e=>"code"in e,X0=e=>(SCa(e.error,e.json,e.io),e.exitCode??dCa),ACa=(e,t)=>({...e.bootstrapChannel===!0?{bootstrapChannel:!0}:{},io:t.io,...t.nativeProcessHostIdentity===void 0?{}:{nativeProcessHostIdentity:t.nativeProcessHostIdentity},...t.nodeExecutablePath===void 0?{}:{nodeExecutablePath:t.nodeExecutablePath},...e.profile===void 0?{}:{profile:e.profile},version:t.version,...t.runtimeRootOverride===void 0?{}:{runtimeRootOverride:t.runtimeRootOverride}}),bCa=(e,t)=>(t.dependencies??{startDesktop:d6}).startDesktop(ACa(e,t)).pipe(s.as(0),s.catch(n=>s.sync(()=>X0({error:yc(n),exitCode:n.retryable?lCn:EWt,io:t.io,json:e.json})))),CCa=(e,t)=>sCn({profile:e.profile,...t.runtimeRootOverride===void 0?{}:{runtimeRootOverride:t.runtimeRootOverride},version:t.version}).pipe(s.provide(Rr),s.map(r=>(RWt(r,e.json,t.io),0)),s.catch(r=>s.sync(()=>X0({error:yc(r),exitCode:EWt,io:t.io,json:e.json})))),kCa=e=>({...e.releaseHome===void 0?{}:{home:e.releaseHome},...e.releasePlatform===void 0?{}:{platform:e.releasePlatform},...e.runtimeRootOverride===void 0?{}:{runtimeRootOverride:e.runtimeRootOverride}}),wCa=(e,t,r)=>X0(typeof e=="string"?{error:Id(e),io:r.io,json:t.json}:{error:yc(e),exitCode:e.retryable?lCn:EWt,io:r.io,json:t.json}),NCa=(e,t)=>Lbn(e).pipe(s.flatMap(r=>Dbn(r,kCa(t))),s.provide(t.releaseServices??Mbn),s.map(r=>(RWt(r,e.json,t.io),0)),s.catch(r=>s.sync(()=>wCa(r,e,t)))),PCa=(e,t)=>{let r=Obn(e);if(typeof r!="string")return NCa(r,t);let n=e.includes("--json");return s.sync(()=>X0({error:Id(r),io:t.io,json:n}))},OCa=(e,t)=>e.command==="desktop"?bCa(e,t):e.command==="state-check"?CCa(e,t):s.sync(()=>{let r=e.command==="help"?fCa(t.version):hCa(t.version);return RWt(r,e.json,t.io),0}),LCa=(e,t)=>{let r=rjt(e);return typeof r=="string"?s.sync(()=>X0({error:Id(r),io:t.io,json:e.includes("--json")})):njt(r,{io:t.io,release:q7({...t.releaseHome===void 0?{}:{home:t.releaseHome},version:t.version}),...t.runtimeRootOverride===void 0?{}:{runtimeRootOverride:t.runtimeRootOverride},version:t.version}).pipe(s.provide(t.remotePlatform??$_))},DCa=(e,t)=>iCn(e,{...t.releaseHome===void 0?{}:{home:t.releaseHome},...t.serviceHost===void 0?{}:{host:t.serviceHost},io:t.io,...t.serviceServices===void 0?{}:{services:t.serviceServices}}),rqe=(e,t)=>{if(e[0]==="bridge"||e[0]==="remote")return LCa(e,t);let r=i=>s.sync(()=>X0({error:i,io:t.io,json:e.includes("--json")})),n=RCa(e);if(n!==void 0)return r(n);if(e[0]==="release")return PCa(e,t);if(e[0]==="service")return DCa(e,t);let o=xCa(e);return fCn(o)?r(o):OCa(o,t)};F();var hCn=1e4,h6=class extends ot.Service()("maia/ShutdownDeadline"){},$se=class extends ot.Service()("maia/DesktopParent"){static layer=$e.effect(this,s.gen(function*(){return{closed:(yield*tT.Stdio).stdin.pipe(Ge.runDrain,s.ignore,s.ensuring(s.sync(()=>{process.stdin.destroy()}))),forceExit:s.sync(()=>{process.kill(process.pid,"SIGKILL")})}})).pipe($e.provide(r6))},gCn=e=>s.gen(function*(){let t=yield*$se,r=yield*e.pipe(s.forkChild),n=s.gen(function*(){yield*t.closed;let o=yield*s.serviceOption(h6);if(B.isSome(o)){let i=Number((yield*De.monotonicTimeNanos)/1000000n);yield*fe.set(o.value,i+hCn)}return yield*uo.interrupt(r).pipe(s.forkChild),yield*s.sleep(hCn),yield*t.forceExit,yield*s.never});return yield*uo.join(r).pipe(s.raceFirst(n))}),_Wt=e=>s.gen(function*(){return yield*(yield*no.String("MAIA_DESKTOP_PARENT_PIPE").pipe(no.withDefault("0"),s.orDie))==="1"?gCn(e).pipe(s.provide($se.layer)):e});z();dXe();var yCn=cXe(({fiber:e,teardown:t})=>{let r=!1;e.addObserver(o=>{process.removeListener("SIGINT",n),process.removeListener("SIGTERM",n),t(o,i=>{(r||i!==0)&&process.exit(i)})});function n(){r=!0,e.interruptUnsafe(e.id)}process.on("SIGINT",n),process.on("SIGTERM",n)});F();var UCa=5e3,SCn=e=>s.gen(function*(){let t=yield*Q.make(),r=()=>{Q.doneUnsafe(t,s.succeed(!0))};e.on("error",r),e.on("close",r);let n=s.callback(o=>{if(e.writableLength===0){o(s.succeed(!0));return}e.write("",()=>{o(s.succeed(!0))})});return s.raceFirst(Q.await(t),n)}),FCa=e=>xt.isSuccess(e)?e.value:_r.hasInterruptsOnly(e.cause)?0:GH.getErrorExitCode(_r.squash(e.cause)),HCa=(e,t)=>s.gen(function*(){let r=Number((yield*De.monotonicTimeNanos)/1000000n),n=(yield*fe.get(t))-r;return yield*s.all(e,{concurrency:"unbounded",discard:!0}).pipe(s.timeoutOption(Math.min(UCa,n)))}),BCa=(e,t)=>s.uninterruptibleMask(r=>s.gen(function*(){let n=[yield*SCn(t.stdout),yield*SCn(t.stderr)];yield*s.yieldNow;let o=yield*Q.make(),i=yield*fe.make(Number.POSITIVE_INFINITY),a=yield*s.forkChild(e.pipe(s.onExit(p=>Q.succeed(o,p)),s.provideService(h6,i)),{startImmediately:!0});yield*s.exit(r(uo.await(a))),yield*uo.interrupt(a);let c=yield*Q.await(o),l=FCa(c),u=yield*HCa(n,i);(l!==0||xt.isFailure(c)||B.isNone(u))&&t.exit(l)})),qCa=(e,t)=>{if(xt.isFailure(e)&&!_r.hasInterruptsOnly(e.cause)){GH.defaultTeardown(e,t);return}t(0)},ECn=(e,t)=>{yCn(BCa(e,t),{disableErrorReporting:!0,teardown:qCa})};var WCa=()=>({nodeVersion:"24.22.1",version:"0.1.0-canary.72"}),nqe=WCa(),vWt={stderr(e){process.stderr.write(e)},stdout(e){process.stdout.write(e)}},RCn=void 0,_Cn=jCa(import.meta.url),$Ca=e=>s.try({catch:t=>f("transport_failed",t instanceof Error?t.message:String(t)),try:GAe}).pipe(s.bindTo("nativeProcessHostIdentity"),s.bind("headlessApprovals",()=>wdt),s.flatMap(({headlessApprovals:t,nativeProcessHostIdentity:r})=>d6({...e,afterProfileLock:n=>sRt({modulePath:_Cn,profile:n,running:nqe.version}).pipe(s.provide(Rr)),headlessApprovals:t,...r===void 0?{}:{nativeProcessHostIdentity:r,nodeExecutablePath:_Cn}})));if(process.versions.node===nqe.nodeVersion){let e=rqe(process.argv.slice(2),{dependencies:{startDesktop:t=>$Ca(t).pipe(_Wt)},io:vWt,...RCn===void 0?{}:{runtimeRootOverride:RCn},version:nqe.version});ECn(kdt(process.argv.slice(2),vWt.stderr)(e).pipe(s.provide(Rr)),process)}else vWt.stderr(`Maia Node requires Node ${nqe.nodeVersion}; received ${process.versions.node}.
11893
+ `)},Id=e=>({code:"invalid_argument",message:e,retryable:!1}),tqe=e=>e.replaceAll(/[\p{C}]/gu,"\uFFFD"),ECa=e=>({code:"command_not_implemented",message:`Command '${tqe(e)}' is not implemented.`,retryable:!1}),uCn="The start, help and version forms accept no additional arguments.",pCn="--desktop",RCa=e=>{if(e.length>cCn)return Id(`At most ${String(cCn)} arguments are allowed.`);if(e.some(t=>t.length>dCn))return Id(`Arguments must be at most ${String(dCn)} characters.`)},mCn=()=>Id(l6),_Ca=(e,t)=>{let[r,n,o,i,...a]=e;if(r==="state")return n!=="check"?Id("Use 'maia-node state check [--profile <name>] [--json]'."):o===void 0?{command:"state-check",json:t,profile:cCa}:o!=="--profile"||a.length>0?Id("State check accepts only '--profile <name>' and '--json', each once."):i===void 0?Id("Option '--profile' requires a profile name."):z0(i)?{command:"state-check",json:t,profile:i}:mCn()},vCa=(e,t)=>Id(t?`Option '--profile' cannot come before '${tqe(e)}'; put it after the command.`:`Option '--profile' starts the Node and cannot be used with '${tqe(e)}'.`),TCa=(e,t)=>{let r=e.filter(c=>c==="--profile").length;if(r===0)return;if(r>1)return Id("Option '--profile' may be used only once.");let n=e.indexOf("--profile"),o=e[n+1];if(o===void 0)return Id("Option '--profile' requires a profile name.");if(!z0(o))return mCn();let i=e.filter((c,l)=>l!==n&&l!==n+1),a=i.find(c=>c!==pCn);return a!==void 0?vCa(a,e.indexOf(a)>n):i.length>1?Id(uCn):{command:"desktop",json:t,profile:o}},ICa=(e,t)=>{let r=_Ca(e,t)??TCa(e,t);if(r!==void 0)return r;if(e.length>1)return Id(uCn);let n=e[0];return n===void 0||n===pCn?{command:"desktop",json:t}:lCa.has(n)?{command:"help",json:t}:uCa.has(n)?{command:"version",json:t}:n.startsWith("-")?Id(`Unknown option '${tqe(n)}'.`):ECa(n)},xCa=e=>{let t=e.filter(o=>o==="--json").length;if(t>1)return Id("Option '--json' may be used only once.");let r=e.filter(o=>o===eqe).length;if(r>1)return Id(`Option '${eqe}' may be used only once.`);let n=ICa(e.filter(o=>o!=="--json"&&o!==eqe),t===1);return r===0||fCn(n)?n:n.command==="desktop"?{...n,bootstrapChannel:!0}:Id(`Option '${eqe}' may be used only when starting the Node.`)},fCn=e=>"code"in e,X0=e=>(SCa(e.error,e.json,e.io),e.exitCode??dCa),ACa=(e,t)=>({...e.bootstrapChannel===!0?{bootstrapChannel:!0}:{},io:t.io,...t.nativeProcessHostIdentity===void 0?{}:{nativeProcessHostIdentity:t.nativeProcessHostIdentity},...t.nodeExecutablePath===void 0?{}:{nodeExecutablePath:t.nodeExecutablePath},...e.profile===void 0?{}:{profile:e.profile},version:t.version,...t.runtimeRootOverride===void 0?{}:{runtimeRootOverride:t.runtimeRootOverride}}),bCa=(e,t)=>(t.dependencies??{startDesktop:d6}).startDesktop(ACa(e,t)).pipe(s.as(0),s.catch(n=>s.sync(()=>X0({error:yc(n),exitCode:n.retryable?lCn:EWt,io:t.io,json:e.json})))),CCa=(e,t)=>sCn({profile:e.profile,...t.runtimeRootOverride===void 0?{}:{runtimeRootOverride:t.runtimeRootOverride},version:t.version}).pipe(s.provide(Rr),s.map(r=>(RWt(r,e.json,t.io),0)),s.catch(r=>s.sync(()=>X0({error:yc(r),exitCode:EWt,io:t.io,json:e.json})))),kCa=e=>({...e.releaseHome===void 0?{}:{home:e.releaseHome},...e.releasePlatform===void 0?{}:{platform:e.releasePlatform},...e.runtimeRootOverride===void 0?{}:{runtimeRootOverride:e.runtimeRootOverride}}),wCa=(e,t,r)=>X0(typeof e=="string"?{error:Id(e),io:r.io,json:t.json}:{error:yc(e),exitCode:e.retryable?lCn:EWt,io:r.io,json:t.json}),NCa=(e,t)=>Lbn(e).pipe(s.flatMap(r=>Dbn(r,kCa(t))),s.provide(t.releaseServices??Mbn),s.map(r=>(RWt(r,e.json,t.io),0)),s.catch(r=>s.sync(()=>wCa(r,e,t)))),PCa=(e,t)=>{let r=Obn(e);if(typeof r!="string")return NCa(r,t);let n=e.includes("--json");return s.sync(()=>X0({error:Id(r),io:t.io,json:n}))},OCa=(e,t)=>e.command==="desktop"?bCa(e,t):e.command==="state-check"?CCa(e,t):s.sync(()=>{let r=e.command==="help"?fCa(t.version):hCa(t.version);return RWt(r,e.json,t.io),0}),LCa=(e,t)=>{let r=rjt(e);return typeof r=="string"?s.sync(()=>X0({error:Id(r),io:t.io,json:e.includes("--json")})):njt(r,{io:t.io,release:q7({...t.releaseHome===void 0?{}:{home:t.releaseHome},version:t.version}),...t.runtimeRootOverride===void 0?{}:{runtimeRootOverride:t.runtimeRootOverride},version:t.version}).pipe(s.provide(t.remotePlatform??$_))},DCa=(e,t)=>iCn(e,{...t.releaseHome===void 0?{}:{home:t.releaseHome},...t.serviceHost===void 0?{}:{host:t.serviceHost},io:t.io,...t.serviceServices===void 0?{}:{services:t.serviceServices}}),rqe=(e,t)=>{if(e[0]==="bridge"||e[0]==="remote")return LCa(e,t);let r=i=>s.sync(()=>X0({error:i,io:t.io,json:e.includes("--json")})),n=RCa(e);if(n!==void 0)return r(n);if(e[0]==="release")return PCa(e,t);if(e[0]==="service")return DCa(e,t);let o=xCa(e);return fCn(o)?r(o):OCa(o,t)};F();var hCn=1e4,h6=class extends ot.Service()("maia/ShutdownDeadline"){},$se=class extends ot.Service()("maia/DesktopParent"){static layer=$e.effect(this,s.gen(function*(){return{closed:(yield*tT.Stdio).stdin.pipe(Ge.runDrain,s.ignore,s.ensuring(s.sync(()=>{process.stdin.destroy()}))),forceExit:s.sync(()=>{process.kill(process.pid,"SIGKILL")})}})).pipe($e.provide(r6))},gCn=e=>s.gen(function*(){let t=yield*$se,r=yield*e.pipe(s.forkChild),n=s.gen(function*(){yield*t.closed;let o=yield*s.serviceOption(h6);if(B.isSome(o)){let i=Number((yield*De.monotonicTimeNanos)/1000000n);yield*fe.set(o.value,i+hCn)}return yield*uo.interrupt(r).pipe(s.forkChild),yield*s.sleep(hCn),yield*t.forceExit,yield*s.never});return yield*uo.join(r).pipe(s.raceFirst(n))}),_Wt=e=>s.gen(function*(){return yield*(yield*no.String("MAIA_DESKTOP_PARENT_PIPE").pipe(no.withDefault("0"),s.orDie))==="1"?gCn(e).pipe(s.provide($se.layer)):e});z();dXe();var yCn=cXe(({fiber:e,teardown:t})=>{let r=!1;e.addObserver(o=>{process.removeListener("SIGINT",n),process.removeListener("SIGTERM",n),t(o,i=>{(r||i!==0)&&process.exit(i)})});function n(){r=!0,e.interruptUnsafe(e.id)}process.on("SIGINT",n),process.on("SIGTERM",n)});F();var UCa=5e3,SCn=e=>s.gen(function*(){let t=yield*Q.make(),r=()=>{Q.doneUnsafe(t,s.succeed(!0))};e.on("error",r),e.on("close",r);let n=s.callback(o=>{if(e.writableLength===0){o(s.succeed(!0));return}e.write("",()=>{o(s.succeed(!0))})});return s.raceFirst(Q.await(t),n)}),FCa=e=>xt.isSuccess(e)?e.value:_r.hasInterruptsOnly(e.cause)?0:GH.getErrorExitCode(_r.squash(e.cause)),HCa=(e,t)=>s.gen(function*(){let r=Number((yield*De.monotonicTimeNanos)/1000000n),n=(yield*fe.get(t))-r;return yield*s.all(e,{concurrency:"unbounded",discard:!0}).pipe(s.timeoutOption(Math.min(UCa,n)))}),BCa=(e,t)=>s.uninterruptibleMask(r=>s.gen(function*(){let n=[yield*SCn(t.stdout),yield*SCn(t.stderr)];yield*s.yieldNow;let o=yield*Q.make(),i=yield*fe.make(Number.POSITIVE_INFINITY),a=yield*s.forkChild(e.pipe(s.onExit(p=>Q.succeed(o,p)),s.provideService(h6,i)),{startImmediately:!0});yield*s.exit(r(uo.await(a))),yield*uo.interrupt(a);let c=yield*Q.await(o),l=FCa(c),u=yield*HCa(n,i);(l!==0||xt.isFailure(c)||B.isNone(u))&&t.exit(l)})),qCa=(e,t)=>{if(xt.isFailure(e)&&!_r.hasInterruptsOnly(e.cause)){GH.defaultTeardown(e,t);return}t(0)},ECn=(e,t)=>{yCn(BCa(e,t),{disableErrorReporting:!0,teardown:qCa})};var WCa=()=>({nodeVersion:"24.22.1",version:"0.1.0-canary.74"}),nqe=WCa(),vWt={stderr(e){process.stderr.write(e)},stdout(e){process.stdout.write(e)}},RCn=void 0,_Cn=jCa(import.meta.url),$Ca=e=>s.try({catch:t=>f("transport_failed",t instanceof Error?t.message:String(t)),try:GAe}).pipe(s.bindTo("nativeProcessHostIdentity"),s.bind("headlessApprovals",()=>wdt),s.flatMap(({headlessApprovals:t,nativeProcessHostIdentity:r})=>d6({...e,afterProfileLock:n=>sRt({modulePath:_Cn,profile:n,running:nqe.version}).pipe(s.provide(Rr)),headlessApprovals:t,...r===void 0?{}:{nativeProcessHostIdentity:r,nodeExecutablePath:_Cn}})));if(process.versions.node===nqe.nodeVersion){let e=rqe(process.argv.slice(2),{dependencies:{startDesktop:t=>$Ca(t).pipe(_Wt)},io:vWt,...RCn===void 0?{}:{runtimeRootOverride:RCn},version:nqe.version});ECn(kdt(process.argv.slice(2),vWt.stderr)(e).pipe(s.provide(Rr)),process)}else vWt.stderr(`Maia Node requires Node ${nqe.nodeVersion}; received ${process.versions.node}.
11894
11894
  `),process.exitCode=69;
11895
11895
  //# sourceMappingURL=maia-node-main.mjs.map