evolvingmachines-evolve 0.0.59.dev1426__tar.gz → 0.0.61__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.59.dev1426/evolvingmachines_evolve.egg-info → evolvingmachines_evolve-0.0.61}/PKG-INFO +1 -1
  2. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/bridge/dist/bridge.bundle.cjs +2 -2
  3. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/__init__.py +1 -1
  4. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61/evolvingmachines_evolve.egg-info}/PKG-INFO +1 -1
  5. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/pyproject.toml +1 -1
  6. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/LICENSE +0 -0
  7. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/MANIFEST.in +0 -0
  8. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/README.md +0 -0
  9. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/bridge/__init__.py +0 -0
  10. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/_http.py +0 -0
  11. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/agent.py +0 -0
  12. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/bridge.py +0 -0
  13. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/browser_credentials.py +0 -0
  14. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/browser_profiles.py +0 -0
  15. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/config.py +0 -0
  16. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/hosted.py +0 -0
  17. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/integrations.py +0 -0
  18. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/managed_secrets.py +0 -0
  19. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/pipeline/__init__.py +0 -0
  20. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/pipeline/pipeline.py +0 -0
  21. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/pipeline/types.py +0 -0
  22. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/prompts/__init__.py +0 -0
  23. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/prompts/agent_md/judge.md +0 -0
  24. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/prompts/agent_md/reduce.md +0 -0
  25. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/prompts/agent_md/verify.md +0 -0
  26. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/prompts/user/judge.md +0 -0
  27. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/prompts/user/retry_feedback.md +0 -0
  28. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/prompts/user/verify.md +0 -0
  29. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/py.typed +0 -0
  30. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/results.py +0 -0
  31. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/retry.py +0 -0
  32. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/sandbox_view.py +0 -0
  33. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/schema.py +0 -0
  34. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/sessions_client.py +0 -0
  35. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/storage_client.py +0 -0
  36. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/swarm/__init__.py +0 -0
  37. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/swarm/results.py +0 -0
  38. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/swarm/swarm.py +0 -0
  39. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/swarm/types.py +0 -0
  40. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolve/utils.py +0 -0
  41. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolvingmachines_evolve.egg-info/SOURCES.txt +0 -0
  42. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolvingmachines_evolve.egg-info/dependency_links.txt +0 -0
  43. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolvingmachines_evolve.egg-info/requires.txt +0 -0
  44. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/evolvingmachines_evolve.egg-info/top_level.txt +0 -0
  45. {evolvingmachines_evolve-0.0.59.dev1426 → evolvingmachines_evolve-0.0.61}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolvingmachines-evolve
