evolvingmachines-evolve 0.0.65.dev1542__tar.gz → 0.0.67__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {evolvingmachines_evolve-0.0.65.dev1542/evolvingmachines_evolve.egg-info → evolvingmachines_evolve-0.0.67}/PKG-INFO +1 -1
  2. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/bridge/dist/bridge.bundle.cjs +2 -2
  3. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/__init__.py +1 -1
  4. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67/evolvingmachines_evolve.egg-info}/PKG-INFO +1 -1
  5. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/pyproject.toml +1 -1
  6. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/LICENSE +0 -0
  7. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/MANIFEST.in +0 -0
  8. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/README.md +0 -0
  9. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/bridge/__init__.py +0 -0
  10. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/_http.py +0 -0
  11. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/agent.py +0 -0
  12. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/bridge.py +0 -0
  13. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/browser_credentials.py +0 -0
  14. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/browser_profiles.py +0 -0
  15. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/config.py +0 -0
  16. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/hosted.py +0 -0
  17. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/integrations.py +0 -0
  18. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/managed_secrets.py +0 -0
  19. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/pipeline/__init__.py +0 -0
  20. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/pipeline/pipeline.py +0 -0
  21. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/pipeline/types.py +0 -0
  22. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/prompts/__init__.py +0 -0
  23. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/prompts/agent_md/judge.md +0 -0
  24. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/prompts/agent_md/reduce.md +0 -0
  25. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/prompts/agent_md/verify.md +0 -0
  26. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/prompts/user/judge.md +0 -0
  27. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/prompts/user/retry_feedback.md +0 -0
  28. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/prompts/user/verify.md +0 -0
  29. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/py.typed +0 -0
  30. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/results.py +0 -0
  31. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/retry.py +0 -0
  32. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/sandbox_view.py +0 -0
  33. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/schema.py +0 -0
  34. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/sessions_client.py +0 -0
  35. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/storage_client.py +0 -0
  36. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/swarm/__init__.py +0 -0
  37. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/swarm/results.py +0 -0
  38. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/swarm/swarm.py +0 -0
  39. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/swarm/types.py +0 -0
  40. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolve/utils.py +0 -0
  41. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolvingmachines_evolve.egg-info/SOURCES.txt +0 -0
  42. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolvingmachines_evolve.egg-info/dependency_links.txt +0 -0
  43. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolvingmachines_evolve.egg-info/requires.txt +0 -0
  44. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/evolvingmachines_evolve.egg-info/top_level.txt +0 -0
  45. {evolvingmachines_evolve-0.0.65.dev1542 → evolvingmachines_evolve-0.0.67}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolvingmachines-evolve
3
- Version: 0.0.65.dev1542
3
+ Version: 0.0.67
4
4
  Summary: Pythonic SDK for multi-agent orchestration in E2B sandboxes
5
5
  Author-email: "Swarmlink, Inc." <brandomagnani@evolvingmachines.ai>
6
6
  License: Apache-2.0
@@ -214,7 +214,7 @@ ${e}
214
214
 
215
215
  }; __evolve_eos=$?; printf '%s' '${t}' 2>/dev/null >&9; exec 9>&-; (exit $__evolve_eos)`:e}function SRe(e,t){return e.endsWith(`${t}
216
216
  `)?e.slice(0,-(t.length+1)):e.endsWith(t)?e.slice(0,-t.length):e}function tS(e,t){let n=ARe(e);return{stdout:SRe(n.stdout,t),stderr:n.stderr}}function VW(e,t){let n=`${e}