3
- Version: 0.0.59.dev1426
3
+ Version: 0.0.61
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 fRe(e,t){return e.endsWith(`${t}
216
216
  `)?e.slice(0,-(t.length+1)):e.endsWith(t)?e.slice(0,-t.length):e}function Q0(e,t){let n=_Re(e);return{stdout:fRe(n.stdout,t),stderr:n.stderr}}function DW(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 UW(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 pRe(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 dMt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!pRe(e)}function fMt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function pMt(e){return/^[^:]+:\d+$/.test(e)}function hMt(e){return e.startsWith("*.")&&e.length>2&&!e.slice(2).includes("*")}function zT(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(pRe(i))n.push(i.includes("/")?i:`${i}/32`);else{if(dMt(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(fMt(i))throw new Kl("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${i}".`,i);if(pMt(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("*")&&!hMt(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>kW)throw new Kl("allowlist-too-large",`Daytona allows at most ${kW} 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>TW)throw new Kl("allowlist-too-large",`Daytona allows at most ${TW} 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 hRe(e){let t=zT(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 mRe(e){let t=qW(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 gRe(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 $W(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function yRe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function vRe(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)vRe(r,t)}function mMt(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=>(vRe(c?.data,t),c)):o}}})}function yMt(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function GPe(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 bRe(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=yMt(a,o);;){let c=GPe(a,cy,0),l=GPe(a,ly,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=cy.length):l!==-1&&(u=l,d="stderr",f=ly.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 SRe(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=bRe(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 _Re(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function bMt(e,t){let n=FPe(e),r=t==="children"?`[ -e ${n} ] || exit ${EW}; [ -d ${n} ] || exit ${jPe};`:`[ -e ${n} ] || [ -L ${n} ] || exit ${EW};`,a=t==="children"?`find -H ${n} -mindepth 1 -maxdepth 1 -printf '${JPe}'`:`find ${n} -maxdepth 0 -printf '${JPe}'`;return`sh -c ${FPe(`${r} ( ${a}; printf 'STATUS:%d' "$?" ) | base64`)}`}function SMt(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+wW<=r.length;o+=wW){let[c,l,u,d,f,p,m,y]=r.slice(o,o+wW),b=c==="f"?"file":c==="d"?"dir":c==="l"?"symlink":"other",v={name:y,path:n==="children"?Q2t(e,y):e,type:b,size:Number(l),mtime:KPe(Number(u)),mode:Z2t(d),owner:f,group:p};b==="symlink"&&(v.target=m),s.push(v)}return s}function _Mt(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function xRe(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>PM)return{sandboxes:r,complete:!1,pagesFetched:PM,stoppedAtLimit:!1,error:`sandbox list exceeded ${PM} sandboxes scanned`};if(t?.state){let o=yRe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push($W(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 MM(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 zW({...e,apiKey:t})}var HPe,xW,CM,WPe,EW,jPe,NM,FW,XPe,TW,kW,ZPe,nMt,LW,QPe,eRe,Mh,tRe,PM,Kl,nRe,aMt,RM,rRe,iRe,sMt,aRe,AW,sRe,VPe,xy,$T,VW,oRe,cMt,qPe,lMt,cRe,lRe,gMt,wRe,JPe,wW,vMt,IRe,qT,zW,wMt,IMt,xMt,EMt,TMt,kMt,OMt,AMt,PMt,RMt,CMt,NMt,MMt,DMt,UMt,BMt,FMt,LMt,VMt,qMt,$Mt,zMt,IW,GT=Q(()=>{"use strict";BPe();HPe=require("crypto"),xW=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}},CM=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}},WPe=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}};EW=2,jPe=20;NM="c-880c264ce574",FW={[`evolve-all-${NM}`]:`evolvingmachines/evolve-all:${NM}`,"evolve-all":"evolvingmachines/evolve-all"},XPe=10,TW=10,kW=20,ZPe=18e4,nMt=2e3,LW=6e5,QPe=5e3,eRe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},Mh=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),tRe=100,PM=1e4;Kl=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},nRe=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}},aMt=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}},RM=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}},rRe=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"}},iRe=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"}},sMt=new Set(["pending_build","building_snapshot","pulling_snapshot"]);aRe=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}},AW="evolve_boot",sRe=5e3,VPe=30;xy=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}};$T=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}},VW=Symbol("daytona-snapshot-gone"),oRe=new Set(["pending","pulling","building","snapshotting"]),cMt=3;qPe=new Set(["error","build_failed"]),lMt=new Set(["latest","lts","stable"]);cRe=6e4,lRe=2e3;gMt=class extends yy{constructor(e,t){super(e);let n=this;n.sandboxApi=mMt(n.sandboxApi,t)}};wRe=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=eRe;followLogs(e,t,n,r,a){return this.managedStream?SRe(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=zPe(),s=await this.sandbox.process.executeSessionCommand(r,{command:NW(UW(MW(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=DW(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=Q0(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=Q0(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}=Q0(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=Q0(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=zPe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:NW(UW(MW(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=DW(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,...Q0(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}}},JPe="%y\\0%s\\0%T@\\0%m\\0%u\\0%g\\0%l\\0%f\\0",wW=8,vMt=1800*1e3;IRe=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=rMt(e),n=iMt(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 CM(e,"daytona");return t}async findListing(e,t){let n=await this.commands.run(bMt(e,t));if(n.exitCode===EW)throw new CM(e,"daytona");if(n.exitCode===jPe)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 SMt(e,n.stdout,t)}catch(r){throw/printf|unrecognized|invalid option/i.test(n.stderr)?new xW("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(YPe(t),t.length===0)return new Uint8Array(0);let n=await this.sandbox.downloadUrl(e);return eMt(n,t,{provider:"daytona",path:e,timeoutMs:vMt})}async watchDir(e,t,n){throw new xW("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)}},qT=class{constructor(e,t,n){this.sandbox=e;let r=new wRe(e,t,n);this.commands=r,this.files=new IRe(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(),$W(this.sandbox)}async metrics(){let e=await this.sandbox.getMetricsLatest();return{cpuPct:e.cpuUsedPct,memUsedMb:e.memUsed/IW,memTotalMb:e.memTotal/IW,diskUsedMb:e.diskUsed/IW,sampledAt:KPe(e.timestamp),source:"daytona:getMetricsLatest"}}async updateNetwork(e){let t=hRe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw mRe(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()}},zW=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:LW,pollMs:QPe};snapshotDeleteTiming={timeoutMs:cRe,pollMs:lRe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new gMt(t,e.managedToolboxUrl):new yy(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-${NM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new iRe;if(e.bootCommand!==void 0)throw new rRe;for(let f of e.phaseNetworkPolicies??[])zT(f);let t=zT(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:XPe,...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 RM(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 qT(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),p=f?.state;if(f&&oRe.has(p??"")&&(u=p),f&&(p==="active"||p==="inactive")&&l)throw new RM(s);if(f&&p==="inactive"&&(p=(await PW(this.client,s,f)).state),f&&qPe.has(p??"")&&(RW(s)?d=await $Pe(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 RM||f instanceof xy)throw f;let p=FW[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(!uRe(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 $T||y instanceof xy)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 gRe(p)?new nRe(p,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new qT(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await dRe(this.client,e,this.snapshotConflictTiming);if(t===VW)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 PW(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(qPe.has(t.state??"")&&RW(e)&&await $Pe(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 qT(n,this.sandboxUsers.get(e),this.managedStream)}async inspect(e,t){let n=await this.getSandboxRecord(e);if(n.state!=="started")throw new WPe(e,"daytona",n.state??"unknown");return new qT(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 xRe(this.listStream(e),e)}listStream(e){let t=e?.state?_Mt(e.state):void 0,n={limit:tRe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};wMt=xRe;IMt=UW,xMt=NW,EMt=zT,TMt=hRe,kMt=mRe,OMt=gRe,AMt=$W,PMt=yRe,RMt=PW,CMt=dRe,NMt=uRe,MMt=RW,DMt=FW,UMt=MW,BMt=fRe,FMt=Q0,LMt=DW,VMt=bRe,qMt=SRe,$Mt=_Re,zMt=qT,IW=1024*1024});var ERe=_(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0});DM.Metadata=void 0;DM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=eS(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)JW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else JW(a,i),n.set(a,[i]);return r},append(a,i){a=eS(a),JW(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=eS(a),n.delete(a)},get(a){var i;return a=eS(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=eS(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=eS(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=GMt(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function eS(e){return e.toLowerCase()}function JW(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 GMt(e){return Symbol.iterator in e}});var UM=_(JT=>{"use strict";Object.defineProperty(JT,"__esModule",{value:!0});JT.Status=void 0;var JMt;(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"})(JMt=JT.Status||(JT.Status={}))});var kRe=_(TRe=>{"use strict";Object.defineProperty(TRe,"__esModule",{value:!0})});var ARe=_(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0})});var RRe=_(PRe=>{"use strict";Object.defineProperty(PRe,"__esModule",{value:!0})});var CRe=_(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0});BM.composeClientMiddleware=void 0;function HMt(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}BM.composeClientMiddleware=HMt});var DRe=_(Dh=>{"use strict";Dh.__esModule=void 0;Dh.__esModule=!0;var WMt=typeof Object.setPrototypeOf=="function",jMt=typeof Object.getPrototypeOf=="function",YMt=typeof Object.defineProperty=="function",KMt=typeof Object.create=="function",XMt=typeof Object.prototype.hasOwnProperty=="function",ZMt=function(t,n){WMt?Object.setPrototypeOf(t,n):t.__proto__=n};Dh.setPrototypeOf=ZMt;var QMt=function(t){return jMt?Object.getPrototypeOf(t):t.__proto__||t.prototype};Dh.getPrototypeOf=QMt;var NRe=!1,eDt=function e(t,n,r){if(YMt&&!NRe)try{Object.defineProperty(t,n,r)}catch{NRe=!0,e(t,n,r)}else t[n]=r.value};Dh.defineProperty=eDt;var MRe=function(t,n){return XMt?t.hasOwnProperty(t,n):t[n]===void 0};Dh.hasOwnProperty=MRe;var tDt=function(t,n){if(KMt)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)MRe(n,i)&&(a[i]=n[i].value);return a};Dh.objectCreate=tDt});var WW=_(tS=>{"use strict";tS.__esModule=void 0;tS.__esModule=!0;var LM=DRe(),nDt=LM.setPrototypeOf,rDt=LM.getPrototypeOf,HW=LM.defineProperty,iDt=LM.objectCreate,aDt=new Error().toString()==="[object Error]",FM="";function HT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?FM||"Error":o[1]}(),r=n==="Error",a=r?FM:n,i=Error.apply(this,arguments);if(nDt(i,rDt(this)),!(i instanceof t)||!(i instanceof HT)){var i=this;Error.apply(this,arguments),HW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(HW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?HT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return aDt&&HW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}FM=HT.name||"ExtendableError";HT.prototype=iDt(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});tS.ExtendableError=HT;tS.default=tS.ExtendableError});var URe=_(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.ClientError=void 0;var sDt=WW(),oDt=UM(),jW=class e extends sDt.ExtendableError{constructor(t,n,r){super(`${t} ${oDt.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)}};VM.ClientError=jW});var FRe=_(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0})});var VRe=_(LRe=>{"use strict";Object.defineProperty(LRe,"__esModule",{value:!0})});var qRe=_(qM=>{"use strict";Object.defineProperty(qM,"__esModule",{value:!0});qM.composeServerMiddleware=void 0;function cDt(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}qM.composeServerMiddleware=cDt});var $Re=_($M=>{"use strict";Object.defineProperty($M,"__esModule",{value:!0});$M.ServerError=void 0;var lDt=WW(),uDt=UM(),YW=class e extends lDt.ExtendableError{constructor(t,n){super(`${uDt.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)}};$M.ServerError=YW});var Xc=_($a=>{"use strict";var dDt=$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)&&dDt(t,e,n)};Object.defineProperty($a,"__esModule",{value:!0});Xl(ERe(),$a);Xl(UM(),$a);Xl(kRe(),$a);Xl(ARe(),$a);Xl(RRe(),$a);Xl(CRe(),$a);Xl(URe(),$a);Xl(FRe(),$a);Xl(VRe(),$a);Xl(qRe(),$a);Xl($Re(),$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 zRe;(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"})(zRe||(Zc.Status=zRe={}));var GRe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(GRe||(Zc.LogVerbosity=GRe={}));var JRe;(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"})(JRe||(Zc.Propagate=JRe={}));Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var KW=_(($In,fDt)=>{fDt.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 XW,ZW,QW,e7;Object.defineProperty(hc,"__esModule",{value:!0});hc.log=hc.setLoggerVerbosity=hc.setLogger=hc.getLogger=void 0;hc.trace=IDt;hc.isTracerEnabled=WRe;var Uh=Yt(),pDt=require("process"),hDt=KW().version,mDt={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},Ey=mDt,nS=Uh.LogVerbosity.ERROR,gDt=(ZW=(XW=process.env.GRPC_NODE_VERBOSITY)!==null&&XW!==void 0?XW:process.env.GRPC_VERBOSITY)!==null&&ZW!==void 0?ZW:"";switch(gDt.toUpperCase()){case"DEBUG":nS=Uh.LogVerbosity.DEBUG;break;case"INFO":nS=Uh.LogVerbosity.INFO;break;case"ERROR":nS=Uh.LogVerbosity.ERROR;break;case"NONE":nS=Uh.LogVerbosity.NONE;break;default:}var yDt=()=>Ey;hc.getLogger=yDt;var vDt=e=>{Ey=e};hc.setLogger=vDt;var bDt=e=>{nS=e};hc.setLoggerVerbosity=bDt;var SDt=(e,...t)=>{let n;if(e>=nS){switch(e){case Uh.LogVerbosity.DEBUG:n=Ey.debug;break;case Uh.LogVerbosity.INFO:n=Ey.info;break;case Uh.LogVerbosity.ERROR:n=Ey.error;break}n||(n=Ey.error),n&&n.bind(Ey)(...t)}};hc.log=SDt;var _Dt=(e7=(QW=process.env.GRPC_NODE_TRACE)!==null&&QW!==void 0?QW:process.env.GRPC_TRACE)!==null&&e7!==void 0?e7:"",t7=new Set,HRe=new Set;for(let e of _Dt.split(","))e.startsWith("-")?HRe.add(e.substring(1)):t7.add(e);var wDt=t7.has("all");function IDt(e,t,n){WRe(t)&&(0,hc.log)(e,new Date().toISOString()+" | v"+hDt+" "+pDt.pid+" | "+t+" | "+n)}function WRe(e){return!HRe.has(e)&&(wDt||t7.has(e))}});var GM=_(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.getErrorMessage=xDt;zM.getErrorCode=EDt;function xDt(e){return e instanceof Error?e.message:String(e)}function EDt(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ma=_(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.Metadata=void 0;var TDt=hr(),kDt=Yt(),ODt=GM(),ADt=/^[:0-9a-z_.-]+$/,PDt=/^[ -~]*$/;function RDt(e){return ADt.test(e)}function CDt(e){return PDt.test(e)}function YRe(e){return e.endsWith("-bin")}function NDt(e){return!e.startsWith("grpc-")}function JM(e){return e.toLowerCase()}function jRe(e,t){if(!RDt(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(YRe(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(!CDt(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var n7=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=JM(t),jRe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=JM(t),jRe(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(MDt));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{YRe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(NDt(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,ODt.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,TDt.log)(kDt.LogVerbosity.ERROR,s)}}return n}};HM.Metadata=n7;var MDt=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var jM=_(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.CallCredentials=void 0;var s7=ma();function DDt(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var rS=class e{static createFromMetadataGenerator(t){return new i7(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;DDt(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 s7.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new a7}};WM.CallCredentials=rS;var r7=class e extends rS{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new s7.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}},i7=class e extends rS{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 r7([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},a7=class e extends rS{generateMetadata(t){return Promise.resolve(new s7.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var c7=_(WT=>{"use strict";Object.defineProperty(WT,"__esModule",{value:!0});WT.CIPHER_SUITES=void 0;WT.getDefaultRootsData=BDt;var UDt=require("fs");WT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var KRe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,o7=null;function BDt(){return KRe?(o7===null&&(o7=UDt.readFileSync(KRe)),o7):null}});var no=_(iS=>{"use strict";Object.defineProperty(iS,"__esModule",{value:!0});iS.parseUri=LDt;iS.splitHostPort=VDt;iS.combineHostPort=qDt;iS.uriToString=$Dt;var FDt=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function LDt(e){let t=FDt.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var XRe=/^\d+$/;function VDt(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 XRe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?XRe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function qDt(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function $Dt(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=zDt;dp.registerDefaultScheme=GDt;dp.createResolver=JDt;dp.getDefaultAuthority=HDt;dp.mapUriDefaultScheme=WDt;var u7=no();dp.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var aS={},l7=null;function zDt(e,t){aS[e]=t}function GDt(e){l7=e}function JDt(e,t,n){if(e.scheme!==void 0&&e.scheme in aS)return new aS[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,u7.uriToString)(e)}`)}function HDt(e){if(e.scheme!==void 0&&e.scheme in aS)return aS[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,u7.uriToString)(e)}`)}function WDt(e){return e.scheme===void 0||!(e.scheme in aS)?l7!==null?{scheme:l7,authority:void 0,path:(0,u7.uriToString)(e)}:null:e}});var sS=_(YT=>{"use strict";Object.defineProperty(YT,"__esModule",{value:!0});YT.ChannelCredentials=void 0;YT.createCertificateProviderChannelCredentials=XDt;var jT=require("tls"),XM=jM(),f7=c7(),ZRe=no(),jDt=Zl(),YDt=hr(),KDt=Yt();function d7(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var Ty=class{compose(t){return new m7(this,t)}static createSsl(t,n,r,a){var i;if(d7(t,"Root certificate"),d7(n,"Private key"),d7(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,jT.createSecureContext)({ca:(i=t??(0,f7.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:f7.CIPHER_SUITES});return new YM(s,a??{})}static createFromSecureContext(t,n){return new YM(t,n??{})}static createInsecure(){return new p7}};YT.ChannelCredentials=Ty;var p7=class e extends Ty{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??XM.CallCredentials.createEmpty(),destroy(){}}}};function QRe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,ZRe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,jDt.getDefaultAuthority)(o),l=(0,ZRe.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:jT.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 h7=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,jT.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(){}},YM=class e extends Ty{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=QRe(this.secureContext,this.verifyOptions,t,n);return new h7(a,r??XM.CallCredentials.createEmpty())}},KM=class e extends Ty{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??XM.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,jT.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:f7.CIPHER_SUITES})}catch(r){return(0,YDt.log)(KDt.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};KM.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=QRe(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,jT.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 XDt(e,t,n){return new KM(e,t,n??{})}var m7=class e extends Ty{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??XM.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Fh=_(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.createChildChannelControlHelper=e3t;Td.registerLoadBalancerType=t3t;Td.registerDefaultLoadBalancerType=n3t;Td.createLoadBalancer=r3t;Td.isLoadBalancerNameRegistered=i3t;Td.parseLoadBalancingConfig=eCe;Td.getDefaultConfig=a3t;Td.selectLbConfigFromList=s3t;var ZDt=hr(),QDt=Yt();function e3t(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={},KT=null;function t3t(e,t,n){Bh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function n3t(e){KT=e}function r3t(e,t){let n=e.getLoadBalancerName();return n in Bh?new Bh[n].LoadBalancer(t):null}function i3t(e){return e in Bh}function eCe(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 a3t(){if(!KT)throw new Error("No default load balancer type registered");return new Bh[KT].LoadBalancingConfig}function s3t(e,t=!1){for(let n of e)try{return eCe(n)}catch(r){(0,ZDt.log)(QDt.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&KT?new Bh[KT].LoadBalancingConfig:null}});var g7=_(XT=>{"use strict";Object.defineProperty(XT,"__esModule",{value:!0});XT.validateRetryThrottling=tCe;XT.validateServiceConfig=nCe;XT.extractAndSelectServiceConfig=g3t;var o3t=require("os"),ZM=Yt(),QM=/^\d+(\.\d{1,9})?s$/,c3t="node";function l3t(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 u3t(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"||!QM.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"||!QM.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(ZM.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(ZM.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 d3t(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"||!QM.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(ZM.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(ZM.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 f3t(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(l3t(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"&&QM.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=u3t(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=d3t(e.hedgingPolicy));return n}function tCe(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 p3t(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 nCe(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(p3t(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(f3t(r));"retryThrottling"in e&&(t.retryThrottling=tCe(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 h3t(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:nCe(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 m3t(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=h3t(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===o3t.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===c3t&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function g3t(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 m3t(a,t)}return null}});var ro=_(eD=>{"use strict";Object.defineProperty(eD,"__esModule",{value:!0});eD.ConnectivityState=void 0;var rCe;(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"})(rCe||(eD.ConnectivityState=rCe={}))});var fp=_(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.QueuePicker=Lh.UnavailablePicker=Lh.PickResultType=void 0;var y3t=ma(),v3t=Yt(),tD;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(tD||(Lh.PickResultType=tD={}));var y7=class{constructor(t){this.status=Object.assign({code:v3t.Status.UNAVAILABLE,details:"No connection established",metadata:new y3t.Metadata},t)}pick(t){return{pickResultType:tD.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Lh.UnavailablePicker=y7;var v7=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:tD.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Lh.QueuePicker=v7});var oS=_(rD=>{"use strict";Object.defineProperty(rD,"__esModule",{value:!0});rD.BackoffTimeout=void 0;var b3t=Yt(),S3t=hr(),_3t="backoff",w3t=1e3,I3t=1.6,x3t=12e4,E3t=.2;function T3t(e,t){return Math.random()*(t-e)+e}var nD=class e{constructor(t,n){this.callback=t,this.initialDelay=w3t,this.multiplier=I3t,this.maxDelay=x3t,this.jitter=E3t,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){S3t.trace(b3t.LogVerbosity.DEBUG,_3t,"{"+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+T3t(-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}};rD.BackoffTimeout=nD;nD.nextId=0});var aD=_(iD=>{"use strict";Object.defineProperty(iD,"__esModule",{value:!0});iD.ChildLoadBalancerHandler=void 0;var k3t=Fh(),O3t=ro(),A3t="child_load_balancer_helper",b7=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===O3t.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,k3t.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 A3t}};iD.ChildLoadBalancerHandler=b7});var sCe=_(sD=>{"use strict";Object.defineProperty(sD,"__esModule",{value:!0});sD.ResolvingLoadBalancer=void 0;var P3t=Fh(),R3t=g7(),No=ro(),iCe=Zl(),ZT=fp(),C3t=oS(),S7=Yt(),N3t=ma(),M3t=hr(),D3t=Yt(),U3t=no(),B3t=aD(),F3t="resolving_load_balancer";function aCe(e){M3t.trace(D3t.LogVerbosity.DEBUG,F3t,e)}var L3t=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function V3t(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 q3t(e,t,n,r){for(let a of n)if(V3t(e,t,a,r))return a;return null}function $3t(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 L3t){let l=q3t(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:S7.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:S7.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var _7=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=No.ConnectivityState.IDLE,this.latestChildPicker=new ZT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,R3t.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(No.ConnectivityState.IDLE,new ZT.QueuePicker(this),null),this.childLoadBalancer=new B3t.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(aCe("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,iCe.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 C3t.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,P3t.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:S7.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new N3t.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[iCe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:$3t(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===No.ConnectivityState.IDLE&&this.updateState(No.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){aCe((0,U3t.uriToString)(this.target)+" "+No.ConnectivityState[this.currentState]+" -> "+No.ConnectivityState[t]),t===No.ConnectivityState.IDLE&&(n=new ZT.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===No.ConnectivityState.IDLE&&(this.updateState(No.ConnectivityState.TRANSIENT_FAILURE,new ZT.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===No.ConnectivityState.IDLE||this.currentState===No.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=No.ConnectivityState.IDLE,this.latestChildPicker=new ZT.QueuePicker(this),this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};sD.ResolvingLoadBalancer=_7});var oCe=_(QT=>{"use strict";Object.defineProperty(QT,"__esModule",{value:!0});QT.recognizedOptions=void 0;QT.channelOptionsEqual=z3t;QT.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 z3t(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 Mo=_(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.EndpointMap=void 0;Ql.isTcpSubchannelAddress=tk;Ql.subchannelAddressEqual=oD;Ql.subchannelAddressToString=lCe;Ql.stringToSubchannelAddress=J3t;Ql.endpointEqual=H3t;Ql.endpointToString=W3t;Ql.endpointHasAddress=uCe;var cCe=require("net");function tk(e){return"port"in e}function oD(e,t){return!e&&!t?!0:!e||!t?!1:tk(e)?tk(t)&&e.host===t.host&&e.port===t.port:!tk(t)&&e.path===t.path}function lCe(e){return tk(e)?(0,cCe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var G3t=443;function J3t(e,t){return(0,cCe.isIP)(e)?{host:e,port:t??G3t}:{path:e}}function H3t(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!oD(e.addresses[n],t.addresses[n]))return!1;return!0}function W3t(e){return"["+e.addresses.map(lCe).join(", ")+"]"}function uCe(e,t){for(let n of e.addresses)if(oD(n,t))return!0;return!1}function ek(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(oD(n,a)){r=!0;break}if(!r)return!1}return!0}var w7=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(uCe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)ek(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(ek(t,n.key))return n.value}set(t,n){for(let r of this.map)if(ek(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(ek(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(ek(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=w7});var dCe=_(P7=>{"use strict";Object.defineProperty(P7,"t",{value:!0});var cD=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}},I7=class extends cD{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)}},x7=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},E7=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},T7=class extends E7{};function ky(){throw new RangeError("Iterator access denied!")}var k7=class extends T7{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?I7:cD,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&&ky(),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&&ky();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)}},O7=class extends x7{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&ky(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&ky(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&ky(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&ky(),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 O7{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&ky();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)}},A7=class extends k7{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]}}};P7.OrderedMap=A7});var uD=_(lD=>{"use strict";Object.defineProperty(lD,"__esModule",{value:!0});lD.registerAdminService=j3t;lD.addAdminServicesToServer=Y3t;var fCe=[];function j3t(e,t){fCe.push({getServiceDefinition:e,getHandlers:t})}function Y3t(e){for(let{getServiceDefinition:t,getHandlers:n}of fCe)e.addService(t(),n())}});var pCe=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.ClientDuplexStreamImpl=tu.ClientWritableStreamImpl=tu.ClientReadableStreamImpl=tu.ClientUnaryCallImpl=void 0;tu.callErrorFromStatus=X3t;var K3t=require("events"),D7=require("stream"),nk=Yt();function X3t(e,t){let n=`${e.code} ${nk.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 UW(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 pRe(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 dMt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!pRe(e)}function fMt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function pMt(e){return/^[^:]+:\d+$/.test(e)}function hMt(e){return e.startsWith("*.")&&e.length>2&&!e.slice(2).includes("*")}function zT(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(pRe(i))n.push(i.includes("/")?i:`${i}/32`);else{if(dMt(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(fMt(i))throw new Kl("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${i}".`,i);if(pMt(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("*")&&!hMt(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>kW)throw new Kl("allowlist-too-large",`Daytona allows at most ${kW} 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>TW)throw new Kl("allowlist-too-large",`Daytona allows at most ${TW} 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 hRe(e){let t=zT(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 mRe(e){let t=qW(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 gRe(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 $W(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function yRe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function vRe(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)vRe(r,t)}function mMt(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=>(vRe(c?.data,t),c)):o}}})}function yMt(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function GPe(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 bRe(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=yMt(a,o);;){let c=GPe(a,cy,0),l=GPe(a,ly,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=cy.length):l!==-1&&(u=l,d="stderr",f=ly.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 SRe(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=bRe(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 _Re(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function bMt(e,t){let n=FPe(e),r=t==="children"?`[ -e ${n} ] || exit ${EW}; [ -d ${n} ] || exit ${jPe};`:`[ -e ${n} ] || [ -L ${n} ] || exit ${EW};`,a=t==="children"?`find -H ${n} -mindepth 1 -maxdepth 1 -printf '${JPe}'`:`find ${n} -maxdepth 0 -printf '${JPe}'`;return`sh -c ${FPe(`${r} ( ${a}; printf 'STATUS:%d' "$?" ) | base64`)}`}function SMt(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+wW<=r.length;o+=wW){let[c,l,u,d,f,p,m,y]=r.slice(o,o+wW),b=c==="f"?"file":c==="d"?"dir":c==="l"?"symlink":"other",v={name:y,path:n==="children"?Q2t(e,y):e,type:b,size:Number(l),mtime:KPe(Number(u)),mode:Z2t(d),owner:f,group:p};b==="symlink"&&(v.target=m),s.push(v)}return s}function _Mt(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function xRe(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>PM)return{sandboxes:r,complete:!1,pagesFetched:PM,stoppedAtLimit:!1,error:`sandbox list exceeded ${PM} sandboxes scanned`};if(t?.state){let o=yRe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push($W(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 MM(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 zW({...e,apiKey:t})}var HPe,xW,CM,WPe,EW,jPe,NM,FW,XPe,TW,kW,ZPe,nMt,LW,QPe,eRe,Mh,tRe,PM,Kl,nRe,aMt,RM,rRe,iRe,sMt,aRe,AW,sRe,VPe,xy,$T,VW,oRe,cMt,qPe,lMt,cRe,lRe,gMt,wRe,JPe,wW,vMt,IRe,qT,zW,wMt,IMt,xMt,EMt,TMt,kMt,OMt,AMt,PMt,RMt,CMt,NMt,MMt,DMt,UMt,BMt,FMt,LMt,VMt,qMt,$Mt,zMt,IW,GT=Q(()=>{"use strict";BPe();HPe=require("crypto"),xW=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}},CM=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}},WPe=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}};EW=2,jPe=20;NM="c-4bfce70a407f",FW={[`evolve-all-${NM}`]:`evolvingmachines/evolve-all:${NM}`,"evolve-all":"evolvingmachines/evolve-all"},XPe=10,TW=10,kW=20,ZPe=18e4,nMt=2e3,LW=6e5,QPe=5e3,eRe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},Mh=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),tRe=100,PM=1e4;Kl=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},nRe=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}},aMt=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}},RM=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}},rRe=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"}},iRe=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"}},sMt=new Set(["pending_build","building_snapshot","pulling_snapshot"]);aRe=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}},AW="evolve_boot",sRe=5e3,VPe=30;xy=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}};$T=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}},VW=Symbol("daytona-snapshot-gone"),oRe=new Set(["pending","pulling","building","snapshotting"]),cMt=3;qPe=new Set(["error","build_failed"]),lMt=new Set(["latest","lts","stable"]);cRe=6e4,lRe=2e3;gMt=class extends yy{constructor(e,t){super(e);let n=this;n.sandboxApi=mMt(n.sandboxApi,t)}};wRe=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=eRe;followLogs(e,t,n,r,a){return this.managedStream?SRe(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=zPe(),s=await this.sandbox.process.executeSessionCommand(r,{command:NW(UW(MW(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=DW(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=Q0(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=Q0(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}=Q0(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=Q0(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=zPe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:NW(UW(MW(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=DW(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,...Q0(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}}},JPe="%y\\0%s\\0%T@\\0%m\\0%u\\0%g\\0%l\\0%f\\0",wW=8,vMt=1800*1e3;IRe=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=rMt(e),n=iMt(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 CM(e,"daytona");return t}async findListing(e,t){let n=await this.commands.run(bMt(e,t));if(n.exitCode===EW)throw new CM(e,"daytona");if(n.exitCode===jPe)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 SMt(e,n.stdout,t)}catch(r){throw/printf|unrecognized|invalid option/i.test(n.stderr)?new xW("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(YPe(t),t.length===0)return new Uint8Array(0);let n=await this.sandbox.downloadUrl(e);return eMt(n,t,{provider:"daytona",path:e,timeoutMs:vMt})}async watchDir(e,t,n){throw new xW("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)}},qT=class{constructor(e,t,n){this.sandbox=e;let r=new wRe(e,t,n);this.commands=r,this.files=new IRe(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(),$W(this.sandbox)}async metrics(){let e=await this.sandbox.getMetricsLatest();return{cpuPct:e.cpuUsedPct,memUsedMb:e.memUsed/IW,memTotalMb:e.memTotal/IW,diskUsedMb:e.diskUsed/IW,sampledAt:KPe(e.timestamp),source:"daytona:getMetricsLatest"}}async updateNetwork(e){let t=hRe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw mRe(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()}},zW=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:LW,pollMs:QPe};snapshotDeleteTiming={timeoutMs:cRe,pollMs:lRe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new gMt(t,e.managedToolboxUrl):new yy(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-${NM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new iRe;if(e.bootCommand!==void 0)throw new rRe;for(let f of e.phaseNetworkPolicies??[])zT(f);let t=zT(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:XPe,...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 RM(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 qT(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),p=f?.state;if(f&&oRe.has(p??"")&&(u=p),f&&(p==="active"||p==="inactive")&&l)throw new RM(s);if(f&&p==="inactive"&&(p=(await PW(this.client,s,f)).state),f&&qPe.has(p??"")&&(RW(s)?d=await $Pe(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 RM||f instanceof xy)throw f;let p=FW[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(!uRe(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 $T||y instanceof xy)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 gRe(p)?new nRe(p,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new qT(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await dRe(this.client,e,this.snapshotConflictTiming);if(t===VW)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 PW(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(qPe.has(t.state??"")&&RW(e)&&await $Pe(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 qT(n,this.sandboxUsers.get(e),this.managedStream)}async inspect(e,t){let n=await this.getSandboxRecord(e);if(n.state!=="started")throw new WPe(e,"daytona",n.state??"unknown");return new qT(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 xRe(this.listStream(e),e)}listStream(e){let t=e?.state?_Mt(e.state):void 0,n={limit:tRe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};wMt=xRe;IMt=UW,xMt=NW,EMt=zT,TMt=hRe,kMt=mRe,OMt=gRe,AMt=$W,PMt=yRe,RMt=PW,CMt=dRe,NMt=uRe,MMt=RW,DMt=FW,UMt=MW,BMt=fRe,FMt=Q0,LMt=DW,VMt=bRe,qMt=SRe,$Mt=_Re,zMt=qT,IW=1024*1024});var ERe=_(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0});DM.Metadata=void 0;DM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=eS(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)JW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else JW(a,i),n.set(a,[i]);return r},append(a,i){a=eS(a),JW(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=eS(a),n.delete(a)},get(a){var i;return a=eS(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=eS(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=eS(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=GMt(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function eS(e){return e.toLowerCase()}function JW(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 GMt(e){return Symbol.iterator in e}});var UM=_(JT=>{"use strict";Object.defineProperty(JT,"__esModule",{value:!0});JT.Status=void 0;var JMt;(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"})(JMt=JT.Status||(JT.Status={}))});var kRe=_(TRe=>{"use strict";Object.defineProperty(TRe,"__esModule",{value:!0})});var ARe=_(ORe=>{"use strict";Object.defineProperty(ORe,"__esModule",{value:!0})});var RRe=_(PRe=>{"use strict";Object.defineProperty(PRe,"__esModule",{value:!0})});var CRe=_(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0});BM.composeClientMiddleware=void 0;function HMt(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}BM.composeClientMiddleware=HMt});var DRe=_(Dh=>{"use strict";Dh.__esModule=void 0;Dh.__esModule=!0;var WMt=typeof Object.setPrototypeOf=="function",jMt=typeof Object.getPrototypeOf=="function",YMt=typeof Object.defineProperty=="function",KMt=typeof Object.create=="function",XMt=typeof Object.prototype.hasOwnProperty=="function",ZMt=function(t,n){WMt?Object.setPrototypeOf(t,n):t.__proto__=n};Dh.setPrototypeOf=ZMt;var QMt=function(t){return jMt?Object.getPrototypeOf(t):t.__proto__||t.prototype};Dh.getPrototypeOf=QMt;var NRe=!1,eDt=function e(t,n,r){if(YMt&&!NRe)try{Object.defineProperty(t,n,r)}catch{NRe=!0,e(t,n,r)}else t[n]=r.value};Dh.defineProperty=eDt;var MRe=function(t,n){return XMt?t.hasOwnProperty(t,n):t[n]===void 0};Dh.hasOwnProperty=MRe;var tDt=function(t,n){if(KMt)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)MRe(n,i)&&(a[i]=n[i].value);return a};Dh.objectCreate=tDt});var WW=_(tS=>{"use strict";tS.__esModule=void 0;tS.__esModule=!0;var LM=DRe(),nDt=LM.setPrototypeOf,rDt=LM.getPrototypeOf,HW=LM.defineProperty,iDt=LM.objectCreate,aDt=new Error().toString()==="[object Error]",FM="";function HT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?FM||"Error":o[1]}(),r=n==="Error",a=r?FM:n,i=Error.apply(this,arguments);if(nDt(i,rDt(this)),!(i instanceof t)||!(i instanceof HT)){var i=this;Error.apply(this,arguments),HW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(HW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?HT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return aDt&&HW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}FM=HT.name||"ExtendableError";HT.prototype=iDt(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});tS.ExtendableError=HT;tS.default=tS.ExtendableError});var URe=_(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0});VM.ClientError=void 0;var sDt=WW(),oDt=UM(),jW=class e extends sDt.ExtendableError{constructor(t,n,r){super(`${t} ${oDt.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)}};VM.ClientError=jW});var FRe=_(BRe=>{"use strict";Object.defineProperty(BRe,"__esModule",{value:!0})});var VRe=_(LRe=>{"use strict";Object.defineProperty(LRe,"__esModule",{value:!0})});var qRe=_(qM=>{"use strict";Object.defineProperty(qM,"__esModule",{value:!0});qM.composeServerMiddleware=void 0;function cDt(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}qM.composeServerMiddleware=cDt});var $Re=_($M=>{"use strict";Object.defineProperty($M,"__esModule",{value:!0});$M.ServerError=void 0;var lDt=WW(),uDt=UM(),YW=class e extends lDt.ExtendableError{constructor(t,n){super(`${uDt.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)}};$M.ServerError=YW});var Xc=_($a=>{"use strict";var dDt=$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)&&dDt(t,e,n)};Object.defineProperty($a,"__esModule",{value:!0});Xl(ERe(),$a);Xl(UM(),$a);Xl(kRe(),$a);Xl(ARe(),$a);Xl(RRe(),$a);Xl(CRe(),$a);Xl(URe(),$a);Xl(FRe(),$a);Xl(VRe(),$a);Xl(qRe(),$a);Xl($Re(),$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 zRe;(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"})(zRe||(Zc.Status=zRe={}));var GRe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(GRe||(Zc.LogVerbosity=GRe={}));var JRe;(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"})(JRe||(Zc.Propagate=JRe={}));Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var KW=_(($In,fDt)=>{fDt.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 XW,ZW,QW,e7;Object.defineProperty(hc,"__esModule",{value:!0});hc.log=hc.setLoggerVerbosity=hc.setLogger=hc.getLogger=void 0;hc.trace=IDt;hc.isTracerEnabled=WRe;var Uh=Yt(),pDt=require("process"),hDt=KW().version,mDt={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},Ey=mDt,nS=Uh.LogVerbosity.ERROR,gDt=(ZW=(XW=process.env.GRPC_NODE_VERBOSITY)!==null&&XW!==void 0?XW:process.env.GRPC_VERBOSITY)!==null&&ZW!==void 0?ZW:"";switch(gDt.toUpperCase()){case"DEBUG":nS=Uh.LogVerbosity.DEBUG;break;case"INFO":nS=Uh.LogVerbosity.INFO;break;case"ERROR":nS=Uh.LogVerbosity.ERROR;break;case"NONE":nS=Uh.LogVerbosity.NONE;break;default:}var yDt=()=>Ey;hc.getLogger=yDt;var vDt=e=>{Ey=e};hc.setLogger=vDt;var bDt=e=>{nS=e};hc.setLoggerVerbosity=bDt;var SDt=(e,...t)=>{let n;if(e>=nS){switch(e){case Uh.LogVerbosity.DEBUG:n=Ey.debug;break;case Uh.LogVerbosity.INFO:n=Ey.info;break;case Uh.LogVerbosity.ERROR:n=Ey.error;break}n||(n=Ey.error),n&&n.bind(Ey)(...t)}};hc.log=SDt;var _Dt=(e7=(QW=process.env.GRPC_NODE_TRACE)!==null&&QW!==void 0?QW:process.env.GRPC_TRACE)!==null&&e7!==void 0?e7:"",t7=new Set,HRe=new Set;for(let e of _Dt.split(","))e.startsWith("-")?HRe.add(e.substring(1)):t7.add(e);var wDt=t7.has("all");function IDt(e,t,n){WRe(t)&&(0,hc.log)(e,new Date().toISOString()+" | v"+hDt+" "+pDt.pid+" | "+t+" | "+n)}function WRe(e){return!HRe.has(e)&&(wDt||t7.has(e))}});var GM=_(zM=>{"use strict";Object.defineProperty(zM,"__esModule",{value:!0});zM.getErrorMessage=xDt;zM.getErrorCode=EDt;function xDt(e){return e instanceof Error?e.message:String(e)}function EDt(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ma=_(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.Metadata=void 0;var TDt=hr(),kDt=Yt(),ODt=GM(),ADt=/^[:0-9a-z_.-]+$/,PDt=/^[ -~]*$/;function RDt(e){return ADt.test(e)}function CDt(e){return PDt.test(e)}function YRe(e){return e.endsWith("-bin")}function NDt(e){return!e.startsWith("grpc-")}function JM(e){return e.toLowerCase()}function jRe(e,t){if(!RDt(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(YRe(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(!CDt(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var n7=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=JM(t),jRe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=JM(t),jRe(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(MDt));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{YRe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(NDt(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,ODt.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,TDt.log)(kDt.LogVerbosity.ERROR,s)}}return n}};HM.Metadata=n7;var MDt=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var jM=_(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0});WM.CallCredentials=void 0;var s7=ma();function DDt(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var rS=class e{static createFromMetadataGenerator(t){return new i7(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;DDt(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 s7.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new a7}};WM.CallCredentials=rS;var r7=class e extends rS{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new s7.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}},i7=class e extends rS{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 r7([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},a7=class e extends rS{generateMetadata(t){return Promise.resolve(new s7.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var c7=_(WT=>{"use strict";Object.defineProperty(WT,"__esModule",{value:!0});WT.CIPHER_SUITES=void 0;WT.getDefaultRootsData=BDt;var UDt=require("fs");WT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var KRe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,o7=null;function BDt(){return KRe?(o7===null&&(o7=UDt.readFileSync(KRe)),o7):null}});var no=_(iS=>{"use strict";Object.defineProperty(iS,"__esModule",{value:!0});iS.parseUri=LDt;iS.splitHostPort=VDt;iS.combineHostPort=qDt;iS.uriToString=$Dt;var FDt=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function LDt(e){let t=FDt.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var XRe=/^\d+$/;function VDt(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 XRe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?XRe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function qDt(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function $Dt(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=zDt;dp.registerDefaultScheme=GDt;dp.createResolver=JDt;dp.getDefaultAuthority=HDt;dp.mapUriDefaultScheme=WDt;var u7=no();dp.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var aS={},l7=null;function zDt(e,t){aS[e]=t}function GDt(e){l7=e}function JDt(e,t,n){if(e.scheme!==void 0&&e.scheme in aS)return new aS[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,u7.uriToString)(e)}`)}function HDt(e){if(e.scheme!==void 0&&e.scheme in aS)return aS[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,u7.uriToString)(e)}`)}function WDt(e){return e.scheme===void 0||!(e.scheme in aS)?l7!==null?{scheme:l7,authority:void 0,path:(0,u7.uriToString)(e)}:null:e}});var sS=_(YT=>{"use strict";Object.defineProperty(YT,"__esModule",{value:!0});YT.ChannelCredentials=void 0;YT.createCertificateProviderChannelCredentials=XDt;var jT=require("tls"),XM=jM(),f7=c7(),ZRe=no(),jDt=Zl(),YDt=hr(),KDt=Yt();function d7(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var Ty=class{compose(t){return new m7(this,t)}static createSsl(t,n,r,a){var i;if(d7(t,"Root certificate"),d7(n,"Private key"),d7(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,jT.createSecureContext)({ca:(i=t??(0,f7.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:f7.CIPHER_SUITES});return new YM(s,a??{})}static createFromSecureContext(t,n){return new YM(t,n??{})}static createInsecure(){return new p7}};YT.ChannelCredentials=Ty;var p7=class e extends Ty{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??XM.CallCredentials.createEmpty(),destroy(){}}}};function QRe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,ZRe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,jDt.getDefaultAuthority)(o),l=(0,ZRe.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:jT.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 h7=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,jT.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(){}},YM=class e extends Ty{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=QRe(this.secureContext,this.verifyOptions,t,n);return new h7(a,r??XM.CallCredentials.createEmpty())}},KM=class e extends Ty{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??XM.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,jT.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:f7.CIPHER_SUITES})}catch(r){return(0,YDt.log)(KDt.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};KM.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=QRe(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,jT.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 XDt(e,t,n){return new KM(e,t,n??{})}var m7=class e extends Ty{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??XM.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Fh=_(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.createChildChannelControlHelper=e3t;Td.registerLoadBalancerType=t3t;Td.registerDefaultLoadBalancerType=n3t;Td.createLoadBalancer=r3t;Td.isLoadBalancerNameRegistered=i3t;Td.parseLoadBalancingConfig=eCe;Td.getDefaultConfig=a3t;Td.selectLbConfigFromList=s3t;var ZDt=hr(),QDt=Yt();function e3t(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={},KT=null;function t3t(e,t,n){Bh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function n3t(e){KT=e}function r3t(e,t){let n=e.getLoadBalancerName();return n in Bh?new Bh[n].LoadBalancer(t):null}function i3t(e){return e in Bh}function eCe(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 a3t(){if(!KT)throw new Error("No default load balancer type registered");return new Bh[KT].LoadBalancingConfig}function s3t(e,t=!1){for(let n of e)try{return eCe(n)}catch(r){(0,ZDt.log)(QDt.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&KT?new Bh[KT].LoadBalancingConfig:null}});var g7=_(XT=>{"use strict";Object.defineProperty(XT,"__esModule",{value:!0});XT.validateRetryThrottling=tCe;XT.validateServiceConfig=nCe;XT.extractAndSelectServiceConfig=g3t;var o3t=require("os"),ZM=Yt(),QM=/^\d+(\.\d{1,9})?s$/,c3t="node";function l3t(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 u3t(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"||!QM.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"||!QM.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(ZM.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(ZM.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 d3t(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"||!QM.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(ZM.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(ZM.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 f3t(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(l3t(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"&&QM.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=u3t(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=d3t(e.hedgingPolicy));return n}function tCe(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 p3t(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 nCe(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(p3t(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(f3t(r));"retryThrottling"in e&&(t.retryThrottling=tCe(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 h3t(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:nCe(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 m3t(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=h3t(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===o3t.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===c3t&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function g3t(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 m3t(a,t)}return null}});var ro=_(eD=>{"use strict";Object.defineProperty(eD,"__esModule",{value:!0});eD.ConnectivityState=void 0;var rCe;(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"})(rCe||(eD.ConnectivityState=rCe={}))});var fp=_(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.QueuePicker=Lh.UnavailablePicker=Lh.PickResultType=void 0;var y3t=ma(),v3t=Yt(),tD;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(tD||(Lh.PickResultType=tD={}));var y7=class{constructor(t){this.status=Object.assign({code:v3t.Status.UNAVAILABLE,details:"No connection established",metadata:new y3t.Metadata},t)}pick(t){return{pickResultType:tD.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Lh.UnavailablePicker=y7;var v7=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:tD.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Lh.QueuePicker=v7});var oS=_(rD=>{"use strict";Object.defineProperty(rD,"__esModule",{value:!0});rD.BackoffTimeout=void 0;var b3t=Yt(),S3t=hr(),_3t="backoff",w3t=1e3,I3t=1.6,x3t=12e4,E3t=.2;function T3t(e,t){return Math.random()*(t-e)+e}var nD=class e{constructor(t,n){this.callback=t,this.initialDelay=w3t,this.multiplier=I3t,this.maxDelay=x3t,this.jitter=E3t,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){S3t.trace(b3t.LogVerbosity.DEBUG,_3t,"{"+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+T3t(-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}};rD.BackoffTimeout=nD;nD.nextId=0});var aD=_(iD=>{"use strict";Object.defineProperty(iD,"__esModule",{value:!0});iD.ChildLoadBalancerHandler=void 0;var k3t=Fh(),O3t=ro(),A3t="child_load_balancer_helper",b7=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===O3t.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,k3t.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 A3t}};iD.ChildLoadBalancerHandler=b7});var sCe=_(sD=>{"use strict";Object.defineProperty(sD,"__esModule",{value:!0});sD.ResolvingLoadBalancer=void 0;var P3t=Fh(),R3t=g7(),No=ro(),iCe=Zl(),ZT=fp(),C3t=oS(),S7=Yt(),N3t=ma(),M3t=hr(),D3t=Yt(),U3t=no(),B3t=aD(),F3t="resolving_load_balancer";function aCe(e){M3t.trace(D3t.LogVerbosity.DEBUG,F3t,e)}var L3t=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function V3t(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 q3t(e,t,n,r){for(let a of n)if(V3t(e,t,a,r))return a;return null}function $3t(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 L3t){let l=q3t(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:S7.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:S7.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var _7=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=No.ConnectivityState.IDLE,this.latestChildPicker=new ZT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,R3t.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(No.ConnectivityState.IDLE,new ZT.QueuePicker(this),null),this.childLoadBalancer=new B3t.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(aCe("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,iCe.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 C3t.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,P3t.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:S7.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new N3t.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[iCe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:$3t(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===No.ConnectivityState.IDLE&&this.updateState(No.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){aCe((0,U3t.uriToString)(this.target)+" "+No.ConnectivityState[this.currentState]+" -> "+No.ConnectivityState[t]),t===No.ConnectivityState.IDLE&&(n=new ZT.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===No.ConnectivityState.IDLE&&(this.updateState(No.ConnectivityState.TRANSIENT_FAILURE,new ZT.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===No.ConnectivityState.IDLE||this.currentState===No.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=No.ConnectivityState.IDLE,this.latestChildPicker=new ZT.QueuePicker(this),this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};sD.ResolvingLoadBalancer=_7});var oCe=_(QT=>{"use strict";Object.defineProperty(QT,"__esModule",{value:!0});QT.recognizedOptions=void 0;QT.channelOptionsEqual=z3t;QT.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 z3t(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 Mo=_(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.EndpointMap=void 0;Ql.isTcpSubchannelAddress=tk;Ql.subchannelAddressEqual=oD;Ql.subchannelAddressToString=lCe;Ql.stringToSubchannelAddress=J3t;Ql.endpointEqual=H3t;Ql.endpointToString=W3t;Ql.endpointHasAddress=uCe;var cCe=require("net");function tk(e){return"port"in e}function oD(e,t){return!e&&!t?!0:!e||!t?!1:tk(e)?tk(t)&&e.host===t.host&&e.port===t.port:!tk(t)&&e.path===t.path}function lCe(e){return tk(e)?(0,cCe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var G3t=443;function J3t(e,t){return(0,cCe.isIP)(e)?{host:e,port:t??G3t}:{path:e}}function H3t(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!oD(e.addresses[n],t.addresses[n]))return!1;return!0}function W3t(e){return"["+e.addresses.map(lCe).join(", ")+"]"}function uCe(e,t){for(let n of e.addresses)if(oD(n,t))return!0;return!1}function ek(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(oD(n,a)){r=!0;break}if(!r)return!1}return!0}var w7=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(uCe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)ek(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(ek(t,n.key))return n.value}set(t,n){for(let r of this.map)if(ek(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(ek(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(ek(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=w7});var dCe=_(P7=>{"use strict";Object.defineProperty(P7,"t",{value:!0});var cD=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}},I7=class extends cD{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)}},x7=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},E7=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},T7=class extends E7{};function ky(){throw new RangeError("Iterator access denied!")}var k7=class extends T7{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?I7:cD,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&&ky(),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&&ky();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)}},O7=class extends x7{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&ky(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&ky(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&ky(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&ky(),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 O7{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&ky();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)}},A7=class extends k7{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]}}};P7.OrderedMap=A7});var uD=_(lD=>{"use strict";Object.defineProperty(lD,"__esModule",{value:!0});lD.registerAdminService=j3t;lD.addAdminServicesToServer=Y3t;var fCe=[];function j3t(e,t){fCe.push({getServiceDefinition:e,getHandlers:t})}function Y3t(e){for(let{getServiceDefinition:t,getHandlers:n}of fCe)e.addService(t(),n())}});var pCe=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.ClientDuplexStreamImpl=tu.ClientWritableStreamImpl=tu.ClientReadableStreamImpl=tu.ClientUnaryCallImpl=void 0;tu.callErrorFromStatus=X3t;var K3t=require("events"),D7=require("stream"),nk=Yt();function X3t(e,t){let n=`${e.code} ${nk.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 R7=class extends K3t.EventEmitter{constructor(){super()}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(nk.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=R7;var C7=class extends D7.Readable{constructor(t){super({objectMode:!0}),this.deserialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(nk.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=C7;var N7=class extends D7.Writable{constructor(t){super({objectMode:!0}),this.serialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(nk.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=N7;var M7=class extends D7.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(nk.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=M7});var Ay=_(Oy=>{"use strict";Object.defineProperty(Oy,"__esModule",{value:!0});Oy.InterceptingListenerImpl=void 0;Oy.statusOrFromValue=Q3t;Oy.statusOrFromError=eUt;Oy.isInterceptingListener=tUt;var Z3t=ma();function Q3t(e){return{ok:!0,value:e}}function eUt(e){var t;return{ok:!1,error:Object.assign(Object.assign({},e),{metadata:(t=e.metadata)!==null&&t!==void 0?t:new Z3t.Metadata})}}function tUt(e){return e.onReceiveMetadata!==void 0&&e.onReceiveMetadata.length===1}var U7=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)})}};Oy.InterceptingListenerImpl=U7});var z7=_(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.InterceptingCall=nu.RequesterBuilder=nu.ListenerBuilder=nu.InterceptorConfigurationError=void 0;nu.getInterceptingCall=aUt;var nUt=ma(),hCe=Ay(),mCe=Yt(),gCe=GM(),ik=class e extends Error{constructor(t){super(t),this.name="InterceptorConfigurationError",Error.captureStackTrace(this,e)}};nu.InterceptorConfigurationError=ik;var F7=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=F7;var L7=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=L7;var B7={onReceiveMetadata:(e,t)=>{t(e)},onReceiveMessage:(e,t)=>{t(e)},onReceiveStatus:(e,t)=>{t(e)}},rk={start:(e,t,n)=>{n(e,t)},sendMessage:(e,t)=>{t(e)},halfClose:e=>{e()},cancel:e=>{e()}},V7=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:rk.start,sendMessage:(a=n.sendMessage)!==null&&a!==void 0?a:rk.sendMessage,halfClose:(i=n.halfClose)!==null&&i!==void 0?i:rk.halfClose,cancel:(s=n.cancel)!==null&&s!==void 0?s:rk.cancel}:this.requester=rk}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,hCe.isInterceptingListener)(d))y=d;else{let b={onReceiveMetadata:(f=d.onReceiveMetadata)!==null&&f!==void 0?f:B7.onReceiveMetadata,onReceiveMessage:(p=d.onReceiveMessage)!==null&&p!==void 0?p:B7.onReceiveMessage,onReceiveStatus:(m=d.onReceiveStatus)!==null&&m!==void 0?m:B7.onReceiveStatus};y=new hCe.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=V7;function rUt(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 dD=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(mCe.Status.INTERNAL,`Request message serialization failure: ${(0,gCe.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:mCe.Status.INTERNAL,details:`Response message parsing error: ${(0,gCe.getErrorMessage)(o)}`,metadata:new nUt.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()}},q7=class extends dD{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()}},$7=class extends dD{};function iUt(e,t,n){let r=rUt(e,n.path,t);return n.responseStream?new $7(r,n):new q7(r,n)}function aUt(e,t,n,r){if(e.clientInterceptors.length>0&&e.clientInterceptorProviders.length>0)throw new ik("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 ik("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=>iUt(r,o,t))(i)}});var H7=_(pD=>{"use strict";Object.defineProperty(pD,"__esModule",{value:!0});pD.Client=void 0;var kd=pCe(),sUt=W7(),oUt=ro(),Vh=Yt(),cS=ma(),fD=z7(),ru=Symbol(),lS=Symbol(),uS=Symbol(),pp=Symbol();function G7(e){return typeof e=="function"}function dS(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 av(this.#e,a.id,{isV2:!0});n=r.sandboxes[r.sandboxes.length-1].createdAt}}},L9e=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]}};av=class z9e{#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=U9e(RWt(this.#e.cpClient,this.sandboxId))),this.#t}get stdout(){if(this.#f("stdout"),!this.#n){this.#a=new AbortController;let t=LU(HHe(this.#e.cpClient,this.sandboxId,1,this.#a.signal),()=>this.#a?.abort());this.#n=Cw(t.pipeThrough(new TextDecoderStream))}return this.#n}get stderr(){if(this.#f("stderr"),!this.#r){this.#s=new AbortController;let t=LU(HHe(this.#e.cpClient,this.sandboxId,2,this.#s.signal),()=>this.#s?.abort());this.#r=Cw(t.pipeThrough(new TextDecoderStream))}return this.#r}get filesystem(){return this.#i(),this.#m||(this.#m=new M9e((t,n)=>this.#y(t,n))),this.#m}get experimentalSidecars(){return this.#i(),this.#g||(this.#g=new mWt({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(),q9e(t),HU(n?.env??{});let[a,i]=PX(n?.secrets??[]);Object.assign(a,n?.env??{}),await Fw(this.#e,i);let s={...n,env:a,secrets:i},[o,c]=await this.#o(),l=rv(),u=kWt(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 PWt(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 BU}#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<z9e.#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,RX.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 j8t.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 BU;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=Nw(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 T6t;this.#u={};for(let r of n.tunnels)this.#u[r.containerPort]=new L9e(r.host,r.port,r.unencryptedHost,r.unencryptedPort);return this.#u}async snapshotFilesystem(t){this.#i();let n=GHe(t?.ttlMs),r=t?.timeoutMs||55e3,[a,i]=await this.#o(),s=HX.create({taskId:a,snapshotId:rv(),ttlSeconds:n}),o=await i.snapshotFilesystem(s,{timeoutMs:r});if(!o.imageId)throw new Error("Sandbox snapshot filesystem response missing `imageId`");return new dv(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=OWt(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=WX.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=GX.create({taskId:n,networkAccess:oo.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(zX.create({taskId:r}),{timeoutMs:n})}async snapshotDirectory(t,n){this.#i();let r=GHe(n?.ttlMs),a=n?.timeoutMs||55e3,[i,s]=await this.#o(),o=AWt(i,t,rv(),r,n),c=await s.snapshotDirectory(o,{timeoutMs:a});if(!c.imageId)throw new Error("Sandbox snapshot directory response missing `imageId`");return new dv(this.#e,c.imageId,"")}async poll(){this.#i();let t=await this.#v(0);return Nw(t.result)}},PWt=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=U9e(CWt(n,e,t));let c=s==="ignore"?ReadableStream.from([]):LU(WHe(n,e,t,1,this.#r)),l=o==="ignore"?ReadableStream.from([]):LU(WHe(n,e,t,2,this.#r));i==="text"?(this.stdout=Cw(c.pipeThrough(new TextDecoderStream)),this.stderr=Cw(l.pipeThrough(new TextDecoderStream))):(this.stdout=Cw(c),this.stderr=Cw(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 W9e=_((MOn,H9e)=>{H9e.exports=require("events")});var Y9e=_((UOn,j9e)=>{j9e.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 YX=_((FOn,X9e)=>{var K9e=Y9e();X9e.exports=class{constructor(t){this.hwm=t||16,this.head=new K9e(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 K9e(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 Lw=_((LOn,Z9e)=>{function NWt(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function MWt(e){return Buffer.isEncoding(e)}function DWt(e,t,n){return Buffer.alloc(e,t,n)}function UWt(e){return Buffer.allocUnsafe(e)}function BWt(e){return Buffer.allocUnsafeSlow(e)}function FWt(e,t){return Buffer.byteLength(e,t)}function LWt(e,t){return Buffer.compare(e,t)}function VWt(e,t){return Buffer.concat(e,t)}function qWt(e,t,n,r,a){return cr(e).copy(t,n,r,a)}function $Wt(e,t){return cr(e).equals(t)}function zWt(e,t,n,r,a){return cr(e).fill(t,n,r,a)}function GWt(e,t,n){return Buffer.from(e,t,n)}function JWt(e,t,n,r){return cr(e).includes(t,n,r)}function HWt(e,t,n,r){return cr(e).indexOf(t,n,r)}function WWt(e,t,n,r){return cr(e).lastIndexOf(t,n,r)}function jWt(e){return cr(e).swap16()}function YWt(e){return cr(e).swap32()}function KWt(e){return cr(e).swap64()}function cr(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function XWt(e,t,n,r){return cr(e).toString(t,n,r)}function ZWt(e,t,n,r,a){return cr(e).write(t,n,r,a)}function QWt(e,t){return cr(e).readDoubleBE(t)}function e7t(e,t){return cr(e).readDoubleLE(t)}function t7t(e,t){return cr(e).readFloatBE(t)}function n7t(e,t){return cr(e).readFloatLE(t)}function r7t(e,t){return cr(e).readInt32BE(t)}function i7t(e,t){return cr(e).readInt32LE(t)}function a7t(e,t){return cr(e).readUInt32BE(t)}function s7t(e,t){return cr(e).readUInt32LE(t)}function o7t(e,t,n){return cr(e).writeDoubleBE(t,n)}function c7t(e,t,n){return cr(e).writeDoubleLE(t,n)}function l7t(e,t,n){return cr(e).writeFloatBE(t,n)}function u7t(e,t,n){return cr(e).writeFloatLE(t,n)}function d7t(e,t,n){return cr(e).writeInt32BE(t,n)}function f7t(e,t,n){return cr(e).writeInt32LE(t,n)}function p7t(e,t,n){return cr(e).writeUInt32BE(t,n)}function h7t(e,t,n){return cr(e).writeUInt32LE(t,n)}Z9e.exports={isBuffer:NWt,isEncoding:MWt,alloc:DWt,allocUnsafe:UWt,allocUnsafeSlow:BWt,byteLength:FWt,compare:LWt,concat:VWt,copy:qWt,equals:$Wt,fill:zWt,from:GWt,includes:JWt,indexOf:HWt,lastIndexOf:WWt,swap16:jWt,swap32:YWt,swap64:KWt,toBuffer:cr,toString:XWt,write:ZWt,readDoubleBE:QWt,readDoubleLE:e7t,readFloatBE:t7t,readFloatLE:n7t,readInt32BE:r7t,readInt32LE:i7t,readUInt32BE:a7t,readUInt32LE:s7t,writeDoubleBE:o7t,writeDoubleLE:c7t,writeFloatBE:l7t,writeFloatLE:u7t,writeInt32BE:d7t,writeInt32LE:f7t,writeUInt32BE:p7t,writeUInt32LE:h7t}});var eKe=_((qOn,Q9e)=>{var m7t=Lw();Q9e.exports=class{constructor(t){this.encoding=t}get remaining(){return 0}decode(t){return m7t.toString(t,this.encoding)}flush(){return""}}});var nKe=_((zOn,tKe)=>{var g7t=Lw();tKe.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 g7t.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 iKe=_((JOn,rKe)=>{var y7t=eKe(),v7t=nKe();rKe.exports=class{constructor(t="utf8"){switch(this.encoding=b7t(t),this.encoding){case"utf8":this.decoder=new v7t;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new y7t(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 b7t(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 dZ=_((HOn,kKe)=>{var{EventEmitter:S7t}=W9e(),eB=new Error("Stream was destroyed"),KX=new Error("Premature close"),uKe=YX(),_7t=iKe(),XX=typeof queueMicrotask>"u"?e=>global.process.nextTick(e):queueMicrotask,si=(1<<29)-1,ef=1,iZ=2,vv=4,fO=8,dKe=si^ef,w7t=si^iZ,yO=16,Vw=32,zw=64,ym=128,vO=256,aZ=512,bv=1024,ZX=2048,sZ=4096,oZ=8192,zu=16384,gm=32768,tB=65536,Sv=131072,fKe=vO|aZ,I7t=yO|tB,x7t=zw|yO,E7t=sZ|ym,cZ=vO|Sv,T7t=si^yO,k7t=si^zw,O7t=si^(zw|tB),aKe=si^tB,A7t=si^vO,P7t=si^(ym|oZ),R7t=si^bv,sKe=si^fKe,pKe=si^gm,C7t=si^Vw,hKe=si^Sv,N7t=si^cZ,Mp=1<<18,$w=2<<18,bO=4<<18,_v=8<<18,SO=16<<18,vm=32<<18,QX=64<<18,qw=128<<18,lZ=256<<18,wv=512<<18,nB=1024<<18,M7t=si^(Mp|lZ),mKe=si^bO,D7t=si^(Mp|wv),U7t=si^SO,B7t=si^_v,gKe=si^qw,F7t=si^$w,yKe=si^nB,pO=yO|Mp,vKe=si^pO,uZ=zu|vm,tf=vv|fO|iZ,_c=tf|ef,bKe=tf|uZ,L7t=mKe&k7t,rB=qw|gm,V7t=rB&vKe,SKe=_c|V7t,q7t=_c|bv|zu,oKe=_c|zu|ym,$7t=_c|bv|ym,z7t=_c|sZ|ym|oZ,G7t=_c|yO|bv|zu|tB|Sv,J7t=tf|bv|zu,H7t=Vw|_c|gm|zw,W7t=gm|ef,j7t=_c|wv|vm,Y7t=_v|SO,_Ke=_v|Mp,K7t=_v|SO|_c|Mp,cKe=_c|Mp|_v|nB,X7t=bO|Mp,Z7t=Mp|lZ,Q7t=_c|wv|_Ke|vm,e5t=SO|tf|wv|vm,t5t=$w|_c|qw|bO,n5t=wv|vm|tf,YU=Symbol.asyncIterator||Symbol("asyncIterator"),KU=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapWritable:a,byteLength:i,byteLengthWritable:s}={}){this.stream=t,this.queue=new uKe,this.highWaterMark=n,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=s||i||TKe,this.map=a||r,this.afterWrite=a5t.bind(this),this.afterUpdateNextTick=c5t.bind(this)}get ended(){return(this.stream._duplexState&vm)!==0}push(t){return this.stream._duplexState&n5t?!1:(this.map!==null&&(t=this.map(t)),this.buffered+=this.byteLength(t),this.queue.push(t),this.buffered<this.highWaterMark?(this.stream._duplexState|=_v,!0):(this.stream._duplexState|=Y7t,!1))}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=B7t),t}end(t){typeof t=="function"?this.stream.once("finish",t):t!=null&&this.push(t),this.stream._duplexState=(this.stream._duplexState|wv)&mKe}autoBatch(t,n){let r=[],a=this.stream;for(r.push(t);(a._duplexState&cKe)===_Ke;)r.push(a._writableState.shift());if(a._duplexState&_c)return n(null);a._writev(r,n)}update(){let t=this.stream;t._duplexState|=$w;do{for(;(t._duplexState&cKe)===_v;){let n=this.shift();t._duplexState|=Z7t,t._write(n,this.afterWrite)}t._duplexState&X7t||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=F7t}updateNonPrimary(){let t=this.stream;if((t._duplexState&Q7t)===wv){t._duplexState=t._duplexState|Mp,t._final(i5t.bind(this));return}if((t._duplexState&tf)===vv){t._duplexState&rB||(t._duplexState|=pO,t._destroy(wKe.bind(this)));return}(t._duplexState&SKe)===ef&&(t._duplexState=(t._duplexState|pO)&dKe,t._open(IKe.bind(this)))}continueUpdate(){return this.stream._duplexState&qw?(this.stream._duplexState&=gKe,!0):!1}updateCallback(){(this.stream._duplexState&t5t)===bO?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&qw||(this.stream._duplexState|=qw,this.stream._duplexState&$w||XX(this.afterUpdateNextTick))}},eZ=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapReadable:a,byteLength:i,byteLengthReadable:s}={}){this.stream=t,this.queue=new uKe,this.highWaterMark=n===0?1:n,this.buffered=0,this.readAhead=n>0,this.error=null,this.pipeline=null,this.byteLength=s||i||TKe,this.map=a||r,this.pipeTo=null,this.afterRead=s5t.bind(this),this.afterUpdateNextTick=o5t.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|=aZ,this.pipeTo=t,this.pipeline=new nZ(this.stream,t,n),n&&this.stream.on("error",lKe),gO(t))t._writableState.pipeline=this.pipeline,n&&t.on("error",lKe),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",r5t.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|bv)&O7t,!1):this.map!==null&&(t=this.map(t),t===null)?(n._duplexState&=aKe,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(t),this.queue.push(t),n._duplexState=(n._duplexState|ym)&aKe,this.buffered<this.highWaterMark)}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=P7t),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&oKe)===ym){let n=this.shift();return this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=sKe),t._duplexState&ZX&&t.emit("data",n),n}return this.readAhead===!1&&(t._duplexState|=Sv,this.updateNextTick()),null}drain(){let t=this.stream;for(;(t._duplexState&oKe)===ym&&t._duplexState&fKe;){let n=this.shift();this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=sKe),t._duplexState&ZX&&t.emit("data",n)}}update(){let t=this.stream;t._duplexState|=Vw;do{for(this.drain();this.buffered<this.highWaterMark&&(t._duplexState&G7t)===Sv;)t._duplexState|=I7t,t._read(this.afterRead),this.drain();(t._duplexState&z7t)===E7t&&(t._duplexState|=oZ,t.emit("readable")),t._duplexState&x7t||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=C7t}updateNonPrimary(){let t=this.stream;if((t._duplexState&$7t)===bv&&(t._duplexState=(t._duplexState|zu)&R7t,t.emit("end"),(t._duplexState&bKe)===uZ&&(t._duplexState|=vv),this.pipeTo!==null&&this.pipeTo.end()),(t._duplexState&tf)===vv){t._duplexState&rB||(t._duplexState|=pO,t._destroy(wKe.bind(this)));return}(t._duplexState&SKe)===ef&&(t._duplexState=(t._duplexState|pO)&dKe,t._open(IKe.bind(this)))}continueUpdate(){return this.stream._duplexState&gm?(this.stream._duplexState&=pKe,!0):!1}updateCallback(){(this.stream._duplexState&H7t)===zw?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&W7t||(this.stream._duplexState|=gm,this.stream._duplexState&Vw||XX(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&gm||(this.stream._duplexState|=gm,this.stream._duplexState&Vw||XX(this.afterUpdateNextTick))}},tZ=class{constructor(t){this.data=null,this.afterTransform=u5t.bind(t),this.afterFinal=null}},nZ=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 r5t(){this.stream._duplexState|=aZ,this.updateCallback()}function i5t(e){let t=this.stream;e&&t.destroy(e),t._duplexState&tf||(t._duplexState|=vm,t.emit("finish")),(t._duplexState&bKe)===uZ&&(t._duplexState|=vv),t._duplexState&=D7t,t._duplexState&$w?this.updateNextTick():this.update()}function wKe(e){let t=this.stream;!e&&this.error!==eB&&(e=this.error),e&&t.emit("error",e),t._duplexState|=fO,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 a5t(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=M7t,this.drains!==null&&l5t(this.drains),(t._duplexState&K7t)===SO&&(t._duplexState&=U7t,(t._duplexState&QX)===QX&&t.emit("drain")),this.updateCallback()}function s5t(e){e&&this.stream.destroy(e),this.stream._duplexState&=T7t,this.readAhead===!1&&!(this.stream._duplexState&vO)&&(this.stream._duplexState&=hKe),this.updateCallback()}function o5t(){this.stream._duplexState&Vw||(this.stream._duplexState&=pKe,this.update())}function c5t(){this.stream._duplexState&$w||(this.stream._duplexState&=gKe,this.update())}function l5t(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function IKe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&vv||(t._duplexState&q7t||(t._duplexState|=zw),t._duplexState&j7t||(t._duplexState|=bO),t.emit("open")),t._duplexState&=vKe,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function u5t(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function d5t(e){this._readableState!==null&&(e==="data"&&(this._duplexState|=ZX|cZ,this._readableState.updateNextTick()),e==="readable"&&(this._duplexState|=sZ,this._readableState.updateNextTick())),this._writableState!==null&&e==="drain"&&(this._duplexState|=QX,this._writableState.updateNextTick())}var hO=class extends S7t{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",_5t.bind(this))),this.on("newListener",d5t)}_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&fO)!==0}get destroying(){return(this._duplexState&tf)!==0}destroy(t){this._duplexState&tf||(t||(t=eB),this._duplexState=(this._duplexState|vv)&L7t,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=t),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=t),this._duplexState|=iZ,this._predestroy(),this._duplexState&=w7t,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},XU=class e extends hO{constructor(t){super(t),this._duplexState|=ef|vm|Sv,this._readableState=new eZ(this,t),t&&(this._readableState.readAhead===!1&&(this._duplexState&=hKe),t.read&&(this._read=t.read),t.eagerOpen&&this._readableState.updateNextTick(),t.encoding&&this.setEncoding(t.encoding))}setEncoding(t){let n=new _7t(t),r=this._readableState.map||h5t;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|=cZ,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?N7t:A7t,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(v5t(t))return t;if(t[YU])return this._fromAsyncIterator(t[YU](),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&J7t)!==0||t._readableState.buffered>=t._readableState.highWaterMark}static isPaused(t){return(t._duplexState&vO)===0}[YU](){let t=this,n=null,r=null,a=null;return this.on("error",l=>{n=l}),this.on("readable",i),this.on("close",s),{[YU](){return this},next(){return new Promise(function(l,u){r=l,a=u;let d=t.read();d!==null?o(d):t._duplexState&fO&&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(eB):r({value:l,done:l===null}),a=r=null)}function c(l){return t.destroy(l),new Promise((u,d)=>{if(t._duplexState&fO)return u({value:void 0,done:!0});t.once("close",function(){l?d(l):u({value:void 0,done:!0})})})}}},ZU=class extends hO{constructor(t){super(t),this._duplexState|=ef|zu,this._writableState=new KU(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|=nB}uncork(){this._duplexState&=yKe,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&e5t)!==0}static drained(t){if(t.destroyed)return Promise.resolve(!1);let n=t._writableState,a=(w5t(t)?Math.min(1,n.queue.length):n.queue.length)+(t._duplexState&lZ?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}},mO=class extends XU{constructor(t){super(t),this._duplexState=ef|this._duplexState&Sv,this._writableState=new KU(this,t),t&&(t.writev&&(this._writev=t.writev),t.write&&(this._write=t.write),t.final&&(this._final=t.final))}cork(){this._duplexState|=nB}uncork(){this._duplexState&=yKe,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}},QU=class extends mO{constructor(t){super(t),this._transformState=new tZ(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(f5t.bind(this))}},rZ=class extends QU{};function f5t(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function p5t(...e){return new Promise((t,n)=>xKe(...e,r=>{if(r)return n(r);t()}))}function xKe(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],gO(a)?a.pipe(i,c):(o(a,!0,l>1,c),a.pipe(i)),a=i;if(r){let l=!1,u=gO(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:KX)))}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(KX)}}function c(l){if(!(!l||s)){s=l;for(let u of n)u.destroy(l)}}}function h5t(e){return e}function EKe(e){return!!e._readableState||!!e._writableState}function gO(e){return typeof e._duplexState=="number"&&EKe(e)}function m5t(e){return!!e._readableState&&e._readableState.ended}function g5t(e){return!!e._writableState&&e._writableState.ended}function y5t(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===eB?null:n}function v5t(e){return gO(e)&&e.readable}function b5t(e){return(e._duplexState&ef)!==ef||(e._duplexState&rB)!==0}function S5t(e){return typeof e=="object"&&e!==null&&typeof e.byteLength=="number"}function TKe(e){return S5t(e)?e.byteLength:1024}function lKe(){}function _5t(){this.destroy(new Error("Stream aborted."))}function w5t(e){return e._writev!==ZU.prototype._writev&&e._writev!==mO.prototype._writev}kKe.exports={pipeline:xKe,pipelinePromise:p5t,isStream:EKe,isStreamx:gO,isEnded:m5t,isFinished:g5t,isDisturbed:b5t,getStreamError:y5t,Stream:hO,Writable:ZU,Readable:XU,Duplex:mO,Transform:QU,PassThrough:rZ}});var hZ=_(Jw=>{var Pn=Lw(),I5t="0000000000000000000",x5t="7777777777777777777",iB=48,OKe=Pn.from([117,115,116,97,114,0]),E5t=Pn.from([iB,iB]),T5t=Pn.from([117,115,116,97,114,32]),k5t=Pn.from([32,0]),O5t=4095,_O=257,pZ=263;Jw.decodeLongPath=function(t,n){return Gw(t,0,t.length,n)};Jw.encodePax=function(t){let n="";t.name&&(n+=fZ(" path="+t.name+`
251
251
  `)),t.linkname&&(n+=fZ(" linkpath="+t.linkname+`
252
252
  `));let r=t.pax;if(r)for(let a in r)n+=fZ(" "+a+"="+r[a]+`
253
- `);return Pn.from(n)};Jw.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};Jw.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&O5t,6),100),Pn.write(n,Sm(t.uid,6),108),Pn.write(n,Sm(t.gid,6),116),D5t(t.size,n,124),Pn.write(n,Sm(t.mtime.getTime()/1e3|0,11),136),n[156]=iB+N5t(t.type),t.linkname&&Pn.write(n,t.linkname,157),Pn.copy(OKe,n,_O),Pn.copy(E5t,n,pZ),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(PKe(n),6),148),n)};Jw.decode=function(t,n,r){let a=t[156]===0?0:t[156]-iB,i=Gw(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=C5t(a),f=t[157]===0?null:Gw(t,157,100,n),p=Gw(t,265,32),m=Gw(t,297,32),y=bm(t,329,8),b=bm(t,337,8),v=PKe(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(A5t(t))t[345]&&(i=Gw(t,345,155,n)+"/"+i);else if(!P5t(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 A5t(e){return Pn.equals(OKe,e.subarray(_O,_O+6))}function P5t(e){return Pn.equals(T5t,e.subarray(_O,_O+6))&&Pn.equals(k5t,e.subarray(pZ,pZ+2))}function R5t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function C5t(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 N5t(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 AKe(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function PKe(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?x5t.slice(0,t)+" ":I5t.slice(0,t-e.length)+e+" "}function M5t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function D5t(e,t,n){e.toString(8).length>11?M5t(e,t,n):Pn.write(t,Sm(e,11),n)}function U5t(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 U5t(e);{for(;t<e.length&&e[t]===32;)t++;let r=R5t(AKe(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 Gw(e,t,n,r){return Pn.toString(e.subarray(t,AKe(e,0,t,t+n)),r)}function fZ(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 DKe=_((jOn,MKe)=>{var{Writable:B5t,Readable:F5t,getStreamError:RKe}=dZ(),L5t=YX(),CKe=Lw(),Hw=hZ(),V5t=CKe.alloc(0),gZ=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new L5t,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 V5t;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 CKe.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)}},yZ=class extends F5t{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(RKe(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=NKe(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},vZ=class extends B5t{constructor(t){super(t),t||(t={}),this._buffer=new gZ,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=mZ,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=Hw.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=Hw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=Hw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=Hw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?Hw.decodePax(t):Object.assign({},this._paxGlobal,Hw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=NKe(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 yZ(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=mZ,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(RKe(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",mZ),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})})})}}};MKe.exports=function(t){return new vZ(t)};function mZ(){}function NKe(e){return e&=511,e&&512-e}});var BKe=_((YOn,bZ)=>{var UKe={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{bZ.exports=require("fs").constants||UKe}catch{bZ.exports=UKe}});var $Ke=_((KOn,qKe)=>{var{Readable:q5t,Writable:$5t,getStreamError:FKe}=dZ(),Iv=Lw(),Ww=BKe(),aB=hZ(),z5t=493,G5t=420,LKe=Iv.alloc(1024),_Z=class extends $5t{constructor(t,n,r){super({mapWritable:H5t,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?Iv.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?Iv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),VKe(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 FKe(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()}},wZ=class extends q5t{constructor(t){super(t),this._drain=SZ,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=SZ),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=J5t(t.mode)),t.mode||(t.mode=t.type==="directory"?z5t:G5t),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=Iv.from(n));let a=new _Z(this,t,r);return Iv.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(LKe),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=aB.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=aB.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(aB.encode(r)),this.push(n),VKe(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(aB.encode(r))}_doDrain(){let t=this._drain;this._drain=SZ,t()}_predestroy(){let t=FKe(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()}};qKe.exports=function(t){return new wZ(t)};function J5t(e){switch(e&Ww.S_IFMT){case Ww.S_IFBLK:return"block-device";case Ww.S_IFCHR:return"character-device";case Ww.S_IFDIR:return"directory";case Ww.S_IFIFO:return"fifo";case Ww.S_IFLNK:return"symlink"}return"file"}function SZ(){}function VKe(e,t){t&=511,t&&e.push(LKe.subarray(0,512-t))}function H5t(e){return Iv.isBuffer(e)?e:Iv.from(e)}});var xZ=_(IZ=>{IZ.extract=DKe();IZ.pack=$Ke()});var pXe={};Ju(pXe,{EVOLVE_IMAGE_VERSION:()=>cB,MODAL_MAX_LIFETIME_MS:()=>CZ,MODAL_MAX_LIST_SANDBOXES:()=>PZ,MODAL_STDIN_CHUNK_BYTES:()=>IO,ModalBootCommandError:()=>rXe,ModalCommands:()=>uXe,ModalFiles:()=>dXe,ModalIdleTimeoutError:()=>TZ,ModalNetworkPolicyError:()=>AZ,ModalProvider:()=>DZ,ModalResourcesError:()=>OZ,ModalSandboxLifetimeError:()=>eXe,ModalVolumeError:()=>lB,SandboxFeatureUnsupportedError:()=>xv,SandboxNotRunningError:()=>KKe,SandboxPathNotFoundError:()=>sB,_testBuildSandboxInfo:()=>Sjt,_testCollectSandboxes:()=>_jt,_testDynamicNetworkPolicyParams:()=>gjt,_testImageMap:()=>hjt,_testMapBootCommand:()=>xjt,_testMapIdleTimeout:()=>Ijt,_testMapNetworkPolicy:()=>mjt,_testMapResources:()=>vjt,_testMapVolumeMounts:()=>Ejt,_testModalSandboxImplCtor:()=>Tjt,_testRequiresDynamicNetwork:()=>yjt,_testResolveImageRegistry:()=>bjt,_testValidateTimeout:()=>wjt,_testWrapCommand:()=>pjt,createModalProvider:()=>dB,isSandboxFeatureUnsupportedError:()=>W5t,isSandboxNotRunningError:()=>Y5t,isSandboxPathNotFoundError:()=>j5t});function RZ(e,t){return!!e&&typeof e=="object"&&e.name===t}function W5t(e){return RZ(e,"SandboxFeatureUnsupportedError")}function j5t(e){return RZ(e,"SandboxPathNotFoundError")}function Y5t(e){return RZ(e,"SandboxNotRunningError")}function K5t(e){return`'${e.replace(/'/g,"'\\''")}'`}function X5t(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 Z5t(e){if(typeof e=="number")return JKe((e&4095).toString(8));if(/^[0-7]{1,4}$/.test(e))return JKe(e);throw new RangeError(`not an octal mode: ${e}`)}function JKe(e){return e.padStart(4,"0")}function Q5t(e){let t=e&wO.constants.S_IFMT;return t===wO.constants.S_IFDIR?"dir":t===wO.constants.S_IFLNK?"symlink":t===wO.constants.S_IFREG?"file":"other"}function ejt(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*tjt(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 tXe(e){if(e>CZ)throw new eXe(e)}function nXe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new TZ(e,"it must be a positive number of milliseconds");if(e>CZ)throw new TZ(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function iXe(e){if(e===void 0)return{};if(e.length===0)throw new rXe(`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 aXe(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith("/")||n==="/")throw new lB("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 lB("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 kZ(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 sXe(e){if(e?.disk!==void 0)throw new OZ(`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 OZ("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??njt,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):rjt,...t!==void 0?{gpu:t}:{}}}function oXe(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 ijt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!oXe(e)}function ajt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function sjt(e){return/^[^:]+:\d+$/.test(e)}function NZ(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(oXe(a))n.push(a.includes("/")?a:`${a}/32`);else{if(ijt(a))throw new AZ("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(ajt(a))n.push(a.includes("/")?a:`${a}/128`);else{if(sjt(a))throw new AZ("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 uB(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=NZ(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:cjt(t.outboundDomainAllowlist??[])}}function cjt(e){return e.length>0?e:[ojt]}function cXe(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 lXe(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 MZ(e,t,n){let{[ZKe]:r,[QKe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}function HKe(e){let t=Q5t(e.mode),n={name:e.name,path:e.path,type:t,size:e.size,mtime:ejt(e.modifiedTime),mode:Z5t(e.permissions),owner:e.owner,group:e.group};return t==="symlink"&&e.symlinkTarget!==null&&(n.target=e.symlinkTarget),n}function WKe(e){return!!e&&typeof e=="object"&&e.name==="SandboxFilesystemNotFoundError"}function ujt(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 fXe(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>=PZ)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${PZ} sandboxes`};let a=await r.getTags();n.push(MZ(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 dB(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 DZ({...e,tokenId:t,tokenSecret:n})}var YKe,wO,xv,sB,KKe,zKe,GKe,cB,XKe,CZ,IO,EZ,ZKe,QKe,eXe,TZ,rXe,lB,OZ,njt,rjt,AZ,ojt,PZ,uXe,dXe,ljt,djt,jKe,fjt,oB,DZ,pjt,hjt,mjt,gjt,yjt,vjt,bjt,Sjt,_jt,wjt,Ijt,xjt,Ejt,Tjt,fB=Q(()=>{"use strict";J9e();YKe=Ve(xZ(),1),wO=require("fs"),xv=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}},sB=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}},KKe=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}};zKe=2,GKe=21;cB="c-880c264ce574",XKe={[`evolve-all-${cB}`]:`evolvingmachines/evolve-all:${cB}`,"evolve-all":"evolvingmachines/evolve-all"},CZ=1440*60*1e3,IO=8*1024*1024;EZ="user",ZKe="evolve.image",QKe="evolve.startedAt",eXe=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}};TZ=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};rXe=class extends Error{constructor(e){super(`Modal bootCommand is invalid: ${e}`),this.name="ModalBootCommandError"}};lB=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}};OZ=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},njt=4,rjt=4096;AZ=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};ojt="sealed.invalid";PZ=1e4,uXe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=kZ(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=kZ(e,this.user,t?.cwd,t?.envs,{sameSession:n}),a=n?["bash","-c",fjt,"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 xv("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)};Jw.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};Jw.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&O5t,6),100),Pn.write(n,Sm(t.uid,6),108),Pn.write(n,Sm(t.gid,6),116),D5t(t.size,n,124),Pn.write(n,Sm(t.mtime.getTime()/1e3|0,11),136),n[156]=iB+N5t(t.type),t.linkname&&Pn.write(n,t.linkname,157),Pn.copy(OKe,n,_O),Pn.copy(E5t,n,pZ),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(PKe(n),6),148),n)};Jw.decode=function(t,n,r){let a=t[156]===0?0:t[156]-iB,i=Gw(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=C5t(a),f=t[157]===0?null:Gw(t,157,100,n),p=Gw(t,265,32),m=Gw(t,297,32),y=bm(t,329,8),b=bm(t,337,8),v=PKe(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(A5t(t))t[345]&&(i=Gw(t,345,155,n)+"/"+i);else if(!P5t(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 A5t(e){return Pn.equals(OKe,e.subarray(_O,_O+6))}function P5t(e){return Pn.equals(T5t,e.subarray(_O,_O+6))&&Pn.equals(k5t,e.subarray(pZ,pZ+2))}function R5t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function C5t(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 N5t(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 AKe(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function PKe(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?x5t.slice(0,t)+" ":I5t.slice(0,t-e.length)+e+" "}function M5t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function D5t(e,t,n){e.toString(8).length>11?M5t(e,t,n):Pn.write(t,Sm(e,11),n)}function U5t(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 U5t(e);{for(;t<e.length&&e[t]===32;)t++;let r=R5t(AKe(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 Gw(e,t,n,r){return Pn.toString(e.subarray(t,AKe(e,0,t,t+n)),r)}function fZ(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 DKe=_((jOn,MKe)=>{var{Writable:B5t,Readable:F5t,getStreamError:RKe}=dZ(),L5t=YX(),CKe=Lw(),Hw=hZ(),V5t=CKe.alloc(0),gZ=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new L5t,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 V5t;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 CKe.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)}},yZ=class extends F5t{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(RKe(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=NKe(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},vZ=class extends B5t{constructor(t){super(t),t||(t={}),this._buffer=new gZ,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=mZ,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=Hw.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=Hw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=Hw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=Hw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?Hw.decodePax(t):Object.assign({},this._paxGlobal,Hw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=NKe(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 yZ(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=mZ,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(RKe(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",mZ),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})})})}}};MKe.exports=function(t){return new vZ(t)};function mZ(){}function NKe(e){return e&=511,e&&512-e}});var BKe=_((YOn,bZ)=>{var UKe={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{bZ.exports=require("fs").constants||UKe}catch{bZ.exports=UKe}});var $Ke=_((KOn,qKe)=>{var{Readable:q5t,Writable:$5t,getStreamError:FKe}=dZ(),Iv=Lw(),Ww=BKe(),aB=hZ(),z5t=493,G5t=420,LKe=Iv.alloc(1024),_Z=class extends $5t{constructor(t,n,r){super({mapWritable:H5t,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?Iv.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?Iv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),VKe(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 FKe(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()}},wZ=class extends q5t{constructor(t){super(t),this._drain=SZ,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=SZ),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=J5t(t.mode)),t.mode||(t.mode=t.type==="directory"?z5t:G5t),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=Iv.from(n));let a=new _Z(this,t,r);return Iv.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(LKe),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=aB.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=aB.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(aB.encode(r)),this.push(n),VKe(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(aB.encode(r))}_doDrain(){let t=this._drain;this._drain=SZ,t()}_predestroy(){let t=FKe(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()}};qKe.exports=function(t){return new wZ(t)};function J5t(e){switch(e&Ww.S_IFMT){case Ww.S_IFBLK:return"block-device";case Ww.S_IFCHR:return"character-device";case Ww.S_IFDIR:return"directory";case Ww.S_IFIFO:return"fifo";case Ww.S_IFLNK:return"symlink"}return"file"}function SZ(){}function VKe(e,t){t&=511,t&&e.push(LKe.subarray(0,512-t))}function H5t(e){return Iv.isBuffer(e)?e:Iv.from(e)}});var xZ=_(IZ=>{IZ.extract=DKe();IZ.pack=$Ke()});var pXe={};Ju(pXe,{EVOLVE_IMAGE_VERSION:()=>cB,MODAL_MAX_LIFETIME_MS:()=>CZ,MODAL_MAX_LIST_SANDBOXES:()=>PZ,MODAL_STDIN_CHUNK_BYTES:()=>IO,ModalBootCommandError:()=>rXe,ModalCommands:()=>uXe,ModalFiles:()=>dXe,ModalIdleTimeoutError:()=>TZ,ModalNetworkPolicyError:()=>AZ,ModalProvider:()=>DZ,ModalResourcesError:()=>OZ,ModalSandboxLifetimeError:()=>eXe,ModalVolumeError:()=>lB,SandboxFeatureUnsupportedError:()=>xv,SandboxNotRunningError:()=>KKe,SandboxPathNotFoundError:()=>sB,_testBuildSandboxInfo:()=>Sjt,_testCollectSandboxes:()=>_jt,_testDynamicNetworkPolicyParams:()=>gjt,_testImageMap:()=>hjt,_testMapBootCommand:()=>xjt,_testMapIdleTimeout:()=>Ijt,_testMapNetworkPolicy:()=>mjt,_testMapResources:()=>vjt,_testMapVolumeMounts:()=>Ejt,_testModalSandboxImplCtor:()=>Tjt,_testRequiresDynamicNetwork:()=>yjt,_testResolveImageRegistry:()=>bjt,_testValidateTimeout:()=>wjt,_testWrapCommand:()=>pjt,createModalProvider:()=>dB,isSandboxFeatureUnsupportedError:()=>W5t,isSandboxNotRunningError:()=>Y5t,isSandboxPathNotFoundError:()=>j5t});function RZ(e,t){return!!e&&typeof e=="object"&&e.name===t}function W5t(e){return RZ(e,"SandboxFeatureUnsupportedError")}function j5t(e){return RZ(e,"SandboxPathNotFoundError")}function Y5t(e){return RZ(e,"SandboxNotRunningError")}function K5t(e){return`'${e.replace(/'/g,"'\\''")}'`}function X5t(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 Z5t(e){if(typeof e=="number")return JKe((e&4095).toString(8));if(/^[0-7]{1,4}$/.test(e))return JKe(e);throw new RangeError(`not an octal mode: ${e}`)}function JKe(e){return e.padStart(4,"0")}function Q5t(e){let t=e&wO.constants.S_IFMT;return t===wO.constants.S_IFDIR?"dir":t===wO.constants.S_IFLNK?"symlink":t===wO.constants.S_IFREG?"file":"other"}function ejt(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*tjt(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 tXe(e){if(e>CZ)throw new eXe(e)}function nXe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new TZ(e,"it must be a positive number of milliseconds");if(e>CZ)throw new TZ(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function iXe(e){if(e===void 0)return{};if(e.length===0)throw new rXe(`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 aXe(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith("/")||n==="/")throw new lB("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 lB("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 kZ(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 sXe(e){if(e?.disk!==void 0)throw new OZ(`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 OZ("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??njt,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):rjt,...t!==void 0?{gpu:t}:{}}}function oXe(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 ijt(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!oXe(e)}function ajt(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function sjt(e){return/^[^:]+:\d+$/.test(e)}function NZ(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(oXe(a))n.push(a.includes("/")?a:`${a}/32`);else{if(ijt(a))throw new AZ("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(ajt(a))n.push(a.includes("/")?a:`${a}/128`);else{if(sjt(a))throw new AZ("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 uB(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=NZ(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:cjt(t.outboundDomainAllowlist??[])}}function cjt(e){return e.length>0?e:[ojt]}function cXe(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 lXe(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 MZ(e,t,n){let{[ZKe]:r,[QKe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}function HKe(e){let t=Q5t(e.mode),n={name:e.name,path:e.path,type:t,size:e.size,mtime:ejt(e.modifiedTime),mode:Z5t(e.permissions),owner:e.owner,group:e.group};return t==="symlink"&&e.symlinkTarget!==null&&(n.target=e.symlinkTarget),n}function WKe(e){return!!e&&typeof e=="object"&&e.name==="SandboxFilesystemNotFoundError"}function ujt(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 fXe(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>=PZ)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${PZ} sandboxes`};let a=await r.getTags();n.push(MZ(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 dB(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 DZ({...e,tokenId:t,tokenSecret:n})}var YKe,wO,xv,sB,KKe,zKe,GKe,cB,XKe,CZ,IO,EZ,ZKe,QKe,eXe,TZ,rXe,lB,OZ,njt,rjt,AZ,ojt,PZ,uXe,dXe,ljt,djt,jKe,fjt,oB,DZ,pjt,hjt,mjt,gjt,yjt,vjt,bjt,Sjt,_jt,wjt,Ijt,xjt,Ejt,Tjt,fB=Q(()=>{"use strict";J9e();YKe=Ve(xZ(),1),wO=require("fs"),xv=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}},sB=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}},KKe=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}};zKe=2,GKe=21;cB="c-4bfce70a407f",XKe={[`evolve-all-${cB}`]:`evolvingmachines/evolve-all:${cB}`,"evolve-all":"evolvingmachines/evolve-all"},CZ=1440*60*1e3,IO=8*1024*1024;EZ="user",ZKe="evolve.image",QKe="evolve.startedAt",eXe=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}};TZ=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};rXe=class extends Error{constructor(e){super(`Modal bootCommand is invalid: ${e}`),this.name="ModalBootCommandError"}};lB=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}};OZ=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},njt=4,rjt=4096;AZ=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};ojt="sealed.invalid";PZ=1e4,uXe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=kZ(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=kZ(e,this.user,t?.cwd,t?.envs,{sameSession:n}),a=n?["bash","-c",fjt,"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 xv("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 xv("commands.connect","modal","the Modal SDK cannot attach to a process by id")}async sendStdin(e,t){throw new xv("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}}},dXe=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+=IO)await e.writeBytes(t.subarray(n,n+IO))}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>=IO&&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,YKe.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=>HKe(t))}catch(t){throw WKe(t)?new sB(e,"modal"):t}}async stat(e){try{return HKe(await this.sandbox.filesystem.stat(e))}catch(t){throw WKe(t)?new sB(e,"modal"):t}}async readRange(e,t){if(X5t(t),t.length===0)return new Uint8Array(0);let n=K5t(e),r=`[ -e ${n} ] || exit ${zKe}; [ -d ${n} ] && exit ${GKe}; 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 ${djt} ] || exit "\${s[0]}"`,a=await this.sandbox.exec(["bash","-c",r],{mode:"binary",timeoutMs:jKe}),i=await a.stdout.readBytes(),s=await a.wait();if(s===zKe)throw new sB(e,"modal");if(s===GKe)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:jKe,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,tjt(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:IO}));await this.writeStream(e,a)}async uploadUrl(e,t){throw new xv("files.uploadUrl","modal","Modal issues no signed upload URLs")}async downloadUrl(e,t){throw new xv("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:[...ljt]})[Symbol.asyncIterator](),a=!1;return(async()=>{for(;;){let{done:i,value:s}=await r.next();if(i||a)break;for(let o of ujt(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}`)}};ljt=["Create","Modify","Remove"];djt=141,jKe=3e5,fjt=["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("; "),oB=class{constructor(e,t,n){this.sandbox=e,this.commands=new uXe(e,n),this.files=new dXe(e,n),this.image=t}commands;files;image;get sandboxId(){return this.sandbox.sandboxId}async metrics(){throw new xv("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 MZ(this.sandbox.sandboxId,e,this.image)}async updateNetwork(e){await this.sandbox.updateNetworkPolicy(uB(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.")}},DZ=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 I9e({tokenId:e.tokenId,tokenSecret:e.tokenSecret}),this.appName=e.appName??"evolve-sandbox",this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.imageName=e.imageName??`evolve-all-${cB}`,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=lXe(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=XKe[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;tXe(t);let n=nXe(e.idleTimeoutMs),r=iXe(e.bootCommand),a=aXe(e.volumes);for(let b of e.phaseNetworkPolicies??[])uB(b);let i=cXe(e.network,e.phaseNetworkPolicies)?uB(e.network):NZ(e.network),s=sXe(e.resources),o=e.user??EZ,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,[ZKe]:l,[QKe]: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 oB(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 lB(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)??EZ;return new oB(n,void 0,r)}async inspect(e,t){let n=await this.attachSandbox(e),r=await n.poll();if(r!==null)throw new KKe(e,"modal",`exited with code ${r}`);let a=t?.user??this.sandboxUsers.get(e)??EZ;return new oB(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 fXe(()=>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}}}};pjt=kZ,hjt=XKe,mjt=NZ,gjt=uB,yjt=cXe,vjt=sXe,bjt=lXe,Sjt=MZ,_jt=fXe,wjt=tXe,Ijt=nXe,xjt=iXe,Ejt=aXe,Tjt=oB});var _Xe={};Ju(_Xe,{MAX_INLINE_ARCHIVE_BYTES:()=>SXe,crc32Fallback:()=>vXe,extractTarGz:()=>Bjt,shouldStore:()=>yXe,tarGzTopLevelName:()=>Fjt,tarGzipDirectory:()=>Ujt,tarGzipDirectoryToFile:()=>bXe});async function Ojt(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(kjt.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 yXe(e,t){if(t<Ajt)return!1;let n=await(0,Ya.open)(e,"r"),r;try{let a=Buffer.allocUnsafe(hXe),{bytesRead:i}=await n.read(a,0,hXe,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 vXe(e,t=0){let n=~t;for(let r=0;r<e.length;r++)n=Cjt[(n^e[r])&255]^n>>>8;return~n>>>0}async function Djt(e){let t=Symbol("pending"),n=await Promise.race([e,Promise.resolve(t)]);return n===t?null:n}async function bXe(e,t){let n=await Ojt(e),r=(0,xO.pack)(),a=(0,Tv.createWriteStream)(t);a.on("error",()=>{}),r.on("error",()=>{});let i=new Mjt(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 yXe(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,Ev.pipeline)((0,Tv.createReadStream)(u),p),y=!1,b=null;for(m.then(()=>{},()=>{}).then(()=>{y=!0,b?.(mXe)});;){if(!y){let S=await new Promise((w,I)=>{b=w,c().then(w,I)});if(b=null,S===mXe)continue;if(o=null,S.done)break;await i.write(S.value);continue}await new Promise(S=>setImmediate(S));let v=await Djt(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,Ev.finished)(a)}catch(l){throw o?.catch(()=>{}),r.destroy(),a.destroy(),l}}async function Ujt(e,t=SXe){let n=await(0,Ya.mkdtemp)((0,Dp.join)((0,gXe.tmpdir)(),"evolve-tar-"));try{let r=(0,Dp.join)(n,"archive.tar.gz");await bXe(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 Bjt(e,t,n){let r=(0,xO.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,Ev.pipeline)(s,(0,Tv.createWriteStream)(l)),a.push(c.join("/"))}})();try{await Promise.all([(0,Ev.pipeline)((0,Tv.createReadStream)(e),(0,nf.createGunzip)(),r),i])}catch(s){throw r.destroy(),s}return a}async function Fjt(e){let t=(0,xO.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,Ev.pipeline)((0,Tv.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,Tv,Ya,gXe,Dp,Ev,xO,kjt,Ajt,hXe,Pjt,Rjt,UZ,Cjt,Njt,Mjt,mXe,SXe,wXe=Q(()=>{"use strict";nf=Ve(require("zlib"),1),Tv=require("fs"),Ya=require("fs/promises"),gXe=require("os"),Dp=require("path"),Ev=require("stream/promises"),xO=Ve(xZ(),1),kjt=new Set([".git",".DS_Store",".venv"]);Ajt=64*1024,hXe=128*1024,Pjt=65535,Rjt=1024*1024,UZ=32*1024;Cjt=(()=>{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})(),Njt=nf.default.crc32??vXe,Mjt=class pB{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(pB.HEADER)),this.held.push(t),this.heldBytes+=t.length,await this.drainHeld(!1)}async close(){this.started||(this.started=!0,await this.out(pB.HEADER)),await this.drainHeld(!0),await this.out(pB.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?Pjt:Rjt;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=Njt(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>=UZ?Buffer.from(t.subarray(t.length-UZ)):this.window?Buffer.concat([this.window,t]).subarray(-UZ):Buffer.from(t)}out(t){return new Promise((n,r)=>{this.sink.write(t,a=>a==null?n():r(a))})}},mXe=Symbol("feed settled");SXe=256*1024*1024});var TXe={};Ju(TXe,{ManagedModalProvider:()=>$jt,ManagedModalWriteLimitError:()=>IXe,_testManagedModalSandbox:()=>zjt});function Ljt(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 EXe(e){return{sandboxId:e.sandboxId,image:e.image??"",metadata:e.metadata??{},startedAt:e.startedAt??""}}var IXe,xXe,Vjt,qjt,BZ,$jt,zjt,kXe=Q(()=>{"use strict";IXe=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}};xXe=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)}}},Vjt=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(`
@@ -534,7 +534,7 @@ async def list_checkpoints(
534
534
  await store.close()
535
535
 
536
536
 
537
- __version__ = '0.0.59.dev1426'
537
+ __version__ = '0.0.61'
538
538
 
539
539
  __all__ = [
540
540
  # Main classes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolvingmachines-evolve
3
- Version: 0.0.59.dev1426
3
+ Version: 0.0.61
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.59.dev1426"
7
+ version = "0.0.61"
8
8
  description = "Pythonic SDK for multi-agent orchestration in E2B sandboxes"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"