217
- `,r="",a=i=>{for(let s=Math.min(i.length,n.length);s>0;s--)if(n.startsWith(i.slice(i.length-s)))return s;return 0};return{push(i){r+=i;let s=a(r);s!==r.length&&(t(r.slice(0,r.length-s)),r=r.slice(r.length-s))},flush(){let i=r===n||r===e?"":r;r="",i&&t(i)}}}function qW(e,t,n,r){let a=e;return t&&(a=`cd '${t.replace(/'/g,"'\\''")}' && ${a}`),n&&Object.keys(n).length>0&&(a=`${Object.entries(n).filter(([,i])=>i!=null).map(([i,s])=>`export ${i}='${String(s).replace(/'/g,"'\\''")}'`).join("; ")}; ${a}`),r==="root"&&(a=`echo ${Buffer.from(a).toString("base64")} | base64 -d | sudo -n bash`),a}function _Re(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function xMt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!_Re(e)}function EMt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function TMt(e){return/^[^:]+:\d+$/.test(e)}function kMt(e){return e.startsWith("*.")&&e.length>2&&!e.slice(2).includes("*")}function HT(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return e?{networkBlockAll:!1}:{}}let t=e.allowedDestinations??[];if(t.length===0)return{networkBlockAll:!0};for(let i of t){if(i.trim()==="")throw new Kl("invalid-destination",`network.allowedDestinations contains an empty destination (${JSON.stringify(i)}). Every entry must be a hostname, *.wildcard domain, IPv4 address, or IPv4 CIDR \u2014 remove the blank entry (an empty allowlist would open the sandbox, not seal it).`,i);if(i.includes(","))throw new Kl("invalid-destination",`network.allowedDestinations entry "${i}" contains a comma. Daytona's allowlists are sent as one comma-joined string, so a comma inside an entry would smuggle extra destinations past the list caps \u2014 pass one destination per array entry.`,i)}let n=[],r=[];for(let i of t)if(_Re(i))n.push(i.includes("/")?i:`${i}/32`);else{if(xMt(i))throw new Kl("invalid-ipv4",`"${i}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,i);if(EMt(i))throw new Kl("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${i}".`,i);if(TMt(i))throw new Kl("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${i}" and list just the host or IP.`,i);if(i.includes("*")&&!kMt(i))throw new Kl("wildcard-hostname",`Daytona's domain allowlist supports exactly one wildcard form \u2014 a "*." prefix ("*.example.com" allows example.com and its subdomains) \u2014 and cannot express "${i}". Use a *.prefix wildcard, a concrete hostname, or an IPv4 CIDR instead.`,i);r.push(i)}if(n.length>0&&r.length>0)throw new Kl("mixed-allowlist",`Daytona's networkAllowList (IPv4 CIDRs) and domainAllowList (DNS names) are mutually exclusive \u2014 at most one may be non-empty per sandbox, and this policy names both kinds (CIDRs: ${n.join(", ")}; domains: ${r.join(", ")}). List only IPs/CIDRs or only hostnames for this sandbox.`);if(r.length>0){let i=[...new Set(r)];if(i.length>CW)throw new Kl("allowlist-too-large",`Daytona allows at most ${CW} entries in its domain allowlist; this policy names ${i.length} domains (${i.join(", ")}). Consolidate under *.prefix wildcards or reduce the list.`);return{networkBlockAll:!1,domainAllowList:i.join(",")}}let a=[...new Set(n)];if(a.length>RW)throw new Kl("allowlist-too-large",`Daytona allows at most ${RW} entries in its network allowlist; this policy resolved to ${a.length} CIDRs (${a.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return{networkBlockAll:!1,networkAllowList:a.join(",")}}function wRe(e){let t=HT(e);return t.networkAllowList!==void 0||t.domainAllowList!==void 0?{networkBlockAll:!1,networkAllowList:t.networkAllowList??"",domainAllowList:t.domainAllowList??""}:{networkBlockAll:t.networkBlockAll===!0,networkAllowList:"",domainAllowList:""}}function IRe(e){let t=HW(e),n=(e instanceof Error?e.message:String(e)).toLowerCase(),r=n.includes("network policy")||n.includes("network settings")||n.includes("network configuration"),a=n.includes("tier")||n.includes("plan")||n.includes("upgrade")||n.includes("not allowed")||n.includes("not permitted")||n.includes("cannot override");return(t===402||t===403)&&(a||r)?!0:r&&a}function xRe(e){let t=e.indexOf("/");if(t<0)return;let n=e.substring(0,t);return n.includes(".")||n.includes(":")||n==="localhost"?n:void 0}function WW(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function ERe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function TRe(e,t){if(!e||typeof e!="object")return;let n=e;if(typeof n.toolboxProxyUrl=="string"&&(n.toolboxProxyUrl=t),Array.isArray(n.items))for(let r of n.items)TRe(r,t)}function OMt(e,t){return new Proxy(e,{get(n,r,a){if(r==="getToolboxProxyUrl")return async()=>({data:{url:t}});let i=Reflect.get(n,r,a);return typeof i!="function"?i:function(...s){let o=i.apply(n,s);return o instanceof Promise?o.then(c=>(TRe(c?.data,t),c)):o}}})}function PMt(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function ZPe(e,t,n){e:for(let r=n;r+t.length<=e.length;r++){for(let a=0;a<t.length;a++)if(e[r+a]!==t[a])continue e;return r}return-1}function kRe(e,t){let n=new TextDecoder("utf-8"),r=new TextDecoder("utf-8"),a=new Uint8Array(0),i="stdout",s=o=>{o.length!==0&&(i==="stdout"?e(n.decode(o,{stream:!0})):t(r.decode(o,{stream:!0})))};return{push(o){for(a=PMt(a,o);;){let c=ZPe(a,ly,0),l=ZPe(a,uy,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=ly.length):l!==-1&&(u=l,d="stderr",f=uy.length),u===-1){let p=Math.max(0,a.length-(Rh-1));s(a.subarray(0,p)),a=a.slice(p);return}s(a.subarray(0,u)),i=d,a=a.slice(u+f)}},flush(){s(a),a=new Uint8Array(0);let o=n.decode();o&&e(o);let c=r.decode();c&&t(c)}}}async function ORe(e,t,n,r,a,i,s){let o=`${e.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(n)}/command/${encodeURIComponent(r)}/logs?follow=true`,c=await fetch(o,{headers:{Authorization:`Bearer ${e.apiKey}`,accept:"application/octet-stream"},...s?{signal:s}:{}});if(!c.ok)throw new Error(`Daytona managed log follow failed: ${c.status} ${await c.text()}`);if(!c.body)return;let l=kRe(a,i),u=c.body.getReader();try{for(;;){let{done:d,value:f}=await u.read();if(d)break;f&&l.push(f)}}finally{l.flush(),await u.cancel().catch(()=>{})}}function ARe(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function CMt(e,t){let n=HPe(e),r=t==="children"?`[ -e ${n} ] || exit ${PW}; [ -d ${n} ] || exit ${nRe};`:`[ -e ${n} ] || [ -L ${n} ] || exit ${PW};`,a=t==="children"?`find -H ${n} -mindepth 1 -maxdepth 1 -printf '${QPe}'`:`find ${n} -maxdepth 0 -printf '${QPe}'`;return`sh -c ${HPe(`${r} ( ${a}; printf 'STATUS:%d' "$?" ) | base64`)}`}function NMt(e,t,n){let r=Buffer.from(t.replace(/\s+/g,""),"base64").toString("utf-8").split("\0"),a=r.pop()??"",i=/^STATUS:(\d+)$/.exec(a);if(!i)throw new Error(`daytona: the listing of ${e} ended without find's status (${a.slice(0,40)})`);if(i[1]!=="0")throw new Error(`daytona: find exited ${i[1]} listing ${e}`);let s=[];for(let o=0;o+kW<=r.length;o+=kW){let[c,l,u,d,f,p,m,y]=r.slice(o,o+kW),b=c==="f"?"file":c==="d"?"dir":c==="l"?"symlink":"other",v={name:y,path:n==="children"?fMt(e,y):e,type:b,size:Number(l),mtime:iRe(Number(u)),mode:dMt(d),owner:f,group:p};b==="symlink"&&(v.target=m),s.push(v)}return s}function MMt(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function CRe(e,t){let n=t?.limit,r=[],a=0,i=new Set;try{for await(let s of e){if(n!==void 0&&r.length>=n)return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!0,error:`stopped at the requested limit of ${n} with more sandboxes available`};if(a+=1,a>NM)return{sandboxes:r,complete:!1,pagesFetched:NM,stoppedAtLimit:!1,error:`sandbox list exceeded ${NM} sandboxes scanned`};if(t?.state){let o=ERe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push(WW(s)))}}catch(s){return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!1,error:`sandbox list failed: ${s instanceof Error?s.message:String(s)}`}}return{sandboxes:r,complete:!0,pagesFetched:a,stoppedAtLimit:!1}}function BM(e={}){let t=e.apiKey??process.env.DAYTONA_API_KEY;if(!t)throw new Error("Daytona API key required. Set DAYTONA_API_KEY environment variable or pass apiKey in config. Get your key at https://app.daytona.io/dashboard/keys");return new jW({...e,apiKey:t})}var eRe,AW,DM,tRe,PW,nRe,UM,zW,aRe,RW,CW,sRe,mMt,GW,oRe,cRe,Mh,lRe,NM,Kl,uRe,vMt,MM,dRe,fRe,bMt,pRe,MW,hRe,jPe,Ey,JT,JW,mRe,_Mt,YPe,wMt,gRe,yRe,AMt,PRe,QPe,kW,RMt,RRe,GT,jW,DMt,UMt,BMt,FMt,LMt,VMt,qMt,$Mt,zMt,GMt,JMt,HMt,WMt,jMt,YMt,KMt,XMt,ZMt,QMt,eDt,tDt,nDt,OW,WT=Q(()=>{"use strict";JPe();eRe=require("crypto"),AW=class extends Error{feature;provider;reason;constructor(e,t,n){super(`${t} does not support ${e}${n?`: ${n}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=e,this.provider=t,this.reason=n}},DM=class extends Error{path;provider;constructor(e,t){super(`${t}: no such file or directory: ${e}`),this.name="SandboxPathNotFoundError",this.path=e,this.provider=t}},tRe=class extends Error{sandboxId;provider;state;constructor(e,t,n){super(`${t} sandbox ${e} is not running (${n}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=e,this.provider=t,this.state=n}};PW=2,nRe=20;UM="c-ebdfafe2ef1a",zW={[`evolve-all-${UM}`]:`evolvingmachines/evolve-all:${UM}`,"evolve-all":"evolvingmachines/evolve-all"},aRe=10,RW=10,CW=20,sRe=18e4,mMt=2e3,GW=6e5,oRe=5e3,cRe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},Mh=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),lRe=100,NM=1e4;Kl=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},uRe=class extends Error{image;constructor(e,t){let n=t instanceof Error?t.message:String(t??"unknown error");super(`Failed to pull image "${e}" on Daytona: ${n}. Private registry images require the registry pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret; AWS ECR registrations name an IAM role Daytona assumes (no password). Register the registry at https://app.daytona.io, then retry. Also ensure the image is linux/amd64 and pinned to a tag or digest (floating tags like "latest" are rejected by Daytona's snapshot builder).`),this.name="DaytonaImagePullError",this.image=e}},vMt=class extends Error{snapshot;constructor(e){super(`Daytona cannot constrain the GPU type for "${e}": the snapshot already exists and pins its resources \u2014 pre-build a snapshot with the desired GPU type under its own name.`),this.name="DaytonaGpuTypeError",this.snapshot=e}},MM=class extends Error{snapshot;constructor(e){super(`Daytona snapshot "${e}" already exists and pins its cpu/memory/disk sizing \u2014 create-from-snapshot cannot resize it, so the requested \`resources\` cannot be enforced. Pre-build a snapshot with the desired sizing under its own name (sizing-addressed), or omit \`resources\` to accept the snapshot's pinned sizing.`),this.name="DaytonaResourcesError",this.snapshot=e}},dRe=class extends Error{constructor(){super("Daytona takes no create-time boot command: it never runs an image entrypoint or any argv at boot (harbor daytona/environment.py:706-708 works around exactly that, starting dockerd by hand). The boot is already inert \u2014 run the process by exec after create."),this.name="DaytonaBootCommandError"}},fRe=class extends Error{constructor(){super("Daytona has no separate idle timeout: auto-stop IS its only clock and it already measures inactivity, so `timeoutMs` is what sets it (autoStopInterval). Set the inactivity bound with `timeoutMs`; a hard bound on the process itself is enforced in-box instead (see withInBoxTimeout)."),this.name="DaytonaIdleTimeoutError"}},bMt=new Set(["pending_build","building_snapshot","pulling_snapshot"]);pRe=class extends Error{phase;state;sandboxId;constructor(e,t,n){super(`Daytona sandbox boot abandoned during ${e} (provider state ${t??"not yet reported"}, sandbox ${n??"not yet created"})`),this.name="DaytonaBootAbortedError",this.phase=e,this.state=t,this.sandboxId=n}},MW="evolve_boot",hRe=5e3,jPe=30;Ey=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" exists but could not be activated: ${t}. Daytona deactivates snapshots unused for 2 weeks; activation normally completes in seconds. Retry, or activate it manually in the Daytona dashboard (Snapshots page).`),this.name="DaytonaSnapshotActivationError",this.snapshot=e}};JT=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" is being created by another process and this run could not wait it out: ${t}.`),this.name="DaytonaSnapshotConflictError",this.snapshot=e}},JW=Symbol("daytona-snapshot-gone"),mRe=new Set(["pending","pulling","building","snapshotting"]),_Mt=3;YPe=new Set(["error","build_failed"]),wMt=new Set(["latest","lts","stable"]);gRe=6e4,yRe=2e3;AMt=class extends vy{constructor(e,t){super(e);let n=this;n.sandboxApi=OMt(n.sandboxApi,t)}};PRe=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=cRe;followLogs(e,t,n,r,a){return this.managedStream?ORe(this.managedStream,this.sandbox.id,e,t,n,r,a):this.sandbox.process.getSessionCommandLogs(e,t,n,r)}async run(e,t){let n=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(r);try{let a=!!(t?.onStdout||t?.onStderr),i=XPe(),s=await this.sandbox.process.executeSessionCommand(r,{command:FW(qW(LW(e,i),t?.cwd,t?.envs,this.user),n),runAsync:a},n),o=s.cmdId;if(a&&!o)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(a&&o){let u="",d="",f=!0,p=Date.now(),m=VW(i,T=>{u+=T,t?.onStdout?.(T)}),y=new AbortController,b=this.followLogs(r,o,T=>{f&&(p=Date.now(),m.push(T))},T=>{f&&(p=Date.now(),d+=T,t?.onStderr?.(T))},y.signal),v=!1,S,w=b.then(()=>{},T=>{v||(S=T)}),I;try{I=await this.awaitStreamedExit(r,o,b,()=>p,t?.timeoutMs)}finally{v=!0,y.abort(),await Promise.race([w,Mh(this.streamTimings.drainMs)]),f=!1,S===void 0&&m.flush()}if(S!==void 0){let T;try{let R=await this.sandbox.process.getSessionCommandLogs(r,o);T=tS(R,i)}catch{throw S}if(!T.stdout.startsWith(u)||!T.stderr.startsWith(d))throw S;let k=T.stdout.slice(u.length),O=T.stderr.slice(d.length);u=T.stdout,d=T.stderr,k&&t?.onStdout?.(k),O&&t?.onStderr?.(O)}else if(!u&&!d)try{let T=await this.sandbox.process.getSessionCommandLogs(r,o),k=tS(T,i);u=k.stdout,d=k.stderr,u&&t?.onStdout?.(u),d&&t?.onStderr?.(d)}catch{}return{exitCode:I,stdout:u,stderr:d}}let{stdout:c,stderr:l}=tS(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=tS(u,i);c=d.stdout,l=d.stderr||l}catch{}return{exitCode:s.exitCode??0,stdout:c,stderr:l}}finally{try{await this.sandbox.process.deleteSession(r)}catch{}}}async awaitStreamedExit(e,t,n,r,a){let i=this.streamTimings,s,o,c=n.then(()=>{s=Date.now()},d=>{s=Date.now(),o=d}),l=a!==void 0&&a>0?Date.now()+a+i.killGraceMs:void 0,u=i.pollMinMs;for(;;){let d=await this.sandbox.process.getSessionCommand(e,t);if(d.exitCode!==void 0&&d.exitCode!==null){for(;s===void 0;){let m=Date.now()-r();if(m>=i.drainMs)break;await Promise.race([c,Mh(i.drainMs-m)])}return d.exitCode}let f=s!==void 0?s+i.settleMs:void 0,p=l!==void 0&&f!==void 0?Math.min(l,f):l??f;if(p!==void 0&&Date.now()>=p)throw o!==void 0?o:new Error(`Daytona reported no exit code for command ${t} after `+(s!==void 0?"its log stream closed":`${a}ms`));await Mh(u),u=Math.min(u*2,i.pollMaxMs)}}async spawn(e,t){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let r=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,a=Date.now(),i=t?.timeoutMs,s=XPe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:FW(qW(LW(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=VW(s,t.onStdout||(()=>{}));this.followLogs(n,o,u=>l.push(u),t.onStderr||(()=>{})).catch(()=>{}).finally(()=>l.flush())}let c=this.sandbox;return{processId:n,wait:async()=>{if(!o)return{exitCode:0,stdout:"",stderr:""};for(;;){if(i&&Date.now()-a>=i){try{await c.process.deleteSession(n)}catch{}return{exitCode:124,stdout:"",stderr:"operation timed out"}}try{let l=await c.process.getSessionCommand(n,o);if(l.exitCode!==void 0)try{let u=await c.process.getSessionCommandLogs(n,o);return{exitCode:l.exitCode,...tS(u,s)}}catch{return{exitCode:l.exitCode,stdout:"",stderr:""}}}catch(l){let u=l instanceof Error?l.message.toLowerCase():String(l).toLowerCase();if(u.includes("not found")){let d=u.includes("sandbox");try{await c.refreshData(),d=!1}catch(f){(f instanceof Error?f.message.toLowerCase():String(f).toLowerCase()).includes("not found")&&(d=!0)}return{exitCode:-1,stdout:"",stderr:d?"sandbox deleted during run":"session terminated"}}throw l}await Mh(500)}},kill:async()=>{try{return await c.process.deleteSession(n),!0}catch{return!1}}}}async list(){try{return(await this.sandbox.process.listSessions()).map(e=>({processId:e.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return[]}}async kill(e){try{return await this.sandbox.process.deleteSession(e),!0}catch{return!1}}},QPe="%y\\0%s\\0%T@\\0%m\\0%u\\0%g\\0%l\\0%f\\0",kW=8,RMt=1800*1e3;RRe=class{constructor(e,t){this.sandbox=e,this.commands=t}async read(e){let t=new Uint8Array(await this.sandbox.fs.downloadFile(e));if(!t.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{}return t}async write(e,t){let n;if(typeof t=="string")n=Buffer.from(t,"utf-8");else if(Buffer.isBuffer(t))n=t;else if(t instanceof ArrayBuffer)n=Buffer.from(t);else if(t instanceof Uint8Array)n=Buffer.from(t);else throw new Error(`Unsupported content type: ${typeof t}`);await this.sandbox.fs.uploadFile(n,e)}async writeBatch(e){let t=e.map(n=>{let r;if(typeof n.data=="string")r=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))r=n.data;else if(n.data instanceof ArrayBuffer)r=Buffer.from(n.data);else if(n.data instanceof Uint8Array)r=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return{source:r,destination:n.path}});await this.sandbox.fs.uploadFiles(t)}async writeFromPath(e,t){await this.sandbox.fs.uploadFile(t,e)}async makeDir(e){await this.sandbox.fs.createFolder(e,"755")}async exists(e){try{let t=gMt(e),n=yMt(e);return(await this.sandbox.fs.listFiles(t)).some(r=>r.name===n)}catch{return!1}}async list(e){return this.findListing(e,"children")}async stat(e){let[t]=await this.findListing(e,"self");if(!t)throw new DM(e,"daytona");return t}async findListing(e,t){let n=await this.commands.run(CMt(e,t));if(n.exitCode===PW)throw new DM(e,"daytona");if(n.exitCode===nRe)throw new Error(`daytona: ${e} is not a directory`);if(n.exitCode!==0)throw new Error(`daytona: listing ${e} failed (exit ${n.exitCode}): ${n.stderr.trim()}`);try{return NMt(e,n.stdout,t)}catch(r){throw/printf|unrecognized|invalid option/i.test(n.stderr)?new AW("files.list","daytona",`this image's find has no -printf (GNU findutils is needed to list entries as themselves): ${n.stderr.trim()}`):r}}async readRange(e,t){if(rRe(t),t.length===0)return new Uint8Array(0);let n=await this.sandbox.downloadUrl(e);return pMt(n,t,{provider:"daytona",path:e,timeoutMs:RMt})}async watchDir(e,t,n){throw new AW("files.watchDir","daytona","the Daytona SDK has no filesystem watcher; poll files.list() on the directories you have open")}async remove(e){await this.sandbox.fs.deleteFile(e,!0)}async rename(e,t){await this.sandbox.fs.moveFiles(e,t)}},GT=class{constructor(e,t,n){this.sandbox=e;let r=new PRe(e,t,n);this.commands=r,this.files=new RRe(e,r)}commands;files;get sandboxId(){return this.sandbox.id}async getHost(e){return(await this.sandbox.getPreviewLink(e)).url}async isRunning(){try{await this.sandbox.refreshData()}catch{return!1}return this.sandbox.state==="started"}async getInfo(){return await this.sandbox.refreshData(),WW(this.sandbox)}async metrics(){let e=await this.sandbox.getMetricsLatest();return{cpuPct:e.cpuUsedPct,memUsedMb:e.memUsed/OW,memTotalMb:e.memTotal/OW,diskUsedMb:e.diskUsed/OW,sampledAt:iRe(e.timestamp),source:"daytona:getMetricsLatest"}}async updateNetwork(e){let t=wRe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw IRe(n)?new Kl("org-tier-forbidden",`Daytona refused to change this sandbox's network policy: organizations on Tier 1 or Tier 2 cannot override network policy at the sandbox level. Raise the organization's tier, or run this workload on a provider whose plan permits runtime policy changes (underlying error: ${n instanceof Error?n.message:String(n)}).`):n}}async kill(){await this.sandbox.delete()}async pause(){await this.sandbox.stop()}},jW=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:GW,pollMs:oRe};snapshotDeleteTiming={timeoutMs:gRe,pollMs:yRe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new AMt(t,e.managedToolboxUrl):new vy(t),e.managedToolboxUrl&&(this.managedStream={toolboxUrl:e.managedToolboxUrl,apiKey:e.apiKey}),this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.snapshotName=e.snapshotName??(e.managedToolboxUrl?"evolve-all":`evolve-all-${UM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new fRe;if(e.bootCommand!==void 0)throw new dRe;for(let f of e.phaseNetworkPolicies??[])HT(f);let t=HT(e.network),n=e.user,r=n&&n!=="root"?n:void 0,a=e.timeoutMs??this.defaultTimeoutMs,i=Math.max(1,Math.ceil(a/6e4)),s=e.image||this.snapshotName,o={envVars:e.envs,labels:e.metadata,autoStopInterval:i,autoDeleteInterval:aRe,...r?{user:r}:{},...t},c,l=e.resources!==void 0&&(e.resources.cpu!==void 0||e.resources.memory!==void 0||e.resources.disk!==void 0||e.resources.gpu!==void 0||e.resources.gpuTypes!==void 0);if(this.managedStream){if(l)throw new MM(s);let f=await this.client.create({snapshot:s,...o},{timeout:600});return e.workingDirectory&&await f.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(f.id,n),new GT(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),p=f?.state;if(f&&mRe.has(p??"")&&(u=p),f&&(p==="active"||p==="inactive")&&l)throw new MM(s);if(f&&p==="inactive"&&(p=(await DW(this.client,s,f)).state),f&&YPe.has(p??"")&&(UW(s)?d=await KPe(this.client,s,f,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${s}" is dead (state "${p}") but this provider cannot rebuild that name \u2014 delete it in the Daytona dashboard (Snapshots page), or rebuild it with the tooling that created it.`)),f&&p==="active")console.log(`[daytona] Using cached snapshot: ${s}`),c=await this.client.create({snapshot:s,...o},{timeout:600});else throw new Error("Snapshot not active")}catch(f){if(f instanceof MM||f instanceof Ey)throw f;let p=zW[s]??s,m=u!==void 0&&!l;m?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") \u2014 joining that build rather than starting a second one.`):u!==void 0?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") and cannot carry the requested sizing \u2014 pulling image directly instead: ${p}`):(console.log(`[daytona] Snapshot "${s}" not found, building from image: ${p}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(d===!1)throw new Error(`dead snapshot "${s}" was not confirmed removed \u2014 not racing its removal`);let y=()=>this.client.snapshot.create({name:s,image:Oh.base(p),resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{onLogs:v=>console.log(`[daytona] ${v}`)}),b=async()=>{await y(),console.log(`[daytona] Snapshot "${s}" ready (rebuilt here after a dead build).`)};if(u!==void 0){if(!m)throw new Error(`snapshot "${s}" is mid-build (state "${u}") and cannot be resized`);await this.joinInFlightSnapshotBuild(s)&&await b()}else try{await y(),console.log(`[daytona] Snapshot "${s}" ready (built here).`)}catch(v){if(!vRe(v)||l)throw v;await this.joinInFlightSnapshotBuild(s)&&await b()}c=await this.client.create({snapshot:s,...o},{timeout:600})}catch(y){if(y instanceof JT||y instanceof Ey)throw y;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${y instanceof Error?y.message:y}`);try{c=await this.client.create({image:p,...o,resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{timeout:600,onSnapshotCreateLogs:b=>console.log(`[daytona] ${b}`)})}catch(b){throw xRe(p)?new uRe(p,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new GT(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await bRe(this.client,e,this.snapshotConflictTiming);if(t===JW)return!0;if(t.state==="active")return console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(t.state==="inactive")return await DW(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(YPe.has(t.state??"")&&UW(e)&&await KPe(this.client,e,t,this.snapshotDeleteTiming))return!0;throw new Error(`the in-flight build of snapshot "${e}" ended in state "${t.state??"unknown"}"`)}async connect(e,t){let n=await this.client.get(e);return n.state!=="started"&&await n.start(),new GT(n,this.sandboxUsers.get(e),this.managedStream)}async inspect(e,t){let n=await this.getSandboxRecord(e);if(n.state!=="started")throw new tRe(e,"daytona",n.state??"unknown");return new GT(n,t?.user??this.sandboxUsers.get(e),this.managedStream)}async getSandboxRecord(e){return this.client.get(e)}async list(e){let t=await this.paginate(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.paginate(e);return n}async paginate(e){return CRe(this.listStream(e),e)}listStream(e){let t=e?.state?MMt(e.state):void 0,n={limit:lRe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};DMt=CRe;UMt=qW,BMt=FW,FMt=HT,LMt=wRe,VMt=IRe,qMt=xRe,$Mt=WW,zMt=ERe,GMt=DW,JMt=bRe,HMt=vRe,WMt=UW,jMt=zW,YMt=LW,KMt=SRe,XMt=tS,ZMt=VW,QMt=kRe,eDt=ORe,tDt=ARe,nDt=GT,OW=1024*1024});var NRe=_(FM=>{"use strict";Object.defineProperty(FM,"__esModule",{value:!0});FM.Metadata=void 0;FM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=nS(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)KW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else KW(a,i),n.set(a,[i]);return r},append(a,i){a=nS(a),KW(a,i);let s=n.get(a);return s==null&&(s=[],n.set(a,s)),s.push(i),a.endsWith("-bin")||n.set(a,[s.join(", ")]),r},delete(a){a=nS(a),n.delete(a)},get(a){var i;return a=nS(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=nS(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=nS(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=rDt(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function nS(e){return e.toLowerCase()}function KW(e,t){if(!/^[0-9a-z_.-]+$/.test(e))throw new Error(`Metadata key '${e}' contains illegal characters`);if(e.endsWith("-bin")){if(!(t instanceof Uint8Array))throw new Error(`Metadata key '${e}' ends with '-bin', thus it must have binary value`)}else{if(typeof t!="string")throw new Error(`Metadata key '${e}' doesn't end with '-bin', thus it must have string value`);if(!/^[ -~]*$/.test(t))throw new Error(`Metadata value '${t}' of key '${e}' contains illegal characters`)}}function rDt(e){return Symbol.iterator in e}});var LM=_(jT=>{"use strict";Object.defineProperty(jT,"__esModule",{value:!0});jT.Status=void 0;var iDt;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(iDt=jT.Status||(jT.Status={}))});var DRe=_(MRe=>{"use strict";Object.defineProperty(MRe,"__esModule",{value:!0})});var BRe=_(URe=>{"use strict";Object.defineProperty(URe,"__esModule",{value:!0})});var LRe=_(FRe=>{"use strict";Object.defineProperty(FRe,"__esModule",{value:!0})});var VRe=_(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.composeClientMiddleware=void 0;function aDt(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}VM.composeClientMiddleware=aDt});var zRe=_(Dh=>{"use strict";Dh.__esModule=void 0;Dh.__esModule=!0;var sDt=typeof Object.setPrototypeOf=="function",oDt=typeof Object.getPrototypeOf=="function",cDt=typeof Object.defineProperty=="function",lDt=typeof Object.create=="function",uDt=typeof Object.prototype.hasOwnProperty=="function",dDt=function(t,n){sDt?Object.setPrototypeOf(t,n):t.__proto__=n};Dh.setPrototypeOf=dDt;var fDt=function(t){return oDt?Object.getPrototypeOf(t):t.__proto__||t.prototype};Dh.getPrototypeOf=fDt;var qRe=!1,pDt=function e(t,n,r){if(cDt&&!qRe)try{Object.defineProperty(t,n,r)}catch{qRe=!0,e(t,n,r)}else t[n]=r.value};Dh.defineProperty=pDt;var $Re=function(t,n){return uDt?t.hasOwnProperty(t,n):t[n]===void 0};Dh.hasOwnProperty=$Re;var hDt=function(t,n){if(lDt)return Object.create(t,n);var r=function(){};r.prototype=t;var a=new r;if(typeof n>"u")return a;if(typeof n=="null")throw new Error("PropertyDescriptors must not be null.");if(typeof n=="object")for(var i in n)$Re(n,i)&&(a[i]=n[i].value);return a};Dh.objectCreate=hDt});var ZW=_(rS=>{"use strict";rS.__esModule=void 0;rS.__esModule=!0;var $M=zRe(),mDt=$M.setPrototypeOf,gDt=$M.getPrototypeOf,XW=$M.defineProperty,yDt=$M.objectCreate,vDt=new Error().toString()==="[object Error]",qM="";function YT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?qM||"Error":o[1]}(),r=n==="Error",a=r?qM:n,i=Error.apply(this,arguments);if(mDt(i,gDt(this)),!(i instanceof t)||!(i instanceof YT)){var i=this;Error.apply(this,arguments),XW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(XW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?YT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return vDt&&XW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}qM=YT.name||"ExtendableError";YT.prototype=yDt(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});rS.ExtendableError=YT;rS.default=rS.ExtendableError});var GRe=_(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.ClientError=void 0;var bDt=ZW(),SDt=LM(),QW=class e extends bDt.ExtendableError{constructor(t,n,r){super(`${t} ${SDt.Status[n]}: ${r}`),this.path=t,this.code=n,this.details=r,this.name="ClientError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ClientError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ClientError"]===!0||t.name==="ClientError"&&t["@@nice-grpc"]===!0)}};zM.ClientError=QW});var HRe=_(JRe=>{"use strict";Object.defineProperty(JRe,"__esModule",{value:!0})});var jRe=_(WRe=>{"use strict";Object.defineProperty(WRe,"__esModule",{value:!0})});var YRe=_(GM=>{"use strict";Object.defineProperty(GM,"__esModule",{value:!0});GM.composeServerMiddleware=void 0;function _Dt(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}GM.composeServerMiddleware=_Dt});var KRe=_(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.ServerError=void 0;var wDt=ZW(),IDt=LM(),e7=class e extends wDt.ExtendableError{constructor(t,n){super(`${IDt.Status[t]}: ${n}`),this.code=t,this.details=n,this.name="ServerError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ServerError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ServerError"]===!0||t.name==="ServerError"&&t["@@nice-grpc"]===!0)}};JM.ServerError=e7});var Xc=_($a=>{"use strict";var xDt=$a&&$a.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Xl=$a&&$a.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&xDt(t,e,n)};Object.defineProperty($a,"__esModule",{value:!0});Xl(NRe(),$a);Xl(LM(),$a);Xl(DRe(),$a);Xl(BRe(),$a);Xl(LRe(),$a);Xl(VRe(),$a);Xl(GRe(),$a);Xl(HRe(),$a);Xl(jRe(),$a);Xl(YRe(),$a);Xl(KRe(),$a)});var Yt=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=Zc.Propagate=Zc.LogVerbosity=Zc.Status=void 0;var XRe;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(XRe||(Zc.Status=XRe={}));var ZRe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(ZRe||(Zc.LogVerbosity=ZRe={}));var QRe;(function(e){e[e.DEADLINE=1]="DEADLINE",e[e.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",e[e.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",e[e.CANCELLATION=8]="CANCELLATION",e[e.DEFAULTS=65535]="DEFAULTS"})(QRe||(Zc.Propagate=QRe={}));Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var t7=_((nxn,EDt)=>{EDt.exports={name:"@grpc/grpc-js",version:"1.14.4",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var hr=_(hc=>{"use strict";var n7,r7,i7,a7;Object.defineProperty(hc,"__esModule",{value:!0});hc.log=hc.setLoggerVerbosity=hc.setLogger=hc.getLogger=void 0;hc.trace=UDt;hc.isTracerEnabled=tCe;var Uh=Yt(),TDt=require("process"),kDt=t7().version,ODt={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},Ty=ODt,iS=Uh.LogVerbosity.ERROR,ADt=(r7=(n7=process.env.GRPC_NODE_VERBOSITY)!==null&&n7!==void 0?n7:process.env.GRPC_VERBOSITY)!==null&&r7!==void 0?r7:"";switch(ADt.toUpperCase()){case"DEBUG":iS=Uh.LogVerbosity.DEBUG;break;case"INFO":iS=Uh.LogVerbosity.INFO;break;case"ERROR":iS=Uh.LogVerbosity.ERROR;break;case"NONE":iS=Uh.LogVerbosity.NONE;break;default:}var PDt=()=>Ty;hc.getLogger=PDt;var RDt=e=>{Ty=e};hc.setLogger=RDt;var CDt=e=>{iS=e};hc.setLoggerVerbosity=CDt;var NDt=(e,...t)=>{let n;if(e>=iS){switch(e){case Uh.LogVerbosity.DEBUG:n=Ty.debug;break;case Uh.LogVerbosity.INFO:n=Ty.info;break;case Uh.LogVerbosity.ERROR:n=Ty.error;break}n||(n=Ty.error),n&&n.bind(Ty)(...t)}};hc.log=NDt;var MDt=(a7=(i7=process.env.GRPC_NODE_TRACE)!==null&&i7!==void 0?i7:process.env.GRPC_TRACE)!==null&&a7!==void 0?a7:"",s7=new Set,eCe=new Set;for(let e of MDt.split(","))e.startsWith("-")?eCe.add(e.substring(1)):s7.add(e);var DDt=s7.has("all");function UDt(e,t,n){tCe(t)&&(0,hc.log)(e,new Date().toISOString()+" | v"+kDt+" "+TDt.pid+" | "+t+" | "+n)}function tCe(e){return!eCe.has(e)&&(DDt||s7.has(e))}});var WM=_(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.getErrorMessage=BDt;HM.getErrorCode=FDt;function BDt(e){return e instanceof Error?e.message:String(e)}function FDt(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ga=_(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.Metadata=void 0;var LDt=hr(),VDt=Yt(),qDt=WM(),$Dt=/^[:0-9a-z_.-]+$/,zDt=/^[ -~]*$/;function GDt(e){return $Dt.test(e)}function JDt(e){return zDt.test(e)}function rCe(e){return e.endsWith("-bin")}function HDt(e){return!e.startsWith("grpc-")}function jM(e){return e.toLowerCase()}function nCe(e,t){if(!GDt(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(rCe(e)){if(!Buffer.isBuffer(t))throw new Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(t))throw new Error("keys that don't end with '-bin' must have String values");if(!JDt(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var o7=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=jM(t),nCe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=jM(t),nCe(t,n);let r=this.internalRepr.get(t);r===void 0?this.internalRepr.set(t,[n]):r.push(n)}remove(t){t=jM(t),this.internalRepr.delete(t)}get(t){return t=jM(t),this.internalRepr.get(t)||[]}getMap(){let t={};for(let[n,r]of this.internalRepr)if(r.length>0){let a=r[0];t[n]=Buffer.isBuffer(a)?Buffer.from(a):a}return t}clone(){let t=new e(this.options),n=t.internalRepr;for(let[r,a]of this.internalRepr){let i=a.map(s=>Buffer.isBuffer(s)?Buffer.from(s):s);n.set(r,i)}return t}merge(t){for(let[n,r]of t.internalRepr){let a=(this.internalRepr.get(n)||[]).concat(r);this.internalRepr.set(n,a)}}setOptions(t){this.options=t}getOptions(){return this.options}toHttp2Headers(){let t={};for(let[n,r]of this.internalRepr)n.startsWith(":")||(t[n]=r.map(WDt));return t}toJSON(){let t={};for(let[n,r]of this.internalRepr)t[n]=r;return t}setOpaque(t,n){this.opaqueData.set(t,n)}getOpaque(t){return this.opaqueData.get(t)}static fromHttp2Headers(t){let n=new e;for(let r of Object.keys(t)){if(r.charAt(0)===":")continue;let a=t[r];try{rCe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(HDt(r)?a.split(",").forEach(i=>{n.add(r,Buffer.from(i.trim(),"base64"))}):n.add(r,Buffer.from(a,"base64"))):Array.isArray(a)?a.forEach(i=>{n.add(r,i)}):a!==void 0&&n.add(r,a)}catch(i){let s=`Failed to add metadata entry ${r}: ${a}. ${(0,qDt.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,LDt.log)(VDt.LogVerbosity.ERROR,s)}}return n}};YM.Metadata=o7;var WDt=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var XM=_(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.CallCredentials=void 0;var d7=ga();function jDt(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var aS=class e{static createFromMetadataGenerator(t){return new l7(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;jDt(t)?a=t.getRequestHeaders(n.service_url):a=new Promise((i,s)=>{t.getRequestMetadata(n.service_url,(o,c)=>{if(o){s(o);return}if(!c){s(new Error("Headers not set by metadata plugin"));return}i(c)})}),a.then(i=>{let s=new d7.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new u7}};KM.CallCredentials=aS;var c7=class e extends aS{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new d7.Metadata,r=await Promise.all(this.creds.map(a=>a.generateMetadata(t)));for(let a of r)n.merge(a);return n}compose(t){return new e(this.creds.concat([t]))}_equals(t){return this===t?!0:t instanceof e?this.creds.every((n,r)=>n._equals(t.creds[r])):!1}},l7=class e extends aS{constructor(t){super(),this.metadataGenerator=t}generateMetadata(t){return new Promise((n,r)=>{this.metadataGenerator(t,(a,i)=>{i!==void 0?n(i):r(a)})})}compose(t){return new c7([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},u7=class e extends aS{generateMetadata(t){return Promise.resolve(new d7.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var p7=_(KT=>{"use strict";Object.defineProperty(KT,"__esModule",{value:!0});KT.CIPHER_SUITES=void 0;KT.getDefaultRootsData=KDt;var YDt=require("fs");KT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var iCe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,f7=null;function KDt(){return iCe?(f7===null&&(f7=YDt.readFileSync(iCe)),f7):null}});var ro=_(sS=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});sS.parseUri=ZDt;sS.splitHostPort=QDt;sS.combineHostPort=e3t;sS.uriToString=t3t;var XDt=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function ZDt(e){let t=XDt.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var aCe=/^\d+$/;function QDt(e){if(e.startsWith("[")){let t=e.indexOf("]");if(t===-1)return null;let n=e.substring(1,t);if(n.indexOf(":")===-1)return null;if(e.length>t+1)if(e[t+1]===":"){let r=e.substring(t+2);return aCe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?aCe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function e3t(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function t3t(e){let t="";return e.scheme!==void 0&&(t+=e.scheme+":"),e.authority!==void 0&&(t+="//"+e.authority+"/"),t+=e.path,t}});var Zl=_(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});dp.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;dp.registerResolver=n3t;dp.registerDefaultScheme=r3t;dp.createResolver=i3t;dp.getDefaultAuthority=a3t;dp.mapUriDefaultScheme=s3t;var m7=ro();dp.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var oS={},h7=null;function n3t(e,t){oS[e]=t}function r3t(e){h7=e}function i3t(e,t,n){if(e.scheme!==void 0&&e.scheme in oS)return new oS[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,m7.uriToString)(e)}`)}function a3t(e){if(e.scheme!==void 0&&e.scheme in oS)return oS[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,m7.uriToString)(e)}`)}function s3t(e){return e.scheme===void 0||!(e.scheme in oS)?h7!==null?{scheme:h7,authority:void 0,path:(0,m7.uriToString)(e)}:null:e}});var cS=_(ZT=>{"use strict";Object.defineProperty(ZT,"__esModule",{value:!0});ZT.ChannelCredentials=void 0;ZT.createCertificateProviderChannelCredentials=u3t;var XT=require("tls"),eD=XM(),y7=p7(),sCe=ro(),o3t=Zl(),c3t=hr(),l3t=Yt();function g7(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var ky=class{compose(t){return new S7(this,t)}static createSsl(t,n,r,a){var i;if(g7(t,"Root certificate"),g7(n,"Private key"),g7(r,"Certificate chain"),n&&!r)throw new Error("Private key must be given with accompanying certificate chain");if(!n&&r)throw new Error("Certificate chain must be given with accompanying private key");let s=(0,XT.createSecureContext)({ca:(i=t??(0,y7.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:y7.CIPHER_SUITES});return new ZM(s,a??{})}static createFromSecureContext(t,n){return new ZM(t,n??{})}static createInsecure(){return new v7}};ZT.ChannelCredentials=ky;var v7=class e extends ky{constructor(){super()}compose(t){throw new Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals(t){return t instanceof e}_createSecureConnector(t,n,r){return{connect(a){return Promise.resolve({socket:a,secure:!1})},waitForReady:()=>Promise.resolve(),getCallCredentials:()=>r??eD.CallCredentials.createEmpty(),destroy(){}}}};function oCe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,sCe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,o3t.getDefaultAuthority)(o),l=(0,sCe.splitHostPort)(c),u=(a=l?.host)!==null&&a!==void 0?a:c;if(s.host=u,t.checkServerIdentity&&(s.checkServerIdentity=t.checkServerIdentity),t.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=t.rejectUnauthorized),s.ALPNProtocols=["h2"],r["grpc.ssl_target_name_override"]){let d=r["grpc.ssl_target_name_override"],f=(i=s.checkServerIdentity)!==null&&i!==void 0?i:XT.checkServerIdentity;s.checkServerIdentity=(p,m)=>f(d,m),s.servername=d}else s.servername=u;return r["grpc-node.tls_enable_trace"]&&(s.enableTrace=!0),s}var b7=class{constructor(t,n){this.connectionOptions=t,this.callCredentials=n}connect(t){let n=Object.assign({socket:t},this.connectionOptions);return new Promise((r,a)=>{let i=(0,XT.connect)(n,()=>{var s;if((!((s=this.connectionOptions.rejectUnauthorized)!==null&&s!==void 0)||s)&&!i.authorized){a(i.authorizationError);return}r({socket:i,secure:!0})});i.on("error",s=>{a(s)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}},ZM=class e extends ky{constructor(t,n){super(),this.secureContext=t,this.verifyOptions=n}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.secureContext===t.secureContext&&this.verifyOptions.checkServerIdentity===t.verifyOptions.checkServerIdentity:!1}_createSecureConnector(t,n,r){let a=oCe(this.secureContext,this.verifyOptions,t,n);return new b7(a,r??eD.CallCredentials.createEmpty())}},QM=class e extends ky{constructor(t,n,r){super(),this.caCertificateProvider=t,this.identityCertificateProvider=n,this.verifyOptions=r,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals(t){var n,r;return this===t?!0:t instanceof e?this.caCertificateProvider===t.caCertificateProvider&&this.identityCertificateProvider===t.identityCertificateProvider&&((n=this.verifyOptions)===null||n===void 0?void 0:n.checkServerIdentity)===((r=t.verifyOptions)===null||r===void 0?void 0:r.checkServerIdentity):!1}ref(){var t;this.refcount===0&&(this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.addIdentityCertificateListener(this.identityCertificateUpdateListener)),this.refcount+=1}unref(){var t;this.refcount-=1,this.refcount===0&&(this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.removeIdentityCertificateListener(this.identityCertificateUpdateListener))}_createSecureConnector(t,n,r){return this.ref(),new e.SecureConnectorImpl(this,t,n,r??eD.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let t of this.secureContextWatchers)t(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate(t){this.latestCaUpdate=t,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate(t){this.latestIdentityUpdate=t,this.maybeUpdateWatchers()}hasReceivedUpdates(){return!(this.latestCaUpdate===void 0||this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)}getSecureContext(){return this.hasReceivedUpdates()?Promise.resolve(this.getLatestSecureContext()):new Promise(t=>{this.secureContextWatchers.push(t)})}getLatestSecureContext(){var t,n;if(!this.latestCaUpdate||this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,XT.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:(t=this.latestIdentityUpdate)===null||t===void 0?void 0:t.privateKey,cert:(n=this.latestIdentityUpdate)===null||n===void 0?void 0:n.certificate,ciphers:y7.CIPHER_SUITES})}catch(r){return(0,c3t.log)(l3t.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};QM.SecureConnectorImpl=class{constructor(e,t,n,r){this.parent=e,this.channelTarget=t,this.options=n,this.callCredentials=r}connect(e){return new Promise((t,n)=>{let r=this.parent.getLatestSecureContext();if(!r){n(new Error("Failed to load credentials"));return}e.closed&&n(new Error("Socket closed while loading credentials"));let a=oCe(r,this.parent.verifyOptions,this.channelTarget,this.options),i=Object.assign({socket:e},a),s=()=>{n(new Error("Socket closed"))},o=l=>{n(l)},c=(0,XT.connect)(i,()=>{var l;if(c.removeListener("close",s),c.removeListener("error",o),(!((l=this.parent.verifyOptions.rejectUnauthorized)!==null&&l!==void 0)||l)&&!c.authorized){n(c.authorizationError);return}t({socket:c,secure:!0})});c.once("close",s),c.once("error",o)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function u3t(e,t,n){return new QM(e,t,n??{})}var S7=class e extends ky{constructor(t,n){if(super(),this.channelCredentials=t,this.callCredentials=n,!t._isSecure())throw new Error("Cannot compose insecure credentials")}compose(t){let n=this.callCredentials.compose(t);return new e(this.channelCredentials,n)}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.channelCredentials._equals(t.channelCredentials)&&this.callCredentials._equals(t.callCredentials):!1}_createSecureConnector(t,n,r){let a=this.callCredentials.compose(r??eD.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Fh=_(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.createChildChannelControlHelper=p3t;Td.registerLoadBalancerType=h3t;Td.registerDefaultLoadBalancerType=m3t;Td.createLoadBalancer=g3t;Td.isLoadBalancerNameRegistered=y3t;Td.parseLoadBalancingConfig=cCe;Td.getDefaultConfig=v3t;Td.selectLbConfigFromList=b3t;var d3t=hr(),f3t=Yt();function p3t(e,t){var n,r,a,i,s,o,c,l,u,d;return{createSubchannel:(r=(n=t.createSubchannel)===null||n===void 0?void 0:n.bind(t))!==null&&r!==void 0?r:e.createSubchannel.bind(e),updateState:(i=(a=t.updateState)===null||a===void 0?void 0:a.bind(t))!==null&&i!==void 0?i:e.updateState.bind(e),requestReresolution:(o=(s=t.requestReresolution)===null||s===void 0?void 0:s.bind(t))!==null&&o!==void 0?o:e.requestReresolution.bind(e),addChannelzChild:(l=(c=t.addChannelzChild)===null||c===void 0?void 0:c.bind(t))!==null&&l!==void 0?l:e.addChannelzChild.bind(e),removeChannelzChild:(d=(u=t.removeChannelzChild)===null||u===void 0?void 0:u.bind(t))!==null&&d!==void 0?d:e.removeChannelzChild.bind(e)}}var Bh={},QT=null;function h3t(e,t,n){Bh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function m3t(e){QT=e}function g3t(e,t){let n=e.getLoadBalancerName();return n in Bh?new Bh[n].LoadBalancer(t):null}function y3t(e){return e in Bh}function cCe(e){let t=Object.keys(e);if(t.length!==1)throw new Error("Provided load balancing config has multiple conflicting entries");let n=t[0];if(n in Bh)try{return Bh[n].LoadBalancingConfig.createFromJson(e[n])}catch(r){throw new Error(`${n}: ${r.message}`)}else throw new Error(`Unrecognized load balancing config name ${n}`)}function v3t(){if(!QT)throw new Error("No default load balancer type registered");return new Bh[QT].LoadBalancingConfig}function b3t(e,t=!1){for(let n of e)try{return cCe(n)}catch(r){(0,d3t.log)(f3t.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&QT?new Bh[QT].LoadBalancingConfig:null}});var _7=_(ek=>{"use strict";Object.defineProperty(ek,"__esModule",{value:!0});ek.validateRetryThrottling=lCe;ek.validateServiceConfig=uCe;ek.extractAndSelectServiceConfig=A3t;var S3t=require("os"),tD=Yt(),nD=/^\d+(\.\d{1,9})?s$/,_3t="node";function w3t(e){if("service"in e&&e.service!==""){if(typeof e.service!="string")throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof e.service}`);if("method"in e&&e.method!==""){if(typeof e.method!="string")throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof e.service}`);return{service:e.service,method:e.method}}else return{service:e.service}}else{if("method"in e&&e.method!==void 0)throw new Error("Invalid method config name: method set with empty or unset service");return{}}}function I3t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in e)||typeof e.initialBackoff!="string"||!nD.test(e.initialBackoff))throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in e)||typeof e.maxBackoff!="string"||!nD.test(e.maxBackoff))throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in e)||typeof e.backoffMultiplier!="number"||e.backoffMultiplier<=0)throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!("retryableStatusCodes"in e&&Array.isArray(e.retryableStatusCodes)))throw new Error("Invalid method config retry policy: retryableStatusCodes is required");if(e.retryableStatusCodes.length===0)throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let t of e.retryableStatusCodes)if(typeof t=="number"){if(!Object.values(tD.Status).includes(t))throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof t=="string"){if(!Object.values(tD.Status).includes(t.toUpperCase()))throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:e.maxAttempts,initialBackoff:e.initialBackoff,maxBackoff:e.maxBackoff,backoffMultiplier:e.backoffMultiplier,retryableStatusCodes:e.retryableStatusCodes}}function x3t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in e&&(typeof e.hedgingDelay!="string"||!nD.test(e.hedgingDelay)))throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in e&&Array.isArray(e.nonFatalStatusCodes))for(let n of e.nonFatalStatusCodes)if(typeof n=="number"){if(!Object.values(tD.Status).includes(n))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof n=="string"){if(!Object.values(tD.Status).includes(n.toUpperCase()))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let t={maxAttempts:e.maxAttempts};return e.hedgingDelay&&(t.hedgingDelay=e.hedgingDelay),e.nonFatalStatusCodes&&(t.nonFatalStatusCodes=e.nonFatalStatusCodes),t}function E3t(e){var t;let n={name:[]};if(!("name"in e)||!Array.isArray(e.name))throw new Error("Invalid method config: invalid name array");for(let r of e.name)n.name.push(w3t(r));if("waitForReady"in e){if(typeof e.waitForReady!="boolean")throw new Error("Invalid method config: invalid waitForReady");n.waitForReady=e.waitForReady}if("timeout"in e)if(typeof e.timeout=="object"){if(!("seconds"in e.timeout)||typeof e.timeout.seconds!="number")throw new Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in e.timeout)||typeof e.timeout.nanos!="number")throw new Error("Invalid method config: invalid timeout.nanos");n.timeout=e.timeout}else if(typeof e.timeout=="string"&&nD.test(e.timeout)){let r=e.timeout.substring(0,e.timeout.length-1).split(".");n.timeout={seconds:r[0]|0,nanos:((t=r[1])!==null&&t!==void 0?t:0)|0}}else throw new Error("Invalid method config: invalid timeout");if("maxRequestBytes"in e){if(typeof e.maxRequestBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxRequestBytes=e.maxRequestBytes}if("maxResponseBytes"in e){if(typeof e.maxResponseBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxResponseBytes=e.maxResponseBytes}if("retryPolicy"in e){if("hedgingPolicy"in e)throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");n.retryPolicy=I3t(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=x3t(e.hedgingPolicy));return n}function lCe(e){if(!("maxTokens"in e)||typeof e.maxTokens!="number"||e.maxTokens<=0||e.maxTokens>1e3)throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in e)||typeof e.tokenRatio!="number"||e.tokenRatio<=0)throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+e.maxTokens.toFixed(3),tokenRatio:+e.tokenRatio.toFixed(3)}}function T3t(e){if(!(typeof e=="object"&&e!==null))throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof e}`);let t=Object.keys(e);if(t.length>1)throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${t}`);if(t.length===0)throw new Error("Invalid loadBalancingConfig: load balancing policy name required");return{[t[0]]:e[t[0]]}}function uCe(e){let t={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in e)if(typeof e.loadBalancingPolicy=="string")t.loadBalancingPolicy=e.loadBalancingPolicy;else throw new Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in e)if(Array.isArray(e.loadBalancingConfig))for(let r of e.loadBalancingConfig)t.loadBalancingConfig.push(T3t(r));else throw new Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in e&&Array.isArray(e.methodConfig))for(let r of e.methodConfig)t.methodConfig.push(E3t(r));"retryThrottling"in e&&(t.retryThrottling=lCe(e.retryThrottling));let n=[];for(let r of t.methodConfig)for(let a of r.name){for(let i of n)if(a.service===i.service&&a.method===i.method)throw new Error(`Invalid service config: duplicate name ${a.service}/${a.method}`);n.push(a)}return t}function k3t(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:uCe(e.serviceConfig)};if("clientLanguage"in e)if(Array.isArray(e.clientLanguage)){t.clientLanguage=[];for(let r of e.clientLanguage)if(typeof r=="string")t.clientLanguage.push(r);else throw new Error("Invalid service config choice: invalid clientLanguage")}else throw new Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in e)if(Array.isArray(e.clientHostname)){t.clientHostname=[];for(let r of e.clientHostname)if(typeof r=="string")t.clientHostname.push(r);else throw new Error("Invalid service config choice: invalid clientHostname")}else throw new Error("Invalid service config choice: invalid clientHostname");if("percentage"in e)if(typeof e.percentage=="number"&&0<=e.percentage&&e.percentage<=100)t.percentage=e.percentage;else throw new Error("Invalid service config choice: invalid percentage");let n=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let r in e)if(!n.includes(r))throw new Error(`Invalid service config choice: unexpected field ${r}`);return t}function O3t(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=k3t(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===S3t.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===_3t&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function A3t(e,t){for(let n of e)if(n.length>0&&n[0].startsWith("grpc_config=")){let r=n.join("").substring(12),a=JSON.parse(r);return O3t(a,t)}return null}});var io=_(rD=>{"use strict";Object.defineProperty(rD,"__esModule",{value:!0});rD.ConnectivityState=void 0;var dCe;(function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.READY=2]="READY",e[e.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",e[e.SHUTDOWN=4]="SHUTDOWN"})(dCe||(rD.ConnectivityState=dCe={}))});var fp=_(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.QueuePicker=Lh.UnavailablePicker=Lh.PickResultType=void 0;var P3t=ga(),R3t=Yt(),iD;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(iD||(Lh.PickResultType=iD={}));var w7=class{constructor(t){this.status=Object.assign({code:R3t.Status.UNAVAILABLE,details:"No connection established",metadata:new P3t.Metadata},t)}pick(t){return{pickResultType:iD.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Lh.UnavailablePicker=w7;var I7=class{constructor(t,n){this.loadBalancer=t,this.childPicker=n,this.calledExitIdle=!1}pick(t){return this.calledExitIdle||(process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0),this.childPicker?this.childPicker.pick(t):{pickResultType:iD.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Lh.QueuePicker=I7});var lS=_(sD=>{"use strict";Object.defineProperty(sD,"__esModule",{value:!0});sD.BackoffTimeout=void 0;var C3t=Yt(),N3t=hr(),M3t="backoff",D3t=1e3,U3t=1.6,B3t=12e4,F3t=.2;function L3t(e,t){return Math.random()*(t-e)+e}var aD=class e{constructor(t,n){this.callback=t,this.initialDelay=D3t,this.multiplier=U3t,this.maxDelay=B3t,this.jitter=F3t,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=e.getNextId(),n&&(n.initialDelay&&(this.initialDelay=n.initialDelay),n.multiplier&&(this.multiplier=n.multiplier),n.jitter&&(this.jitter=n.jitter),n.maxDelay&&(this.maxDelay=n.maxDelay)),this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace(t){N3t.trace(C3t.LogVerbosity.DEBUG,M3t,"{"+this.id+"} "+t)}runTimer(t){var n,r;this.trace("runTimer(delay="+t+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+t),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},t),this.hasRef||(r=(n=this.timerId).unref)===null||r===void 0||r.call(n)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let t=Math.min(this.nextDelay*this.multiplier,this.maxDelay),n=t*this.jitter;this.nextDelay=t+L3t(-n,n)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let t=new Date,n=this.startTime;n.setMilliseconds(n.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),t<n?this.runTimer(n.getTime()-t.getTime()):this.running=!1}}isRunning(){return this.running}ref(){var t,n;this.hasRef=!0,(n=(t=this.timerId).ref)===null||n===void 0||n.call(t)}unref(){var t,n;this.hasRef=!1,(n=(t=this.timerId).unref)===null||n===void 0||n.call(t)}getEndTime(){return this.endTime}};sD.BackoffTimeout=aD;aD.nextId=0});var cD=_(oD=>{"use strict";Object.defineProperty(oD,"__esModule",{value:!0});oD.ChildLoadBalancerHandler=void 0;var V3t=Fh(),q3t=io(),$3t="child_load_balancer_helper",x7=class{constructor(t){this.channelControlHelper=t,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(n){this.parent=n,this.child=null}createSubchannel(n,r){return this.parent.channelControlHelper.createSubchannel(n,r)}updateState(n,r,a){var i;if(this.calledByPendingChild()){if(n===q3t.ConnectivityState.CONNECTING)return;(i=this.parent.currentChild)===null||i===void 0||i.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(n,r,a)}requestReresolution(){var n;let r=(n=this.parent.pendingChild)!==null&&n!==void 0?n:this.parent.currentChild;this.child===r&&this.parent.channelControlHelper.requestReresolution()}setChild(n){this.child=n}addChannelzChild(n){this.parent.channelControlHelper.addChannelzChild(n)}removeChannelzChild(n){this.parent.channelControlHelper.removeChannelzChild(n)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance(t,n){return t.getLoadBalancerName()!==n.getLoadBalancerName()}updateAddressList(t,n,r,a){let i;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,n)){let s=new this.ChildPolicyHelper(this),o=(0,V3t.createLoadBalancer)(n,s);s.setChild(o),this.currentChild===null?(this.currentChild=o,i=this.currentChild):(this.pendingChild&&this.pendingChild.destroy(),this.pendingChild=o,i=this.pendingChild)}else this.pendingChild===null?i=this.currentChild:i=this.pendingChild;return this.latestConfig=n,i.updateAddressList(t,n,r,a)}exitIdle(){this.currentChild&&(this.currentChild.exitIdle(),this.pendingChild&&this.pendingChild.exitIdle())}resetBackoff(){this.currentChild&&(this.currentChild.resetBackoff(),this.pendingChild&&this.pendingChild.resetBackoff())}destroy(){this.currentChild&&(this.currentChild.destroy(),this.currentChild=null),this.pendingChild&&(this.pendingChild.destroy(),this.pendingChild=null)}getTypeName(){return $3t}};oD.ChildLoadBalancerHandler=x7});var hCe=_(lD=>{"use strict";Object.defineProperty(lD,"__esModule",{value:!0});lD.ResolvingLoadBalancer=void 0;var z3t=Fh(),G3t=_7(),Mo=io(),fCe=Zl(),tk=fp(),J3t=lS(),E7=Yt(),H3t=ga(),W3t=hr(),j3t=Yt(),Y3t=ro(),K3t=cD(),X3t="resolving_load_balancer";function pCe(e){W3t.trace(j3t.LogVerbosity.DEBUG,X3t,e)}var Z3t=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function Q3t(e,t,n,r){for(let a of n.name)switch(r){case"EMPTY":if(!a.service&&!a.method)return!0;break;case"SERVICE":if(a.service===e&&!a.method)return!0;break;case"SERVICE_AND_METHOD":if(a.service===e&&a.method===t)return!0}return!1}function eUt(e,t,n,r){for(let a of n)if(Q3t(e,t,a,r))return a;return null}function tUt(e){return{invoke(t,n){var r,a;let i=t.split("/").filter(c=>c.length>0),s=(r=i[0])!==null&&r!==void 0?r:"",o=(a=i[1])!==null&&a!==void 0?a:"";if(e&&e.methodConfig)for(let c of Z3t){let l=eUt(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:E7.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:E7.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var T7=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=Mo.ConnectivityState.IDLE,this.latestChildPicker=new tk.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=Mo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,G3t.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(Mo.ConnectivityState.IDLE,new tk.QueuePicker(this),null),this.childLoadBalancer=new K3t.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(pCe("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0):this.updateResolution()},updateState:(o,c,l)=>{this.latestChildState=o,this.latestChildPicker=c,this.latestChildErrorMessage=l,this.updateState(o,c,l)},addChannelzChild:n.addChannelzChild.bind(n),removeChannelzChild:n.removeChannelzChild.bind(n)}),this.innerResolver=(0,fCe.createResolver)(t,this.handleResolverResult.bind(this),r);let s={initialDelay:r["grpc.initial_reconnect_backoff_ms"],maxDelay:r["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new J3t.BackoffTimeout(()=>{this.continueResolving?(this.updateResolution(),this.continueResolving=!1):this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},s),this.backoffTimeout.unref()}handleResolverResult(t,n,r,a){var i,s;this.backoffTimeout.stop(),this.backoffTimeout.reset();let o=!0,c=null;if(r===null?c=this.defaultServiceConfig:r.ok?c=r.value:this.previousServiceConfig!==null?c=this.previousServiceConfig:(o=!1,this.handleResolutionFailure(r.error)),c!==null){let l=(i=c?.loadBalancingConfig)!==null&&i!==void 0?i:[],u=(0,z3t.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:E7.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new H3t.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[fCe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:tUt(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===Mo.ConnectivityState.IDLE&&this.updateState(Mo.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){pCe((0,Y3t.uriToString)(this.target)+" "+Mo.ConnectivityState[this.currentState]+" -> "+Mo.ConnectivityState[t]),t===Mo.ConnectivityState.IDLE&&(n=new tk.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===Mo.ConnectivityState.IDLE&&(this.updateState(Mo.ConnectivityState.TRANSIENT_FAILURE,new tk.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===Mo.ConnectivityState.IDLE||this.currentState===Mo.ConnectivityState.TRANSIENT_FAILURE)&&(this.backoffTimeout.isRunning()?this.continueResolving=!0:this.updateResolution()),this.childLoadBalancer.exitIdle()}updateAddressList(t,n){throw new Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=Mo.ConnectivityState.IDLE,this.latestChildPicker=new tk.QueuePicker(this),this.currentState=Mo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};lD.ResolvingLoadBalancer=T7});var mCe=_(nk=>{"use strict";Object.defineProperty(nk,"__esModule",{value:!0});nk.recognizedOptions=void 0;nk.channelOptionsEqual=nUt;nk.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function nUt(e,t){let n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let a=0;a<n.length;a+=1)if(n[a]!==r[a]||e[n[a]]!==t[r[a]])return!1;return!0}});var Do=_(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.EndpointMap=void 0;Ql.isTcpSubchannelAddress=ik;Ql.subchannelAddressEqual=uD;Ql.subchannelAddressToString=yCe;Ql.stringToSubchannelAddress=iUt;Ql.endpointEqual=aUt;Ql.endpointToString=sUt;Ql.endpointHasAddress=vCe;var gCe=require("net");function ik(e){return"port"in e}function uD(e,t){return!e&&!t?!0:!e||!t?!1:ik(e)?ik(t)&&e.host===t.host&&e.port===t.port:!ik(t)&&e.path===t.path}function yCe(e){return ik(e)?(0,gCe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var rUt=443;function iUt(e,t){return(0,gCe.isIP)(e)?{host:e,port:t??rUt}:{path:e}}function aUt(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!uD(e.addresses[n],t.addresses[n]))return!1;return!0}function sUt(e){return"["+e.addresses.map(yCe).join(", ")+"]"}function vCe(e,t){for(let n of e.addresses)if(uD(n,t))return!0;return!1}function rk(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n of e.addresses){let r=!1;for(let a of t.addresses)if(uD(n,a)){r=!0;break}if(!r)return!1}return!0}var k7=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(vCe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)rk(i,r.key)&&(a=!0);a||(n.push(r.value),this.map.delete(r))}return n}get(t){for(let n of this.map)if(rk(t,n.key))return n.value}set(t,n){for(let r of this.map)if(rk(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(rk(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(rk(t,n.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let t of this.map)yield t.key}*values(){for(let t of this.map)yield t.value}*entries(){for(let t of this.map)yield[t.key,t.value]}};Ql.EndpointMap=k7});var bCe=_(D7=>{"use strict";Object.defineProperty(D7,"t",{value:!0});var dD=class{constructor(t,n,r=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=t,this.l=n,this.p=r}I(){let t=this,n=t.o.o===t;if(n&&t.p===1)t=t.h;else if(t.i)for(t=t.i;t.h;)t=t.h;else{if(n)return t.o;let r=t.o;for(;r.i===t;)t=r,r=t.o;t=r}return t}B(){let t=this;if(t.h){for(t=t.h;t.i;)t=t.i;return t}else{let n=t.o;for(;n.h===t;)t=n,n=t.o;return t.h!==n?n:t}}_(){let t=this.o,n=this.h,r=n.i;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.i=this,this.o=n,this.h=r,r&&(r.o=this),n}g(){let t=this.o,n=this.i,r=n.h;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.h=this,this.o=n,this.i=r,r&&(r.o=this),n}},O7=class extends dD{constructor(){super(...arguments),this.M=1}_(){let t=super._();return this.O(),t.O(),t}g(){let t=super.g();return this.O(),t.O(),t}O(){this.M=1,this.i&&(this.M+=this.i.M),this.h&&(this.M+=this.h.M)}},A7=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},P7=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},R7=class extends P7{};function Oy(){throw new RangeError("Iterator access denied!")}var C7=class extends R7{constructor(t=function(r,a){return r<a?-1:r>a?1:0},n=!1){super(),this.v=void 0,this.A=t,this.enableIndex=n,this.N=n?O7:dD,this.C=new this.N}R(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)t=t.h;else if(a>0)r=t,t=t.i;else return t}return r}K(t,n){let r=this.C;for(;t;)this.A(t.u,n)<=0?t=t.h:(r=t,t=t.i);return r}L(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)r=t,t=t.h;else if(a>0)t=t.i;else return t}return r}k(t,n){let r=this.C;for(;t;)this.A(t.u,n)<0?(r=t,t=t.h):t=t.i;return r}P(t){for(;;){let n=t.o;if(n===this.C)return;if(t.p===1){t.p=0;return}if(t===n.i){let r=n.h;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n._():n._();else if(r.h&&r.h.p===1){r.p=n.p,n.p=0,r.h.p=0,n===this.v?this.v=n._():n._();return}else r.i&&r.i.p===1?(r.p=1,r.i.p=0,r.g()):(r.p=1,t=n)}else{let r=n.i;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n.g():n.g();else if(r.i&&r.i.p===1){r.p=n.p,n.p=0,r.i.p=0,n===this.v?this.v=n.g():n.g();return}else r.h&&r.h.p===1?(r.p=1,r.h.p=0,r._()):(r.p=1,t=n)}}}S(t){if(this.m===1){this.clear();return}let n=t;for(;n.i||n.h;){if(n.h)for(n=n.h;n.i;)n=n.i;else n=n.i;let a=t.u;t.u=n.u,n.u=a;let i=t.l;t.l=n.l,n.l=i,t=n}this.C.i===n?this.C.i=n.o:this.C.h===n&&(this.C.h=n.o),this.P(n);let r=n.o;if(n===r.i?r.i=void 0:r.h=void 0,this.m-=1,this.v.p=0,this.enableIndex)for(;r!==this.C;)r.M-=1,r=r.o}U(t){let n=typeof t=="number"?t:void 0,r=typeof t=="function"?t:void 0,a=typeof t>"u"?[]:void 0,i=0,s=this.v,o=[];for(;o.length||s;)if(s)o.push(s),s=s.i;else{if(s=o.pop(),i===n)return s;a&&a.push(s),r&&r(s,i,this),i+=1,s=s.h}return a}j(t){for(;;){let n=t.o;if(n.p===0)return;let r=n.o;if(n===r.i){let a=r.h;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.h){if(t.p=0,t.i&&(t.i.o=n),t.h&&(t.h.o=r),n.h=t.i,r.i=t.h,t.i=n,t.h=r,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r.g():r.g(),r.p=1;return}}else{let a=r.i;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.i){if(t.p=0,t.i&&(t.i.o=r),t.h&&(t.h.o=n),r.h=t.i,n.i=t.h,t.i=r,t.h=n,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r._():r._(),r.p=1;return}}this.enableIndex&&(n.O(),r.O(),t.O());return}}q(t,n,r){if(this.v===void 0)return this.m+=1,this.v=new this.N(t,n,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let a,i=this.C.i,s=this.A(i.u,t);if(s===0)return i.l=n,this.m;if(s>0)i.i=new this.N(t,n),i.i.o=i,a=i.i,this.C.i=a;else{let o=this.C.h,c=this.A(o.u,t);if(c===0)return o.l=n,this.m;if(c<0)o.h=new this.N(t,n),o.h.o=o,a=o.h,this.C.h=a;else{if(r!==void 0){let l=r.T;if(l!==this.C){let u=this.A(l.u,t);if(u===0)return l.l=n,this.m;if(u>0){let d=l.I(),f=this.A(d.u,t);if(f===0)return d.l=n,this.m;f<0&&(a=new this.N(t,n),d.h===void 0?(d.h=a,a.o=d):(l.i=a,a.o=l))}}}if(a===void 0)for(a=this.v;;){let l=this.A(a.u,t);if(l>0){if(a.i===void 0){a.i=new this.N(t,n),a.i.o=a,a=a.i;break}a=a.i}else if(l<0){if(a.h===void 0){a.h=new this.N(t,n),a.h.o=a,a=a.h;break}a=a.h}else return a.l=n,this.m}}}if(this.enableIndex){let o=a.o;for(;o!==this.C;)o.M+=1,o=o.o}return this.j(a),this.m+=1,this.m}H(t,n){for(;t;){let r=this.A(t.u,n);if(r<0)t=t.h;else if(r>0)t=t.i;else return t}return t||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator(t,n){let r=t.T;if(r===this.C&&Oy(),this.m===1)return r.u=n,!0;let a=r.B().u;if(r===this.C.i)return this.A(a,n)>0?(r.u=n,!0):!1;let i=r.I().u;return r===this.C.h?this.A(i,n)<0?(r.u=n,!0):!1:this.A(i,n)>=0||this.A(a,n)<=0?!1:(r.u=n,!0)}eraseElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return this.S(n),this.m}eraseElementByKey(t){if(this.m===0)return!1;let n=this.H(this.v,t);return n===this.C?!1:(this.S(n),!0)}eraseElementByIterator(t){let n=t.T;n===this.C&&Oy();let r=n.h===void 0;return t.iteratorType===0?r&&t.next():(!r||n.i===void 0)&&t.next(),this.S(n),t}getHeight(){if(this.m===0)return 0;function t(n){return n?Math.max(t(n.i),t(n.h))+1:0}return t(this.v)}},N7=class extends A7{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&Oy(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&Oy(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&Oy(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&Oy(),this.T=this.T.I(),this})}get index(){let t=this.T,n=this.C.o;if(t===this.C)return n?n.M-1:0;let r=0;for(t.i&&(r+=t.i.M);t!==n;){let a=t.o;t===a.h&&(r+=1,a.i&&(r+=a.i.M)),t=a}return r}isAccessible(){return this.T!==this.C}},eu=class e extends N7{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&Oy();let t=this;return new Proxy([],{get(n,r){return r==="0"?t.T.u:r==="1"?t.T.l:(n[0]=t.T.u,n[1]=t.T.l,n[r])},set(n,r,a){if(r!=="1")throw new TypeError("prop must be 1");return t.T.l=a,!0}})}copy(){return new e(this.T,this.C,this.container,this.iteratorType)}},M7=class extends C7{constructor(t=[],n,r){super(n,r);let a=this;t.forEach(function(i){a.setElement(i[0],i[1])})}begin(){return new eu(this.C.i||this.C,this.C,this)}end(){return new eu(this.C,this.C,this)}rBegin(){return new eu(this.C.h||this.C,this.C,this,1)}rEnd(){return new eu(this.C,this.C,this,1)}front(){if(this.m===0)return;let t=this.C.i;return[t.u,t.l]}back(){if(this.m===0)return;let t=this.C.h;return[t.u,t.l]}lowerBound(t){let n=this.R(this.v,t);return new eu(n,this.C,this)}upperBound(t){let n=this.K(this.v,t);return new eu(n,this.C,this)}reverseLowerBound(t){let n=this.L(this.v,t);return new eu(n,this.C,this)}reverseUpperBound(t){let n=this.k(this.v,t);return new eu(n,this.C,this)}forEach(t){this.U(function(n,r,a){t([n.u,n.l],r,a)})}setElement(t,n,r){return this.q(t,n,r)}getElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return[n.u,n.l]}find(t){let n=this.H(this.v,t);return new eu(n,this.C,this)}getElementByKey(t){return this.H(this.v,t).l}union(t){let n=this;return t.forEach(function(r){n.setElement(r[0],r[1])}),this.m}*[Symbol.iterator](){let t=this.m,n=this.U();for(let r=0;r<t;++r){let a=n[r];yield[a.u,a.l]}}};D7.OrderedMap=M7});var pD=_(fD=>{"use strict";Object.defineProperty(fD,"__esModule",{value:!0});fD.registerAdminService=oUt;fD.addAdminServicesToServer=cUt;var SCe=[];function oUt(e,t){SCe.push({getServiceDefinition:e,getHandlers:t})}function cUt(e){for(let{getServiceDefinition:t,getHandlers:n}of SCe)e.addService(t(),n())}});var _Ce=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.ClientDuplexStreamImpl=tu.ClientWritableStreamImpl=tu.ClientReadableStreamImpl=tu.ClientUnaryCallImpl=void 0;tu.callErrorFromStatus=uUt;var lUt=require("events"),V7=require("stream"),ak=Yt();function uUt(e,t){let n=`${e.code} ${ak.Status[e.code]}: ${e.details}`,a=`${new Error(n).stack}
217
+ `,r="",a=i=>{for(let s=Math.min(i.length,n.length);s>0;s--)if(n.startsWith(i.slice(i.length-s)))return s;return 0};return{push(i){r+=i;let s=a(r);s!==r.length&&(t(r.slice(0,r.length-s)),r=r.slice(r.length-s))},flush(){let i=r===n||r===e?"":r;r="",i&&t(i)}}}function qW(e,t,n,r){let a=e;return t&&(a=`cd '${t.replace(/'/g,"'\\''")}' && ${a}`),n&&Object.keys(n).length>0&&(a=`${Object.entries(n).filter(([,i])=>i!=null).map(([i,s])=>`export ${i}='${String(s).replace(/'/g,"'\\''")}'`).join("; ")}; ${a}`),r==="root"&&(a=`echo ${Buffer.from(a).toString("base64")} | base64 -d | sudo -n bash`),a}function _Re(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function xMt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!_Re(e)}function EMt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function TMt(e){return/^[^:]+:\d+$/.test(e)}function kMt(e){return e.startsWith("*.")&&e.length>2&&!e.slice(2).includes("*")}function HT(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return e?{networkBlockAll:!1}:{}}let t=e.allowedDestinations??[];if(t.length===0)return{networkBlockAll:!0};for(let i of t){if(i.trim()==="")throw new Kl("invalid-destination",`network.allowedDestinations contains an empty destination (${JSON.stringify(i)}). Every entry must be a hostname, *.wildcard domain, IPv4 address, or IPv4 CIDR \u2014 remove the blank entry (an empty allowlist would open the sandbox, not seal it).`,i);if(i.includes(","))throw new Kl("invalid-destination",`network.allowedDestinations entry "${i}" contains a comma. Daytona's allowlists are sent as one comma-joined string, so a comma inside an entry would smuggle extra destinations past the list caps \u2014 pass one destination per array entry.`,i)}let n=[],r=[];for(let i of t)if(_Re(i))n.push(i.includes("/")?i:`${i}/32`);else{if(xMt(i))throw new Kl("invalid-ipv4",`"${i}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,i);if(EMt(i))throw new Kl("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${i}".`,i);if(TMt(i))throw new Kl("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${i}" and list just the host or IP.`,i);if(i.includes("*")&&!kMt(i))throw new Kl("wildcard-hostname",`Daytona's domain allowlist supports exactly one wildcard form \u2014 a "*." prefix ("*.example.com" allows example.com and its subdomains) \u2014 and cannot express "${i}". Use a *.prefix wildcard, a concrete hostname, or an IPv4 CIDR instead.`,i);r.push(i)}if(n.length>0&&r.length>0)throw new Kl("mixed-allowlist",`Daytona's networkAllowList (IPv4 CIDRs) and domainAllowList (DNS names) are mutually exclusive \u2014 at most one may be non-empty per sandbox, and this policy names both kinds (CIDRs: ${n.join(", ")}; domains: ${r.join(", ")}). List only IPs/CIDRs or only hostnames for this sandbox.`);if(r.length>0){let i=[...new Set(r)];if(i.length>CW)throw new Kl("allowlist-too-large",`Daytona allows at most ${CW} entries in its domain allowlist; this policy names ${i.length} domains (${i.join(", ")}). Consolidate under *.prefix wildcards or reduce the list.`);return{networkBlockAll:!1,domainAllowList:i.join(",")}}let a=[...new Set(n)];if(a.length>RW)throw new Kl("allowlist-too-large",`Daytona allows at most ${RW} entries in its network allowlist; this policy resolved to ${a.length} CIDRs (${a.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return{networkBlockAll:!1,networkAllowList:a.join(",")}}function wRe(e){let t=HT(e);return t.networkAllowList!==void 0||t.domainAllowList!==void 0?{networkBlockAll:!1,networkAllowList:t.networkAllowList??"",domainAllowList:t.domainAllowList??""}:{networkBlockAll:t.networkBlockAll===!0,networkAllowList:"",domainAllowList:""}}function IRe(e){let t=HW(e),n=(e instanceof Error?e.message:String(e)).toLowerCase(),r=n.includes("network policy")||n.includes("network settings")||n.includes("network configuration"),a=n.includes("tier")||n.includes("plan")||n.includes("upgrade")||n.includes("not allowed")||n.includes("not permitted")||n.includes("cannot override");return(t===402||t===403)&&(a||r)?!0:r&&a}function xRe(e){let t=e.indexOf("/");if(t<0)return;let n=e.substring(0,t);return n.includes(".")||n.includes(":")||n==="localhost"?n:void 0}function WW(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function ERe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function TRe(e,t){if(!e||typeof e!="object")return;let n=e;if(typeof n.toolboxProxyUrl=="string"&&(n.toolboxProxyUrl=t),Array.isArray(n.items))for(let r of n.items)TRe(r,t)}function OMt(e,t){return new Proxy(e,{get(n,r,a){if(r==="getToolboxProxyUrl")return async()=>({data:{url:t}});let i=Reflect.get(n,r,a);return typeof i!="function"?i:function(...s){let o=i.apply(n,s);return o instanceof Promise?o.then(c=>(TRe(c?.data,t),c)):o}}})}function PMt(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function ZPe(e,t,n){e:for(let r=n;r+t.length<=e.length;r++){for(let a=0;a<t.length;a++)if(e[r+a]!==t[a])continue e;return r}return-1}function kRe(e,t){let n=new TextDecoder("utf-8"),r=new TextDecoder("utf-8"),a=new Uint8Array(0),i="stdout",s=o=>{o.length!==0&&(i==="stdout"?e(n.decode(o,{stream:!0})):t(r.decode(o,{stream:!0})))};return{push(o){for(a=PMt(a,o);;){let c=ZPe(a,ly,0),l=ZPe(a,uy,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=ly.length):l!==-1&&(u=l,d="stderr",f=uy.length),u===-1){let p=Math.max(0,a.length-(Rh-1));s(a.subarray(0,p)),a=a.slice(p);return}s(a.subarray(0,u)),i=d,a=a.slice(u+f)}},flush(){s(a),a=new Uint8Array(0);let o=n.decode();o&&e(o);let c=r.decode();c&&t(c)}}}async function ORe(e,t,n,r,a,i,s){let o=`${e.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(n)}/command/${encodeURIComponent(r)}/logs?follow=true`,c=await fetch(o,{headers:{Authorization:`Bearer ${e.apiKey}`,accept:"application/octet-stream"},...s?{signal:s}:{}});if(!c.ok)throw new Error(`Daytona managed log follow failed: ${c.status} ${await c.text()}`);if(!c.body)return;let l=kRe(a,i),u=c.body.getReader();try{for(;;){let{done:d,value:f}=await u.read();if(d)break;f&&l.push(f)}}finally{l.flush(),await u.cancel().catch(()=>{})}}function ARe(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function CMt(e,t){let n=HPe(e),r=t==="children"?`[ -e ${n} ] || exit ${PW}; [ -d ${n} ] || exit ${nRe};`:`[ -e ${n} ] || [ -L ${n} ] || exit ${PW};`,a=t==="children"?`find -H ${n} -mindepth 1 -maxdepth 1 -printf '${QPe}'`:`find ${n} -maxdepth 0 -printf '${QPe}'`;return`sh -c ${HPe(`${r} ( ${a}; printf 'STATUS:%d' "$?" ) | base64`)}`}function NMt(e,t,n){let r=Buffer.from(t.replace(/\s+/g,""),"base64").toString("utf-8").split("\0"),a=r.pop()??"",i=/^STATUS:(\d+)$/.exec(a);if(!i)throw new Error(`daytona: the listing of ${e} ended without find's status (${a.slice(0,40)})`);if(i[1]!=="0")throw new Error(`daytona: find exited ${i[1]} listing ${e}`);let s=[];for(let o=0;o+kW<=r.length;o+=kW){let[c,l,u,d,f,p,m,y]=r.slice(o,o+kW),b=c==="f"?"file":c==="d"?"dir":c==="l"?"symlink":"other",v={name:y,path:n==="children"?fMt(e,y):e,type:b,size:Number(l),mtime:iRe(Number(u)),mode:dMt(d),owner:f,group:p};b==="symlink"&&(v.target=m),s.push(v)}return s}function MMt(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function CRe(e,t){let n=t?.limit,r=[],a=0,i=new Set;try{for await(let s of e){if(n!==void 0&&r.length>=n)return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!0,error:`stopped at the requested limit of ${n} with more sandboxes available`};if(a+=1,a>NM)return{sandboxes:r,complete:!1,pagesFetched:NM,stoppedAtLimit:!1,error:`sandbox list exceeded ${NM} sandboxes scanned`};if(t?.state){let o=ERe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push(WW(s)))}}catch(s){return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!1,error:`sandbox list failed: ${s instanceof Error?s.message:String(s)}`}}return{sandboxes:r,complete:!0,pagesFetched:a,stoppedAtLimit:!1}}function BM(e={}){let t=e.apiKey??process.env.DAYTONA_API_KEY;if(!t)throw new Error("Daytona API key required. Set DAYTONA_API_KEY environment variable or pass apiKey in config. Get your key at https://app.daytona.io/dashboard/keys");return new jW({...e,apiKey:t})}var eRe,AW,DM,tRe,PW,nRe,UM,zW,aRe,RW,CW,sRe,mMt,GW,oRe,cRe,Mh,lRe,NM,Kl,uRe,vMt,MM,dRe,fRe,bMt,pRe,MW,hRe,jPe,Ey,JT,JW,mRe,_Mt,YPe,wMt,gRe,yRe,AMt,PRe,QPe,kW,RMt,RRe,GT,jW,DMt,UMt,BMt,FMt,LMt,VMt,qMt,$Mt,zMt,GMt,JMt,HMt,WMt,jMt,YMt,KMt,XMt,ZMt,QMt,eDt,tDt,nDt,OW,WT=Q(()=>{"use strict";JPe();eRe=require("crypto"),AW=class extends Error{feature;provider;reason;constructor(e,t,n){super(`${t} does not support ${e}${n?`: ${n}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=e,this.provider=t,this.reason=n}},DM=class extends Error{path;provider;constructor(e,t){super(`${t}: no such file or directory: ${e}`),this.name="SandboxPathNotFoundError",this.path=e,this.provider=t}},tRe=class extends Error{sandboxId;provider;state;constructor(e,t,n){super(`${t} sandbox ${e} is not running (${n}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=e,this.provider=t,this.state=n}};PW=2,nRe=20;UM="c-5ae94df74154",zW={[`evolve-all-${UM}`]:`evolvingmachines/evolve-all:${UM}`,"evolve-all":"evolvingmachines/evolve-all"},aRe=10,RW=10,CW=20,sRe=18e4,mMt=2e3,GW=6e5,oRe=5e3,cRe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},Mh=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),lRe=100,NM=1e4;Kl=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},uRe=class extends Error{image;constructor(e,t){let n=t instanceof Error?t.message:String(t??"unknown error");super(`Failed to pull image "${e}" on Daytona: ${n}. Private registry images require the registry pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret; AWS ECR registrations name an IAM role Daytona assumes (no password). Register the registry at https://app.daytona.io, then retry. Also ensure the image is linux/amd64 and pinned to a tag or digest (floating tags like "latest" are rejected by Daytona's snapshot builder).`),this.name="DaytonaImagePullError",this.image=e}},vMt=class extends Error{snapshot;constructor(e){super(`Daytona cannot constrain the GPU type for "${e}": the snapshot already exists and pins its resources \u2014 pre-build a snapshot with the desired GPU type under its own name.`),this.name="DaytonaGpuTypeError",this.snapshot=e}},MM=class extends Error{snapshot;constructor(e){super(`Daytona snapshot "${e}" already exists and pins its cpu/memory/disk sizing \u2014 create-from-snapshot cannot resize it, so the requested \`resources\` cannot be enforced. Pre-build a snapshot with the desired sizing under its own name (sizing-addressed), or omit \`resources\` to accept the snapshot's pinned sizing.`),this.name="DaytonaResourcesError",this.snapshot=e}},dRe=class extends Error{constructor(){super("Daytona takes no create-time boot command: it never runs an image entrypoint or any argv at boot (harbor daytona/environment.py:706-708 works around exactly that, starting dockerd by hand). The boot is already inert \u2014 run the process by exec after create."),this.name="DaytonaBootCommandError"}},fRe=class extends Error{constructor(){super("Daytona has no separate idle timeout: auto-stop IS its only clock and it already measures inactivity, so `timeoutMs` is what sets it (autoStopInterval). Set the inactivity bound with `timeoutMs`; a hard bound on the process itself is enforced in-box instead (see withInBoxTimeout)."),this.name="DaytonaIdleTimeoutError"}},bMt=new Set(["pending_build","building_snapshot","pulling_snapshot"]);pRe=class extends Error{phase;state;sandboxId;constructor(e,t,n){super(`Daytona sandbox boot abandoned during ${e} (provider state ${t??"not yet reported"}, sandbox ${n??"not yet created"})`),this.name="DaytonaBootAbortedError",this.phase=e,this.state=t,this.sandboxId=n}},MW="evolve_boot",hRe=5e3,jPe=30;Ey=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" exists but could not be activated: ${t}. Daytona deactivates snapshots unused for 2 weeks; activation normally completes in seconds. Retry, or activate it manually in the Daytona dashboard (Snapshots page).`),this.name="DaytonaSnapshotActivationError",this.snapshot=e}};JT=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" is being created by another process and this run could not wait it out: ${t}.`),this.name="DaytonaSnapshotConflictError",this.snapshot=e}},JW=Symbol("daytona-snapshot-gone"),mRe=new Set(["pending","pulling","building","snapshotting"]),_Mt=3;YPe=new Set(["error","build_failed"]),wMt=new Set(["latest","lts","stable"]);gRe=6e4,yRe=2e3;AMt=class extends vy{constructor(e,t){super(e);let n=this;n.sandboxApi=OMt(n.sandboxApi,t)}};PRe=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=cRe;followLogs(e,t,n,r,a){return this.managedStream?ORe(this.managedStream,this.sandbox.id,e,t,n,r,a):this.sandbox.process.getSessionCommandLogs(e,t,n,r)}async run(e,t){let n=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(r);try{let a=!!(t?.onStdout||t?.onStderr),i=XPe(),s=await this.sandbox.process.executeSessionCommand(r,{command:FW(qW(LW(e,i),t?.cwd,t?.envs,this.user),n),runAsync:a},n),o=s.cmdId;if(a&&!o)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(a&&o){let u="",d="",f=!0,p=Date.now(),m=VW(i,T=>{u+=T,t?.onStdout?.(T)}),y=new AbortController,b=this.followLogs(r,o,T=>{f&&(p=Date.now(),m.push(T))},T=>{f&&(p=Date.now(),d+=T,t?.onStderr?.(T))},y.signal),v=!1,S,w=b.then(()=>{},T=>{v||(S=T)}),I;try{I=await this.awaitStreamedExit(r,o,b,()=>p,t?.timeoutMs)}finally{v=!0,y.abort(),await Promise.race([w,Mh(this.streamTimings.drainMs)]),f=!1,S===void 0&&m.flush()}if(S!==void 0){let T;try{let R=await this.sandbox.process.getSessionCommandLogs(r,o);T=tS(R,i)}catch{throw S}if(!T.stdout.startsWith(u)||!T.stderr.startsWith(d))throw S;let k=T.stdout.slice(u.length),O=T.stderr.slice(d.length);u=T.stdout,d=T.stderr,k&&t?.onStdout?.(k),O&&t?.onStderr?.(O)}else if(!u&&!d)try{let T=await this.sandbox.process.getSessionCommandLogs(r,o),k=tS(T,i);u=k.stdout,d=k.stderr,u&&t?.onStdout?.(u),d&&t?.onStderr?.(d)}catch{}return{exitCode:I,stdout:u,stderr:d}}let{stdout:c,stderr:l}=tS(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=tS(u,i);c=d.stdout,l=d.stderr||l}catch{}return{exitCode:s.exitCode??0,stdout:c,stderr:l}}finally{try{await this.sandbox.process.deleteSession(r)}catch{}}}async awaitStreamedExit(e,t,n,r,a){let i=this.streamTimings,s,o,c=n.then(()=>{s=Date.now()},d=>{s=Date.now(),o=d}),l=a!==void 0&&a>0?Date.now()+a+i.killGraceMs:void 0,u=i.pollMinMs;for(;;){let d=await this.sandbox.process.getSessionCommand(e,t);if(d.exitCode!==void 0&&d.exitCode!==null){for(;s===void 0;){let m=Date.now()-r();if(m>=i.drainMs)break;await Promise.race([c,Mh(i.drainMs-m)])}return d.exitCode}let f=s!==void 0?s+i.settleMs:void 0,p=l!==void 0&&f!==void 0?Math.min(l,f):l??f;if(p!==void 0&&Date.now()>=p)throw o!==void 0?o:new Error(`Daytona reported no exit code for command ${t} after `+(s!==void 0?"its log stream closed":`${a}ms`));await Mh(u),u=Math.min(u*2,i.pollMaxMs)}}async spawn(e,t){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let r=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,a=Date.now(),i=t?.timeoutMs,s=XPe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:FW(qW(LW(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=VW(s,t.onStdout||(()=>{}));this.followLogs(n,o,u=>l.push(u),t.onStderr||(()=>{})).catch(()=>{}).finally(()=>l.flush())}let c=this.sandbox;return{processId:n,wait:async()=>{if(!o)return{exitCode:0,stdout:"",stderr:""};for(;;){if(i&&Date.now()-a>=i){try{await c.process.deleteSession(n)}catch{}return{exitCode:124,stdout:"",stderr:"operation timed out"}}try{let l=await c.process.getSessionCommand(n,o);if(l.exitCode!==void 0)try{let u=await c.process.getSessionCommandLogs(n,o);return{exitCode:l.exitCode,...tS(u,s)}}catch{return{exitCode:l.exitCode,stdout:"",stderr:""}}}catch(l){let u=l instanceof Error?l.message.toLowerCase():String(l).toLowerCase();if(u.includes("not found")){let d=u.includes("sandbox");try{await c.refreshData(),d=!1}catch(f){(f instanceof Error?f.message.toLowerCase():String(f).toLowerCase()).includes("not found")&&(d=!0)}return{exitCode:-1,stdout:"",stderr:d?"sandbox deleted during run":"session terminated"}}throw l}await Mh(500)}},kill:async()=>{try{return await c.process.deleteSession(n),!0}catch{return!1}}}}async list(){try{return(await this.sandbox.process.listSessions()).map(e=>({processId:e.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return[]}}async kill(e){try{return await this.sandbox.process.deleteSession(e),!0}catch{return!1}}},QPe="%y\\0%s\\0%T@\\0%m\\0%u\\0%g\\0%l\\0%f\\0",kW=8,RMt=1800*1e3;RRe=class{constructor(e,t){this.sandbox=e,this.commands=t}async read(e){let t=new Uint8Array(await this.sandbox.fs.downloadFile(e));if(!t.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{}return t}async write(e,t){let n;if(typeof t=="string")n=Buffer.from(t,"utf-8");else if(Buffer.isBuffer(t))n=t;else if(t instanceof ArrayBuffer)n=Buffer.from(t);else if(t instanceof Uint8Array)n=Buffer.from(t);else throw new Error(`Unsupported content type: ${typeof t}`);await this.sandbox.fs.uploadFile(n,e)}async writeBatch(e){let t=e.map(n=>{let r;if(typeof n.data=="string")r=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))r=n.data;else if(n.data instanceof ArrayBuffer)r=Buffer.from(n.data);else if(n.data instanceof Uint8Array)r=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return{source:r,destination:n.path}});await this.sandbox.fs.uploadFiles(t)}async writeFromPath(e,t){await this.sandbox.fs.uploadFile(t,e)}async makeDir(e){await this.sandbox.fs.createFolder(e,"755")}async exists(e){try{let t=gMt(e),n=yMt(e);return(await this.sandbox.fs.listFiles(t)).some(r=>r.name===n)}catch{return!1}}async list(e){return this.findListing(e,"children")}async stat(e){let[t]=await this.findListing(e,"self");if(!t)throw new DM(e,"daytona");return t}async findListing(e,t){let n=await this.commands.run(CMt(e,t));if(n.exitCode===PW)throw new DM(e,"daytona");if(n.exitCode===nRe)throw new Error(`daytona: ${e} is not a directory`);if(n.exitCode!==0)throw new Error(`daytona: listing ${e} failed (exit ${n.exitCode}): ${n.stderr.trim()}`);try{return NMt(e,n.stdout,t)}catch(r){throw/printf|unrecognized|invalid option/i.test(n.stderr)?new AW("files.list","daytona",`this image's find has no -printf (GNU findutils is needed to list entries as themselves): ${n.stderr.trim()}`):r}}async readRange(e,t){if(rRe(t),t.length===0)return new Uint8Array(0);let n=await this.sandbox.downloadUrl(e);return pMt(n,t,{provider:"daytona",path:e,timeoutMs:RMt})}async watchDir(e,t,n){throw new AW("files.watchDir","daytona","the Daytona SDK has no filesystem watcher; poll files.list() on the directories you have open")}async remove(e){await this.sandbox.fs.deleteFile(e,!0)}async rename(e,t){await this.sandbox.fs.moveFiles(e,t)}},GT=class{constructor(e,t,n){this.sandbox=e;let r=new PRe(e,t,n);this.commands=r,this.files=new RRe(e,r)}commands;files;get sandboxId(){return this.sandbox.id}async getHost(e){return(await this.sandbox.getPreviewLink(e)).url}async isRunning(){try{await this.sandbox.refreshData()}catch{return!1}return this.sandbox.state==="started"}async getInfo(){return await this.sandbox.refreshData(),WW(this.sandbox)}async metrics(){let e=await this.sandbox.getMetricsLatest();return{cpuPct:e.cpuUsedPct,memUsedMb:e.memUsed/OW,memTotalMb:e.memTotal/OW,diskUsedMb:e.diskUsed/OW,sampledAt:iRe(e.timestamp),source:"daytona:getMetricsLatest"}}async updateNetwork(e){let t=wRe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw IRe(n)?new Kl("org-tier-forbidden",`Daytona refused to change this sandbox's network policy: organizations on Tier 1 or Tier 2 cannot override network policy at the sandbox level. Raise the organization's tier, or run this workload on a provider whose plan permits runtime policy changes (underlying error: ${n instanceof Error?n.message:String(n)}).`):n}}async kill(){await this.sandbox.delete()}async pause(){await this.sandbox.stop()}},jW=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:GW,pollMs:oRe};snapshotDeleteTiming={timeoutMs:gRe,pollMs:yRe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new AMt(t,e.managedToolboxUrl):new vy(t),e.managedToolboxUrl&&(this.managedStream={toolboxUrl:e.managedToolboxUrl,apiKey:e.apiKey}),this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.snapshotName=e.snapshotName??(e.managedToolboxUrl?"evolve-all":`evolve-all-${UM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new fRe;if(e.bootCommand!==void 0)throw new dRe;for(let f of e.phaseNetworkPolicies??[])HT(f);let t=HT(e.network),n=e.user,r=n&&n!=="root"?n:void 0,a=e.timeoutMs??this.defaultTimeoutMs,i=Math.max(1,Math.ceil(a/6e4)),s=e.image||this.snapshotName,o={envVars:e.envs,labels:e.metadata,autoStopInterval:i,autoDeleteInterval:aRe,...r?{user:r}:{},...t},c,l=e.resources!==void 0&&(e.resources.cpu!==void 0||e.resources.memory!==void 0||e.resources.disk!==void 0||e.resources.gpu!==void 0||e.resources.gpuTypes!==void 0);if(this.managedStream){if(l)throw new MM(s);let f=await this.client.create({snapshot:s,...o},{timeout:600});return e.workingDirectory&&await f.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(f.id,n),new GT(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),p=f?.state;if(f&&mRe.has(p??"")&&(u=p),f&&(p==="active"||p==="inactive")&&l)throw new MM(s);if(f&&p==="inactive"&&(p=(await DW(this.client,s,f)).state),f&&YPe.has(p??"")&&(UW(s)?d=await KPe(this.client,s,f,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${s}" is dead (state "${p}") but this provider cannot rebuild that name \u2014 delete it in the Daytona dashboard (Snapshots page), or rebuild it with the tooling that created it.`)),f&&p==="active")console.log(`[daytona] Using cached snapshot: ${s}`),c=await this.client.create({snapshot:s,...o},{timeout:600});else throw new Error("Snapshot not active")}catch(f){if(f instanceof MM||f instanceof Ey)throw f;let p=zW[s]??s,m=u!==void 0&&!l;m?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") \u2014 joining that build rather than starting a second one.`):u!==void 0?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") and cannot carry the requested sizing \u2014 pulling image directly instead: ${p}`):(console.log(`[daytona] Snapshot "${s}" not found, building from image: ${p}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(d===!1)throw new Error(`dead snapshot "${s}" was not confirmed removed \u2014 not racing its removal`);let y=()=>this.client.snapshot.create({name:s,image:Oh.base(p),resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{onLogs:v=>console.log(`[daytona] ${v}`)}),b=async()=>{await y(),console.log(`[daytona] Snapshot "${s}" ready (rebuilt here after a dead build).`)};if(u!==void 0){if(!m)throw new Error(`snapshot "${s}" is mid-build (state "${u}") and cannot be resized`);await this.joinInFlightSnapshotBuild(s)&&await b()}else try{await y(),console.log(`[daytona] Snapshot "${s}" ready (built here).`)}catch(v){if(!vRe(v)||l)throw v;await this.joinInFlightSnapshotBuild(s)&&await b()}c=await this.client.create({snapshot:s,...o},{timeout:600})}catch(y){if(y instanceof JT||y instanceof Ey)throw y;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${y instanceof Error?y.message:y}`);try{c=await this.client.create({image:p,...o,resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{timeout:600,onSnapshotCreateLogs:b=>console.log(`[daytona] ${b}`)})}catch(b){throw xRe(p)?new uRe(p,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new GT(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await bRe(this.client,e,this.snapshotConflictTiming);if(t===JW)return!0;if(t.state==="active")return console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(t.state==="inactive")return await DW(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(YPe.has(t.state??"")&&UW(e)&&await KPe(this.client,e,t,this.snapshotDeleteTiming))return!0;throw new Error(`the in-flight build of snapshot "${e}" ended in state "${t.state??"unknown"}"`)}async connect(e,t){let n=await this.client.get(e);return n.state!=="started"&&await n.start(),new GT(n,this.sandboxUsers.get(e),this.managedStream)}async inspect(e,t){let n=await this.getSandboxRecord(e);if(n.state!=="started")throw new tRe(e,"daytona",n.state??"unknown");return new GT(n,t?.user??this.sandboxUsers.get(e),this.managedStream)}async getSandboxRecord(e){return this.client.get(e)}async list(e){let t=await this.paginate(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.paginate(e);return n}async paginate(e){return CRe(this.listStream(e),e)}listStream(e){let t=e?.state?MMt(e.state):void 0,n={limit:lRe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};DMt=CRe;UMt=qW,BMt=FW,FMt=HT,LMt=wRe,VMt=IRe,qMt=xRe,$Mt=WW,zMt=ERe,GMt=DW,JMt=bRe,HMt=vRe,WMt=UW,jMt=zW,YMt=LW,KMt=SRe,XMt=tS,ZMt=VW,QMt=kRe,eDt=ORe,tDt=ARe,nDt=GT,OW=1024*1024});var NRe=_(FM=>{"use strict";Object.defineProperty(FM,"__esModule",{value:!0});FM.Metadata=void 0;FM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=nS(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)KW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else KW(a,i),n.set(a,[i]);return r},append(a,i){a=nS(a),KW(a,i);let s=n.get(a);return s==null&&(s=[],n.set(a,s)),s.push(i),a.endsWith("-bin")||n.set(a,[s.join(", ")]),r},delete(a){a=nS(a),n.delete(a)},get(a){var i;return a=nS(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=nS(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=nS(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=rDt(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function nS(e){return e.toLowerCase()}function KW(e,t){if(!/^[0-9a-z_.-]+$/.test(e))throw new Error(`Metadata key '${e}' contains illegal characters`);if(e.endsWith("-bin")){if(!(t instanceof Uint8Array))throw new Error(`Metadata key '${e}' ends with '-bin', thus it must have binary value`)}else{if(typeof t!="string")throw new Error(`Metadata key '${e}' doesn't end with '-bin', thus it must have string value`);if(!/^[ -~]*$/.test(t))throw new Error(`Metadata value '${t}' of key '${e}' contains illegal characters`)}}function rDt(e){return Symbol.iterator in e}});var LM=_(jT=>{"use strict";Object.defineProperty(jT,"__esModule",{value:!0});jT.Status=void 0;var iDt;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(iDt=jT.Status||(jT.Status={}))});var DRe=_(MRe=>{"use strict";Object.defineProperty(MRe,"__esModule",{value:!0})});var BRe=_(URe=>{"use strict";Object.defineProperty(URe,"__esModule",{value:!0})});var LRe=_(FRe=>{"use strict";Object.defineProperty(FRe,"__esModule",{value:!0})});var VRe=_(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.composeClientMiddleware=void 0;function aDt(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}VM.composeClientMiddleware=aDt});var zRe=_(Dh=>{"use strict";Dh.__esModule=void 0;Dh.__esModule=!0;var sDt=typeof Object.setPrototypeOf=="function",oDt=typeof Object.getPrototypeOf=="function",cDt=typeof Object.defineProperty=="function",lDt=typeof Object.create=="function",uDt=typeof Object.prototype.hasOwnProperty=="function",dDt=function(t,n){sDt?Object.setPrototypeOf(t,n):t.__proto__=n};Dh.setPrototypeOf=dDt;var fDt=function(t){return oDt?Object.getPrototypeOf(t):t.__proto__||t.prototype};Dh.getPrototypeOf=fDt;var qRe=!1,pDt=function e(t,n,r){if(cDt&&!qRe)try{Object.defineProperty(t,n,r)}catch{qRe=!0,e(t,n,r)}else t[n]=r.value};Dh.defineProperty=pDt;var $Re=function(t,n){return uDt?t.hasOwnProperty(t,n):t[n]===void 0};Dh.hasOwnProperty=$Re;var hDt=function(t,n){if(lDt)return Object.create(t,n);var r=function(){};r.prototype=t;var a=new r;if(typeof n>"u")return a;if(typeof n=="null")throw new Error("PropertyDescriptors must not be null.");if(typeof n=="object")for(var i in n)$Re(n,i)&&(a[i]=n[i].value);return a};Dh.objectCreate=hDt});var ZW=_(rS=>{"use strict";rS.__esModule=void 0;rS.__esModule=!0;var $M=zRe(),mDt=$M.setPrototypeOf,gDt=$M.getPrototypeOf,XW=$M.defineProperty,yDt=$M.objectCreate,vDt=new Error().toString()==="[object Error]",qM="";function YT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?qM||"Error":o[1]}(),r=n==="Error",a=r?qM:n,i=Error.apply(this,arguments);if(mDt(i,gDt(this)),!(i instanceof t)||!(i instanceof YT)){var i=this;Error.apply(this,arguments),XW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(XW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?YT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return vDt&&XW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}qM=YT.name||"ExtendableError";YT.prototype=yDt(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});rS.ExtendableError=YT;rS.default=rS.ExtendableError});var GRe=_(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.ClientError=void 0;var bDt=ZW(),SDt=LM(),QW=class e extends bDt.ExtendableError{constructor(t,n,r){super(`${t} ${SDt.Status[n]}: ${r}`),this.path=t,this.code=n,this.details=r,this.name="ClientError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ClientError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ClientError"]===!0||t.name==="ClientError"&&t["@@nice-grpc"]===!0)}};zM.ClientError=QW});var HRe=_(JRe=>{"use strict";Object.defineProperty(JRe,"__esModule",{value:!0})});var jRe=_(WRe=>{"use strict";Object.defineProperty(WRe,"__esModule",{value:!0})});var YRe=_(GM=>{"use strict";Object.defineProperty(GM,"__esModule",{value:!0});GM.composeServerMiddleware=void 0;function _Dt(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}GM.composeServerMiddleware=_Dt});var KRe=_(JM=>{"use strict";Object.defineProperty(JM,"__esModule",{value:!0});JM.ServerError=void 0;var wDt=ZW(),IDt=LM(),e7=class e extends wDt.ExtendableError{constructor(t,n){super(`${IDt.Status[t]}: ${n}`),this.code=t,this.details=n,this.name="ServerError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ServerError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ServerError"]===!0||t.name==="ServerError"&&t["@@nice-grpc"]===!0)}};JM.ServerError=e7});var Xc=_($a=>{"use strict";var xDt=$a&&$a.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Xl=$a&&$a.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&xDt(t,e,n)};Object.defineProperty($a,"__esModule",{value:!0});Xl(NRe(),$a);Xl(LM(),$a);Xl(DRe(),$a);Xl(BRe(),$a);Xl(LRe(),$a);Xl(VRe(),$a);Xl(GRe(),$a);Xl(HRe(),$a);Xl(jRe(),$a);Xl(YRe(),$a);Xl(KRe(),$a)});var Yt=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=Zc.Propagate=Zc.LogVerbosity=Zc.Status=void 0;var XRe;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(XRe||(Zc.Status=XRe={}));var ZRe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(ZRe||(Zc.LogVerbosity=ZRe={}));var QRe;(function(e){e[e.DEADLINE=1]="DEADLINE",e[e.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",e[e.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",e[e.CANCELLATION=8]="CANCELLATION",e[e.DEFAULTS=65535]="DEFAULTS"})(QRe||(Zc.Propagate=QRe={}));Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var t7=_((nxn,EDt)=>{EDt.exports={name:"@grpc/grpc-js",version:"1.14.4",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var hr=_(hc=>{"use strict";var n7,r7,i7,a7;Object.defineProperty(hc,"__esModule",{value:!0});hc.log=hc.setLoggerVerbosity=hc.setLogger=hc.getLogger=void 0;hc.trace=UDt;hc.isTracerEnabled=tCe;var Uh=Yt(),TDt=require("process"),kDt=t7().version,ODt={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},Ty=ODt,iS=Uh.LogVerbosity.ERROR,ADt=(r7=(n7=process.env.GRPC_NODE_VERBOSITY)!==null&&n7!==void 0?n7:process.env.GRPC_VERBOSITY)!==null&&r7!==void 0?r7:"";switch(ADt.toUpperCase()){case"DEBUG":iS=Uh.LogVerbosity.DEBUG;break;case"INFO":iS=Uh.LogVerbosity.INFO;break;case"ERROR":iS=Uh.LogVerbosity.ERROR;break;case"NONE":iS=Uh.LogVerbosity.NONE;break;default:}var PDt=()=>Ty;hc.getLogger=PDt;var RDt=e=>{Ty=e};hc.setLogger=RDt;var CDt=e=>{iS=e};hc.setLoggerVerbosity=CDt;var NDt=(e,...t)=>{let n;if(e>=iS){switch(e){case Uh.LogVerbosity.DEBUG:n=Ty.debug;break;case Uh.LogVerbosity.INFO:n=Ty.info;break;case Uh.LogVerbosity.ERROR:n=Ty.error;break}n||(n=Ty.error),n&&n.bind(Ty)(...t)}};hc.log=NDt;var MDt=(a7=(i7=process.env.GRPC_NODE_TRACE)!==null&&i7!==void 0?i7:process.env.GRPC_TRACE)!==null&&a7!==void 0?a7:"",s7=new Set,eCe=new Set;for(let e of MDt.split(","))e.startsWith("-")?eCe.add(e.substring(1)):s7.add(e);var DDt=s7.has("all");function UDt(e,t,n){tCe(t)&&(0,hc.log)(e,new Date().toISOString()+" | v"+kDt+" "+TDt.pid+" | "+t+" | "+n)}function tCe(e){return!eCe.has(e)&&(DDt||s7.has(e))}});var WM=_(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.getErrorMessage=BDt;HM.getErrorCode=FDt;function BDt(e){return e instanceof Error?e.message:String(e)}function FDt(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ga=_(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.Metadata=void 0;var LDt=hr(),VDt=Yt(),qDt=WM(),$Dt=/^[:0-9a-z_.-]+$/,zDt=/^[ -~]*$/;function GDt(e){return $Dt.test(e)}function JDt(e){return zDt.test(e)}function rCe(e){return e.endsWith("-bin")}function HDt(e){return!e.startsWith("grpc-")}function jM(e){return e.toLowerCase()}function nCe(e,t){if(!GDt(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(rCe(e)){if(!Buffer.isBuffer(t))throw new Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(t))throw new Error("keys that don't end with '-bin' must have String values");if(!JDt(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var o7=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=jM(t),nCe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=jM(t),nCe(t,n);let r=this.internalRepr.get(t);r===void 0?this.internalRepr.set(t,[n]):r.push(n)}remove(t){t=jM(t),this.internalRepr.delete(t)}get(t){return t=jM(t),this.internalRepr.get(t)||[]}getMap(){let t={};for(let[n,r]of this.internalRepr)if(r.length>0){let a=r[0];t[n]=Buffer.isBuffer(a)?Buffer.from(a):a}return t}clone(){let t=new e(this.options),n=t.internalRepr;for(let[r,a]of this.internalRepr){let i=a.map(s=>Buffer.isBuffer(s)?Buffer.from(s):s);n.set(r,i)}return t}merge(t){for(let[n,r]of t.internalRepr){let a=(this.internalRepr.get(n)||[]).concat(r);this.internalRepr.set(n,a)}}setOptions(t){this.options=t}getOptions(){return this.options}toHttp2Headers(){let t={};for(let[n,r]of this.internalRepr)n.startsWith(":")||(t[n]=r.map(WDt));return t}toJSON(){let t={};for(let[n,r]of this.internalRepr)t[n]=r;return t}setOpaque(t,n){this.opaqueData.set(t,n)}getOpaque(t){return this.opaqueData.get(t)}static fromHttp2Headers(t){let n=new e;for(let r of Object.keys(t)){if(r.charAt(0)===":")continue;let a=t[r];try{rCe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(HDt(r)?a.split(",").forEach(i=>{n.add(r,Buffer.from(i.trim(),"base64"))}):n.add(r,Buffer.from(a,"base64"))):Array.isArray(a)?a.forEach(i=>{n.add(r,i)}):a!==void 0&&n.add(r,a)}catch(i){let s=`Failed to add metadata entry ${r}: ${a}. ${(0,qDt.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,LDt.log)(VDt.LogVerbosity.ERROR,s)}}return n}};YM.Metadata=o7;var WDt=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var XM=_(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.CallCredentials=void 0;var d7=ga();function jDt(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var aS=class e{static createFromMetadataGenerator(t){return new l7(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;jDt(t)?a=t.getRequestHeaders(n.service_url):a=new Promise((i,s)=>{t.getRequestMetadata(n.service_url,(o,c)=>{if(o){s(o);return}if(!c){s(new Error("Headers not set by metadata plugin"));return}i(c)})}),a.then(i=>{let s=new d7.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new u7}};KM.CallCredentials=aS;var c7=class e extends aS{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new d7.Metadata,r=await Promise.all(this.creds.map(a=>a.generateMetadata(t)));for(let a of r)n.merge(a);return n}compose(t){return new e(this.creds.concat([t]))}_equals(t){return this===t?!0:t instanceof e?this.creds.every((n,r)=>n._equals(t.creds[r])):!1}},l7=class e extends aS{constructor(t){super(),this.metadataGenerator=t}generateMetadata(t){return new Promise((n,r)=>{this.metadataGenerator(t,(a,i)=>{i!==void 0?n(i):r(a)})})}compose(t){return new c7([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},u7=class e extends aS{generateMetadata(t){return Promise.resolve(new d7.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var p7=_(KT=>{"use strict";Object.defineProperty(KT,"__esModule",{value:!0});KT.CIPHER_SUITES=void 0;KT.getDefaultRootsData=KDt;var YDt=require("fs");KT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var iCe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,f7=null;function KDt(){return iCe?(f7===null&&(f7=YDt.readFileSync(iCe)),f7):null}});var ro=_(sS=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});sS.parseUri=ZDt;sS.splitHostPort=QDt;sS.combineHostPort=e3t;sS.uriToString=t3t;var XDt=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function ZDt(e){let t=XDt.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var aCe=/^\d+$/;function QDt(e){if(e.startsWith("[")){let t=e.indexOf("]");if(t===-1)return null;let n=e.substring(1,t);if(n.indexOf(":")===-1)return null;if(e.length>t+1)if(e[t+1]===":"){let r=e.substring(t+2);return aCe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?aCe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function e3t(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function t3t(e){let t="";return e.scheme!==void 0&&(t+=e.scheme+":"),e.authority!==void 0&&(t+="//"+e.authority+"/"),t+=e.path,t}});var Zl=_(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});dp.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;dp.registerResolver=n3t;dp.registerDefaultScheme=r3t;dp.createResolver=i3t;dp.getDefaultAuthority=a3t;dp.mapUriDefaultScheme=s3t;var m7=ro();dp.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var oS={},h7=null;function n3t(e,t){oS[e]=t}function r3t(e){h7=e}function i3t(e,t,n){if(e.scheme!==void 0&&e.scheme in oS)return new oS[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,m7.uriToString)(e)}`)}function a3t(e){if(e.scheme!==void 0&&e.scheme in oS)return oS[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,m7.uriToString)(e)}`)}function s3t(e){return e.scheme===void 0||!(e.scheme in oS)?h7!==null?{scheme:h7,authority:void 0,path:(0,m7.uriToString)(e)}:null:e}});var cS=_(ZT=>{"use strict";Object.defineProperty(ZT,"__esModule",{value:!0});ZT.ChannelCredentials=void 0;ZT.createCertificateProviderChannelCredentials=u3t;var XT=require("tls"),eD=XM(),y7=p7(),sCe=ro(),o3t=Zl(),c3t=hr(),l3t=Yt();function g7(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var ky=class{compose(t){return new S7(this,t)}static createSsl(t,n,r,a){var i;if(g7(t,"Root certificate"),g7(n,"Private key"),g7(r,"Certificate chain"),n&&!r)throw new Error("Private key must be given with accompanying certificate chain");if(!n&&r)throw new Error("Certificate chain must be given with accompanying private key");let s=(0,XT.createSecureContext)({ca:(i=t??(0,y7.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:y7.CIPHER_SUITES});return new ZM(s,a??{})}static createFromSecureContext(t,n){return new ZM(t,n??{})}static createInsecure(){return new v7}};ZT.ChannelCredentials=ky;var v7=class e extends ky{constructor(){super()}compose(t){throw new Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals(t){return t instanceof e}_createSecureConnector(t,n,r){return{connect(a){return Promise.resolve({socket:a,secure:!1})},waitForReady:()=>Promise.resolve(),getCallCredentials:()=>r??eD.CallCredentials.createEmpty(),destroy(){}}}};function oCe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,sCe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,o3t.getDefaultAuthority)(o),l=(0,sCe.splitHostPort)(c),u=(a=l?.host)!==null&&a!==void 0?a:c;if(s.host=u,t.checkServerIdentity&&(s.checkServerIdentity=t.checkServerIdentity),t.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=t.rejectUnauthorized),s.ALPNProtocols=["h2"],r["grpc.ssl_target_name_override"]){let d=r["grpc.ssl_target_name_override"],f=(i=s.checkServerIdentity)!==null&&i!==void 0?i:XT.checkServerIdentity;s.checkServerIdentity=(p,m)=>f(d,m),s.servername=d}else s.servername=u;return r["grpc-node.tls_enable_trace"]&&(s.enableTrace=!0),s}var b7=class{constructor(t,n){this.connectionOptions=t,this.callCredentials=n}connect(t){let n=Object.assign({socket:t},this.connectionOptions);return new Promise((r,a)=>{let i=(0,XT.connect)(n,()=>{var s;if((!((s=this.connectionOptions.rejectUnauthorized)!==null&&s!==void 0)||s)&&!i.authorized){a(i.authorizationError);return}r({socket:i,secure:!0})});i.on("error",s=>{a(s)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}},ZM=class e extends ky{constructor(t,n){super(),this.secureContext=t,this.verifyOptions=n}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.secureContext===t.secureContext&&this.verifyOptions.checkServerIdentity===t.verifyOptions.checkServerIdentity:!1}_createSecureConnector(t,n,r){let a=oCe(this.secureContext,this.verifyOptions,t,n);return new b7(a,r??eD.CallCredentials.createEmpty())}},QM=class e extends ky{constructor(t,n,r){super(),this.caCertificateProvider=t,this.identityCertificateProvider=n,this.verifyOptions=r,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals(t){var n,r;return this===t?!0:t instanceof e?this.caCertificateProvider===t.caCertificateProvider&&this.identityCertificateProvider===t.identityCertificateProvider&&((n=this.verifyOptions)===null||n===void 0?void 0:n.checkServerIdentity)===((r=t.verifyOptions)===null||r===void 0?void 0:r.checkServerIdentity):!1}ref(){var t;this.refcount===0&&(this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.addIdentityCertificateListener(this.identityCertificateUpdateListener)),this.refcount+=1}unref(){var t;this.refcount-=1,this.refcount===0&&(this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.removeIdentityCertificateListener(this.identityCertificateUpdateListener))}_createSecureConnector(t,n,r){return this.ref(),new e.SecureConnectorImpl(this,t,n,r??eD.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let t of this.secureContextWatchers)t(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate(t){this.latestCaUpdate=t,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate(t){this.latestIdentityUpdate=t,this.maybeUpdateWatchers()}hasReceivedUpdates(){return!(this.latestCaUpdate===void 0||this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)}getSecureContext(){return this.hasReceivedUpdates()?Promise.resolve(this.getLatestSecureContext()):new Promise(t=>{this.secureContextWatchers.push(t)})}getLatestSecureContext(){var t,n;if(!this.latestCaUpdate||this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,XT.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:(t=this.latestIdentityUpdate)===null||t===void 0?void 0:t.privateKey,cert:(n=this.latestIdentityUpdate)===null||n===void 0?void 0:n.certificate,ciphers:y7.CIPHER_SUITES})}catch(r){return(0,c3t.log)(l3t.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};QM.SecureConnectorImpl=class{constructor(e,t,n,r){this.parent=e,this.channelTarget=t,this.options=n,this.callCredentials=r}connect(e){return new Promise((t,n)=>{let r=this.parent.getLatestSecureContext();if(!r){n(new Error("Failed to load credentials"));return}e.closed&&n(new Error("Socket closed while loading credentials"));let a=oCe(r,this.parent.verifyOptions,this.channelTarget,this.options),i=Object.assign({socket:e},a),s=()=>{n(new Error("Socket closed"))},o=l=>{n(l)},c=(0,XT.connect)(i,()=>{var l;if(c.removeListener("close",s),c.removeListener("error",o),(!((l=this.parent.verifyOptions.rejectUnauthorized)!==null&&l!==void 0)||l)&&!c.authorized){n(c.authorizationError);return}t({socket:c,secure:!0})});c.once("close",s),c.once("error",o)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function u3t(e,t,n){return new QM(e,t,n??{})}var S7=class e extends ky{constructor(t,n){if(super(),this.channelCredentials=t,this.callCredentials=n,!t._isSecure())throw new Error("Cannot compose insecure credentials")}compose(t){let n=this.callCredentials.compose(t);return new e(this.channelCredentials,n)}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.channelCredentials._equals(t.channelCredentials)&&this.callCredentials._equals(t.callCredentials):!1}_createSecureConnector(t,n,r){let a=this.callCredentials.compose(r??eD.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Fh=_(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.createChildChannelControlHelper=p3t;Td.registerLoadBalancerType=h3t;Td.registerDefaultLoadBalancerType=m3t;Td.createLoadBalancer=g3t;Td.isLoadBalancerNameRegistered=y3t;Td.parseLoadBalancingConfig=cCe;Td.getDefaultConfig=v3t;Td.selectLbConfigFromList=b3t;var d3t=hr(),f3t=Yt();function p3t(e,t){var n,r,a,i,s,o,c,l,u,d;return{createSubchannel:(r=(n=t.createSubchannel)===null||n===void 0?void 0:n.bind(t))!==null&&r!==void 0?r:e.createSubchannel.bind(e),updateState:(i=(a=t.updateState)===null||a===void 0?void 0:a.bind(t))!==null&&i!==void 0?i:e.updateState.bind(e),requestReresolution:(o=(s=t.requestReresolution)===null||s===void 0?void 0:s.bind(t))!==null&&o!==void 0?o:e.requestReresolution.bind(e),addChannelzChild:(l=(c=t.addChannelzChild)===null||c===void 0?void 0:c.bind(t))!==null&&l!==void 0?l:e.addChannelzChild.bind(e),removeChannelzChild:(d=(u=t.removeChannelzChild)===null||u===void 0?void 0:u.bind(t))!==null&&d!==void 0?d:e.removeChannelzChild.bind(e)}}var Bh={},QT=null;function h3t(e,t,n){Bh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function m3t(e){QT=e}function g3t(e,t){let n=e.getLoadBalancerName();return n in Bh?new Bh[n].LoadBalancer(t):null}function y3t(e){return e in Bh}function cCe(e){let t=Object.keys(e);if(t.length!==1)throw new Error("Provided load balancing config has multiple conflicting entries");let n=t[0];if(n in Bh)try{return Bh[n].LoadBalancingConfig.createFromJson(e[n])}catch(r){throw new Error(`${n}: ${r.message}`)}else throw new Error(`Unrecognized load balancing config name ${n}`)}function v3t(){if(!QT)throw new Error("No default load balancer type registered");return new Bh[QT].LoadBalancingConfig}function b3t(e,t=!1){for(let n of e)try{return cCe(n)}catch(r){(0,d3t.log)(f3t.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&QT?new Bh[QT].LoadBalancingConfig:null}});var _7=_(ek=>{"use strict";Object.defineProperty(ek,"__esModule",{value:!0});ek.validateRetryThrottling=lCe;ek.validateServiceConfig=uCe;ek.extractAndSelectServiceConfig=A3t;var S3t=require("os"),tD=Yt(),nD=/^\d+(\.\d{1,9})?s$/,_3t="node";function w3t(e){if("service"in e&&e.service!==""){if(typeof e.service!="string")throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof e.service}`);if("method"in e&&e.method!==""){if(typeof e.method!="string")throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof e.service}`);return{service:e.service,method:e.method}}else return{service:e.service}}else{if("method"in e&&e.method!==void 0)throw new Error("Invalid method config name: method set with empty or unset service");return{}}}function I3t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in e)||typeof e.initialBackoff!="string"||!nD.test(e.initialBackoff))throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in e)||typeof e.maxBackoff!="string"||!nD.test(e.maxBackoff))throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in e)||typeof e.backoffMultiplier!="number"||e.backoffMultiplier<=0)throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!("retryableStatusCodes"in e&&Array.isArray(e.retryableStatusCodes)))throw new Error("Invalid method config retry policy: retryableStatusCodes is required");if(e.retryableStatusCodes.length===0)throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let t of e.retryableStatusCodes)if(typeof t=="number"){if(!Object.values(tD.Status).includes(t))throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof t=="string"){if(!Object.values(tD.Status).includes(t.toUpperCase()))throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:e.maxAttempts,initialBackoff:e.initialBackoff,maxBackoff:e.maxBackoff,backoffMultiplier:e.backoffMultiplier,retryableStatusCodes:e.retryableStatusCodes}}function x3t(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in e&&(typeof e.hedgingDelay!="string"||!nD.test(e.hedgingDelay)))throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in e&&Array.isArray(e.nonFatalStatusCodes))for(let n of e.nonFatalStatusCodes)if(typeof n=="number"){if(!Object.values(tD.Status).includes(n))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof n=="string"){if(!Object.values(tD.Status).includes(n.toUpperCase()))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let t={maxAttempts:e.maxAttempts};return e.hedgingDelay&&(t.hedgingDelay=e.hedgingDelay),e.nonFatalStatusCodes&&(t.nonFatalStatusCodes=e.nonFatalStatusCodes),t}function E3t(e){var t;let n={name:[]};if(!("name"in e)||!Array.isArray(e.name))throw new Error("Invalid method config: invalid name array");for(let r of e.name)n.name.push(w3t(r));if("waitForReady"in e){if(typeof e.waitForReady!="boolean")throw new Error("Invalid method config: invalid waitForReady");n.waitForReady=e.waitForReady}if("timeout"in e)if(typeof e.timeout=="object"){if(!("seconds"in e.timeout)||typeof e.timeout.seconds!="number")throw new Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in e.timeout)||typeof e.timeout.nanos!="number")throw new Error("Invalid method config: invalid timeout.nanos");n.timeout=e.timeout}else if(typeof e.timeout=="string"&&nD.test(e.timeout)){let r=e.timeout.substring(0,e.timeout.length-1).split(".");n.timeout={seconds:r[0]|0,nanos:((t=r[1])!==null&&t!==void 0?t:0)|0}}else throw new Error("Invalid method config: invalid timeout");if("maxRequestBytes"in e){if(typeof e.maxRequestBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxRequestBytes=e.maxRequestBytes}if("maxResponseBytes"in e){if(typeof e.maxResponseBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxResponseBytes=e.maxResponseBytes}if("retryPolicy"in e){if("hedgingPolicy"in e)throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");n.retryPolicy=I3t(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=x3t(e.hedgingPolicy));return n}function lCe(e){if(!("maxTokens"in e)||typeof e.maxTokens!="number"||e.maxTokens<=0||e.maxTokens>1e3)throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in e)||typeof e.tokenRatio!="number"||e.tokenRatio<=0)throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+e.maxTokens.toFixed(3),tokenRatio:+e.tokenRatio.toFixed(3)}}function T3t(e){if(!(typeof e=="object"&&e!==null))throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof e}`);let t=Object.keys(e);if(t.length>1)throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${t}`);if(t.length===0)throw new Error("Invalid loadBalancingConfig: load balancing policy name required");return{[t[0]]:e[t[0]]}}function uCe(e){let t={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in e)if(typeof e.loadBalancingPolicy=="string")t.loadBalancingPolicy=e.loadBalancingPolicy;else throw new Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in e)if(Array.isArray(e.loadBalancingConfig))for(let r of e.loadBalancingConfig)t.loadBalancingConfig.push(T3t(r));else throw new Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in e&&Array.isArray(e.methodConfig))for(let r of e.methodConfig)t.methodConfig.push(E3t(r));"retryThrottling"in e&&(t.retryThrottling=lCe(e.retryThrottling));let n=[];for(let r of t.methodConfig)for(let a of r.name){for(let i of n)if(a.service===i.service&&a.method===i.method)throw new Error(`Invalid service config: duplicate name ${a.service}/${a.method}`);n.push(a)}return t}function k3t(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:uCe(e.serviceConfig)};if("clientLanguage"in e)if(Array.isArray(e.clientLanguage)){t.clientLanguage=[];for(let r of e.clientLanguage)if(typeof r=="string")t.clientLanguage.push(r);else throw new Error("Invalid service config choice: invalid clientLanguage")}else throw new Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in e)if(Array.isArray(e.clientHostname)){t.clientHostname=[];for(let r of e.clientHostname)if(typeof r=="string")t.clientHostname.push(r);else throw new Error("Invalid service config choice: invalid clientHostname")}else throw new Error("Invalid service config choice: invalid clientHostname");if("percentage"in e)if(typeof e.percentage=="number"&&0<=e.percentage&&e.percentage<=100)t.percentage=e.percentage;else throw new Error("Invalid service config choice: invalid percentage");let n=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let r in e)if(!n.includes(r))throw new Error(`Invalid service config choice: unexpected field ${r}`);return t}function O3t(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=k3t(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===S3t.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===_3t&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function A3t(e,t){for(let n of e)if(n.length>0&&n[0].startsWith("grpc_config=")){let r=n.join("").substring(12),a=JSON.parse(r);return O3t(a,t)}return null}});var io=_(rD=>{"use strict";Object.defineProperty(rD,"__esModule",{value:!0});rD.ConnectivityState=void 0;var dCe;(function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.READY=2]="READY",e[e.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",e[e.SHUTDOWN=4]="SHUTDOWN"})(dCe||(rD.ConnectivityState=dCe={}))});var fp=_(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.QueuePicker=Lh.UnavailablePicker=Lh.PickResultType=void 0;var P3t=ga(),R3t=Yt(),iD;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(iD||(Lh.PickResultType=iD={}));var w7=class{constructor(t){this.status=Object.assign({code:R3t.Status.UNAVAILABLE,details:"No connection established",metadata:new P3t.Metadata},t)}pick(t){return{pickResultType:iD.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Lh.UnavailablePicker=w7;var I7=class{constructor(t,n){this.loadBalancer=t,this.childPicker=n,this.calledExitIdle=!1}pick(t){return this.calledExitIdle||(process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0),this.childPicker?this.childPicker.pick(t):{pickResultType:iD.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Lh.QueuePicker=I7});var lS=_(sD=>{"use strict";Object.defineProperty(sD,"__esModule",{value:!0});sD.BackoffTimeout=void 0;var C3t=Yt(),N3t=hr(),M3t="backoff",D3t=1e3,U3t=1.6,B3t=12e4,F3t=.2;function L3t(e,t){return Math.random()*(t-e)+e}var aD=class e{constructor(t,n){this.callback=t,this.initialDelay=D3t,this.multiplier=U3t,this.maxDelay=B3t,this.jitter=F3t,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=e.getNextId(),n&&(n.initialDelay&&(this.initialDelay=n.initialDelay),n.multiplier&&(this.multiplier=n.multiplier),n.jitter&&(this.jitter=n.jitter),n.maxDelay&&(this.maxDelay=n.maxDelay)),this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace(t){N3t.trace(C3t.LogVerbosity.DEBUG,M3t,"{"+this.id+"} "+t)}runTimer(t){var n,r;this.trace("runTimer(delay="+t+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+t),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},t),this.hasRef||(r=(n=this.timerId).unref)===null||r===void 0||r.call(n)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let t=Math.min(this.nextDelay*this.multiplier,this.maxDelay),n=t*this.jitter;this.nextDelay=t+L3t(-n,n)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let t=new Date,n=this.startTime;n.setMilliseconds(n.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),t<n?this.runTimer(n.getTime()-t.getTime()):this.running=!1}}isRunning(){return this.running}ref(){var t,n;this.hasRef=!0,(n=(t=this.timerId).ref)===null||n===void 0||n.call(t)}unref(){var t,n;this.hasRef=!1,(n=(t=this.timerId).unref)===null||n===void 0||n.call(t)}getEndTime(){return this.endTime}};sD.BackoffTimeout=aD;aD.nextId=0});var cD=_(oD=>{"use strict";Object.defineProperty(oD,"__esModule",{value:!0});oD.ChildLoadBalancerHandler=void 0;var V3t=Fh(),q3t=io(),$3t="child_load_balancer_helper",x7=class{constructor(t){this.channelControlHelper=t,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(n){this.parent=n,this.child=null}createSubchannel(n,r){return this.parent.channelControlHelper.createSubchannel(n,r)}updateState(n,r,a){var i;if(this.calledByPendingChild()){if(n===q3t.ConnectivityState.CONNECTING)return;(i=this.parent.currentChild)===null||i===void 0||i.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(n,r,a)}requestReresolution(){var n;let r=(n=this.parent.pendingChild)!==null&&n!==void 0?n:this.parent.currentChild;this.child===r&&this.parent.channelControlHelper.requestReresolution()}setChild(n){this.child=n}addChannelzChild(n){this.parent.channelControlHelper.addChannelzChild(n)}removeChannelzChild(n){this.parent.channelControlHelper.removeChannelzChild(n)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance(t,n){return t.getLoadBalancerName()!==n.getLoadBalancerName()}updateAddressList(t,n,r,a){let i;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,n)){let s=new this.ChildPolicyHelper(this),o=(0,V3t.createLoadBalancer)(n,s);s.setChild(o),this.currentChild===null?(this.currentChild=o,i=this.currentChild):(this.pendingChild&&this.pendingChild.destroy(),this.pendingChild=o,i=this.pendingChild)}else this.pendingChild===null?i=this.currentChild:i=this.pendingChild;return this.latestConfig=n,i.updateAddressList(t,n,r,a)}exitIdle(){this.currentChild&&(this.currentChild.exitIdle(),this.pendingChild&&this.pendingChild.exitIdle())}resetBackoff(){this.currentChild&&(this.currentChild.resetBackoff(),this.pendingChild&&this.pendingChild.resetBackoff())}destroy(){this.currentChild&&(this.currentChild.destroy(),this.currentChild=null),this.pendingChild&&(this.pendingChild.destroy(),this.pendingChild=null)}getTypeName(){return $3t}};oD.ChildLoadBalancerHandler=x7});var hCe=_(lD=>{"use strict";Object.defineProperty(lD,"__esModule",{value:!0});lD.ResolvingLoadBalancer=void 0;var z3t=Fh(),G3t=_7(),Mo=io(),fCe=Zl(),tk=fp(),J3t=lS(),E7=Yt(),H3t=ga(),W3t=hr(),j3t=Yt(),Y3t=ro(),K3t=cD(),X3t="resolving_load_balancer";function pCe(e){W3t.trace(j3t.LogVerbosity.DEBUG,X3t,e)}var Z3t=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function Q3t(e,t,n,r){for(let a of n.name)switch(r){case"EMPTY":if(!a.service&&!a.method)return!0;break;case"SERVICE":if(a.service===e&&!a.method)return!0;break;case"SERVICE_AND_METHOD":if(a.service===e&&a.method===t)return!0}return!1}function eUt(e,t,n,r){for(let a of n)if(Q3t(e,t,a,r))return a;return null}function tUt(e){return{invoke(t,n){var r,a;let i=t.split("/").filter(c=>c.length>0),s=(r=i[0])!==null&&r!==void 0?r:"",o=(a=i[1])!==null&&a!==void 0?a:"";if(e&&e.methodConfig)for(let c of Z3t){let l=eUt(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:E7.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:E7.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var T7=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=Mo.ConnectivityState.IDLE,this.latestChildPicker=new tk.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=Mo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,G3t.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(Mo.ConnectivityState.IDLE,new tk.QueuePicker(this),null),this.childLoadBalancer=new K3t.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(pCe("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0):this.updateResolution()},updateState:(o,c,l)=>{this.latestChildState=o,this.latestChildPicker=c,this.latestChildErrorMessage=l,this.updateState(o,c,l)},addChannelzChild:n.addChannelzChild.bind(n),removeChannelzChild:n.removeChannelzChild.bind(n)}),this.innerResolver=(0,fCe.createResolver)(t,this.handleResolverResult.bind(this),r);let s={initialDelay:r["grpc.initial_reconnect_backoff_ms"],maxDelay:r["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new J3t.BackoffTimeout(()=>{this.continueResolving?(this.updateResolution(),this.continueResolving=!1):this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},s),this.backoffTimeout.unref()}handleResolverResult(t,n,r,a){var i,s;this.backoffTimeout.stop(),this.backoffTimeout.reset();let o=!0,c=null;if(r===null?c=this.defaultServiceConfig:r.ok?c=r.value:this.previousServiceConfig!==null?c=this.previousServiceConfig:(o=!1,this.handleResolutionFailure(r.error)),c!==null){let l=(i=c?.loadBalancingConfig)!==null&&i!==void 0?i:[],u=(0,z3t.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:E7.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new H3t.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[fCe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:tUt(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===Mo.ConnectivityState.IDLE&&this.updateState(Mo.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){pCe((0,Y3t.uriToString)(this.target)+" "+Mo.ConnectivityState[this.currentState]+" -> "+Mo.ConnectivityState[t]),t===Mo.ConnectivityState.IDLE&&(n=new tk.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===Mo.ConnectivityState.IDLE&&(this.updateState(Mo.ConnectivityState.TRANSIENT_FAILURE,new tk.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===Mo.ConnectivityState.IDLE||this.currentState===Mo.ConnectivityState.TRANSIENT_FAILURE)&&(this.backoffTimeout.isRunning()?this.continueResolving=!0:this.updateResolution()),this.childLoadBalancer.exitIdle()}updateAddressList(t,n){throw new Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=Mo.ConnectivityState.IDLE,this.latestChildPicker=new tk.QueuePicker(this),this.currentState=Mo.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};lD.ResolvingLoadBalancer=T7});var mCe=_(nk=>{"use strict";Object.defineProperty(nk,"__esModule",{value:!0});nk.recognizedOptions=void 0;nk.channelOptionsEqual=nUt;nk.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function nUt(e,t){let n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let a=0;a<n.length;a+=1)if(n[a]!==r[a]||e[n[a]]!==t[r[a]])return!1;return!0}});var Do=_(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.EndpointMap=void 0;Ql.isTcpSubchannelAddress=ik;Ql.subchannelAddressEqual=uD;Ql.subchannelAddressToString=yCe;Ql.stringToSubchannelAddress=iUt;Ql.endpointEqual=aUt;Ql.endpointToString=sUt;Ql.endpointHasAddress=vCe;var gCe=require("net");function ik(e){return"port"in e}function uD(e,t){return!e&&!t?!0:!e||!t?!1:ik(e)?ik(t)&&e.host===t.host&&e.port===t.port:!ik(t)&&e.path===t.path}function yCe(e){return ik(e)?(0,gCe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var rUt=443;function iUt(e,t){return(0,gCe.isIP)(e)?{host:e,port:t??rUt}:{path:e}}function aUt(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!uD(e.addresses[n],t.addresses[n]))return!1;return!0}function sUt(e){return"["+e.addresses.map(yCe).join(", ")+"]"}function vCe(e,t){for(let n of e.addresses)if(uD(n,t))return!0;return!1}function rk(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n of e.addresses){let r=!1;for(let a of t.addresses)if(uD(n,a)){r=!0;break}if(!r)return!1}return!0}var k7=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(vCe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)rk(i,r.key)&&(a=!0);a||(n.push(r.value),this.map.delete(r))}return n}get(t){for(let n of this.map)if(rk(t,n.key))return n.value}set(t,n){for(let r of this.map)if(rk(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(rk(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(rk(t,n.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let t of this.map)yield t.key}*values(){for(let t of this.map)yield t.value}*entries(){for(let t of this.map)yield[t.key,t.value]}};Ql.EndpointMap=k7});var bCe=_(D7=>{"use strict";Object.defineProperty(D7,"t",{value:!0});var dD=class{constructor(t,n,r=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=t,this.l=n,this.p=r}I(){let t=this,n=t.o.o===t;if(n&&t.p===1)t=t.h;else if(t.i)for(t=t.i;t.h;)t=t.h;else{if(n)return t.o;let r=t.o;for(;r.i===t;)t=r,r=t.o;t=r}return t}B(){let t=this;if(t.h){for(t=t.h;t.i;)t=t.i;return t}else{let n=t.o;for(;n.h===t;)t=n,n=t.o;return t.h!==n?n:t}}_(){let t=this.o,n=this.h,r=n.i;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.i=this,this.o=n,this.h=r,r&&(r.o=this),n}g(){let t=this.o,n=this.i,r=n.h;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.h=this,this.o=n,this.i=r,r&&(r.o=this),n}},O7=class extends dD{constructor(){super(...arguments),this.M=1}_(){let t=super._();return this.O(),t.O(),t}g(){let t=super.g();return this.O(),t.O(),t}O(){this.M=1,this.i&&(this.M+=this.i.M),this.h&&(this.M+=this.h.M)}},A7=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},P7=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},R7=class extends P7{};function Oy(){throw new RangeError("Iterator access denied!")}var C7=class extends R7{constructor(t=function(r,a){return r<a?-1:r>a?1:0},n=!1){super(),this.v=void 0,this.A=t,this.enableIndex=n,this.N=n?O7:dD,this.C=new this.N}R(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)t=t.h;else if(a>0)r=t,t=t.i;else return t}return r}K(t,n){let r=this.C;for(;t;)this.A(t.u,n)<=0?t=t.h:(r=t,t=t.i);return r}L(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)r=t,t=t.h;else if(a>0)t=t.i;else return t}return r}k(t,n){let r=this.C;for(;t;)this.A(t.u,n)<0?(r=t,t=t.h):t=t.i;return r}P(t){for(;;){let n=t.o;if(n===this.C)return;if(t.p===1){t.p=0;return}if(t===n.i){let r=n.h;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n._():n._();else if(r.h&&r.h.p===1){r.p=n.p,n.p=0,r.h.p=0,n===this.v?this.v=n._():n._();return}else r.i&&r.i.p===1?(r.p=1,r.i.p=0,r.g()):(r.p=1,t=n)}else{let r=n.i;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n.g():n.g();else if(r.i&&r.i.p===1){r.p=n.p,n.p=0,r.i.p=0,n===this.v?this.v=n.g():n.g();return}else r.h&&r.h.p===1?(r.p=1,r.h.p=0,r._()):(r.p=1,t=n)}}}S(t){if(this.m===1){this.clear();return}let n=t;for(;n.i||n.h;){if(n.h)for(n=n.h;n.i;)n=n.i;else n=n.i;let a=t.u;t.u=n.u,n.u=a;let i=t.l;t.l=n.l,n.l=i,t=n}this.C.i===n?this.C.i=n.o:this.C.h===n&&(this.C.h=n.o),this.P(n);let r=n.o;if(n===r.i?r.i=void 0:r.h=void 0,this.m-=1,this.v.p=0,this.enableIndex)for(;r!==this.C;)r.M-=1,r=r.o}U(t){let n=typeof t=="number"?t:void 0,r=typeof t=="function"?t:void 0,a=typeof t>"u"?[]:void 0,i=0,s=this.v,o=[];for(;o.length||s;)if(s)o.push(s),s=s.i;else{if(s=o.pop(),i===n)return s;a&&a.push(s),r&&r(s,i,this),i+=1,s=s.h}return a}j(t){for(;;){let n=t.o;if(n.p===0)return;let r=n.o;if(n===r.i){let a=r.h;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.h){if(t.p=0,t.i&&(t.i.o=n),t.h&&(t.h.o=r),n.h=t.i,r.i=t.h,t.i=n,t.h=r,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r.g():r.g(),r.p=1;return}}else{let a=r.i;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.i){if(t.p=0,t.i&&(t.i.o=r),t.h&&(t.h.o=n),r.h=t.i,n.i=t.h,t.i=r,t.h=n,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r._():r._(),r.p=1;return}}this.enableIndex&&(n.O(),r.O(),t.O());return}}q(t,n,r){if(this.v===void 0)return this.m+=1,this.v=new this.N(t,n,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let a,i=this.C.i,s=this.A(i.u,t);if(s===0)return i.l=n,this.m;if(s>0)i.i=new this.N(t,n),i.i.o=i,a=i.i,this.C.i=a;else{let o=this.C.h,c=this.A(o.u,t);if(c===0)return o.l=n,this.m;if(c<0)o.h=new this.N(t,n),o.h.o=o,a=o.h,this.C.h=a;else{if(r!==void 0){let l=r.T;if(l!==this.C){let u=this.A(l.u,t);if(u===0)return l.l=n,this.m;if(u>0){let d=l.I(),f=this.A(d.u,t);if(f===0)return d.l=n,this.m;f<0&&(a=new this.N(t,n),d.h===void 0?(d.h=a,a.o=d):(l.i=a,a.o=l))}}}if(a===void 0)for(a=this.v;;){let l=this.A(a.u,t);if(l>0){if(a.i===void 0){a.i=new this.N(t,n),a.i.o=a,a=a.i;break}a=a.i}else if(l<0){if(a.h===void 0){a.h=new this.N(t,n),a.h.o=a,a=a.h;break}a=a.h}else return a.l=n,this.m}}}if(this.enableIndex){let o=a.o;for(;o!==this.C;)o.M+=1,o=o.o}return this.j(a),this.m+=1,this.m}H(t,n){for(;t;){let r=this.A(t.u,n);if(r<0)t=t.h;else if(r>0)t=t.i;else return t}return t||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator(t,n){let r=t.T;if(r===this.C&&Oy(),this.m===1)return r.u=n,!0;let a=r.B().u;if(r===this.C.i)return this.A(a,n)>0?(r.u=n,!0):!1;let i=r.I().u;return r===this.C.h?this.A(i,n)<0?(r.u=n,!0):!1:this.A(i,n)>=0||this.A(a,n)<=0?!1:(r.u=n,!0)}eraseElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return this.S(n),this.m}eraseElementByKey(t){if(this.m===0)return!1;let n=this.H(this.v,t);return n===this.C?!1:(this.S(n),!0)}eraseElementByIterator(t){let n=t.T;n===this.C&&Oy();let r=n.h===void 0;return t.iteratorType===0?r&&t.next():(!r||n.i===void 0)&&t.next(),this.S(n),t}getHeight(){if(this.m===0)return 0;function t(n){return n?Math.max(t(n.i),t(n.h))+1:0}return t(this.v)}},N7=class extends A7{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&Oy(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&Oy(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&Oy(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&Oy(),this.T=this.T.I(),this})}get index(){let t=this.T,n=this.C.o;if(t===this.C)return n?n.M-1:0;let r=0;for(t.i&&(r+=t.i.M);t!==n;){let a=t.o;t===a.h&&(r+=1,a.i&&(r+=a.i.M)),t=a}return r}isAccessible(){return this.T!==this.C}},eu=class e extends N7{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&Oy();let t=this;return new Proxy([],{get(n,r){return r==="0"?t.T.u:r==="1"?t.T.l:(n[0]=t.T.u,n[1]=t.T.l,n[r])},set(n,r,a){if(r!=="1")throw new TypeError("prop must be 1");return t.T.l=a,!0}})}copy(){return new e(this.T,this.C,this.container,this.iteratorType)}},M7=class extends C7{constructor(t=[],n,r){super(n,r);let a=this;t.forEach(function(i){a.setElement(i[0],i[1])})}begin(){return new eu(this.C.i||this.C,this.C,this)}end(){return new eu(this.C,this.C,this)}rBegin(){return new eu(this.C.h||this.C,this.C,this,1)}rEnd(){return new eu(this.C,this.C,this,1)}front(){if(this.m===0)return;let t=this.C.i;return[t.u,t.l]}back(){if(this.m===0)return;let t=this.C.h;return[t.u,t.l]}lowerBound(t){let n=this.R(this.v,t);return new eu(n,this.C,this)}upperBound(t){let n=this.K(this.v,t);return new eu(n,this.C,this)}reverseLowerBound(t){let n=this.L(this.v,t);return new eu(n,this.C,this)}reverseUpperBound(t){let n=this.k(this.v,t);return new eu(n,this.C,this)}forEach(t){this.U(function(n,r,a){t([n.u,n.l],r,a)})}setElement(t,n,r){return this.q(t,n,r)}getElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return[n.u,n.l]}find(t){let n=this.H(this.v,t);return new eu(n,this.C,this)}getElementByKey(t){return this.H(this.v,t).l}union(t){let n=this;return t.forEach(function(r){n.setElement(r[0],r[1])}),this.m}*[Symbol.iterator](){let t=this.m,n=this.U();for(let r=0;r<t;++r){let a=n[r];yield[a.u,a.l]}}};D7.OrderedMap=M7});var pD=_(fD=>{"use strict";Object.defineProperty(fD,"__esModule",{value:!0});fD.registerAdminService=oUt;fD.addAdminServicesToServer=cUt;var SCe=[];function oUt(e,t){SCe.push({getServiceDefinition:e,getHandlers:t})}function cUt(e){for(let{getServiceDefinition:t,getHandlers:n}of SCe)e.addService(t(),n())}});var _Ce=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.ClientDuplexStreamImpl=tu.ClientWritableStreamImpl=tu.ClientReadableStreamImpl=tu.ClientUnaryCallImpl=void 0;tu.callErrorFromStatus=uUt;var lUt=require("events"),V7=require("stream"),ak=Yt();function uUt(e,t){let n=`${e.code} ${ak.Status[e.code]}: ${e.details}`,a=`${new Error(n).stack}
218
218
  for call at
219
219
  ${t}`;return Object.assign(new Error(n),e,{stack:a})}var U7=class extends lUt.EventEmitter{constructor(){super()}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(ak.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}};tu.ClientUnaryCallImpl=U7;var B7=class extends V7.Readable{constructor(t){super({objectMode:!0}),this.deserialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(ak.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_read(t){var n;(n=this.call)===null||n===void 0||n.startRead()}};tu.ClientReadableStreamImpl=B7;var F7=class extends V7.Writable{constructor(t){super({objectMode:!0}),this.serialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(ak.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_write(t,n,r){var a;let i={callback:r},s=Number(n);Number.isNaN(s)||(i.flags=s),(a=this.call)===null||a===void 0||a.sendMessageWithContext(i,t)}_final(t){var n;(n=this.call)===null||n===void 0||n.halfClose(),t()}};tu.ClientWritableStreamImpl=F7;var L7=class extends V7.Duplex{constructor(t,n){super({objectMode:!0}),this.serialize=t,this.deserialize=n}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(ak.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_read(t){var n;(n=this.call)===null||n===void 0||n.startRead()}_write(t,n,r){var a;let i={callback:r},s=Number(n);Number.isNaN(s)||(i.flags=s),(a=this.call)===null||a===void 0||a.sendMessageWithContext(i,t)}_final(t){var n;(n=this.call)===null||n===void 0||n.halfClose(),t()}};tu.ClientDuplexStreamImpl=L7});var Py=_(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});Ay.InterceptingListenerImpl=void 0;Ay.statusOrFromValue=fUt;Ay.statusOrFromError=pUt;Ay.isInterceptingListener=hUt;var dUt=ga();function fUt(e){return{ok:!0,value:e}}function pUt(e){var t;return{ok:!1,error:Object.assign(Object.assign({},e),{metadata:(t=e.metadata)!==null&&t!==void 0?t:new dUt.Metadata})}}function hUt(e){return e.onReceiveMetadata!==void 0&&e.onReceiveMetadata.length===1}var q7=class{constructor(t,n){this.listener=t,this.nextListener=n,this.processingMetadata=!1,this.hasPendingMessage=!1,this.processingMessage=!1,this.pendingStatus=null}processPendingMessage(){this.hasPendingMessage&&(this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1)}processPendingStatus(){this.pendingStatus&&this.nextListener.onReceiveStatus(this.pendingStatus)}onReceiveMetadata(t){this.processingMetadata=!0,this.listener.onReceiveMetadata(t,n=>{this.processingMetadata=!1,this.nextListener.onReceiveMetadata(n),this.processPendingMessage(),this.processPendingStatus()})}onReceiveMessage(t){this.processingMessage=!0,this.listener.onReceiveMessage(t,n=>{this.processingMessage=!1,this.processingMetadata?(this.pendingMessage=n,this.hasPendingMessage=!0):(this.nextListener.onReceiveMessage(n),this.processPendingStatus())})}onReceiveStatus(t){this.listener.onReceiveStatus(t,n=>{this.processingMetadata||this.processingMessage?this.pendingStatus=n:this.nextListener.onReceiveStatus(n)})}};Ay.InterceptingListenerImpl=q7});var j7=_(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.InterceptingCall=nu.RequesterBuilder=nu.ListenerBuilder=nu.InterceptorConfigurationError=void 0;nu.getInterceptingCall=vUt;var mUt=ga(),wCe=Py(),ICe=Yt(),xCe=WM(),ok=class e extends Error{constructor(t){super(t),this.name="InterceptorConfigurationError",Error.captureStackTrace(this,e)}};nu.InterceptorConfigurationError=ok;var z7=class{constructor(){this.metadata=void 0,this.message=void 0,this.status=void 0}withOnReceiveMetadata(t){return this.metadata=t,this}withOnReceiveMessage(t){return this.message=t,this}withOnReceiveStatus(t){return this.status=t,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveStatus:this.status}}};nu.ListenerBuilder=z7;var G7=class{constructor(){this.start=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withStart(t){return this.start=t,this}withSendMessage(t){return this.message=t,this}withHalfClose(t){return this.halfClose=t,this}withCancel(t){return this.cancel=t,this}build(){return{start:this.start,sendMessage:this.message,halfClose:this.halfClose,cancel:this.cancel}}};nu.RequesterBuilder=G7;var $7={onReceiveMetadata:(e,t)=>{t(e)},onReceiveMessage:(e,t)=>{t(e)},onReceiveStatus:(e,t)=>{t(e)}},sk={start:(e,t,n)=>{n(e,t)},sendMessage:(e,t)=>{t(e)},halfClose:e=>{e()},cancel:e=>{e()}},J7=class{constructor(t,n){var r,a,i,s;this.nextCall=t,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,n?this.requester={start:(r=n.start)!==null&&r!==void 0?r:sk.start,sendMessage:(a=n.sendMessage)!==null&&a!==void 0?a:sk.sendMessage,halfClose:(i=n.halfClose)!==null&&i!==void 0?i:sk.halfClose,cancel:(s=n.cancel)!==null&&s!==void 0?s:sk.cancel}:this.requester=sk}cancelWithStatus(t,n){this.requester.cancel(()=>{this.nextCall.cancelWithStatus(t,n)})}getPeer(){return this.nextCall.getPeer()}processPendingMessage(){this.pendingMessageContext&&(this.nextCall.sendMessageWithContext(this.pendingMessageContext,this.pendingMessage),this.pendingMessageContext=null,this.pendingMessage=null)}processPendingHalfClose(){this.pendingHalfClose&&this.nextCall.halfClose()}start(t,n){var r,a,i,s,o,c;let l={onReceiveMetadata:(a=(r=n?.onReceiveMetadata)===null||r===void 0?void 0:r.bind(n))!==null&&a!==void 0?a:u=>{},onReceiveMessage:(s=(i=n?.onReceiveMessage)===null||i===void 0?void 0:i.bind(n))!==null&&s!==void 0?s:u=>{},onReceiveStatus:(c=(o=n?.onReceiveStatus)===null||o===void 0?void 0:o.bind(n))!==null&&c!==void 0?c:u=>{}};this.processingMetadata=!0,this.requester.start(t,l,(u,d)=>{var f,p,m;this.processingMetadata=!1;let y;if((0,wCe.isInterceptingListener)(d))y=d;else{let b={onReceiveMetadata:(f=d.onReceiveMetadata)!==null&&f!==void 0?f:$7.onReceiveMetadata,onReceiveMessage:(p=d.onReceiveMessage)!==null&&p!==void 0?p:$7.onReceiveMessage,onReceiveStatus:(m=d.onReceiveStatus)!==null&&m!==void 0?m:$7.onReceiveStatus};y=new wCe.InterceptingListenerImpl(b,l)}this.nextCall.start(u,y),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext(t,n){this.processingMessage=!0,this.requester.sendMessage(n,r=>{this.processingMessage=!1,this.processingMetadata?(this.pendingMessageContext=t,this.pendingMessage=n):(this.nextCall.sendMessageWithContext(t,r),this.processPendingHalfClose())})}sendMessage(t){this.sendMessageWithContext({},t)}startRead(){this.nextCall.startRead()}halfClose(){this.requester.halfClose(()=>{this.processingMetadata||this.processingMessage?this.pendingHalfClose=!0:this.nextCall.halfClose()})}getAuthContext(){return this.nextCall.getAuthContext()}};nu.InterceptingCall=J7;function gUt(e,t,n){var r,a;let i=(r=n.deadline)!==null&&r!==void 0?r:1/0,s=n.host,o=(a=n.parent)!==null&&a!==void 0?a:null,c=n.propagate_flags,l=n.credentials,u=e.createCall(t,i,s,o,c);return l&&u.setCredentials(l),u}var hD=class{constructor(t,n){this.call=t,this.methodDefinition=n}cancelWithStatus(t,n){this.call.cancelWithStatus(t,n)}getPeer(){return this.call.getPeer()}sendMessageWithContext(t,n){let r;try{r=this.methodDefinition.requestSerialize(n)}catch(a){this.call.cancelWithStatus(ICe.Status.INTERNAL,`Request message serialization failure: ${(0,xCe.getErrorMessage)(a)}`);return}this.call.sendMessageWithContext(t,r)}sendMessage(t){this.sendMessageWithContext({},t)}start(t,n){let r=null;this.call.start(t,{onReceiveMetadata:a=>{var i;(i=n?.onReceiveMetadata)===null||i===void 0||i.call(n,a)},onReceiveMessage:a=>{var i;let s;try{s=this.methodDefinition.responseDeserialize(a)}catch(o){r={code:ICe.Status.INTERNAL,details:`Response message parsing error: ${(0,xCe.getErrorMessage)(o)}`,metadata:new mUt.Metadata},this.call.cancelWithStatus(r.code,r.details);return}(i=n?.onReceiveMessage)===null||i===void 0||i.call(n,s)},onReceiveStatus:a=>{var i,s;r?(i=n?.onReceiveStatus)===null||i===void 0||i.call(n,r):(s=n?.onReceiveStatus)===null||s===void 0||s.call(n,a)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}},H7=class extends hD{constructor(t,n){super(t,n)}start(t,n){var r,a;let i=!1,s={onReceiveMetadata:(a=(r=n?.onReceiveMetadata)===null||r===void 0?void 0:r.bind(n))!==null&&a!==void 0?a:o=>{},onReceiveMessage:o=>{var c;i=!0,(c=n?.onReceiveMessage)===null||c===void 0||c.call(n,o)},onReceiveStatus:o=>{var c,l;i||(c=n?.onReceiveMessage)===null||c===void 0||c.call(n,null),(l=n?.onReceiveStatus)===null||l===void 0||l.call(n,o)}};super.start(t,s),this.call.startRead()}},W7=class extends hD{};function yUt(e,t,n){let r=gUt(e,n.path,t);return n.responseStream?new W7(r,n):new H7(r,n)}function vUt(e,t,n,r){if(e.clientInterceptors.length>0&&e.clientInterceptorProviders.length>0)throw new ok("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if(e.callInterceptors.length>0&&e.callInterceptorProviders.length>0)throw new ok("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let a=[];e.callInterceptors.length>0||e.callInterceptorProviders.length>0?a=[].concat(e.callInterceptors,e.callInterceptorProviders.map(o=>o(t))).filter(o=>o):a=[].concat(e.clientInterceptors,e.clientInterceptorProviders.map(o=>o(t))).filter(o=>o);let i=Object.assign({},n,{method_definition:t});return a.reduceRight((o,c)=>l=>c(l,o),o=>yUt(r,o,t))(i)}});var X7=_(gD=>{"use strict";Object.defineProperty(gD,"__esModule",{value:!0});gD.Client=void 0;var kd=_Ce(),bUt=Z7(),SUt=io(),Vh=Yt(),uS=ga(),mD=j7(),ru=Symbol(),dS=Symbol(),fS=Symbol(),pp=Symbol();function Y7(e){return typeof e=="function"}function pS(e){var t;return((t=e.stack)===null||t===void 0?void 0:t.split(`
220
220
  `).slice(1).join(`
@@ -250,7 +250,7 @@ const app = await modal.apps.fromName("my-app");
250
250
  modal.sandboxes.experimentalList({ appId: app.appId });`);let t=e.tags?Object.entries(e.tags).map(([r,a])=>({tagName:r,tagValue:a})):[],n;for(;;){let r=await this.#e.cpClient.sandboxListV2({appId:e.appId,beforeTimestamp:n,includeFinished:!1,tags:t});if(!r.sandboxes||r.sandboxes.length===0)return;for(let a of r.sandboxes)yield new sv(this.#e,a.id,{isV2:!0});n=r.sandboxes[r.sandboxes.length-1].createdAt}}},W9e=class{constructor(e,t,n,r){this.host=e,this.port=t,this.unencryptedHost=n,this.unencryptedPort=r}get url(){let e=`https://${this.host}`;return this.port!==443&&(e+=`:${this.port}`),e}get tlsSocket(){return[this.host,this.port]}get tcpSocket(){if(!this.unencryptedHost||this.unencryptedPort===void 0)throw new wt("This tunnel is not configured for unencrypted TCP.");return[this.unencryptedHost,this.unencryptedPort]}};sv=class X9e{#e;sandboxId;#t;#n;#r;#a;#s;#l;#u;#c;#p;#d;#h=!0;#m;#g;constructor(t,n,r={}){this.#e=t,this.sandboxId=n,this.#c=r.isV2??!1,this.#l=r.taskId||void 0,this.#u=r.tunnels}get stdin(){return this.#f("stdin"),this.#t||(this.#t=G9e(GWt(this.#e.cpClient,this.sandboxId))),this.#t}get stdout(){if(this.#f("stdout"),!this.#n){this.#a=new AbortController;let t=$U(e6e(this.#e.cpClient,this.sandboxId,1,this.#a.signal),()=>this.#a?.abort());this.#n=Mw(t.pipeThrough(new TextDecoderStream))}return this.#n}get stderr(){if(this.#f("stderr"),!this.#r){this.#s=new AbortController;let t=$U(e6e(this.#e.cpClient,this.sandboxId,2,this.#s.signal),()=>this.#s?.abort());this.#r=Mw(t.pipeThrough(new TextDecoderStream))}return this.#r}get filesystem(){return this.#i(),this.#m||(this.#m=new $9e((t,n)=>this.#y(t,n))),this.#m}get experimentalSidecars(){return this.#i(),this.#g||(this.#g=new OWt({client:this.#e,exec:(t,n,r)=>this.#y(t,n,r),commandRouter:()=>this.#o()})),this.#g}async setTags(t){this.#i(),this.#f("setTags");let n=Object.entries(t).map(([r,a])=>({tagName:r,tagValue:a}));try{await this.#e.cpClient.sandboxTagsSet({environmentName:this.#e.environmentName(),sandboxId:this.sandboxId,tags:n})}catch(r){throw r instanceof Fs.ClientError&&r.code===Fs.Status.INVALID_ARGUMENT?new wt(r.details||r.message):r}}async getTags(){this.#i(),this.#f("getTags");let t;try{t=await this.#e.cpClient.sandboxTagsGet({sandboxId:this.sandboxId})}catch(r){throw r instanceof Fs.ClientError&&r.code===Fs.Status.INVALID_ARGUMENT?new wt(r.details||r.message):r}let n={};for(let r of t.tags)n[r.tagName]=r.tagValue;return n}async exec(t,n){return this.#y(t,n)}async#y(t,n,r){this.#i(),Y9e(t),YU(n?.env??{});let[a,i]=DX(n?.secrets??[]);Object.assign(a,n?.env??{}),await Vw(this.#e,i);let s={...n,env:a,secrets:i},[o,c]=await this.#o(),l=iv(),u=VWt(o,l,t,s,r);await c.execStart(u),this.#e.logger.debug("Created ContainerProcess","exec_id",l,"sandbox_id",this.sandboxId,"container_id",r??"","command",t);let d=n?.timeoutMs?Date.now()+n.timeoutMs:null;return new zWt(o,l,c,n,d)}async#o(){this.#i();let t=await this.#I(),n=await this.#x(t);return[t,n]}#i(){if(!this.#h)throw new VU}#f(t){if(this.#c)throw new wt(`Sandbox.${t} is not supported for V2 sandboxes`)}#v(t){let n={sandboxId:this.sandboxId,timeout:t};return this.#c?this.#e.cpClient.sandboxWaitV2(n):this.#e.cpClient.sandboxWait(n)}#b(){let t={sandboxId:this.sandboxId};return this.#c?this.#e.cpClient.sandboxGetTaskIdV2(t):this.#e.cpClient.sandboxGetTaskId(t)}#S(t){let n={sandboxId:this.sandboxId,timeout:t/1e3};return this.#c?this.#e.cpClient.sandboxGetTunnelsV2(n):this.#e.cpClient.sandboxGetTunnels(n)}async#_(){let t={sandboxId:this.sandboxId};if(this.#c){await this.#e.cpClient.sandboxTerminateV2(t);return}await this.#e.cpClient.sandboxTerminate(t)}static#w=600;async#I(){if(this.#l!==void 0)return this.#l;for(let t=0;t<X9e.#w;t++){let n=await this.#b();if(n.taskResult)throw n.taskResult.status===1||!n.taskResult.exception?new Error(`Sandbox ${this.sandboxId} has already completed`):new Error(`Sandbox ${this.sandboxId} has already completed with result: exception:"${n.taskResult.exception}"`);if(n.taskId)return this.#l=n.taskId,this.#l;await(0,UX.setTimeout)(500)}throw new Error(`Timed out waiting for task ID for Sandbox ${this.sandboxId}`)}async#x(t){if(this.#p!==void 0)return this.#p;if(this.#d!==void 0)return this.#d;let n=(async()=>{let r=await oWt.tryInit(this.#e.cpClient,t,this.sandboxId,this.#c,this.#e.logger,this.#e.profile);if(!r)throw new Error("Command router access is not available for this sandbox");if(!this.#h)throw r.close(),new VU;return this.#p=r,r})();this.#d=n;try{return await n}catch(r){throw this.#d===n&&(this.#d=void 0),r}}async createConnectToken(t){this.#i(),this.#f("createConnectToken");let n=t?.port??8080;if(!Number.isInteger(n)||n<1||n>65535)throw new wt(`createConnectToken() expects \`port\` in [1, 65535], got ${n}`);let r=await this.#e.cpClient.sandboxCreateConnectToken({sandboxId:this.sandboxId,userMetadata:t?.userMetadata,port:n});return{url:r.url,token:r.token}}async terminate(t){this.#i(),await this.#_();let n;return t?.wait&&(n=await this.wait()),this.#l=void 0,this.detach(),n}detach(){this.#p?.close(),this.#h=!1,this.#p=void 0,this.#d=void 0}async wait(){for(;;){let t=await this.#v(10);if(t.result){let n=Dw(t.result);return this.#e.logger.debug("Sandbox wait completed","sandbox_id",this.sandboxId,"status",t.result.status,"return_code",n),n}}}async waitUntilReady(t=3e5){if(this.#i(),t<=0)throw new wt(`timeoutMs must be positive, got ${t}`);let[n,r]=await this.#o();await r.sandboxWaitUntilReady(n,t)}async tunnels(t=5e4){if(this.#i(),this.#u)return this.#u;let n=await this.#S(t);if(n.result?.status===4)throw new L6t;this.#u={};for(let r of n.tunnels)this.#u[r.containerPort]=new W9e(r.host,r.port,r.unencryptedHost,r.unencryptedPort);return this.#u}async snapshotFilesystem(t){this.#i();let n=ZHe(t?.ttlMs),r=t?.timeoutMs||55e3,[a,i]=await this.#o(),s=XX.create({taskId:a,snapshotId:iv(),ttlSeconds:n}),o=await i.snapshotFilesystem(s,{timeoutMs:r});if(!o.imageId)throw new Error("Sandbox snapshot filesystem response missing `imageId`");return new fv(this.#e,o.imageId,"")}async mountImage(t,n,r){this.#i();let[a,i]=await this.#o();if(n&&!n.imageId)throw new Error("Image must be built before mounting. Call `image.build(app)` first.");let s=n?.imageId??"",o=qWt(a,t,s,r);await i.mountDirectory(o)}async unmountImage(t){this.#i();let[n,r]=await this.#o(),a=new TextEncoder().encode(t),i=ZX.create({taskId:n,path:a});await r.unmountDirectory(i)}async updateNetworkPolicy(t){if(this.#i(),t.outboundCidrAllowlist===void 0||t.outboundDomainAllowlist===void 0)throw new wt("updateNetworkPolicy currently requires both outboundCidrAllowlist and outboundDomainAllowlist to be set");let[n,r]=await this.#o(),a=YX.create({taskId:n,networkAccess:co.create({networkAccessType:3,allowedCidrs:t.outboundCidrAllowlist,allowedDomains:t.outboundDomainAllowlist})});await r.setNetworkAccess(a)}async reloadVolumes(t){if(this.#i(),t?.timeoutMs!==void 0&&t.timeoutMs<0)throw new wt("`timeoutMs` must not be negative");let n=t?.timeoutMs||55e3,[r,a]=await this.#o();await a.reloadVolumes(jX.create({taskId:r}),{timeoutMs:n})}async snapshotDirectory(t,n){this.#i();let r=ZHe(n?.ttlMs),a=n?.timeoutMs||55e3,[i,s]=await this.#o(),o=$Wt(i,t,iv(),r,n),c=await s.snapshotDirectory(o,{timeoutMs:a});if(!c.imageId)throw new Error("Sandbox snapshot directory response missing `imageId`");return new fv(this.#e,c.imageId,"")}async poll(){this.#i();let t=await this.#v(0);return Dw(t.result)}},zWt=class{stdin;stdout;stderr;#e;#t;#n;#r;constructor(e,t,n,r,a){this.#e=e,this.#t=t,this.#n=n,this.#r=a??null;let i=r?.mode??"text",s=r?.stdout??"pipe",o=r?.stderr??"pipe";this.stdin=G9e(JWt(n,e,t));let c=s==="ignore"?ReadableStream.from([]):$U(t6e(n,e,t,1,this.#r)),l=o==="ignore"?ReadableStream.from([]):$U(t6e(n,e,t,2,this.#r));i==="text"?(this.stdout=Mw(c.pipeThrough(new TextDecoderStream)),this.stderr=Mw(l.pipeThrough(new TextDecoderStream))):(this.stdout=Mw(c),this.stderr=Mw(l))}async closeStdin(){await this.#n.execStdinWrite(this.#e,this.#t,0,new Uint8Array(0),!0).catch(()=>{})}async wait(){let e=await this.#n.execWait(this.#e,this.#t,this.#r);if(e.code!==void 0)return e.code;if(e.signal!==void 0)return 128+e.signal;throw new wt("Unexpected exit status")}}});var tKe=_((jOn,eKe)=>{eKe.exports=require("events")});var rKe=_((KOn,nKe)=>{nKe.exports=class{constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var eZ=_((ZOn,aKe)=>{var iKe=rKe();aKe.exports=class{constructor(t){this.hwm=t||16,this.head=new iKe(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(t){if(this.length++,!this.head.push(t)){let n=this.head;this.head=n.next=new iKe(2*this.head.buffer.length),this.head.push(t)}}shift(){this.length!==0&&this.length--;let t=this.tail.shift();if(t===void 0&&this.tail.next){let n=this.tail.next;return this.tail.next=null,this.tail=n,this.tail.shift()}return t}peek(){let t=this.tail.peek();return t===void 0&&this.tail.next?this.tail.next.peek():t}isEmpty(){return this.length===0}}});var qw=_((QOn,sKe)=>{function HWt(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function WWt(e){return Buffer.isEncoding(e)}function jWt(e,t,n){return Buffer.alloc(e,t,n)}function YWt(e){return Buffer.allocUnsafe(e)}function KWt(e){return Buffer.allocUnsafeSlow(e)}function XWt(e,t){return Buffer.byteLength(e,t)}function ZWt(e,t){return Buffer.compare(e,t)}function QWt(e,t){return Buffer.concat(e,t)}function e7t(e,t,n,r,a){return cr(e).copy(t,n,r,a)}function t7t(e,t){return cr(e).equals(t)}function n7t(e,t,n,r,a){return cr(e).fill(t,n,r,a)}function r7t(e,t,n){return Buffer.from(e,t,n)}function i7t(e,t,n,r){return cr(e).includes(t,n,r)}function a7t(e,t,n,r){return cr(e).indexOf(t,n,r)}function s7t(e,t,n,r){return cr(e).lastIndexOf(t,n,r)}function o7t(e){return cr(e).swap16()}function c7t(e){return cr(e).swap32()}function l7t(e){return cr(e).swap64()}function cr(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function u7t(e,t,n,r){return cr(e).toString(t,n,r)}function d7t(e,t,n,r,a){return cr(e).write(t,n,r,a)}function f7t(e,t){return cr(e).readDoubleBE(t)}function p7t(e,t){return cr(e).readDoubleLE(t)}function h7t(e,t){return cr(e).readFloatBE(t)}function m7t(e,t){return cr(e).readFloatLE(t)}function g7t(e,t){return cr(e).readInt32BE(t)}function y7t(e,t){return cr(e).readInt32LE(t)}function v7t(e,t){return cr(e).readUInt32BE(t)}function b7t(e,t){return cr(e).readUInt32LE(t)}function S7t(e,t,n){return cr(e).writeDoubleBE(t,n)}function _7t(e,t,n){return cr(e).writeDoubleLE(t,n)}function w7t(e,t,n){return cr(e).writeFloatBE(t,n)}function I7t(e,t,n){return cr(e).writeFloatLE(t,n)}function x7t(e,t,n){return cr(e).writeInt32BE(t,n)}function E7t(e,t,n){return cr(e).writeInt32LE(t,n)}function T7t(e,t,n){return cr(e).writeUInt32BE(t,n)}function k7t(e,t,n){return cr(e).writeUInt32LE(t,n)}sKe.exports={isBuffer:HWt,isEncoding:WWt,alloc:jWt,allocUnsafe:YWt,allocUnsafeSlow:KWt,byteLength:XWt,compare:ZWt,concat:QWt,copy:e7t,equals:t7t,fill:n7t,from:r7t,includes:i7t,indexOf:a7t,lastIndexOf:s7t,swap16:o7t,swap32:c7t,swap64:l7t,toBuffer:cr,toString:u7t,write:d7t,readDoubleBE:f7t,readDoubleLE:p7t,readFloatBE:h7t,readFloatLE:m7t,readInt32BE:g7t,readInt32LE:y7t,readUInt32BE:v7t,readUInt32LE:b7t,writeDoubleBE:S7t,writeDoubleLE:_7t,writeFloatBE:w7t,writeFloatLE:I7t,writeInt32BE:x7t,writeInt32LE:E7t,writeUInt32BE:T7t,writeUInt32LE:k7t}});var cKe=_((tAn,oKe)=>{var O7t=qw();oKe.exports=class{constructor(t){this.encoding=t}get remaining(){return 0}decode(t){return O7t.toString(t,this.encoding)}flush(){return""}}});var uKe=_((rAn,lKe)=>{var A7t=qw();lKe.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(t){if(this.bytesNeeded===0){let r=!0;for(let a=Math.max(0,t.byteLength-4),i=t.byteLength;a<i&&r;a++)r=t[a]<=127;if(r)return A7t.toString(t,"utf8")}let n="";for(let r=0,a=t.byteLength;r<a;r++){let i=t[r];if(this.bytesNeeded===0){i<=127?n+=String.fromCharCode(i):(this.bytesSeen=1,i>=194&&i<=223?(this.bytesNeeded=2,this.codePoint=i&31):i>=224&&i<=239?(i===224?this.lowerBoundary=160:i===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=i&15):i>=240&&i<=244?(i===240&&(this.lowerBoundary=144),i===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=i&7):n+="\uFFFD");continue}if(i<this.lowerBoundary||i>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,n+="\uFFFD";continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|i&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(n+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return n}flush(){let t=this.bytesNeeded>0?"\uFFFD":"";return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t}}});var fKe=_((aAn,dKe)=>{var P7t=cKe(),R7t=uKe();dKe.exports=class{constructor(t="utf8"){switch(this.encoding=C7t(t),this.encoding){case"utf8":this.decoder=new R7t;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new P7t(this.encoding)}}get remaining(){return this.decoder.remaining}push(t){return typeof t=="string"?t:this.decoder.decode(t)}write(t){return this.push(t)}end(t){let n="";return t&&(n=this.push(t)),n+=this.decoder.flush(),n}};function C7t(e){switch(e=e.toLowerCase(),e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:throw new Error("Unknown encoding: "+e)}}});var gZ=_((sAn,DKe)=>{var{EventEmitter:N7t}=tKe(),rB=new Error("Stream was destroyed"),tZ=new Error("Premature close"),vKe=eZ(),M7t=fKe(),nZ=typeof queueMicrotask>"u"?e=>global.process.nextTick(e):queueMicrotask,si=(1<<29)-1,ef=1,lZ=2,bv=4,mO=8,bKe=si^ef,D7t=si^lZ,SO=16,$w=32,Jw=64,ym=128,_O=256,uZ=512,Sv=1024,rZ=2048,dZ=4096,fZ=8192,zu=16384,gm=32768,iB=65536,_v=131072,SKe=_O|uZ,U7t=SO|iB,B7t=Jw|SO,F7t=dZ|ym,pZ=_O|_v,L7t=si^SO,V7t=si^Jw,q7t=si^(Jw|iB),pKe=si^iB,$7t=si^_O,z7t=si^(ym|fZ),G7t=si^Sv,hKe=si^SKe,_Ke=si^gm,J7t=si^$w,wKe=si^_v,H7t=si^pZ,Mp=1<<18,Gw=2<<18,wO=4<<18,wv=8<<18,IO=16<<18,vm=32<<18,iZ=64<<18,zw=128<<18,hZ=256<<18,Iv=512<<18,aB=1024<<18,W7t=si^(Mp|hZ),IKe=si^wO,j7t=si^(Mp|Iv),Y7t=si^IO,K7t=si^wv,xKe=si^zw,X7t=si^Gw,EKe=si^aB,gO=SO|Mp,TKe=si^gO,mZ=zu|vm,tf=bv|mO|lZ,_c=tf|ef,kKe=tf|mZ,Z7t=IKe&V7t,sB=zw|gm,Q7t=sB&TKe,OKe=_c|Q7t,e5t=_c|Sv|zu,mKe=_c|zu|ym,t5t=_c|Sv|ym,n5t=_c|dZ|ym|fZ,r5t=_c|SO|Sv|zu|iB|_v,i5t=tf|Sv|zu,a5t=$w|_c|gm|Jw,s5t=gm|ef,o5t=_c|Iv|vm,c5t=wv|IO,AKe=wv|Mp,l5t=wv|IO|_c|Mp,gKe=_c|Mp|wv|aB,u5t=wO|Mp,d5t=Mp|hZ,f5t=_c|Iv|AKe|vm,p5t=IO|tf|Iv|vm,h5t=Gw|_c|zw|wO,m5t=Iv|vm|tf,ZU=Symbol.asyncIterator||Symbol("asyncIterator"),QU=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapWritable:a,byteLength:i,byteLengthWritable:s}={}){this.stream=t,this.queue=new vKe,this.highWaterMark=n,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=s||i||MKe,this.map=a||r,this.afterWrite=v5t.bind(this),this.afterUpdateNextTick=_5t.bind(this)}get ended(){return(this.stream._duplexState&vm)!==0}push(t){return this.stream._duplexState&m5t?!1:(this.map!==null&&(t=this.map(t)),this.buffered+=this.byteLength(t),this.queue.push(t),this.buffered<this.highWaterMark?(this.stream._duplexState|=wv,!0):(this.stream._duplexState|=c5t,!1))}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=K7t),t}end(t){typeof t=="function"?this.stream.once("finish",t):t!=null&&this.push(t),this.stream._duplexState=(this.stream._duplexState|Iv)&IKe}autoBatch(t,n){let r=[],a=this.stream;for(r.push(t);(a._duplexState&gKe)===AKe;)r.push(a._writableState.shift());if(a._duplexState&_c)return n(null);a._writev(r,n)}update(){let t=this.stream;t._duplexState|=Gw;do{for(;(t._duplexState&gKe)===wv;){let n=this.shift();t._duplexState|=d5t,t._write(n,this.afterWrite)}t._duplexState&u5t||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=X7t}updateNonPrimary(){let t=this.stream;if((t._duplexState&f5t)===Iv){t._duplexState=t._duplexState|Mp,t._final(y5t.bind(this));return}if((t._duplexState&tf)===bv){t._duplexState&sB||(t._duplexState|=gO,t._destroy(PKe.bind(this)));return}(t._duplexState&OKe)===ef&&(t._duplexState=(t._duplexState|gO)&bKe,t._open(RKe.bind(this)))}continueUpdate(){return this.stream._duplexState&zw?(this.stream._duplexState&=xKe,!0):!1}updateCallback(){(this.stream._duplexState&h5t)===wO?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&zw||(this.stream._duplexState|=zw,this.stream._duplexState&Gw||nZ(this.afterUpdateNextTick))}},aZ=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapReadable:a,byteLength:i,byteLengthReadable:s}={}){this.stream=t,this.queue=new vKe,this.highWaterMark=n===0?1:n,this.buffered=0,this.readAhead=n>0,this.error=null,this.pipeline=null,this.byteLength=s||i||MKe,this.map=a||r,this.pipeTo=null,this.afterRead=b5t.bind(this),this.afterUpdateNextTick=S5t.bind(this)}get ended(){return(this.stream._duplexState&zu)!==0}pipe(t,n){if(this.pipeTo!==null)throw new Error("Can only pipe to one destination");if(typeof n!="function"&&(n=null),this.stream._duplexState|=uZ,this.pipeTo=t,this.pipeline=new oZ(this.stream,t,n),n&&this.stream.on("error",yKe),bO(t))t._writableState.pipeline=this.pipeline,n&&t.on("error",yKe),t.on("finish",this.pipeline.finished.bind(this.pipeline));else{let r=this.pipeline.done.bind(this.pipeline,t),a=this.pipeline.done.bind(this.pipeline,t,null);t.on("error",r),t.on("close",a),t.on("finish",this.pipeline.finished.bind(this.pipeline))}t.on("drain",g5t.bind(this)),this.stream.emit("piping",t),t.emit("pipe",this.stream)}push(t){let n=this.stream;return t===null?(this.highWaterMark=0,n._duplexState=(n._duplexState|Sv)&q7t,!1):this.map!==null&&(t=this.map(t),t===null)?(n._duplexState&=pKe,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(t),this.queue.push(t),n._duplexState=(n._duplexState|ym)&pKe,this.buffered<this.highWaterMark)}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=z7t),t}unshift(t){let n=[this.map!==null?this.map(t):t];for(;this.buffered>0;)n.push(this.shift());for(let r=0;r<n.length-1;r++){let a=n[r];this.buffered+=this.byteLength(a),this.queue.push(a)}this.push(n[n.length-1])}read(){let t=this.stream;if((t._duplexState&mKe)===ym){let n=this.shift();return this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=hKe),t._duplexState&rZ&&t.emit("data",n),n}return this.readAhead===!1&&(t._duplexState|=_v,this.updateNextTick()),null}drain(){let t=this.stream;for(;(t._duplexState&mKe)===ym&&t._duplexState&SKe;){let n=this.shift();this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=hKe),t._duplexState&rZ&&t.emit("data",n)}}update(){let t=this.stream;t._duplexState|=$w;do{for(this.drain();this.buffered<this.highWaterMark&&(t._duplexState&r5t)===_v;)t._duplexState|=U7t,t._read(this.afterRead),this.drain();(t._duplexState&n5t)===F7t&&(t._duplexState|=fZ,t.emit("readable")),t._duplexState&B7t||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=J7t}updateNonPrimary(){let t=this.stream;if((t._duplexState&t5t)===Sv&&(t._duplexState=(t._duplexState|zu)&G7t,t.emit("end"),(t._duplexState&kKe)===mZ&&(t._duplexState|=bv),this.pipeTo!==null&&this.pipeTo.end()),(t._duplexState&tf)===bv){t._duplexState&sB||(t._duplexState|=gO,t._destroy(PKe.bind(this)));return}(t._duplexState&OKe)===ef&&(t._duplexState=(t._duplexState|gO)&bKe,t._open(RKe.bind(this)))}continueUpdate(){return this.stream._duplexState&gm?(this.stream._duplexState&=_Ke,!0):!1}updateCallback(){(this.stream._duplexState&a5t)===Jw?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&s5t||(this.stream._duplexState|=gm,this.stream._duplexState&$w||nZ(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&gm||(this.stream._duplexState|=gm,this.stream._duplexState&$w||nZ(this.afterUpdateNextTick))}},sZ=class{constructor(t){this.data=null,this.afterTransform=I5t.bind(t),this.afterFinal=null}},oZ=class{constructor(t,n,r){this.from=t,this.to=n,this.afterPipe=r,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(t,n){if(n&&(this.error=n),t===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&zu)||!this.pipeToFinished)&&this.from.destroy(this.error||new Error("Writable stream closed prematurely"));return}if(t===this.from&&(this.from=null,this.to!==null)){t._duplexState&zu||this.to.destroy(this.error||new Error("Readable stream closed before ending"));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function g5t(){this.stream._duplexState|=uZ,this.updateCallback()}function y5t(e){let t=this.stream;e&&t.destroy(e),t._duplexState&tf||(t._duplexState|=vm,t.emit("finish")),(t._duplexState&kKe)===mZ&&(t._duplexState|=bv),t._duplexState&=j7t,t._duplexState&Gw?this.updateNextTick():this.update()}function PKe(e){let t=this.stream;!e&&this.error!==rB&&(e=this.error),e&&t.emit("error",e),t._duplexState|=mO,t.emit("close");let n=t._readableState,r=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),r!==null){for(;r.drains!==null&&r.drains.length>0;)r.drains.shift().resolve(!1);r.pipeline!==null&&r.pipeline.done(t,e)}}function v5t(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=W7t,this.drains!==null&&w5t(this.drains),(t._duplexState&l5t)===IO&&(t._duplexState&=Y7t,(t._duplexState&iZ)===iZ&&t.emit("drain")),this.updateCallback()}function b5t(e){e&&this.stream.destroy(e),this.stream._duplexState&=L7t,this.readAhead===!1&&!(this.stream._duplexState&_O)&&(this.stream._duplexState&=wKe),this.updateCallback()}function S5t(){this.stream._duplexState&$w||(this.stream._duplexState&=_Ke,this.update())}function _5t(){this.stream._duplexState&Gw||(this.stream._duplexState&=xKe,this.update())}function w5t(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function RKe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&bv||(t._duplexState&e5t||(t._duplexState|=Jw),t._duplexState&o5t||(t._duplexState|=wO),t.emit("open")),t._duplexState&=TKe,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function I5t(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function x5t(e){this._readableState!==null&&(e==="data"&&(this._duplexState|=rZ|pZ,this._readableState.updateNextTick()),e==="readable"&&(this._duplexState|=dZ,this._readableState.updateNextTick())),this._writableState!==null&&e==="drain"&&(this._duplexState|=iZ,this._writableState.updateNextTick())}var yO=class extends N7t{constructor(t){super(),this._duplexState=0,this._readableState=null,this._writableState=null,t&&(t.open&&(this._open=t.open),t.destroy&&(this._destroy=t.destroy),t.predestroy&&(this._predestroy=t.predestroy),t.signal&&t.signal.addEventListener("abort",M5t.bind(this))),this.on("newListener",x5t)}_open(t){t(null)}_destroy(t){t(null)}_predestroy(){}get readable(){return this._readableState!==null?!0:void 0}get writable(){return this._writableState!==null?!0:void 0}get destroyed(){return(this._duplexState&mO)!==0}get destroying(){return(this._duplexState&tf)!==0}destroy(t){this._duplexState&tf||(t||(t=rB),this._duplexState=(this._duplexState|bv)&Z7t,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=t),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=t),this._duplexState|=lZ,this._predestroy(),this._duplexState&=D7t,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},eB=class e extends yO{constructor(t){super(t),this._duplexState|=ef|vm|_v,this._readableState=new aZ(this,t),t&&(this._readableState.readAhead===!1&&(this._duplexState&=wKe),t.read&&(this._read=t.read),t.eagerOpen&&this._readableState.updateNextTick(),t.encoding&&this.setEncoding(t.encoding))}setEncoding(t){let n=new M7t(t),r=this._readableState.map||k5t;return this._readableState.map=a,this;function a(i){let s=n.push(i);return s===""&&(i.byteLength!==0||n.remaining>0)?null:r(s)}}_read(t){t(null)}pipe(t,n){return this._readableState.updateNextTick(),this._readableState.pipe(t,n),t}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(t){return this._readableState.updateNextTickIfOpen(),this._readableState.push(t)}unshift(t){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(t)}resume(){return this._duplexState|=pZ,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?H7t:$7t,this}static _fromAsyncIterator(t,n){let r,a=new e({...n,read(s){t.next().then(i).then(s.bind(null,null)).catch(s)},predestroy(){r=t.return()},destroy(s){if(!r)return s(null);r.then(s.bind(null,null)).catch(s)}});return a;function i(s){s.done?a.push(null):a.push(s.value)}}static from(t,n){if(R5t(t))return t;if(t[ZU])return this._fromAsyncIterator(t[ZU](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(a){this.push(r===t.length?null:t[r++]),a(null)}})}static isBackpressured(t){return(t._duplexState&i5t)!==0||t._readableState.buffered>=t._readableState.highWaterMark}static isPaused(t){return(t._duplexState&_O)===0}[ZU](){let t=this,n=null,r=null,a=null;return this.on("error",l=>{n=l}),this.on("readable",i),this.on("close",s),{[ZU](){return this},next(){return new Promise(function(l,u){r=l,a=u;let d=t.read();d!==null?o(d):t._duplexState&mO&&o(null)})},return(){return c(null)},throw(l){return c(l)}};function i(){r!==null&&o(t.read())}function s(){r!==null&&o(null)}function o(l){a!==null&&(n?a(n):l===null&&!(t._duplexState&zu)?a(rB):r({value:l,done:l===null}),a=r=null)}function c(l){return t.destroy(l),new Promise((u,d)=>{if(t._duplexState&mO)return u({value:void 0,done:!0});t.once("close",function(){l?d(l):u({value:void 0,done:!0})})})}}},tB=class extends yO{constructor(t){super(t),this._duplexState|=ef|zu,this._writableState=new QU(this,t),t&&(t.writev&&(this._writev=t.writev),t.write&&(this._write=t.write),t.final&&(this._final=t.final),t.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=aB}uncork(){this._duplexState&=EKe,this._writableState.updateNextTick()}_writev(t,n){n(null)}_write(t,n){this._writableState.autoBatch(t,n)}_final(t){t(null)}static isBackpressured(t){return(t._duplexState&p5t)!==0}static drained(t){if(t.destroyed)return Promise.resolve(!1);let n=t._writableState,a=(D5t(t)?Math.min(1,n.queue.length):n.queue.length)+(t._duplexState&hZ?1:0);return a===0?Promise.resolve(!0):(n.drains===null&&(n.drains=[]),new Promise(i=>{n.drains.push({writes:a,resolve:i})}))}write(t){return this._writableState.updateNextTick(),this._writableState.push(t)}end(t){return this._writableState.updateNextTick(),this._writableState.end(t),this}},vO=class extends eB{constructor(t){super(t),this._duplexState=ef|this._duplexState&_v,this._writableState=new QU(this,t),t&&(t.writev&&(this._writev=t.writev),t.write&&(this._write=t.write),t.final&&(this._final=t.final))}cork(){this._duplexState|=aB}uncork(){this._duplexState&=EKe,this._writableState.updateNextTick()}_writev(t,n){n(null)}_write(t,n){this._writableState.autoBatch(t,n)}_final(t){t(null)}write(t){return this._writableState.updateNextTick(),this._writableState.push(t)}end(t){return this._writableState.updateNextTick(),this._writableState.end(t),this}},nB=class extends vO{constructor(t){super(t),this._transformState=new sZ(this),t&&(t.transform&&(this._transform=t.transform),t.flush&&(this._flush=t.flush))}_write(t,n){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=t:this._transform(t,this._transformState.afterTransform)}_read(t){if(this._transformState.data!==null){let n=this._transformState.data;this._transformState.data=null,t(null),this._transform(n,this._transformState.afterTransform)}else t(null)}destroy(t){super.destroy(t),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(t,n){n(null,t)}_flush(t){t(null)}_final(t){this._transformState.afterFinal=t,this._flush(E5t.bind(this))}},cZ=class extends nB{};function E5t(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function T5t(...e){return new Promise((t,n)=>CKe(...e,r=>{if(r)return n(r);t()}))}function CKe(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]=="function"?n.pop():null;if(n.length<2)throw new Error("Pipeline requires at least 2 streams");let a=n[0],i=null,s=null;for(let l=1;l<n.length;l++)i=n[l],bO(a)?a.pipe(i,c):(o(a,!0,l>1,c),a.pipe(i)),a=i;if(r){let l=!1,u=bO(i)||!!(i._writableState&&i._writableState.autoDestroy);i.on("error",d=>{s===null&&(s=d)}),i.on("finish",()=>{l=!0,u||r(s)}),u&&i.on("close",()=>r(s||(l?null:tZ)))}return i;function o(l,u,d,f){l.on("error",f),l.on("close",p);function p(){if(u&&l._readableState&&!l._readableState.ended||d&&l._writableState&&!l._writableState.ended)return f(tZ)}}function c(l){if(!(!l||s)){s=l;for(let u of n)u.destroy(l)}}}function k5t(e){return e}function NKe(e){return!!e._readableState||!!e._writableState}function bO(e){return typeof e._duplexState=="number"&&NKe(e)}function O5t(e){return!!e._readableState&&e._readableState.ended}function A5t(e){return!!e._writableState&&e._writableState.ended}function P5t(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===rB?null:n}function R5t(e){return bO(e)&&e.readable}function C5t(e){return(e._duplexState&ef)!==ef||(e._duplexState&sB)!==0}function N5t(e){return typeof e=="object"&&e!==null&&typeof e.byteLength=="number"}function MKe(e){return N5t(e)?e.byteLength:1024}function yKe(){}function M5t(){this.destroy(new Error("Stream aborted."))}function D5t(e){return e._writev!==tB.prototype._writev&&e._writev!==vO.prototype._writev}DKe.exports={pipeline:CKe,pipelinePromise:T5t,isStream:NKe,isStreamx:bO,isEnded:O5t,isFinished:A5t,isDisturbed:C5t,getStreamError:P5t,Stream:yO,Writable:tB,Readable:eB,Duplex:vO,Transform:nB,PassThrough:cZ}});var bZ=_(Ww=>{var Pn=qw(),U5t="0000000000000000000",B5t="7777777777777777777",oB=48,UKe=Pn.from([117,115,116,97,114,0]),F5t=Pn.from([oB,oB]),L5t=Pn.from([117,115,116,97,114,32]),V5t=Pn.from([32,0]),q5t=4095,xO=257,vZ=263;Ww.decodeLongPath=function(t,n){return Hw(t,0,t.length,n)};Ww.encodePax=function(t){let n="";t.name&&(n+=yZ(" path="+t.name+`
251
251
  `)),t.linkname&&(n+=yZ(" linkpath="+t.linkname+`
252
252
  `));let r=t.pax;if(r)for(let a in r)n+=yZ(" "+a+"="+r[a]+`
253
- `);return Pn.from(n)};Ww.decodePax=function(t){let n={};for(;t.length;){let r=0;for(;r<t.length&&t[r]!==32;)r++;let a=parseInt(Pn.toString(t.subarray(0,r)),10);if(!a)return n;let i=Pn.toString(t.subarray(r+1,a-1)),s=i.indexOf("=");if(s===-1)return n;n[i.slice(0,s)]=i.slice(s+1),t=t.subarray(a)}return n};Ww.encode=function(t){let n=Pn.alloc(512),r=t.name,a="";if(t.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),Pn.byteLength(r)!==r.length)return null;for(;Pn.byteLength(r)>100;){let i=r.indexOf("/");if(i===-1)return null;a+=a?"/"+r.slice(0,i):r.slice(0,i),r=r.slice(i+1)}return Pn.byteLength(r)>100||Pn.byteLength(a)>155||t.linkname&&Pn.byteLength(t.linkname)>100?null:(Pn.write(n,r),Pn.write(n,Sm(t.mode&q5t,6),100),Pn.write(n,Sm(t.uid,6),108),Pn.write(n,Sm(t.gid,6),116),j5t(t.size,n,124),Pn.write(n,Sm(t.mtime.getTime()/1e3|0,11),136),n[156]=oB+H5t(t.type),t.linkname&&Pn.write(n,t.linkname,157),Pn.copy(UKe,n,xO),Pn.copy(F5t,n,vZ),t.uname&&Pn.write(n,t.uname,265),t.gname&&Pn.write(n,t.gname,297),Pn.write(n,Sm(t.devmajor||0,6),329),Pn.write(n,Sm(t.devminor||0,6),337),a&&Pn.write(n,a,345),Pn.write(n,Sm(FKe(n),6),148),n)};Ww.decode=function(t,n,r){let a=t[156]===0?0:t[156]-oB,i=Hw(t,0,100,n),s=bm(t,100,8),o=bm(t,108,8),c=bm(t,116,8),l=bm(t,124,12),u=bm(t,136,12),d=J5t(a),f=t[157]===0?null:Hw(t,157,100,n),p=Hw(t,265,32),m=Hw(t,297,32),y=bm(t,329,8),b=bm(t,337,8),v=FKe(t);if(v===8*32)return null;if(v!==bm(t,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if($5t(t))t[345]&&(i=Hw(t,345,155,n)+"/"+i);else if(!z5t(t)){if(!r)throw new Error("Invalid tar header: unknown format.")}return a===0&&i&&i[i.length-1]==="/"&&(a=5),{name:i,mode:s,uid:o,gid:c,size:l,mtime:new Date(1e3*u),type:d,linkname:f,uname:p,gname:m,devmajor:y,devminor:b,pax:null}};function $5t(e){return Pn.equals(UKe,e.subarray(xO,xO+6))}function z5t(e){return Pn.equals(L5t,e.subarray(xO,xO+6))&&Pn.equals(V5t,e.subarray(vZ,vZ+2))}function G5t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function J5t(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function H5t(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function BKe(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function FKe(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function Sm(e,t){return e=e.toString(8),e.length>t?B5t.slice(0,t)+" ":U5t.slice(0,t-e.length)+e+" "}function W5t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function j5t(e,t,n){e.toString(8).length>11?W5t(e,t,n):Pn.write(t,Sm(e,11),n)}function Y5t(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let s=e[r];t?n.push(s):n.push(255-s)}let a=0,i=n.length;for(r=0;r<i;r++)a+=n[r]*Math.pow(256,r);return t?a:-1*a}function bm(e,t,n){if(e=e.subarray(t,t+n),t=0,e[t]&128)return Y5t(e);{for(;t<e.length&&e[t]===32;)t++;let r=G5t(BKe(e,32,t,e.length),e.length,e.length);for(;t<r&&e[t]===0;)t++;return r===t?0:parseInt(Pn.toString(e.subarray(t,r)),8)}}function Hw(e,t,n,r){return Pn.toString(e.subarray(t,BKe(e,0,t,t+n)),r)}function yZ(e){let t=Pn.byteLength(e),n=Math.floor(Math.log(t)/Math.log(10))+1;return t+n>=Math.pow(10,n)&&n++,t+n+e}});var zKe=_((cAn,$Ke)=>{var{Writable:K5t,Readable:X5t,getStreamError:LKe}=gZ(),Z5t=eZ(),VKe=qw(),jw=bZ(),Q5t=VKe.alloc(0),_Z=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new Z5t,this._offset=0}push(t){this.buffered+=t.byteLength,this.queue.push(t)}shiftFirst(t){return this._buffered===0?null:this._next(t)}shift(t){if(t>this.buffered)return null;if(t===0)return Q5t;let n=this._next(t);if(t===n.byteLength)return n;let r=[n];for(;(t-=n.byteLength)>0;)n=this._next(t),r.push(n);return VKe.concat(r)}_next(t){let n=this.queue.peek(),r=n.byteLength-this._offset;if(t>=r){let a=this._offset?n.subarray(this._offset,n.byteLength):n;return this.queue.shift(),this._offset=0,this.buffered-=r,this.shifted+=r,a}return this.buffered-=t,this.shifted+=t,n.subarray(this._offset,this._offset+=t)}},wZ=class extends X5t{constructor(t,n,r){super(),this.header=n,this.offset=r,this._parent=t}_read(t){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),t(null)}_predestroy(){this._parent.destroy(LKe(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=qKe(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},IZ=class extends K5t{constructor(t){super(t),t||(t={}),this._buffer=new _Z,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=SZ,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=t.filenameEncoding||"utf-8",this._allowUnknownFormat=!!t.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(t){if(this._locked=!1,t){this.destroy(t),this._continueWrite(t);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=jw.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(t){return this._continueWrite(t),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory"?(this.emit("entry",this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&(this._header.name=this._gnuLongPath,this._gnuLongPath=null),this._gnuLongLinkPath&&(this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null),this._pax&&(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,this._pax=null)}_decodeLongHeader(t){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=jw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=jw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=jw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?jw.decodePax(t):Object.assign({},this._paxGlobal,jw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=qKe(this._header.size);let t=this._buffer.shift(this._header.size);try{this._decodeLongHeader(t)}catch(n){return this._continueWrite(n),!1}return!0}_consumeStream(){let t=this._buffer.shiftFirst(this._missing);if(t===null)return!1;this._missing-=t.byteLength;let n=this._stream.push(t);return this._missing===0?(this._stream.push(null),n&&this._stream._detach(),n&&this._locked===!1):n}_createStream(){return new wZ(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let t=this._buffer.shiftFirst(this._missing);t!==null&&(this._missing-=t.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(t){let n=this._callback;this._callback=SZ,n(t)}_write(t,n){this._callback=n,this._buffer.push(t),this._update()}_final(t){this._finished=this._missing===0&&this._buffer.buffered===0,t(this._finished?null:new Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(t){this._stream&&this._stream.destroy(LKe(this)),t(null)}[Symbol.asyncIterator](){let t=null,n=null,r=null,a=null,i=null,s=this;return this.on("entry",l),this.on("error",f=>{t=f}),this.on("close",u),{[Symbol.asyncIterator](){return this},next(){return new Promise(c)},return(){return d(null)},throw(f){return d(f)}};function o(f){if(!i)return;let p=i;i=null,p(f)}function c(f,p){if(t)return p(t);if(a){f({value:a,done:!1}),a=null;return}n=f,r=p,o(null),s._finished&&n&&(n({value:void 0,done:!0}),n=r=null)}function l(f,p,m){i=m,p.on("error",SZ),n?(n({value:p,done:!1}),n=r=null):a=p}function u(){o(t),n&&(t?r(t):n({value:void 0,done:!0}),n=r=null)}function d(f){return s.destroy(f),o(f),new Promise((p,m)=>{if(s.destroyed)return p({value:void 0,done:!0});s.once("close",function(){f?m(f):p({value:void 0,done:!0})})})}}};$Ke.exports=function(t){return new IZ(t)};function SZ(){}function qKe(e){return e&=511,e&&512-e}});var JKe=_((lAn,xZ)=>{var GKe={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{xZ.exports=require("fs").constants||GKe}catch{xZ.exports=GKe}});var KKe=_((uAn,YKe)=>{var{Readable:ejt,Writable:tjt,getStreamError:HKe}=gZ(),xv=qw(),Yw=JKe(),cB=bZ(),njt=493,rjt=420,WKe=xv.alloc(1024),TZ=class extends tjt{constructor(t,n,r){super({mapWritable:ajt,eagerOpen:!0}),this.written=0,this.header=n,this._callback=r,this._linkname=null,this._isLinkname=n.type==="symlink"&&!n.linkname,this._isVoid=n.type!=="file"&&n.type!=="contiguous-file",this._finished=!1,this._pack=t,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(t){this._openCallback=t,this._pack._stream===this&&this._continueOpen()}_continuePack(t){if(this._callback===null)return;let n=this._callback;this._callback=null,n(t)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let t=this._openCallback;if(this._openCallback=null,t!==null){if(this._pack.destroying)return t(new Error("pack stream destroyed"));if(this._pack._finalized)return t(new Error("pack stream is already finalized"));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),t(null)}}_write(t,n){if(this._isLinkname)return this._linkname=this._linkname?xv.concat([this._linkname,t]):t,n(null);if(this._isVoid)return t.byteLength>0?n(new Error("No body allowed for this entry")):n();if(this.written+=t.byteLength,this._pack.push(t))return n();this._pack._drain=n}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?xv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),jKe(this._pack,this.header.size),this._pack._done(this))}_final(t){if(this.written!==this.header.size)return t(new Error("Size mismatch"));this._finish(),t(null)}_getError(){return HKe(this)||new Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(t){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),t()}},kZ=class extends ejt{constructor(t){super(t),this._drain=EZ,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(t,n,r){if(this._finalized||this.destroying)throw new Error("already finalized or destroyed");typeof n=="function"&&(r=n,n=null),r||(r=EZ),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=ijt(t.mode)),t.mode||(t.mode=t.type==="directory"?njt:rjt),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=xv.from(n));let a=new TZ(this,t,r);return xv.isBuffer(n)?(t.size=n.byteLength,a.write(n),a.end(),a):(a._isVoid,a)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(WKe),this.push(null))}_done(t){t===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(t){if(!t.pax){let n=cB.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=cB.encodePax({name:t.name,linkname:t.linkname,pax:t.pax}),r={name:"PaxHeader",mode:t.mode,uid:t.uid,gid:t.gid,size:n.byteLength,mtime:t.mtime,type:"pax-header",linkname:t.linkname&&"PaxHeader",uname:t.uname,gname:t.gname,devmajor:t.devmajor,devminor:t.devminor};this.push(cB.encode(r)),this.push(n),jKe(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(cB.encode(r))}_doDrain(){let t=this._drain;this._drain=EZ,t()}_predestroy(){let t=HKe(this);for(this._stream&&this._stream.destroy(t);this._pending.length;){let n=this._pending.shift();n.destroy(t),n._continueOpen()}this._doDrain()}_read(t){this._doDrain(),t()}};YKe.exports=function(t){return new kZ(t)};function ijt(e){switch(e&Yw.S_IFMT){case Yw.S_IFBLK:return"block-device";case Yw.S_IFCHR:return"character-device";case Yw.S_IFDIR:return"directory";case Yw.S_IFIFO:return"fifo";case Yw.S_IFLNK:return"symlink"}return"file"}function EZ(){}function jKe(e,t){t&=511,t&&e.push(WKe.subarray(0,512-t))}function ajt(e){return xv.isBuffer(e)?e:xv.from(e)}});var AZ=_(OZ=>{OZ.extract=zKe();OZ.pack=KKe()});var _Xe={};Ju(_Xe,{EVOLVE_IMAGE_VERSION:()=>dB,MODAL_MAX_LIFETIME_MS:()=>BZ,MODAL_MAX_LIST_SANDBOXES:()=>DZ,MODAL_STDIN_CHUNK_BYTES:()=>TO,ModalBootCommandError:()=>dXe,ModalCommands:()=>vXe,ModalFiles:()=>bXe,ModalIdleTimeoutError:()=>RZ,ModalNetworkPolicyError:()=>MZ,ModalProvider:()=>VZ,ModalResourcesError:()=>NZ,ModalSandboxLifetimeError:()=>cXe,ModalVolumeError:()=>fB,SandboxFeatureUnsupportedError:()=>Ev,SandboxNotRunningError:()=>iXe,SandboxPathNotFoundError:()=>lB,_testBuildSandboxInfo:()=>Njt,_testCollectSandboxes:()=>Mjt,_testDynamicNetworkPolicyParams:()=>Ajt,_testImageMap:()=>kjt,_testMapBootCommand:()=>Bjt,_testMapIdleTimeout:()=>Ujt,_testMapNetworkPolicy:()=>Ojt,_testMapResources:()=>Rjt,_testMapVolumeMounts:()=>Fjt,_testModalSandboxImplCtor:()=>Ljt,_testRequiresDynamicNetwork:()=>Pjt,_testResolveImageRegistry:()=>Cjt,_testValidateTimeout:()=>Djt,_testWrapCommand:()=>Tjt,createModalProvider:()=>hB,isSandboxFeatureUnsupportedError:()=>sjt,isSandboxNotRunningError:()=>cjt,isSandboxPathNotFoundError:()=>ojt});function UZ(e,t){return!!e&&typeof e=="object"&&e.name===t}function sjt(e){return UZ(e,"SandboxFeatureUnsupportedError")}function ojt(e){return UZ(e,"SandboxPathNotFoundError")}function cjt(e){return UZ(e,"SandboxNotRunningError")}function ljt(e){return`'${e.replace(/'/g,"'\\''")}'`}function ujt(e){if(!Number.isInteger(e.offset)||e.offset<0)throw new RangeError(`offset must be a non-negative integer, got ${e.offset}`);if(!Number.isInteger(e.length)||e.length<0)throw new RangeError(`length must be a non-negative integer, got ${e.length}`)}function djt(e){if(typeof e=="number")return QKe((e&4095).toString(8));if(/^[0-7]{1,4}$/.test(e))return QKe(e);throw new RangeError(`not an octal mode: ${e}`)}function QKe(e){return e.padStart(4,"0")}function fjt(e){let t=e&EO.constants.S_IFMT;return t===EO.constants.S_IFDIR?"dir":t===EO.constants.S_IFLNK?"symlink":t===EO.constants.S_IFREG?"file":"other"}function pjt(e){let t=e instanceof Date?e:typeof e=="number"?new Date(e*1e3):new Date(e);if(Number.isNaN(t.getTime()))throw new RangeError(`not a timestamp: ${String(e)}`);return t.toISOString()}async function*hjt(e){let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&(yield r)}}finally{t.releaseLock()}}function lXe(e){if(e>BZ)throw new cXe(e)}function uXe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new RZ(e,"it must be a positive number of milliseconds");if(e>BZ)throw new RZ(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function fXe(e){if(e===void 0)return{};if(e.length===0)throw new dXe(`an empty argv is Modal's own "no args" wire shape and would boot the image's ENTRYPOINT/CMD \u2014 omit bootCommand to boot the image's command`);return{command:[...e]}}function pXe(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith("/")||n==="/")throw new fB("invalid-mount-path",n,r.name,`Modal Volume mount path ${JSON.stringify(n)} is invalid: it must be an absolute in-box path other than "/"`);let a=r.name?.trim()??"";if(a.length===0)throw new fB("invalid-name",n,r.name??"",`Modal Volume mounted at ${n} has a blank name`);t.push({mountPath:n,name:a,readOnly:r.readOnly===!0,createIfMissing:r.createIfMissing===!0})}return t}function CZ(e,t,n,r,a){let i="";r&&Object.keys(r).length>0&&(i=Object.entries(r).filter(([,c])=>c!=null).map(([c,l])=>`export ${c}='${String(l).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let s=n?`cd '${n.replace(/'/g,"'\\''")}' && ${i}${e}`:`${i}${e}`;if(t==="root")return["bash","-c",s];let o=Buffer.from(s).toString("base64");return["su",t,a?.sameSession?"--session-command":"-c",`echo ${o} | base64 -d | bash`]}function hXe(e){if(e?.disk!==void 0)throw new NZ(`Modal's JS SDK has no create-time disk-size parameter, so a ${e.disk} GiB disk request cannot be enforced. Drop \`resources.disk\` (containers get Modal's default disk quota) or run on a provider that sizes disk.`);if((e?.gpu===void 0||e.gpu<=0)&&e?.gpuTypes?.length)throw new NZ("resources.gpuTypes was set without a positive resources.gpu count \u2014 declare how many GPUs to reserve, or drop gpuTypes.");let t=e?.gpu!==void 0&&e.gpu>0?`${e.gpuTypes?.length?e.gpuTypes[0]:"any"}:${e.gpu}`:void 0;return{cpu:e?.cpu??mjt,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):gjt,...t!==void 0?{gpu:t}:{}}}function mXe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function yjt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!mXe(e)}function vjt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function bjt(e){return/^[^:]+:\d+$/.test(e)}function FZ(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{}}let t=e.allowedDestinations??[];if(t.length===0)return{blockNetwork:!0};let n=[],r=[];for(let a of t)if(mXe(a))n.push(a.includes("/")?a:`${a}/32`);else{if(yjt(a))throw new MZ("invalid-ipv4",`"${a}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,a);if(vjt(a))n.push(a.includes("/")?a:`${a}/128`);else{if(bjt(a))throw new MZ("port-unsupported",`Modal's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${a}" and list just the host or IP.`,a);r.push(a)}}return{outboundCidrAllowlist:n,outboundDomainAllowlist:r}}function pB(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{outboundCidrAllowlist:["0.0.0.0/0"],outboundDomainAllowlist:["*"]}}let t=FZ(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:_jt(t.outboundDomainAllowlist??[])}}function _jt(e){return e.length>0?e:[Sjt]}function gXe(e,t){if(!t||t.length===0)return!1;let n=a=>a===void 0?"open|":`${a.outbound}|${[...new Set(a.allowedDestinations??[])].sort().join(",")}`,r=n(e);return t.some(a=>n(a)!==r)}function yXe(e){let t=e.split("/")[0];return/^\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com$/.test(t)?"aws-ecr":t==="gcr.io"||t.endsWith(".gcr.io")||t.endsWith("-docker.pkg.dev")?"gcp-artifact-registry":"registry"}function LZ(e,t,n){let{[sXe]:r,[oXe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}function eXe(e){let t=fjt(e.mode),n={name:e.name,path:e.path,type:t,size:e.size,mtime:pjt(e.modifiedTime),mode:djt(e.permissions),owner:e.owner,group:e.group};return t==="symlink"&&e.symlinkTarget!==null&&(n.target=e.symlinkTarget),n}function tXe(e){return!!e&&typeof e=="object"&&e.name==="SandboxFilesystemNotFoundError"}function Ijt(e){if(e.eventType==="Create")return e.paths.map(t=>({path:t,type:"create"}));if(e.eventType==="Remove")return e.paths.map(t=>({path:t,type:"remove"}));if(e.eventType==="Modify"){let t=e.paths.length>=2?"rename":"write";return e.paths.map(n=>({path:n,type:t}))}return[]}async function SXe(e,t){let n=[];try{for await(let r of e()){if(t!==void 0&&n.length>=t)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!0,error:`stopped at the requested limit of ${t} with more sandboxes available`};if(n.length>=DZ)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${DZ} sandboxes`};let a=await r.getTags();n.push(LZ(r.sandboxId,a))}}catch(r){return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list failed: ${r instanceof Error?r.message:String(r)}`}}return{sandboxes:n,complete:!0,pagesFetched:n.length,stoppedAtLimit:!1}}function hB(e={}){let t=e.tokenId??process.env.MODAL_TOKEN_ID,n=e.tokenSecret??process.env.MODAL_TOKEN_SECRET;if(!t||!n)throw new Error("Modal credentials required. Set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables, or pass tokenId/tokenSecret in config. Get your token at https://modal.com/settings/tokens");return new VZ({...e,tokenId:t,tokenSecret:n})}var rXe,EO,Ev,lB,iXe,XKe,ZKe,dB,aXe,BZ,TO,PZ,sXe,oXe,cXe,RZ,dXe,fB,NZ,mjt,gjt,MZ,Sjt,DZ,vXe,bXe,wjt,xjt,nXe,Ejt,uB,VZ,Tjt,kjt,Ojt,Ajt,Pjt,Rjt,Cjt,Njt,Mjt,Djt,Ujt,Bjt,Fjt,Ljt,mB=Q(()=>{"use strict";Q9e();rXe=Ve(AZ(),1),EO=require("fs"),Ev=class extends Error{feature;provider;reason;constructor(e,t,n){super(`${t} does not support ${e}${n?`: ${n}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=e,this.provider=t,this.reason=n}},lB=class extends Error{path;provider;constructor(e,t){super(`${t}: no such file or directory: ${e}`),this.name="SandboxPathNotFoundError",this.path=e,this.provider=t}},iXe=class extends Error{sandboxId;provider;state;constructor(e,t,n){super(`${t} sandbox ${e} is not running (${n}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=e,this.provider=t,this.state=n}};XKe=2,ZKe=21;dB="c-ebdfafe2ef1a",aXe={[`evolve-all-${dB}`]:`evolvingmachines/evolve-all:${dB}`,"evolve-all":"evolvingmachines/evolve-all"},BZ=1440*60*1e3,TO=8*1024*1024;PZ="user",sXe="evolve.image",oXe="evolve.startedAt",cXe=class extends Error{requestedTimeoutMs;constructor(e){let t=(e/36e5).toFixed(1);super(`Modal sandboxes have a hard 24h lifetime cap; requested timeout was ${t}h. For sessions longer than 24h, persist progress with Evolve checkpoints and resume in a fresh sandbox instead of extending the timeout.`),this.name="ModalSandboxLifetimeError",this.requestedTimeoutMs=e}};RZ=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};dXe=class extends Error{constructor(e){super(`Modal bootCommand is invalid: ${e}`),this.name="ModalBootCommandError"}};fB=class extends Error{reason;mountPath;volumeName;constructor(e,t,n,r,a){super(r,a===void 0?void 0:{cause:a}),this.name="ModalVolumeError",this.reason=e,this.mountPath=t,this.volumeName=n}};NZ=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},mjt=4,gjt=4096;MZ=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};Sjt="sealed.invalid";DZ=1e4,vXe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=CZ(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),{stdout:a,stderr:i}=await this.accumulateStreams(r,t?.onStdout,t?.onStderr);return{exitCode:await r.wait(),stdout:a,stderr:i}}async spawn(e,t){let n=t?.stdin===!1,r=CZ(e,this.user,t?.cwd,t?.envs,{sameSession:n}),a=n?["bash","-c",Ejt,"bash",...r]:r,i=await this.sandbox.exec(a,{timeoutMs:t?.timeoutMs}),s="",o="",c=this.accumulateStreams(i,t?.onStdout?l=>{t.onStdout(l)}:void 0,t?.onStderr?l=>{t.onStderr(l)}:void 0).then(({stdout:l,stderr:u})=>{s=l,o=u}).catch(()=>{});return{processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await c,{exitCode:await i.wait(),stdout:s,stderr:o}),kill:async()=>{if(!n)throw new Ev("commands.kill","modal","the Modal SDK cannot signal a running process; spawn it with `stdin: false` and kill() ends it by closing its stdin");let l=i.stdin.getWriter();try{return await l.close(),!0}catch{return!1}}}}async list(){let e=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await e.wait(),(await e.stdout.readText()).trim().split(`
253
+ `);return Pn.from(n)};Ww.decodePax=function(t){let n={};for(;t.length;){let r=0;for(;r<t.length&&t[r]!==32;)r++;let a=parseInt(Pn.toString(t.subarray(0,r)),10);if(!a)return n;let i=Pn.toString(t.subarray(r+1,a-1)),s=i.indexOf("=");if(s===-1)return n;n[i.slice(0,s)]=i.slice(s+1),t=t.subarray(a)}return n};Ww.encode=function(t){let n=Pn.alloc(512),r=t.name,a="";if(t.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),Pn.byteLength(r)!==r.length)return null;for(;Pn.byteLength(r)>100;){let i=r.indexOf("/");if(i===-1)return null;a+=a?"/"+r.slice(0,i):r.slice(0,i),r=r.slice(i+1)}return Pn.byteLength(r)>100||Pn.byteLength(a)>155||t.linkname&&Pn.byteLength(t.linkname)>100?null:(Pn.write(n,r),Pn.write(n,Sm(t.mode&q5t,6),100),Pn.write(n,Sm(t.uid,6),108),Pn.write(n,Sm(t.gid,6),116),j5t(t.size,n,124),Pn.write(n,Sm(t.mtime.getTime()/1e3|0,11),136),n[156]=oB+H5t(t.type),t.linkname&&Pn.write(n,t.linkname,157),Pn.copy(UKe,n,xO),Pn.copy(F5t,n,vZ),t.uname&&Pn.write(n,t.uname,265),t.gname&&Pn.write(n,t.gname,297),Pn.write(n,Sm(t.devmajor||0,6),329),Pn.write(n,Sm(t.devminor||0,6),337),a&&Pn.write(n,a,345),Pn.write(n,Sm(FKe(n),6),148),n)};Ww.decode=function(t,n,r){let a=t[156]===0?0:t[156]-oB,i=Hw(t,0,100,n),s=bm(t,100,8),o=bm(t,108,8),c=bm(t,116,8),l=bm(t,124,12),u=bm(t,136,12),d=J5t(a),f=t[157]===0?null:Hw(t,157,100,n),p=Hw(t,265,32),m=Hw(t,297,32),y=bm(t,329,8),b=bm(t,337,8),v=FKe(t);if(v===8*32)return null;if(v!==bm(t,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if($5t(t))t[345]&&(i=Hw(t,345,155,n)+"/"+i);else if(!z5t(t)){if(!r)throw new Error("Invalid tar header: unknown format.")}return a===0&&i&&i[i.length-1]==="/"&&(a=5),{name:i,mode:s,uid:o,gid:c,size:l,mtime:new Date(1e3*u),type:d,linkname:f,uname:p,gname:m,devmajor:y,devminor:b,pax:null}};function $5t(e){return Pn.equals(UKe,e.subarray(xO,xO+6))}function z5t(e){return Pn.equals(L5t,e.subarray(xO,xO+6))&&Pn.equals(V5t,e.subarray(vZ,vZ+2))}function G5t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function J5t(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function H5t(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function BKe(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function FKe(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function Sm(e,t){return e=e.toString(8),e.length>t?B5t.slice(0,t)+" ":U5t.slice(0,t-e.length)+e+" "}function W5t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function j5t(e,t,n){e.toString(8).length>11?W5t(e,t,n):Pn.write(t,Sm(e,11),n)}function Y5t(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let s=e[r];t?n.push(s):n.push(255-s)}let a=0,i=n.length;for(r=0;r<i;r++)a+=n[r]*Math.pow(256,r);return t?a:-1*a}function bm(e,t,n){if(e=e.subarray(t,t+n),t=0,e[t]&128)return Y5t(e);{for(;t<e.length&&e[t]===32;)t++;let r=G5t(BKe(e,32,t,e.length),e.length,e.length);for(;t<r&&e[t]===0;)t++;return r===t?0:parseInt(Pn.toString(e.subarray(t,r)),8)}}function Hw(e,t,n,r){return Pn.toString(e.subarray(t,BKe(e,0,t,t+n)),r)}function yZ(e){let t=Pn.byteLength(e),n=Math.floor(Math.log(t)/Math.log(10))+1;return t+n>=Math.pow(10,n)&&n++,t+n+e}});var zKe=_((cAn,$Ke)=>{var{Writable:K5t,Readable:X5t,getStreamError:LKe}=gZ(),Z5t=eZ(),VKe=qw(),jw=bZ(),Q5t=VKe.alloc(0),_Z=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new Z5t,this._offset=0}push(t){this.buffered+=t.byteLength,this.queue.push(t)}shiftFirst(t){return this._buffered===0?null:this._next(t)}shift(t){if(t>this.buffered)return null;if(t===0)return Q5t;let n=this._next(t);if(t===n.byteLength)return n;let r=[n];for(;(t-=n.byteLength)>0;)n=this._next(t),r.push(n);return VKe.concat(r)}_next(t){let n=this.queue.peek(),r=n.byteLength-this._offset;if(t>=r){let a=this._offset?n.subarray(this._offset,n.byteLength):n;return this.queue.shift(),this._offset=0,this.buffered-=r,this.shifted+=r,a}return this.buffered-=t,this.shifted+=t,n.subarray(this._offset,this._offset+=t)}},wZ=class extends X5t{constructor(t,n,r){super(),this.header=n,this.offset=r,this._parent=t}_read(t){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),t(null)}_predestroy(){this._parent.destroy(LKe(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=qKe(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},IZ=class extends K5t{constructor(t){super(t),t||(t={}),this._buffer=new _Z,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=SZ,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=t.filenameEncoding||"utf-8",this._allowUnknownFormat=!!t.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(t){if(this._locked=!1,t){this.destroy(t),this._continueWrite(t);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=jw.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(t){return this._continueWrite(t),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory"?(this.emit("entry",this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&(this._header.name=this._gnuLongPath,this._gnuLongPath=null),this._gnuLongLinkPath&&(this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null),this._pax&&(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,this._pax=null)}_decodeLongHeader(t){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=jw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=jw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=jw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?jw.decodePax(t):Object.assign({},this._paxGlobal,jw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=qKe(this._header.size);let t=this._buffer.shift(this._header.size);try{this._decodeLongHeader(t)}catch(n){return this._continueWrite(n),!1}return!0}_consumeStream(){let t=this._buffer.shiftFirst(this._missing);if(t===null)return!1;this._missing-=t.byteLength;let n=this._stream.push(t);return this._missing===0?(this._stream.push(null),n&&this._stream._detach(),n&&this._locked===!1):n}_createStream(){return new wZ(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let t=this._buffer.shiftFirst(this._missing);t!==null&&(this._missing-=t.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(t){let n=this._callback;this._callback=SZ,n(t)}_write(t,n){this._callback=n,this._buffer.push(t),this._update()}_final(t){this._finished=this._missing===0&&this._buffer.buffered===0,t(this._finished?null:new Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(t){this._stream&&this._stream.destroy(LKe(this)),t(null)}[Symbol.asyncIterator](){let t=null,n=null,r=null,a=null,i=null,s=this;return this.on("entry",l),this.on("error",f=>{t=f}),this.on("close",u),{[Symbol.asyncIterator](){return this},next(){return new Promise(c)},return(){return d(null)},throw(f){return d(f)}};function o(f){if(!i)return;let p=i;i=null,p(f)}function c(f,p){if(t)return p(t);if(a){f({value:a,done:!1}),a=null;return}n=f,r=p,o(null),s._finished&&n&&(n({value:void 0,done:!0}),n=r=null)}function l(f,p,m){i=m,p.on("error",SZ),n?(n({value:p,done:!1}),n=r=null):a=p}function u(){o(t),n&&(t?r(t):n({value:void 0,done:!0}),n=r=null)}function d(f){return s.destroy(f),o(f),new Promise((p,m)=>{if(s.destroyed)return p({value:void 0,done:!0});s.once("close",function(){f?m(f):p({value:void 0,done:!0})})})}}};$Ke.exports=function(t){return new IZ(t)};function SZ(){}function qKe(e){return e&=511,e&&512-e}});var JKe=_((lAn,xZ)=>{var GKe={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{xZ.exports=require("fs").constants||GKe}catch{xZ.exports=GKe}});var KKe=_((uAn,YKe)=>{var{Readable:ejt,Writable:tjt,getStreamError:HKe}=gZ(),xv=qw(),Yw=JKe(),cB=bZ(),njt=493,rjt=420,WKe=xv.alloc(1024),TZ=class extends tjt{constructor(t,n,r){super({mapWritable:ajt,eagerOpen:!0}),this.written=0,this.header=n,this._callback=r,this._linkname=null,this._isLinkname=n.type==="symlink"&&!n.linkname,this._isVoid=n.type!=="file"&&n.type!=="contiguous-file",this._finished=!1,this._pack=t,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(t){this._openCallback=t,this._pack._stream===this&&this._continueOpen()}_continuePack(t){if(this._callback===null)return;let n=this._callback;this._callback=null,n(t)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let t=this._openCallback;if(this._openCallback=null,t!==null){if(this._pack.destroying)return t(new Error("pack stream destroyed"));if(this._pack._finalized)return t(new Error("pack stream is already finalized"));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),t(null)}}_write(t,n){if(this._isLinkname)return this._linkname=this._linkname?xv.concat([this._linkname,t]):t,n(null);if(this._isVoid)return t.byteLength>0?n(new Error("No body allowed for this entry")):n();if(this.written+=t.byteLength,this._pack.push(t))return n();this._pack._drain=n}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?xv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),jKe(this._pack,this.header.size),this._pack._done(this))}_final(t){if(this.written!==this.header.size)return t(new Error("Size mismatch"));this._finish(),t(null)}_getError(){return HKe(this)||new Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(t){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),t()}},kZ=class extends ejt{constructor(t){super(t),this._drain=EZ,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(t,n,r){if(this._finalized||this.destroying)throw new Error("already finalized or destroyed");typeof n=="function"&&(r=n,n=null),r||(r=EZ),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=ijt(t.mode)),t.mode||(t.mode=t.type==="directory"?njt:rjt),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=xv.from(n));let a=new TZ(this,t,r);return xv.isBuffer(n)?(t.size=n.byteLength,a.write(n),a.end(),a):(a._isVoid,a)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(WKe),this.push(null))}_done(t){t===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(t){if(!t.pax){let n=cB.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=cB.encodePax({name:t.name,linkname:t.linkname,pax:t.pax}),r={name:"PaxHeader",mode:t.mode,uid:t.uid,gid:t.gid,size:n.byteLength,mtime:t.mtime,type:"pax-header",linkname:t.linkname&&"PaxHeader",uname:t.uname,gname:t.gname,devmajor:t.devmajor,devminor:t.devminor};this.push(cB.encode(r)),this.push(n),jKe(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(cB.encode(r))}_doDrain(){let t=this._drain;this._drain=EZ,t()}_predestroy(){let t=HKe(this);for(this._stream&&this._stream.destroy(t);this._pending.length;){let n=this._pending.shift();n.destroy(t),n._continueOpen()}this._doDrain()}_read(t){this._doDrain(),t()}};YKe.exports=function(t){return new kZ(t)};function ijt(e){switch(e&Yw.S_IFMT){case Yw.S_IFBLK:return"block-device";case Yw.S_IFCHR:return"character-device";case Yw.S_IFDIR:return"directory";case Yw.S_IFIFO:return"fifo";case Yw.S_IFLNK:return"symlink"}return"file"}function EZ(){}function jKe(e,t){t&=511,t&&e.push(WKe.subarray(0,512-t))}function ajt(e){return xv.isBuffer(e)?e:xv.from(e)}});var AZ=_(OZ=>{OZ.extract=zKe();OZ.pack=KKe()});var _Xe={};Ju(_Xe,{EVOLVE_IMAGE_VERSION:()=>dB,MODAL_MAX_LIFETIME_MS:()=>BZ,MODAL_MAX_LIST_SANDBOXES:()=>DZ,MODAL_STDIN_CHUNK_BYTES:()=>TO,ModalBootCommandError:()=>dXe,ModalCommands:()=>vXe,ModalFiles:()=>bXe,ModalIdleTimeoutError:()=>RZ,ModalNetworkPolicyError:()=>MZ,ModalProvider:()=>VZ,ModalResourcesError:()=>NZ,ModalSandboxLifetimeError:()=>cXe,ModalVolumeError:()=>fB,SandboxFeatureUnsupportedError:()=>Ev,SandboxNotRunningError:()=>iXe,SandboxPathNotFoundError:()=>lB,_testBuildSandboxInfo:()=>Njt,_testCollectSandboxes:()=>Mjt,_testDynamicNetworkPolicyParams:()=>Ajt,_testImageMap:()=>kjt,_testMapBootCommand:()=>Bjt,_testMapIdleTimeout:()=>Ujt,_testMapNetworkPolicy:()=>Ojt,_testMapResources:()=>Rjt,_testMapVolumeMounts:()=>Fjt,_testModalSandboxImplCtor:()=>Ljt,_testRequiresDynamicNetwork:()=>Pjt,_testResolveImageRegistry:()=>Cjt,_testValidateTimeout:()=>Djt,_testWrapCommand:()=>Tjt,createModalProvider:()=>hB,isSandboxFeatureUnsupportedError:()=>sjt,isSandboxNotRunningError:()=>cjt,isSandboxPathNotFoundError:()=>ojt});function UZ(e,t){return!!e&&typeof e=="object"&&e.name===t}function sjt(e){return UZ(e,"SandboxFeatureUnsupportedError")}function ojt(e){return UZ(e,"SandboxPathNotFoundError")}function cjt(e){return UZ(e,"SandboxNotRunningError")}function ljt(e){return`'${e.replace(/'/g,"'\\''")}'`}function ujt(e){if(!Number.isInteger(e.offset)||e.offset<0)throw new RangeError(`offset must be a non-negative integer, got ${e.offset}`);if(!Number.isInteger(e.length)||e.length<0)throw new RangeError(`length must be a non-negative integer, got ${e.length}`)}function djt(e){if(typeof e=="number")return QKe((e&4095).toString(8));if(/^[0-7]{1,4}$/.test(e))return QKe(e);throw new RangeError(`not an octal mode: ${e}`)}function QKe(e){return e.padStart(4,"0")}function fjt(e){let t=e&EO.constants.S_IFMT;return t===EO.constants.S_IFDIR?"dir":t===EO.constants.S_IFLNK?"symlink":t===EO.constants.S_IFREG?"file":"other"}function pjt(e){let t=e instanceof Date?e:typeof e=="number"?new Date(e*1e3):new Date(e);if(Number.isNaN(t.getTime()))throw new RangeError(`not a timestamp: ${String(e)}`);return t.toISOString()}async function*hjt(e){let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&(yield r)}}finally{t.releaseLock()}}function lXe(e){if(e>BZ)throw new cXe(e)}function uXe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new RZ(e,"it must be a positive number of milliseconds");if(e>BZ)throw new RZ(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function fXe(e){if(e===void 0)return{};if(e.length===0)throw new dXe(`an empty argv is Modal's own "no args" wire shape and would boot the image's ENTRYPOINT/CMD \u2014 omit bootCommand to boot the image's command`);return{command:[...e]}}function pXe(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith("/")||n==="/")throw new fB("invalid-mount-path",n,r.name,`Modal Volume mount path ${JSON.stringify(n)} is invalid: it must be an absolute in-box path other than "/"`);let a=r.name?.trim()??"";if(a.length===0)throw new fB("invalid-name",n,r.name??"",`Modal Volume mounted at ${n} has a blank name`);t.push({mountPath:n,name:a,readOnly:r.readOnly===!0,createIfMissing:r.createIfMissing===!0})}return t}function CZ(e,t,n,r,a){let i="";r&&Object.keys(r).length>0&&(i=Object.entries(r).filter(([,c])=>c!=null).map(([c,l])=>`export ${c}='${String(l).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let s=n?`cd '${n.replace(/'/g,"'\\''")}' && ${i}${e}`:`${i}${e}`;if(t==="root")return["bash","-c",s];let o=Buffer.from(s).toString("base64");return["su",t,a?.sameSession?"--session-command":"-c",`echo ${o} | base64 -d | bash`]}function hXe(e){if(e?.disk!==void 0)throw new NZ(`Modal's JS SDK has no create-time disk-size parameter, so a ${e.disk} GiB disk request cannot be enforced. Drop \`resources.disk\` (containers get Modal's default disk quota) or run on a provider that sizes disk.`);if((e?.gpu===void 0||e.gpu<=0)&&e?.gpuTypes?.length)throw new NZ("resources.gpuTypes was set without a positive resources.gpu count \u2014 declare how many GPUs to reserve, or drop gpuTypes.");let t=e?.gpu!==void 0&&e.gpu>0?`${e.gpuTypes?.length?e.gpuTypes[0]:"any"}:${e.gpu}`:void 0;return{cpu:e?.cpu??mjt,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):gjt,...t!==void 0?{gpu:t}:{}}}function mXe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function yjt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!mXe(e)}function vjt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function bjt(e){return/^[^:]+:\d+$/.test(e)}function FZ(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{}}let t=e.allowedDestinations??[];if(t.length===0)return{blockNetwork:!0};let n=[],r=[];for(let a of t)if(mXe(a))n.push(a.includes("/")?a:`${a}/32`);else{if(yjt(a))throw new MZ("invalid-ipv4",`"${a}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,a);if(vjt(a))n.push(a.includes("/")?a:`${a}/128`);else{if(bjt(a))throw new MZ("port-unsupported",`Modal's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${a}" and list just the host or IP.`,a);r.push(a)}}return{outboundCidrAllowlist:n,outboundDomainAllowlist:r}}function pB(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{outboundCidrAllowlist:["0.0.0.0/0"],outboundDomainAllowlist:["*"]}}let t=FZ(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:_jt(t.outboundDomainAllowlist??[])}}function _jt(e){return e.length>0?e:[Sjt]}function gXe(e,t){if(!t||t.length===0)return!1;let n=a=>a===void 0?"open|":`${a.outbound}|${[...new Set(a.allowedDestinations??[])].sort().join(",")}`,r=n(e);return t.some(a=>n(a)!==r)}function yXe(e){let t=e.split("/")[0];return/^\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com$/.test(t)?"aws-ecr":t==="gcr.io"||t.endsWith(".gcr.io")||t.endsWith("-docker.pkg.dev")?"gcp-artifact-registry":"registry"}function LZ(e,t,n){let{[sXe]:r,[oXe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}function eXe(e){let t=fjt(e.mode),n={name:e.name,path:e.path,type:t,size:e.size,mtime:pjt(e.modifiedTime),mode:djt(e.permissions),owner:e.owner,group:e.group};return t==="symlink"&&e.symlinkTarget!==null&&(n.target=e.symlinkTarget),n}function tXe(e){return!!e&&typeof e=="object"&&e.name==="SandboxFilesystemNotFoundError"}function Ijt(e){if(e.eventType==="Create")return e.paths.map(t=>({path:t,type:"create"}));if(e.eventType==="Remove")return e.paths.map(t=>({path:t,type:"remove"}));if(e.eventType==="Modify"){let t=e.paths.length>=2?"rename":"write";return e.paths.map(n=>({path:n,type:t}))}return[]}async function SXe(e,t){let n=[];try{for await(let r of e()){if(t!==void 0&&n.length>=t)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!0,error:`stopped at the requested limit of ${t} with more sandboxes available`};if(n.length>=DZ)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${DZ} sandboxes`};let a=await r.getTags();n.push(LZ(r.sandboxId,a))}}catch(r){return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list failed: ${r instanceof Error?r.message:String(r)}`}}return{sandboxes:n,complete:!0,pagesFetched:n.length,stoppedAtLimit:!1}}function hB(e={}){let t=e.tokenId??process.env.MODAL_TOKEN_ID,n=e.tokenSecret??process.env.MODAL_TOKEN_SECRET;if(!t||!n)throw new Error("Modal credentials required. Set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables, or pass tokenId/tokenSecret in config. Get your token at https://modal.com/settings/tokens");return new VZ({...e,tokenId:t,tokenSecret:n})}var rXe,EO,Ev,lB,iXe,XKe,ZKe,dB,aXe,BZ,TO,PZ,sXe,oXe,cXe,RZ,dXe,fB,NZ,mjt,gjt,MZ,Sjt,DZ,vXe,bXe,wjt,xjt,nXe,Ejt,uB,VZ,Tjt,kjt,Ojt,Ajt,Pjt,Rjt,Cjt,Njt,Mjt,Djt,Ujt,Bjt,Fjt,Ljt,mB=Q(()=>{"use strict";Q9e();rXe=Ve(AZ(),1),EO=require("fs"),Ev=class extends Error{feature;provider;reason;constructor(e,t,n){super(`${t} does not support ${e}${n?`: ${n}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=e,this.provider=t,this.reason=n}},lB=class extends Error{path;provider;constructor(e,t){super(`${t}: no such file or directory: ${e}`),this.name="SandboxPathNotFoundError",this.path=e,this.provider=t}},iXe=class extends Error{sandboxId;provider;state;constructor(e,t,n){super(`${t} sandbox ${e} is not running (${n}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=e,this.provider=t,this.state=n}};XKe=2,ZKe=21;dB="c-5ae94df74154",aXe={[`evolve-all-${dB}`]:`evolvingmachines/evolve-all:${dB}`,"evolve-all":"evolvingmachines/evolve-all"},BZ=1440*60*1e3,TO=8*1024*1024;PZ="user",sXe="evolve.image",oXe="evolve.startedAt",cXe=class extends Error{requestedTimeoutMs;constructor(e){let t=(e/36e5).toFixed(1);super(`Modal sandboxes have a hard 24h lifetime cap; requested timeout was ${t}h. For sessions longer than 24h, persist progress with Evolve checkpoints and resume in a fresh sandbox instead of extending the timeout.`),this.name="ModalSandboxLifetimeError",this.requestedTimeoutMs=e}};RZ=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};dXe=class extends Error{constructor(e){super(`Modal bootCommand is invalid: ${e}`),this.name="ModalBootCommandError"}};fB=class extends Error{reason;mountPath;volumeName;constructor(e,t,n,r,a){super(r,a===void 0?void 0:{cause:a}),this.name="ModalVolumeError",this.reason=e,this.mountPath=t,this.volumeName=n}};NZ=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},mjt=4,gjt=4096;MZ=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};Sjt="sealed.invalid";DZ=1e4,vXe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=CZ(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),{stdout:a,stderr:i}=await this.accumulateStreams(r,t?.onStdout,t?.onStderr);return{exitCode:await r.wait(),stdout:a,stderr:i}}async spawn(e,t){let n=t?.stdin===!1,r=CZ(e,this.user,t?.cwd,t?.envs,{sameSession:n}),a=n?["bash","-c",Ejt,"bash",...r]:r,i=await this.sandbox.exec(a,{timeoutMs:t?.timeoutMs}),s="",o="",c=this.accumulateStreams(i,t?.onStdout?l=>{t.onStdout(l)}:void 0,t?.onStderr?l=>{t.onStderr(l)}:void 0).then(({stdout:l,stderr:u})=>{s=l,o=u}).catch(()=>{});return{processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await c,{exitCode:await i.wait(),stdout:s,stderr:o}),kill:async()=>{if(!n)throw new Ev("commands.kill","modal","the Modal SDK cannot signal a running process; spawn it with `stdin: false` and kill() ends it by closing its stdin");let l=i.stdin.getWriter();try{return await l.close(),!0}catch{return!1}}}}async list(){let e=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await e.wait(),(await e.stdout.readText()).trim().split(`
254
254
  `).slice(1).map(t=>{let n=t.trim().split(/\s+/);return{processId:n[0],cmd:n[1]||"",args:n.slice(2),envs:{}}})}async connect(e,t){throw new Ev("commands.connect","modal","the Modal SDK cannot attach to a process by id")}async sendStdin(e,t){throw new Ev("commands.sendStdin","modal","the Modal SDK cannot address a process's stdin by id")}async kill(e){return await(await this.sandbox.exec(["kill","-9",e],{timeoutMs:1e4})).wait()===0}async accumulateStreams(e,t,n){let r="",a="",i=[];return i.push((async()=>{try{for await(let s of e.stdout){let o=typeof s=="string"?s:new TextDecoder().decode(s);r+=o,t?.(o)}}catch{}})()),i.push((async()=>{try{for await(let s of e.stderr){let o=typeof s=="string"?s:new TextDecoder().decode(s);a+=o,n?.(o)}}catch{}})()),await Promise.all(i),{stdout:r,stderr:a}}},bXe=class{constructor(e,t){this.sandbox=e,this.user=t}async chownToUser(e,t=!1){if(this.user==="root")return;let n=t?["chown","-R",`${this.user}:${this.user}`,e]:["chown",`${this.user}:${this.user}`,e];await(await this.sandbox.exec(n,{timeoutMs:t?3e4:1e4})).wait()}async writeStdinChunked(e,t){for(let n=0;n<t.length;n+=TO)await e.writeBytes(t.subarray(n,n+TO))}async writeStdinCoalesced(e,t){let n=[],r=0,a=async()=>{if(r===0)return;let i=n.length===1?n[0]:Buffer.concat(n,r);n=[],r=0,await this.writeStdinChunked(e,i)};for await(let i of t)n.push(i),r+=i.length,r>=TO&&await a();await a()}async read(e){let t=await this.sandbox.exec(["cat",e],{timeoutMs:3e5,mode:"binary"}),n=await t.wait();if(n!==0){let a=await t.stderr.readText();throw new Error(`Failed to read file ${e}: ${a||`exit code ${n}`}`)}let r=await t.stdout.readBytes();if(!r.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(r)}catch{}return r}async write(e,t){let n=this.toBuffer(t),r=e.substring(0,e.lastIndexOf("/"));r&&await this.makeDir(r);let a=e.replace(/'/g,"'\\''"),i=await this.sandbox.exec(["bash","-c",`cat > '${a}'`],{mode:"binary"});await this.writeStdinChunked(i.stdin,new Uint8Array(n)),await i.stdin.getWriter().close(),await i.wait(),await this.chownToUser(e)}async writeBatch(e){let t=(0,rXe.pack)(),n=new Set;for(let a of e){let i=this.toBuffer(a.data),s=a.path.startsWith("/")?a.path.slice(1):a.path;t.entry({name:s},i);let o=a.path.substring(0,a.path.lastIndexOf("/"));o&&n.add(o)}t.finalize();let r=await this.sandbox.exec(["tar","-xf","-","-C","/"],{mode:"binary"});if(await this.writeStdinCoalesced(r.stdin,t),await r.stdin.getWriter().close(),await r.wait(),n.size>0){let a=Array.from(n),i=new Set(a.map(s=>s.split("/").slice(0,4).join("/")));for(let s of i)await this.chownToUser(s,!0)}}async makeDir(e){await(await this.sandbox.exec(["mkdir","-p",e],{timeoutMs:1e4})).wait(),await this.chownToUser(e,!0)}async exists(e){return await(await this.sandbox.exec(["test","-e",e],{timeoutMs:1e4})).wait()===0}async list(e){try{return(await this.sandbox.filesystem.listFiles(e)).map(t=>eXe(t))}catch(t){throw tXe(t)?new lB(e,"modal"):t}}async stat(e){try{return eXe(await this.sandbox.filesystem.stat(e))}catch(t){throw tXe(t)?new lB(e,"modal"):t}}async readRange(e,t){if(ujt(t),t.length===0)return new Uint8Array(0);let n=ljt(e),r=`[ -e ${n} ] || exit ${XKe}; [ -d ${n} ] && exit ${ZKe}; tail -c +${t.offset+1} -- ${n} | head -c ${t.length}; s=("\${PIPESTATUS[@]}"); [ "\${s[1]}" -eq 0 ] || exit "\${s[1]}"; [ "\${s[0]}" -eq 0 ] || [ "\${s[0]}" -eq ${xjt} ] || exit "\${s[0]}"`,a=await this.sandbox.exec(["bash","-c",r],{mode:"binary",timeoutMs:nXe}),i=await a.stdout.readBytes(),s=await a.wait();if(s===XKe)throw new lB(e,"modal");if(s===ZKe)throw new Error(`modal: ${e} is a directory`);if(s!==0){let o=new TextDecoder().decode(await a.stderr.readBytes()).trim();throw new Error(`modal: range read of ${e} failed (exit ${s}): ${o}`)}return i}async remove(e){await(await this.sandbox.exec(["rm","-rf",e],{timeoutMs:3e4})).wait()}async rename(e,t){await(await this.sandbox.exec(["mv",e,t],{timeoutMs:3e4})).wait()}async readStream(e){return(await this.sandbox.exec(["cat",e],{timeoutMs:nXe,mode:"binary"})).stdout}async writeStream(e,t){let n=e.substring(0,e.lastIndexOf("/"));n&&await this.makeDir(n);let r=e.replace(/'/g,"'\\''"),a=await this.sandbox.exec(["bash","-c",`cat > '${r}'`],{mode:"binary"});await this.writeStdinCoalesced(a.stdin,hjt(t)),await a.stdin.getWriter().close(),await a.wait(),await this.chownToUser(e)}async writeFromPath(e,t){let{createReadStream:n}=await import("fs"),{Readable:r}=await import("stream"),a=r.toWeb(n(t,{highWaterMark:TO}));await this.writeStream(e,a)}async uploadUrl(e,t){throw new Ev("files.uploadUrl","modal","Modal issues no signed upload URLs")}async downloadUrl(e,t){throw new Ev("files.downloadUrl","modal","Modal issues no signed download URLs")}async watchDir(e,t,n){await this.stat(e);let r=this.sandbox.filesystem.watch(e,{recursive:n?.recursive??!1,filter:[...wjt]})[Symbol.asyncIterator](),a=!1;return(async()=>{for(;;){let{done:i,value:s}=await r.next();if(i||a)break;for(let o of Ijt(s))await t(o)}})().catch(()=>{}),{stop:async()=>{a=!0,r.return?.().catch(()=>{})}}}toBuffer(e){if(typeof e=="string")return Buffer.from(e,"utf-8");if(e instanceof Buffer)return e;if(e instanceof ArrayBuffer||e instanceof Uint8Array)return Buffer.from(e);throw new Error(`Unsupported data type: ${typeof e}`)}};wjt=["Create","Modify","Remove"];xjt=141,nXe=3e5,Ejt=["set -m","exec 3<&0",'"$@" </dev/null 3<&- & job=$!',"( cat <&3 >/dev/null; kill -TERM -- -$job 2>/dev/null ) & eof=$!","exec 2>/dev/null","trap 'kill -TERM -- -$job' TERM","wait $job; rc=$?","kill -TERM -- -$eof","exit $rc"].join("; "),uB=class{constructor(e,t,n){this.sandbox=e,this.commands=new vXe(e,n),this.files=new bXe(e,n),this.image=t}commands;files;image;get sandboxId(){return this.sandbox.sandboxId}async metrics(){throw new Ev("metrics","modal","Modal has no sandbox metrics API, and /proc and the cgroup files inside its sandbox report host-wide figures (measured 2026-09-16: MemTotal 1 TiB on a 1 GiB sandbox)")}async getHost(e){let t=(await this.sandbox.tunnels())[e];if(!t)throw new Error(`No tunnel found for port ${e}`);return t.url}async isRunning(){try{return await this.sandbox.poll()===null}catch{return!1}}async getInfo(){let e=await this.sandbox.getTags();return LZ(this.sandbox.sandboxId,e,this.image)}async updateNetwork(e){await this.sandbox.updateNetworkPolicy(pB(e))}async kill(){try{await this.sandbox.terminate()}catch{await new Promise(e=>setTimeout(e,500)),await this.sandbox.terminate()}}async pause(){throw new Error("Modal does not support pause/resume. Persist progress with Evolve checkpoints and resume in a fresh sandbox, or use kill() to terminate.")}},VZ=class{providerType="modal";name="Modal";supportsBootCommand=!0;supportsVolumes=!0;client;appName;defaultTimeoutMs;imageName;imageSecretName;_app;sandboxUsers=new Map;constructor(e){!e.endpoint&&process.env.MODAL_SERVER_URL?.startsWith("unix:")?process.env.MODAL_SERVER_URL="https://api.modal.com:443":e.endpoint&&(process.env.MODAL_SERVER_URL=e.endpoint),this.client=new R9e({tokenId:e.tokenId,tokenSecret:e.tokenSecret}),this.appName=e.appName??"evolve-sandbox",this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.imageName=e.imageName??`evolve-all-${dB}`,this.imageSecretName=e.imageSecretName}async getApp(){return this._app||(this._app=await this.client.apps.fromName(this.appName,{createIfMissing:!0})),this._app}async resolveImage(e){let t=yXe(e);if(t==="registry"){let r=this.imageSecretName?await this.client.secrets.fromName(this.imageSecretName):void 0;return this.client.images.fromRegistry(e,r)}if(!this.imageSecretName)throw new Error(`Private registry image "${e}" requires config.imageSecretName \u2014 the name of a Modal Secret holding registry credentials (AWS ECR: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION with read-only ECR IAM). Create one at https://modal.com/secrets`);let n=t==="aws-ecr"?await this.client.secrets.fromName(this.imageSecretName,{requiredKeys:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION"]}):await this.client.secrets.fromName(this.imageSecretName);return t==="aws-ecr"?this.client.images.fromAwsEcr(e,n):this.client.images.fromGcpArtifactRegistry(e,n)}async resolveAndBuildImage(e){let t=aXe[e]??e;if(!/[/:@]/.test(t))try{return{tag:t,image:await this.client.images.fromName(t)}}catch(a){if(!(a instanceof Or))throw a}let n=await this.getApp(),r=await this.resolveImage(t);return{tag:t,image:await r.build(n)}}async publishImageAs(e,t){if(!e.trim())throw new Error("publishImageAs requires a non-empty alias to publish under");let{image:n}=await this.resolveAndBuildImage(t||this.imageName);return await n.publish(e),e}async prepareImage(e){await this.resolveAndBuildImage(e||this.imageName)}async create(e){let t=e.timeoutMs??this.defaultTimeoutMs;lXe(t);let n=uXe(e.idleTimeoutMs),r=fXe(e.bootCommand),a=pXe(e.volumes);for(let b of e.phaseNetworkPolicies??[])pB(b);let i=gXe(e.network,e.phaseNetworkPolicies)?pB(e.network):FZ(e.network),s=hXe(e.resources),o=e.user??PZ,c=await this.getApp(),{tag:l,image:u}=await this.resolveAndBuildImage(e.image||this.imageName),d=await this.resolveVolumes(a),f=e.envs?Object.fromEntries(Object.entries(e.envs).filter(([,b])=>b!=null)):void 0,p=f&&Object.keys(f).length>0?f:void 0,m={...e.metadata,[sXe]:l,[oXe]:new Date().toISOString()},y=await this.client.sandboxes.create(c,u,{cpu:s.cpu,memoryMiB:s.memoryMiB,...s.gpu!==void 0?{gpu:s.gpu}:{},timeoutMs:t,...n,...r,workdir:e.workingDirectory,env:p,tags:m,...i,...d!==void 0?{volumes:d}:{}});return e.workingDirectory&&o!=="root"&&await(await y.exec(["chown","-R",`${o}:${o}`,e.workingDirectory],{timeoutMs:3e4})).wait(),this.sandboxUsers.set(y.sandboxId,o),new uB(y,l,o)}async resolveVolumes(e){if(e.length===0)return;let t={};for(let n of e){let r;try{r=await this.client.volumes.fromName(n.name,{createIfMissing:n.createIfMissing})}catch(a){let i=a instanceof Error?a.message:String(a),s=a instanceof Or||a instanceof Error&&a.name==="NotFoundError";throw new fB(s?"not-found":"resolve-failed",n.mountPath,n.name,s?`Modal Volume "${n.name}" (to mount at ${n.mountPath}) does not exist and createIfMissing was not set: ${i}`:`Modal Volume "${n.name}" (to mount at ${n.mountPath}) could not be resolved: ${i}`,a)}t[n.mountPath]=r.withMountOptions({readOnly:n.readOnly})}return t}async connect(e,t){let n=await this.client.sandboxes.fromId(e),r=this.sandboxUsers.get(e)??PZ;return new uB(n,void 0,r)}async inspect(e,t){let n=await this.attachSandbox(e),r=await n.poll();if(r!==null)throw new iXe(e,"modal",`exited with code ${r}`);let a=t?.user??this.sandboxUsers.get(e)??PZ;return new uB(n,void 0,a)}async attachSandbox(e){return this.client.sandboxes.fromId(e)}async list(e){let t=await this.walk(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.walk(e);return n}async walk(e){if(e?.state&&!e.state.includes("running"))return{sandboxes:[],complete:!0,pagesFetched:0,stoppedAtLimit:!1};let t;try{t=await this.getApp()}catch(n){return{sandboxes:[],complete:!1,pagesFetched:0,stoppedAtLimit:!1,error:`sandbox list failed: ${n instanceof Error?n.message:String(n)}`}}return SXe(()=>this.client.sandboxes.list({appId:t.appId,tags:e?.metadata}),e?.limit)}async listSandboxIds(){let e=new Set;try{let t=await this.getApp();for await(let n of this.client.sandboxes.list({appId:t.appId}))e.add(n.sandboxId);return{ids:e,complete:!0}}catch{return{ids:new Set,complete:!1}}}};Tjt=CZ,kjt=aXe,Ojt=FZ,Ajt=pB,Pjt=gXe,Rjt=hXe,Cjt=yXe,Njt=LZ,Mjt=SXe,Djt=lXe,Ujt=uXe,Bjt=fXe,Fjt=pXe,Ljt=uB});var AXe={};Ju(AXe,{MAX_INLINE_ARCHIVE_BYTES:()=>OXe,crc32Fallback:()=>TXe,extractTarGz:()=>Kjt,shouldStore:()=>EXe,tarGzTopLevelName:()=>Xjt,tarGzipDirectory:()=>Yjt,tarGzipDirectoryToFile:()=>kXe});async function qjt(e){let t=[],n=async r=>{let a=r===""?e:(0,Dp.join)(e,r),i=await(0,Ya.readdir)(a,{withFileTypes:!0});i.sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0);for(let s of i){if(Vjt.has(s.name))continue;let o=r===""?s.name:`${r}/${s.name}`,c=(0,Dp.join)(a,s.name),l=await(0,Ya.lstat)(c);l.isSymbolicLink()||(l.isDirectory()?await n(o):l.isFile()&&t.push({rel:o,abs:c,mode:l.mode&73?493:420,size:l.size}))}};return await n(""),t.sort((r,a)=>r.rel<a.rel?-1:r.rel>a.rel?1:0)}async function EXe(e,t){if(t<$jt)return!1;let n=await(0,Ya.open)(e,"r"),r;try{let a=Buffer.allocUnsafe(wXe),{bytesRead:i}=await n.read(a,0,wXe,0);r=a.subarray(0,i)}finally{await n.close()}return r.length===0?!1:(0,nf.deflateRawSync)(r,{level:1}).length*20>=r.length*19}function TXe(e,t=0){let n=~t;for(let r=0;r<e.length;r++)n=Jjt[(n^e[r])&255]^n>>>8;return~n>>>0}async function jjt(e){let t=Symbol("pending"),n=await Promise.race([e,Promise.resolve(t)]);return n===t?null:n}async function kXe(e,t){let n=await qjt(e),r=(0,kO.pack)(),a=(0,kv.createWriteStream)(t);a.on("error",()=>{}),r.on("error",()=>{});let i=new Wjt(a),s=r[Symbol.asyncIterator](),o=null,c=()=>o??=s.next();try{for(let{rel:l,abs:u,mode:d,size:f}of n){await i.setStored(await EXe(u,f));let p=r.entry({name:l,size:f,mode:d,mtime:new Date(0),uid:0,gid:0,uname:"",gname:"",type:"file"}),m=(0,Tv.pipeline)((0,kv.createReadStream)(u),p),y=!1,b=null;for(m.then(()=>{},()=>{}).then(()=>{y=!0,b?.(IXe)});;){if(!y){let S=await new Promise((w,I)=>{b=w,c().then(w,I)});if(b=null,S===IXe)continue;if(o=null,S.done)break;await i.write(S.value);continue}await new Promise(S=>setImmediate(S));let v=await jjt(c());if(v===null||(o=null,v.done))break;await i.write(v.value)}await m}for(r.finalize();;){let l=await c();if(o=null,l.done)break;await i.write(l.value)}await i.close(),a.end(),await(0,Tv.finished)(a)}catch(l){throw o?.catch(()=>{}),r.destroy(),a.destroy(),l}}async function Yjt(e,t=OXe){let n=await(0,Ya.mkdtemp)((0,Dp.join)((0,xXe.tmpdir)(),"evolve-tar-"));try{let r=(0,Dp.join)(n,"archive.tar.gz");await kXe(e,r);let{size:a}=await(0,Ya.stat)(r);if(a>t)throw new Error(`directory ${e} tars to ${a} bytes compressed \u2014 over the ${t}-byte cap for in-memory archives. Only the sandbox skill mount uses this path; a skill folder this large is not mountable.`);return await(0,Ya.readFile)(r)}finally{await(0,Ya.rm)(n,{recursive:!0,force:!0})}}async function Kjt(e,t,n){let r=(0,kO.extract)(),a=[],i=(async()=>{for await(let s of r){let o=s.header.name,c=o.split("/").filter(u=>u!==""&&u!==".");if(o.startsWith("/")||o.includes("\\")||c.length===0||c.some(u=>u===".."))throw new Error(`refusing to extract "${o}": the path escapes the target directory`);if(c[0]!==n)throw new Error(`refusing to extract "${o}": entry outside ${n}/`);if(s.header.type==="directory"){await(0,Ya.mkdir)((0,Dp.join)(t,...c),{recursive:!0}),s.resume();continue}if(s.header.type!=="file")throw new Error(`refusing to extract "${o}": unsupported entry type "${s.header.type}"`);let l=(0,Dp.join)(t,...c);await(0,Ya.mkdir)((0,Dp.dirname)(l),{recursive:!0}),await(0,Tv.pipeline)(s,(0,kv.createWriteStream)(l)),a.push(c.join("/"))}})();try{await Promise.all([(0,Tv.pipeline)((0,kv.createReadStream)(e),(0,nf.createGunzip)(),r),i])}catch(s){throw r.destroy(),s}return a}async function Xjt(e){let t=(0,kO.extract)(),n=null,r=(async()=>{for await(let a of t){let i=a.header.name,s=i.split("/").filter(o=>o!==""&&o!==".");if(i.startsWith("/")||i.includes("\\")||s.length===0||s.some(o=>o===".."))throw new Error(`refusing to extract "${i}": the path escapes the target directory`);if(n===null)n=s[0];else if(s[0]!==n)throw new Error(`refusing to extract "${i}": the archive holds more than one top-level directory (${n}/)`);a.resume()}})();try{await Promise.all([(0,Tv.pipeline)((0,kv.createReadStream)(e),(0,nf.createGunzip)(),t),r])}catch(a){throw t.destroy(),a}if(n===null)throw new Error("refusing to extract: the archive holds no entries");return n}var nf,kv,Ya,xXe,Dp,Tv,kO,Vjt,$jt,wXe,zjt,Gjt,qZ,Jjt,Hjt,Wjt,IXe,OXe,PXe=Q(()=>{"use strict";nf=Ve(require("zlib"),1),kv=require("fs"),Ya=require("fs/promises"),xXe=require("os"),Dp=require("path"),Tv=require("stream/promises"),kO=Ve(AZ(),1),Vjt=new Set([".git",".DS_Store",".venv"]);$jt=64*1024,wXe=128*1024,zjt=65535,Gjt=1024*1024,qZ=32*1024;Jjt=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})(),Hjt=nf.default.crc32??TXe,Wjt=class gB{constructor(t){this.sink=t}static HEADER=Buffer.from([31,139,8,0,0,0,0,0,0,255]);static FINAL_BLOCK=Buffer.from([1,0,0,255,255]);crc=0;plainLength=0;held=[];heldBytes=0;window=null;stored=!1;started=!1;async setStored(t){t!==this.stored&&(await this.drainHeld(!0),this.stored=t)}async write(t){this.started||(this.started=!0,await this.out(gB.HEADER)),this.held.push(t),this.heldBytes+=t.length,await this.drainHeld(!1)}async close(){this.started||(this.started=!0,await this.out(gB.HEADER)),await this.drainHeld(!0),await this.out(gB.FINAL_BLOCK);let t=Buffer.allocUnsafe(8);t.writeUInt32LE(this.crc>>>0,0),t.writeUInt32LE(this.plainLength%4294967296,4),await this.out(t)}async drainHeld(t){let n=this.stored?zjt:Gjt;for(;this.heldBytes>=n||t&&this.heldBytes>0;){let r=this.held.length===1?this.held[0]:Buffer.concat(this.held,this.heldBytes),a=Math.min(n,r.length),i=r.subarray(a);this.held=i.length>0?[i]:[],this.heldBytes=i.length,await this.emitBlock(r.subarray(0,a))}}async emitBlock(t){if(this.crc=Hjt(t,this.crc),this.plainLength+=t.length,this.stored){let n=Buffer.allocUnsafe(5+t.length);n[0]=0,n.writeUInt16LE(t.length,1),n.writeUInt16LE(t.length^65535,3),t.copy(n,5),await this.out(n)}else await this.out((0,nf.deflateRawSync)(t,{level:9,finishFlush:nf.constants.Z_SYNC_FLUSH,...this.window?{dictionary:this.window}:{}}));this.window=t.length>=qZ?Buffer.from(t.subarray(t.length-qZ)):this.window?Buffer.concat([this.window,t]).subarray(-qZ):Buffer.from(t)}out(t){return new Promise((n,r)=>{this.sink.write(t,a=>a==null?n():r(a))})}},IXe=Symbol("feed settled");OXe=256*1024*1024});var MXe={};Ju(MXe,{ManagedModalProvider:()=>tYt,ManagedModalWriteLimitError:()=>RXe,_testManagedModalSandbox:()=>nYt});function Zjt(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error(`Unsupported data type: ${typeof e}`)}function NXe(e){return{sandboxId:e.sandboxId,image:e.image??"",metadata:e.metadata??{},startedAt:e.startedAt??""}}var RXe,CXe,Qjt,eYt,$Z,tYt,nYt,DXe=Q(()=>{"use strict";RXe=class extends Error{bytes;constructor(e,t){super(`Managed Modal ${e} body is ${t} bytes; the managed door caps every request at 1048576 bytes (1 MiB) of wire bytes, base64 inflation included. Split the payload into smaller writes.`),this.name="ManagedModalWriteLimitError",this.bytes=t}};CXe=class{constructor(e){this.config=e}async request(e,t,n){let r=await fetch(`${this.config.baseUrl}${t}`,{...n,headers:{authorization:`Bearer ${this.config.apiKey}`,...n.headers??{}}});if(!r.ok){let a="";try{a=(await r.json())?.error??""}catch{}throw new Error(`Managed Modal ${e} failed (${r.status})${a?`: ${a}`:""}`)}return r}json(e){return{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}}},Qjt=class{constructor(e,t){this.door=e,this.sandboxId=t}async run(e,t){let n=await this.door.request("exec",`/sandboxes/${encodeURIComponent(this.sandboxId)}/exec`,this.door.json({command:e,...t?.cwd?{cwd:t.cwd}:{},...t?.envs?{envs:t.envs}:{},...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}})),r="",a="",i,s=o=>{if(!o.trim())return;let c;try{c=JSON.parse(o)}catch{throw new Error(`Managed Modal exec stream carried a garbled record: ${o}`)}c.stream==="stdout"&&typeof c.data=="string"?(r+=c.data,t?.onStdout?.(c.data)):c.stream==="stderr"&&typeof c.data=="string"?(a+=c.data,t?.onStderr?.(c.data)):i=c};if(n.body){let o=n.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:u,value:d}=await o.read();if(u)break;l+=c.decode(d,{stream:!0});let f;for(;(f=l.indexOf(`
255
255
  `))!==-1;)s(l.slice(0,f)),l=l.slice(f+1)}l+=c.decode(),s(l)}else for(let o of(await n.text()).split(`
256
256
  `))s(o);if(i?.error!==void 0)throw new Error(`Managed Modal exec failed: ${i.error}`);if(typeof i?.exitCode!="number")throw new Error("Managed Modal exec stream ended without a terminal record \u2014 the connection died mid-run.");return{exitCode:i.exitCode,stdout:r,stderr:a}}async spawn(e,t){let n=this.run(e,t);return n.catch(()=>{}),{processId:`managed-modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:()=>n,kill:async()=>!1}}async list(){return(await this.run("ps -eo pid,comm,args")).stdout.trim().split(`
@@ -547,7 +547,7 @@ async def list_checkpoints(
547
547
  await store.close()
548
548
 
549
549
 
550
- __version__ = '0.0.65.dev1542'
550
+ __version__ = '0.0.67'
551
551
 
552
552
  __all__ = [
553
553
  # Main classes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolvingmachines-evolve
3
- Version: 0.0.65.dev1542
3
+ Version: 0.0.67
4
4
  Summary: Pythonic SDK for multi-agent orchestration in E2B sandboxes
5
5
  Author-email: "Swarmlink, Inc." <brandomagnani@evolvingmachines.ai>
6
6
  License: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "evolvingmachines-evolve"
7
- version = "0.0.65.dev1542"
7
+ version = "0.0.67"
8
8
  description = "Pythonic SDK for multi-agent orchestration in E2B sandboxes"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"