@north-light/cli 0.3.714 → 0.3.715

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 (55) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +2 -2
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/environments.d.ts +4 -0
  6. package/dist/api/dto/execution-start.d.ts +9 -0
  7. package/dist/api/routes.d.ts +1 -0
  8. package/dist/api/routes.js +1 -1
  9. package/dist/clients/attach/viewer.js +3 -3
  10. package/dist/commands/profile/environment.js +2 -2
  11. package/dist/commands/sys/feedback.js +5 -5
  12. package/dist/core/canvas/executions.d.ts +0 -2
  13. package/dist/core/canvas/executions.js +1 -1
  14. package/dist/core/canvas/schema-pg/030-environment-pull-request-write.sql +2 -0
  15. package/dist/core/canvas/schema-version.d.ts +1 -1
  16. package/dist/core/canvas/schema-version.js +1 -1
  17. package/dist/core/environment-recipe.d.ts +1 -0
  18. package/dist/core/environment-recipe.js +1 -1
  19. package/dist/core/ledger/rates.d.ts +0 -2
  20. package/dist/core/ledger/rates.js +1 -1
  21. package/dist/core/runtime/revive.js +2 -2
  22. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  23. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  24. package/dist/core/runtime/runner/types.d.ts +0 -2
  25. package/dist/core/runtime/spawn.js +1 -1
  26. package/dist/daemon/api/handlers/environments.js +1 -1
  27. package/dist/daemon/api/handlers/feedback.d.ts +2 -0
  28. package/dist/daemon/api/handlers/feedback.js +9 -0
  29. package/dist/daemon/api/handlers/git-credential.d.ts +3 -2
  30. package/dist/daemon/api/handlers/git-credential.js +1 -1
  31. package/dist/daemon/api/operations.js +1 -1
  32. package/dist/daemon/api/server.js +1 -1
  33. package/dist/daemon/machine-daemon.js +1 -1
  34. package/dist/daemon/reconcilers/ledger-storage.js +2 -4
  35. package/package.json +3 -3
  36. package/packages/crouter-api/dist/api/client.js +4 -0
  37. package/packages/crouter-api/dist/api/contract.js +1 -1
  38. package/packages/crouter-api/dist/api/routes.js +1 -0
  39. package/packages/crouter-api/dist/commands/profile/environment.js +6 -2
  40. package/packages/crouter-api/dist/commands/sys/feedback.js +12 -2
  41. package/packages/crouter-api/dist/core/canvas/executions.js +2 -3
  42. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  43. package/packages/crouter-api/dist/core/environment-recipe.js +3 -0
  44. package/packages/crouter-api/dist/core/ledger/rates.js +0 -3
  45. package/packages/crouter-api/dist/core/runtime/revive.js +1 -1
  46. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +11 -1
  47. package/packages/crouter-api/dist/core/runtime/runner/types.js +1 -1
  48. package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
  49. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +7 -5
  50. package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
  51. package/packages/crouter-api/package.json +1 -1
  52. package/packages/crouter-identity/package.json +1 -1
  53. package/packages/crouter-plugin/package.json +3 -3
  54. package/runtime.lock.json +14 -14
  55. package/scripts/sandbox-start.mjs +1 -1
@@ -85,8 +85,8 @@ ${i}`);return e.join(`
85
85
  `)||e.includes("\r")||Buffer.byteLength(e,"utf8")+1>vXe?!1:SXe(t,[e])}function _Xe(t,e){if(e.includes(`
86
86
  `)||e.includes("\r"))return!1;let n=Buffer.byteLength(e,"utf8")+1;return n>vXe?!1:(zd!==void 0&&zd.path!==t&&h6(),zd===void 0&&(zd={path:t,records:[],bytes:0},IXe||(process.on("exit",h6),IXe=!0)),zd.path=t,zd.records.push(e),zd.bytes+=n,zd.bytes>=hvn?h6():zd.timer===void 0&&(zd.timer=setTimeout(h6,mvn),zd.timer.unref()),!0)}function h6(){let t=zd;if(!(t===void 0||t.records.length===0)&&(t.timer!==void 0&&clearTimeout(t.timer),zd=void 0,!SXe(t.path,t.records,pvn)))for(let e of t.records)process.stderr.write(`[crtrd] event log append failed: ${e}
87
87
  `)}var vXe,dvn,pvn,hvn,mvn,zd,IXe,xfe=y(()=>{"use strict";vXe=65536,dvn=5*1024*1024,pvn=16*1024*1024,hvn=128*1024,mvn=200;IXe=!1});var bfe,kXe=y(()=>{"use strict";bfe=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"]});function fvn(t){return typeof t=="object"&&t!==null?t:void 0}function TXe(t){return typeof t=="string"?t:""}function RXe(t){if(t instanceof Error){let n={type:t.name||"Error",message:t.message};return typeof t.stack=="string"&&(n.stack=t.stack),t.cause!==void 0&&(n.cause=t.cause instanceof Error?t.cause.message:String(t.cause)),n}if(typeof t=="string")return{type:"Error",message:t};let e=fvn(t);return{type:TXe(e?.name)||"Error",message:TXe(e?.message)||String(t)}}var BXe=y(()=>{"use strict";kXe()});import{AsyncLocalStorage as gvn}from"node:async_hooks";import{randomBytes as Avn}from"node:crypto";function f6(t){if(typeof t!="string"||!yvn.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function Ife(){let t;do t=Avn(16).toString("hex");while(t==="00000000000000000000000000000000");return f6(t)}var yvn,Cfe,DXe,MXe=y(()=>{"use strict";yvn=/^(?!0{32}$)[0-9a-f]{32}$/,Cfe=new gvn;DXe={current:()=>Cfe.getStore(),run:(t,e)=>Cfe.run(f6(t),e),fresh:t=>{let e=Ife();return Cfe.run(e,()=>t(e))}}});function vvn(t){return Buffer.byteLength(t,"utf8")}function g6(t,e,n=128){if(typeof t!="string"||t===""||vvn(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function Svn(t){if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(t))throw new TypeError("ts must be an ISO 8601 timestamp");let e=new Date(t);if(Number.isNaN(e.getTime()))throw new TypeError("ts must be an ISO 8601 timestamp");return e.toISOString()}function _vn(t){if(!Ivn.has(t.class))throw new TypeError("error_class.class is invalid");let e={class:t.class};if(t.status!==void 0){if(!Number.isInteger(t.status))throw new TypeError("error_class.status must be an integer");e.status=t.status}if(t.provider!==void 0&&(e.provider=g6(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!Cvn.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function PXe(t){if(!wvn.has(t.level))throw new TypeError("level is invalid");if(!xvn.has(t.component))throw new TypeError("component is invalid");let e=g6(t.event,"event");if(!Evn.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?DXe.current()??Ife():f6(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():Svn(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=g6(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=g6(t.stream_id,"stream_id")),t.duration_ms!==void 0){if(!Number.isFinite(t.duration_ms)||t.duration_ms<0)throw new TypeError("duration_ms must be finite and non-negative");r.duration_ms=t.duration_ms}if(t.outcome!==void 0){if(!bvn.has(t.outcome))throw new TypeError("outcome is invalid");r.outcome=t.outcome}if(t.attempt!==void 0){if(!Number.isInteger(t.attempt)||t.attempt<=0)throw new TypeError("attempt must be a positive integer");r.attempt=t.attempt}return t.error_class!==void 0&&(r.error_class=_vn(t.error_class)),t.error!==void 0&&(r.error=RXe(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}var Evn,wvn,xvn,bvn,Cvn,Ivn,NXe=y(()=>{"use strict";BXe();MXe();Evn=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,wvn=new Set(["error","warn","info","debug"]),xvn=new Set(["daemon","broker","control-plane","front","sentinel"]),bvn=new Set(["succeeded","failed","skipped"]),Cvn=new Set(["auto","manual","fatal"]),Ivn=new Set(bfe)});function UI(t){return Buffer.byteLength(t,"utf8")}function FI(t,e){if(UI(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-UI(n),i=0,o="";for(let s of t){let a=UI(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function kvn(t){return t===void 0?"[Unsupported undefined]":typeof t=="function"?`[Unsupported function${t.name?` ${t.name}`:""}]`:typeof t=="symbol"?`[Unsupported ${String(t)}]`:`[Unsupported ${t?.constructor?.name??typeof t}]`}function vfe(t,e,n,r){if(r.remaining<=0)return{value:"[Omitted]",altered:!0,dropped:0};if(r.remaining-=1,t===null||typeof t=="boolean")return{value:t,altered:!1,dropped:0};if(typeof t=="string"){let i=FI(t,4096);return{value:i.value,altered:i.altered,dropped:0}}if(typeof t=="number")return Number.isFinite(t)?{value:t,altered:!1,dropped:0}:{value:String(t),altered:!0,dropped:0};if(typeof t=="bigint")return{value:t.toString(),altered:!0,dropped:0};if(t instanceof Date)return{value:Number.isNaN(t.getTime())?"Invalid Date":t.toISOString(),altered:!0,dropped:0};if(typeof t!="object"||t===void 0)return{value:kvn(t),altered:!0,dropped:0};if(n.has(t))return{value:"[Circular]",altered:!0,dropped:0};if(e>=4)return{value:"[Max depth]",altered:!0,dropped:0};n.add(t);try{if(Array.isArray(t)){let u=Math.min(t.length,64),l=[],d=t.length>u,p=t.length-u;for(let h=0;h<u;h+=1){if(r.remaining<=0){d=!0,p+=u-h;break}let m=vfe(t[h],e+1,n,r);l.push(m.value),d||=m.altered,p+=m.dropped}return{value:l,altered:d,dropped:p}}let i;try{i=Object.keys(t).sort()}catch{return{value:"[Unsupported object]",altered:!0,dropped:0}}let o=i.slice(0,64),s={},a=i.length>o.length,c=i.length-o.length;for(let u=0;u<o.length;u+=1){let l=o[u];if(r.remaining<=0){a=!0,c+=o.length-u;break}let d=FI(l,128),p;try{p=vfe(t[l],e+1,n,r)}catch{p={value:"[Unsupported property]",altered:!0,dropped:0}}if(Object.prototype.hasOwnProperty.call(s,d.value)){a=!0,c+=1;continue}s[d.value]=p.value,a||=d.altered||p.altered,c+=p.dropped}return{value:s,altered:a,dropped:c}}finally{n.delete(t)}}function Tvn(t){let e=FI(String(t.type),128),n=FI(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=FI(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=FI(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function A6(t){return JSON.stringify(t)}function CF(t){return UI(A6(t))+1}function LXe(t){let e=t.fields===void 0?void 0:vfe(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:Tvn(t.error),r={v:1,ts:t.ts,level:t.level,event:t.event,component:t.component,operation_id:t.operation_id,...t.node_id===void 0?{}:{node_id:t.node_id},...t.stream_id===void 0?{}:{stream_id:t.stream_id},...t.duration_ms===void 0?{}:{duration_ms:t.duration_ms},...t.outcome===void 0?{}:{outcome:t.outcome},...t.attempt===void 0?{}:{attempt:t.attempt},...t.error_class===void 0?{}:{error_class:t.error_class},...n===void 0?{}:{error:n.value},...e===void 0?{}:{fields:e.value}},i=CF(r),o=e?.altered===!0||n?.altered===!0||i>65536,s=e?.dropped??0;for(o&&Object.assign(r,{record_truncated:!0,original_bytes:i,dropped_fields_count:s});CF(r)>65536&&r.fields!==void 0;){let u=r.fields,l=Object.keys(u);if(l.length===0){delete r.fields;break}l.sort((d,p)=>{let h=UI(A6(u[p]))-UI(A6(u[d]));return h!==0?h:p<d?-1:p>d?1:0}),delete u[l[0]],s+=1,r.record_truncated=!0,r.original_bytes=i,r.dropped_fields_count=s}let a=r.error;CF(r)>65536&&a?.stack!==void 0&&delete a.stack,CF(r)>65536&&a?.cause!==void 0&&delete a.cause,CF(r)>65536&&a!==void 0&&(a.message=FI(a.message,64).value);let c=A6(r);if(UI(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}var QXe=y(()=>{"use strict"});import{AsyncLocalStorage as Rvn}from"node:async_hooks";function FXe(t){Sfe=t}function y6(){return OXe}function E6(){let t=Bvn.getStore();if(t!==void 0)return t;if(OXe)throw new vF;if(Sfe===void 0)throw new IF;return Sfe}var IF,vF,Sfe,OXe,Bvn,JR=y(()=>{"use strict";IF=class extends Error{code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}},vF=class extends Error{code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}},OXe=!1,Bvn=new Rvn});import{existsSync as w6,lstatSync as Pyi,mkdirSync as Dvn,readdirSync as Mvn,readFileSync as $Xe,rmSync as Pvn,statSync as Nvn,symlinkSync as Nyi,writeFileSync as Lvn,cpSync as Lyi,readlinkSync as Qyi,renameSync as Qvn,chmodSync as Ovn,realpathSync as Fvn,closeSync as WXe,fsyncSync as HXe,openSync as GXe,linkSync as Oyi,unlinkSync as Fyi,writeSync as Uyi}from"node:fs";import{dirname as UXe,join as Uvn,relative as Wyi,sep as Hyi}from"node:path";import{homedir as $vn,platform as Wvn}from"node:os";function Jm(t){try{return Fvn(t)}catch{return t}}function qXe(t,e=$vn()){return t==="~"?e:t.startsWith("~/")||Wvn()==="win32"&&t.startsWith("~\\")?Uvn(e,t.slice(2)):t}function x6(t){Dvn(t,{recursive:!0})}function XR(t,e,n){_fe(t,JSON.stringify(e,null,2)+`
88
- `,n)}function Hvn(t){let e=GXe(t,"r");try{HXe(e)}finally{WXe(e)}}function jXe(t){let e=GXe(t,"r");try{HXe(e)}finally{WXe(e)}}function _fe(t,e,n){n?.createParent!==!1&&x6(UXe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(w6(t)?Nvn(t).mode&511:384);try{Lvn(r,e,{mode:i}),Ovn(r,i),n?.durable===!0&&Hvn(r),Qvn(r,t),n?.durable===!0&&jXe(UXe(t))}finally{w6(r)&&Pvn(r,{force:!0})}}function Gvn(t){return JSON.parse($Xe(t,"utf8"))}function $I(t){try{return Gvn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function WI(t){try{return JSON.parse($Xe(t,"utf8"))}catch{return null}}function kfe(t){return w6(t)}function Tfe(t){return w6(t)?Mvn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var Ol=y(()=>{"use strict"});import{homedir as qvn,userInfo as jvn}from"node:os";import{basename as zvn,dirname as Kyi,isAbsolute as Yyi,join as Vd,resolve as zXe}from"node:path";function C6(){let t=zXe(_g()||(process.platform==="linux"?"/":Vd(qvn(),".crouter")));if(Vvn()&&t===Kvn())throw new Error(`refusing to use the account's real crouter root ${t} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return t}function Vvn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function Kvn(){if(b6===void 0)try{b6=zXe(jvn().homedir,".crouter")}catch{b6=null}return b6}function Fl(){return Vd(C6(),"runtime")}function Rfe(){return Vd(C6(),"apps")}function q0(){return Vd(Fl(),"secrets")}function VXe(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=SF(t);return{dir:Vd(n.profiles,e),env:Vd(q0(),"env",zvn(n.root),e),home:n.home}}function Bfe(){return process.platform==="linux"?"/run/crtr":Fl()}function SF(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=Vd(Rfe(),e);return{root:n,profiles:Vd(n,"profiles"),conversations:Vd(n,"conversations"),nodes:Vd(n,"nodes"),files:Vd(n,"files"),home:Vd(n,"home"),cache:Vd(n,"cache")}}var b6,Xm=y(()=>{"use strict";Dc();Kd();JR();Ol()});import{chmodSync as rEi,chownSync as iEi,closeSync as pw,constants as I6,fchmodSync as oEi,fchownSync as sEi,fstatSync as XXe,fsyncSync as aEi,linkSync as cEi,lstatSync as uEi,mkdirSync as lEi,openSync as KXe,readdirSync as dEi,readFileSync as Yvn,readlinkSync as pEi,readSync as hEi,realpathSync as mEi,renameSync as fEi,rmdirSync as gEi,rmSync as AEi,statSync as yEi,symlinkSync as EEi,unlinkSync as wEi,writeSync as xEi}from"node:fs";import{basename as CEi,dirname as IEi,join as vEi,relative as ZXe,resolve as Pfe,sep as YXe}from"node:path";import{loadLinuxNative as Jvn,O_CLOEXEC as Nfe,O_PATH as Lfe,RESOLVE_BENEATH as Xvn,RESOLVE_NO_SYMLINKS as Zvn}from"../../native/linux.js";function eZe(){return Dfe===null&&(Dfe=Jvn()),Dfe}function tSn(t){return t.code}function nSn(t,e){switch(tSn(t)){case"ELOOP":case"EXDEV":return new HI(`path meets a symlink: ${e}`);case"ENXIO":return new HI(`path is not a regular file: ${e}`);case"EAGAIN":return new HI(`path is held by a lease: ${e}`);default:return t}}function Mfe(t,e,n,r,i){try{return t.openat2(e,n,r,eSn)}catch(o){throw nSn(o,i)}}function rSn(t,e,n){let r;try{r=XXe(t)}catch(i){throw pw(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw pw(t),new HI(`path is not a regular file: ${e}`)}function iSn(t,e){let n=ZXe(Pfe(t),Pfe(e));if(n===".."||n.startsWith(`..${YXe}`)||n.startsWith(YXe))throw new Error(`${e} is outside ${t}`);return n}function tZe(t,e,n){if(n&I6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=iSn(t,e),i=eZe();if(!i)return KXe(e,n);let o=KXe("/",JXe),s;try{s=Mfe(i,o,ZXe("/",Pfe(t))||".",JXe,t)}finally{pw(o)}try{return n&Lfe?Mfe(i,s,r||".",n|Nfe,e):rSn(Mfe(i,s,r||".",n|Nfe|I6.O_NONBLOCK,e),e,!0)}finally{pw(s)}}function Qfe(t,e){let n=tZe(t,e,I6.O_RDONLY);try{return Yvn(n)}finally{pw(n)}}function nZe(t,e){if(!eZe())return{path:e,release:()=>{}};let n=tZe(t,e,Lfe),r;try{r=XXe(n)}catch(o){throw pw(n),o}if(!r.isSocket())throw pw(n),new HI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,pw(n))}}}var eSn,JXe,Dfe,HI,_F=y(()=>{"use strict";eSn=Xvn|Zvn,JXe=Lfe|I6.O_DIRECTORY|Nfe,Dfe=null;HI=class extends Error{}});import{join as kg}from"node:path";function Ja(){return Fl()}function rZe(){return kg(Ja(),"on-disk-migration.lock")}function ZR(t){return kg(eB(t),"view.sock")}function oSn(){return kg(Ja(),"nodes")}function iZe(){return kg(Bfe(),"api.sock")}function oZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=sSn}function Ofe(t){if(!oZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function aSn(t){return Ofe(t),kg(oSn(),t)}function cSn(t,e){Ofe(t);let n=e??(Fme()===t?OYe():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return kg(SF(n).nodes,t)}function eB(t){return Ofe(t),process.platform==="linux"?kg(Bfe(),"nodes",t):kg(aSn(t),"run")}function cZe(t,e){return kg(cSn(t,e),"context")}function uZe(t){return kg(eB(t),"job")}var sSn,sZe,aZe,Ul=y(()=>{"use strict";Xm();Dc();_F();sSn=128;sZe="broker-released",aZe="cli-relay-generation"});import{join as uSn}from"node:path";function lSn(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function dSn(t){if(v6===void 0){v6=t;return}if(!lSn(v6,t))throw new Error("event source is already bound for this process")}function lZe(){dSn({component:"daemon",path:uSn(Ja(),"crtrd.log")})}function S6(){return v6}var v6,Ffe=y(()=>{"use strict";Ul()});function dZe(t){return t instanceof sn?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||t.code==="runtime_starting"||t.code==="northlight_unreachable")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}function Ufe(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var sn,hw=y(()=>{"use strict";sn=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}}});var se,$fe=y(()=>{"use strict";se={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonDrain:()=>"/v1/daemon/drain",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,executionStart:t=>`/v1/executions/${t}/start`,executionImportUnpacked:t=>`/v1/executions/${t}/import-unpacked`,environmentGitCredential:t=>`/v1/environments/${t}/git-credential`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeFiles:t=>`/v1/nodes/${t}/files`,nodeFileComplete:(t,e)=>`/v1/nodes/${t}/files/${encodeURIComponent(e)}/complete`,nodeUploads:t=>`/v1/nodes/${t}/uploads`,nodeUploadLink:(t,e)=>`/v1/nodes/${t}/uploads/${encodeURIComponent(e)}/link`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobReport:(t,e)=>`/v1/nodes/${t}/jobs/${e}/report`,nodeJobOutput:(t,e)=>`/v1/nodes/${t}/jobs/${e}/output`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeKick:t=>`/v1/nodes/${t}/kick`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerCycleStart:t=>`/v1/nodes/${t}/broker/cycle-start`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerCycle:t=>`/v1/nodes/${t}/broker/cycle`,nodeBrokerIdle:t=>`/v1/nodes/${t}/broker/idle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeSummaries:t=>`/v1/nodes/${t}/records/summaries`,nodeAttachments:t=>`/v1/nodes/${t}/attachments`,nodeAttachment:(t,e)=>`/v1/nodes/${t}/attachments/${e}`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerStructuredRequest:t=>`/v1/nodes/${t}/broker/structured-request`,nodeBrokerGoal:t=>`/v1/nodes/${t}/broker/goal`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,charges:()=>"/v1/charges",spendLimits:()=>"/v1/spend-limits",spendLimit:t=>`/v1/spend-limits/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",canvasView:t=>`/v1/canvas/view/${encodeURIComponent(t)}`,canvasBrowse:()=>"/v1/canvas/browse",canvasAnalytics:()=>"/v1/canvas/analytics",canvasGraph:()=>"/v1/canvas/graph",canvasPrune:()=>"/v1/canvas/prune",humanReviews:()=>"/v1/human/reviews",humanReview:t=>`/v1/human/reviews/${t}`,humanReviewSubmit:t=>`/v1/human/reviews/${t}/submit`,humanReviewCancel:t=>`/v1/human/reviews/${t}/cancel`,humanReviewDocument:t=>`/v1/human/reviews/${t}/document`,humanReviewComments:t=>`/v1/human/reviews/${t}/comments`,humanReviewCommentEvents:t=>`/v1/human/reviews/${t}/comment-events`,humanComment:t=>`/v1/human/comments/${t}`,humanCommentEdit:t=>`/v1/human/comments/${t}/edit`,humanCommentResolve:t=>`/v1/human/comments/${t}/resolve`,humanCommentReopen:t=>`/v1/human/comments/${t}/reopen`,humanCommentDelete:t=>`/v1/human/comments/${t}/delete`,humanCommentFork:t=>`/v1/human/comments/${t}/fork`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:t=>`/v1/human/inbox/${t}`,humanInboxRespond:t=>`/v1/human/inbox/${t}/respond`,humanInboxProgress:t=>`/v1/human/inbox/${t}/progress`,humanInboxResponse:t=>`/v1/human/inbox/${t}/response`,humanInboxCancel:t=>`/v1/human/inbox/${t}/cancel`,humanInboxFeedbackResolve:(t,e)=>`/v1/human/inbox/${t}/feedback-comments/${e}/resolve`,humanRequests:()=>"/v1/human/requests",humanComponents:()=>"/v1/human/components",humanRequest:t=>`/v1/human/requests/${t}`,humanRequestReplace:t=>`/v1/human/requests/${t}/replace`,humanRequestRespond:t=>`/v1/human/requests/${t}/respond`,humanRequestDismiss:t=>`/v1/human/requests/${t}/dismiss`,humanRequestCancel:t=>`/v1/human/requests/${t}/cancel`,profiles:()=>"/v1/profiles",profile:t=>`/v1/profiles/${t}`,profilePause:t=>`/v1/profiles/${t}/pause`,profileResume:t=>`/v1/profiles/${t}/resume`,profileMetadata:t=>`/v1/profiles/${t}/metadata`,appEnv:()=>"/v1/apps/self/env",appEnvVar:t=>`/v1/apps/self/env/${encodeURIComponent(t)}`,profileEnv:t=>`/v1/profiles/${t}/env`,profileEnvVar:(t,e)=>`/v1/profiles/${t}/env/${e}`,profileEnvironment:t=>`/v1/profiles/${t}/environment`,settings:()=>"/v1/settings",modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthAccount:(t,e)=>`/v1/model-auth/${t}/accounts/${encodeURIComponent(e)}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",exec:()=>"/v1/exec",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectShares:t=>`/v1/objects/${encodeURIComponent(t)}/shares`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",schemas:()=>"/v1/schemas",relations:()=>"/v1/relations",check:()=>"/v1/check",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"}});function hZe(t){pZe=t}function mZe(t){t!==null&&pZe?.(t)}var pZe,Wfe=y(()=>{"use strict"});function _6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Hfe=y(()=>{"use strict"});function fZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Gfe=y(()=>{"use strict"});function gZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var qfe=y(()=>{"use strict"});async function T6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=gSn,retry:i=()=>!0,now:o=Date.now,sleep:s=xZe}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}function tB(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new sn(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}function kr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function GI(t,e){let n=t.status>=200&&t.status<300,r=(await wZe(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new sn(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw Ufe(i)?new sn(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new sn(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function ySn(t){return t==="GET"||t==="HEAD"}async function ESn(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await wZe(t.clone(),Math.min(e??1/0,Date.now()+5e3)),r=JSON.parse(n).error;return r?.origin==="router"&&r.details?.forwarded===!1&&(r.details.runtime_state==="creating"||r.details.runtime_state==="recovering")}catch{return!1}}function wSn(t){return t===429||t>=500}async function jfe(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function wZe(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),tB(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(tB(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function AZe(t){return Math.min(2e3,250*2**(t-1))}function zfe(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function yZe(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function mw(t,e){if(e?.aborted)return new sn(0,"request_aborted","request aborted by caller signal");if(t instanceof sn)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new sn(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new sn(0,"request_aborted","request aborted by caller signal");let n=zfe(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new sn(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new sn(504,"request_timeout",`crtrd request timed out: ${r}`):new sn(503,"transport_error",r)}function xSn(t,e){return t==="GET"||t==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new sn(e.status,e.code,`${e.message}; the ${t} request was sent, so it may or may not have been applied`,{outcome:"unknown"},e.headers)}function EZe(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function k6(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new sn(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=tB(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return xZe(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new sn(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function bSn(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function xZe(t){return new Promise(e=>setTimeout(e,t))}function CSn(t){if(t!==void 0)try{return t()}catch{return}}var pSn,hSn,mSn,fSn,gSn,TF,kF,Tg,ASn,R6=y(()=>{"use strict";hw();$fe();Wfe();Hfe();Gfe();qfe();pSn=3e4,hSn=3e4,mSn=Symbol.for("@north-light/api/local-socket-fetch"),fSn=1e4,gSn=200;TF=2147483647;kF=t=>tB(t??Date.now()),Tg=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??pSn,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[mSn]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??fSn}healthz(){return this.request("GET",se.healthz())}async probeHealthz(e){let n=await this.transport("GET",se.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return GI(n)}async ready(){let e=await this.transport("GET",se.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return GI(e)}status(){return this.request("GET",se.status())}due(){return this.request("GET",se.due())}restartDaemon(){return this.request("POST",se.daemonRestart())}drainDaemon(e={}){let n=e.settle_limit_ms??0;return this.request("POST",se.daemonDrain(),e,{timeout:n+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",se.daemonDrain())}admitDaemon(){return this.request("POST",se.daemonAdmit())}migrateState(e){return this.request("POST",se.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",se.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",se.nodeTelemetry(this.nodePath(e)),n)}async putNodeSummaries(e,n){await this.request("PUT",se.nodeSummaries(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",se.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",kr(se.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}listNodeAttachments(e){return this.request("GET",se.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,n){let r=await this.send("GET",se.nodeAttachment(this.nodePath(e),n));return r.ok||await GI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",se.nodeFiles(this.nodePath(e)),n)}createNodeUpload(e,n){return this.request("POST",se.nodeUploads(this.nodePath(e)),n)}nodeUploadLink(e,n){return this.request("POST",se.nodeUploadLink(this.nodePath(e),n))}completeNodeFile(e,n){return this.request("POST",se.nodeFileComplete(this.nodePath(e),n))}readNodePassiveMessage(e,n){return this.request("GET",kr(se.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",se.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",se.nodes(),e,{timeout:12e4+this.timeoutMs})}listNodes(e){return this.request("GET",kr(se.nodes(),e))}getNode(e){return this.request("GET",se.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",kr(se.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",kr(se.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",kr(se.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await GI(i);return}if(i.body===null)throw new sn(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
89
- `))!==-1;){let d=a.slice(0,l);a=a.slice(l+1),d!==""&&(yield JSON.parse(d))}}if(a+=s.decode(),a.trim()!=="")throw new sn(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,n){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,n):this.request("POST","/v1/structured-requests",e,n)}getStructuredRequest(e,{wait:n=0,budgetMs:r}={}){if(!Number.isInteger(n)||n<0||n>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",kr(`/v1/structured-requests/${this.requestPath(e)}`,{wait:n}),void 0,{budgetMs:r})}cancelStructuredRequest(e,n){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},n)}registerOutcomeDelivery(e,n){return this.request("PUT",se.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",se.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",se.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",se.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,n,r={}){let i=new URLSearchParams;r.tail_lines!==void 0&&i.set("tail_lines",String(r.tail_lines)),r.max_bytes!==void 0&&i.set("max_bytes",String(r.max_bytes));let o=i.size===0?"":`?${i.toString()}`;return this.request("GET",`${se.nodeJobOutput(this.nodePath(e),this.jobPath(n))}${o}`)}stopBashJob(e,n){return this.request("DELETE",se.nodeJob(this.nodePath(e),this.jobPath(n)))}async patchBashJob(e,n,r){await this.request("PATCH",se.nodeJob(this.nodePath(e),this.jobPath(n)),r)}async reportBashJob(e,n,r){await this.request("POST",se.nodeJobReport(this.nodePath(e),this.jobPath(n)),r)}sendMessage(e,n){return this.request("POST",se.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",se.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",se.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",se.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",se.nodeFork(this.nodePath(e)),{})}kickNode(e){return this.request("POST",se.nodeKick(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",se.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",se.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",se.nodeBrokerSessionBound(this.nodePath(e)),n)}cycleStartBroker(e,n,r){return this.request("POST",se.nodeBrokerCycleStart(this.nodePath(e)),n,r)}settleBroker(e,n){return this.request("POST",se.nodeBrokerSettle(this.nodePath(e)),n)}startBrokerCycle(e,n){return this.request("POST",se.nodeBrokerCycle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",se.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",se.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",se.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",se.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",se.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",se.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",se.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",se.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",se.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${se.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",se.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${se.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",se.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",se.executionStart(e))}executionImportUnpacked(e){return this.request("POST",se.executionImportUnpacked(e),{})}gitCredential(e,n){return this.request("POST",se.environmentGitCredential(e),n)}brokerExtensionState(e){return this.request("GET",se.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",se.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",se.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",se.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",se.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",se.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",se.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",se.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",se.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",se.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",se.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",se.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",se.kinds())}patchConfig(e,n){return this.request("PATCH",se.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",se.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",se.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",se.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",se.quarantinedWorktrees())}showLimits(){return this.request("GET",se.limits())}setAppLimits(e,n){return this.request("PUT",se.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(se.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(se.charges(),e))}listSpendLimits(){return this.request("GET",se.spendLimits())}setSpendLimit(e,n){return this.request("PUT",se.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",se.spendLimit(e))}listSpaces(){return this.request("GET",se.spaces())}subscribe(e,n){return this.request("POST",se.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",se.focuses())}focusOf(e){return this.request("GET",kr(se.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(se.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",se.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",se.focus(e),n)}async closeFocus(e){await this.request("DELETE",se.focus(e))}async unsubscribe(e,n){await this.request("DELETE",se.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",se.crons(),e)}listCrons(e){return this.request("GET",kr(se.crons(),e))}showCron(e,n){return this.request("GET",kr(se.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(se.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(se.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(se.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(se.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",se.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",se.nodeAttach(this.nodePath(e)),n??{},{timeout:hSn+this.timeoutMs})}getReports(e,n){return this.request("GET",kr(se.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",kr(se.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",se.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",se.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",kr(se.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",se.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",se.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",kr(se.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",se.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",kr(se.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",se.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",kr(se.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",se.bash(),e,n)}objects={read:(e,n)=>this.request("GET",kr(se.object(e),n)),list:e=>this.request("GET",kr(se.objects(),e)),search:e=>this.request("POST",se.objectsSearch(),e),watch:(e,n={})=>this.request("POST",se.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",kr(se.objectWatch(e),n)),edges:(e,n)=>this.request("GET",kr(se.objectEdges(e),n))};docs={write:e=>this.request("POST",se.docs(),e),edit:(e,n)=>this.request("PATCH",se.doc(e),n),move:(e,n)=>this.request("POST",se.docMove(e),n),delete:e=>this.request("DELETE",se.doc(e)),history:(e,n)=>this.request("GET",kr(se.docHistory(e),n)),lint:(e={})=>this.request("POST",se.docsLint(),e)};documents={browserAccess:()=>this.request("GET",se.documentsBrowserAccess()),reconcilePackages:e=>this.request("POST",se.documentsReconcilePackages(),e)};plugins={appToken:e=>this.request("GET",se.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",se.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",se.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",se.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",se.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",se.profile(e),n??{})}createProfile(e){return this.request("POST",se.profiles(),e)}listProfiles(){return this.request("GET",se.profiles())}updateProfile(e,n){return this.request("PATCH",se.profile(e),n)}listAppEnv(){return this.request("GET",se.appEnv())}setAppEnv(e,n){return this.request("PUT",se.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",se.appEnvVar(e))}listProfileEnv(e){return this.request("GET",se.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",se.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",se.profileEnvVar(e,n))}getProfileEnvironment(e){return this.request("GET",se.profileEnvironment(e))}setProfileEnvironment(e,n){return this.request("PUT",se.profileEnvironment(e),n)}getProfile(e){return this.request("GET",se.profile(e))}pauseProfile(e){return this.request("POST",se.profilePause(e),{})}resumeProfile(e){return this.request("POST",se.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",se.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",se.profile(e),n)}getSettings(){return this.request("GET",se.settings())}putSettings(e){return this.request("PUT",se.settings(),e)}listModelAuth(){return this.request("GET",se.modelAuths())}getModelAuthReadiness(e){return this.request("GET",kr(se.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",se.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",se.modelAuth(e))}patchModelAuthAccount(e,n,r){return this.request("PATCH",se.modelAuthAccount(e,n),r)}removeModelAuthAccount(e,n){return this.request("DELETE",se.modelAuthAccount(e,n))}startModelAuth(e){return this.request("POST",se.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",se.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",se.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",kr(se.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",se.humanReviews(),e)}listReviews(e){return this.request("GET",kr(se.humanReviews(),e))}getReview(e){return this.request("GET",se.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",se.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",se.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",se.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",se.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",kr(se.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",kr(se.humanReviewCommentEvents(this.reviewPath(e)),n))}getReviewComment(e){return this.request("GET",se.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",se.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",se.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",se.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",se.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",se.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",se.humanInbox())}getHumanInboxPage(e){return this.request("GET",se.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,n={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",kr(se.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",se.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",se.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",se.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",se.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",se.humanRequests(),e)}listPageComponents(){return this.request("GET",se.humanComponents())}getHumanRequest(e){return this.request("GET",se.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",se.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",se.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",se.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",se.humanRequestCancel(this.requestPath(e)),n)}resolvePageFeedbackComment(e,n,r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(n)}`);return this.request("POST",se.humanInboxFeedbackResolve(this.ticketId(e),n),{node_id:r})}async dashboard(e){let n=e?.under!==void 0?{under:e.under}:void 0,[r,i]=await Promise.all([this.listNodes(n),this.status()]);return{nodes:r,counts:i.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",se.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",se.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",se.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",se.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",kr(se.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",se.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",se.canvasSnapshot())}analytics(e){return this.request("GET",kr(se.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",se.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",kr(se.canvasLiveRoots(),e))}canvasView(e){return this.request("GET",se.canvasView(e))}canvasRoster(){return this.request("GET",se.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",se.canvasBrowse());return e.ok||await GI(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",se.canvasGraph())}prune(e){return this.request("POST",se.canvasPrune(),e)}async request(e,n,r,i){try{let o=i===void 0?void 0:this.resolveBudget(i),s=await this.send(e,n,r,o);return await GI(s,o?.deadlineAt)}catch(o){throw xSn(e,mw(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw mw(i,r?.signal)}}async send(e,n,r,i={}){let o=this.resolveBudget(i),s=e==="GET"||e==="HEAD"||e==="DELETE",a=o.maxRetries??this.maxRetries,c=Math.min(o.deadlineAt??1/0,Date.now()+ASn);for(let u=0;;u++){let l;try{l=await this.transport(e,n,r,o)}catch(d){if(this.isColdSocketError(d)||this.isInterruptedSocketError(d)){let p=this.availabilityFailure?.();if(p!==void 0)throw p}if(this.isColdSocketError(d))try{await this.handleColdSocket(d,o.deadlineAt),l=await this.transport(e,n,r,o)}catch(p){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!yZe(p,o.signal)?tB(o.deadlineAt):mw(p,o.signal)}else{if(this.isInterruptedSocketError(d)&&this.localSocketTransport&&(!s||u<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&u<a&&!yZe(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await k6(AZe(u+1),o);continue}else throw mw(d,o.signal)}}if(ySn(e)&&a>0&&l.status===503&&await ESn(l,o.deadlineAt)){let d=Math.max(250,(EZe(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await jfe(l,o.deadlineAt),await k6(d,{signal:o.signal});continue}if(s&&u<a&&wSn(l.status)){await jfe(l,o.deadlineAt),await k6(AZe(u+1),o,EZe(l));continue}return l}}resolveBudget(e){let{budgetMs:n,deadlineAt:r,...i}=e;if(n===void 0&&r===void 0)return i;if(n!==void 0&&(!Number.isFinite(n)||n<=0||n>TF))throw new RangeError(`budgetMs must be a positive finite number of at most ${TF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>TF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${TF} ms from now`);return{...i,deadlineAt:Math.min(r??1/0,n===void 0?1/0:Date.now()+n)}}async awaitWithinBudget(e,n){if(n===void 0)return e;let r=n-Date.now();if(r<=0)throw kF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(kF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await GI(await this.transport(e,n,r,o))}catch(s){throw mw(s,o.signal)}}nodePath(e){if(!_6(e))throw new sn(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!fZe(e))throw new sn(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!gZe(e))throw new sn(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!_6(e))throw new sn(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!_6(e))throw new sn(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new sn(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,n,r,i={}){let o=i.deadlineAt===void 0?void 0:i.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(kF(i.deadlineAt));let s=r===void 0?void 0:JSON.stringify(r),a={accept:"application/json",...this.headers,...i.headers};s!==void 0&&(a["content-type"]="application/json");let c=i.timeout??this.timeoutMs,u=o===void 0?c:c>0?Math.min(c,o):o,l=new AbortController,d=o!==void 0&&(c<=0||o<=c),p=u>0?setTimeout(()=>l.abort(d?kF(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,h=i.signal,m=()=>l.abort(h?.reason);h!==void 0&&(h.aborted?l.abort(h.reason):h.addEventListener("abort",m,{once:!0}));let f=()=>{p!==void 0&&clearTimeout(p),h?.removeEventListener("abort",m)};return bSn(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>(mZe(g.headers.get("server-timing")),this.retainRequestLifetime(g,f,()=>l.signal.aborted?l.signal.reason:void 0)),g=>{throw f(),g})}retainRequestLifetime(e,n,r){if(e.body===null)return n(),e;let i=e.body.getReader(),o=!1,s=()=>{o||(o=!0,n())},a=new ReadableStream({async pull(c){try{let{done:u,value:l}=await i.read();u?(s(),c.close()):c.enqueue(l)}catch(u){s(),c.error(r()??u)}},async cancel(c){s(),await i.cancel(c)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){let n=zfe(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=zfe(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw mw(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new sn(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,n,r,i)}catch(o){throw mw(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw kF(n);let i,o;try{await T6({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:s=>s!==i&&s!==o,probe:async s=>{let a=this.availabilityFailure?.();if(a!==void 0)throw o=a,a;let c=this.coldStartFailure?.();if(c!==void 0)throw i=new sn(503,"daemon_unavailable",`crtrd failed to start: ${c}`),i;let u=await this.transport("GET",se.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await jfe(u);return}let l=await u.text();try{if(typeof JSON.parse(l).startup_blocked=="string")return}catch{}throw new sn(u.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${u.status}: ${l.slice(0,500)}`)}})}catch(s){throw s===i&&(this.startupFailureReported=!0),s}}async handleColdSocket(e,n){let r=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;r&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),n));try{await this.awaitAvailability(e,n)}catch(i){if(r&&!this.startupFailureReported){let o=CSn(this.coldStartDiagnostic);if(o!==void 0){let s=mw(i);throw new sn(s.status,s.code,`${s.message}
88
+ `,n)}function Hvn(t){let e=GXe(t,"r");try{HXe(e)}finally{WXe(e)}}function jXe(t){let e=GXe(t,"r");try{HXe(e)}finally{WXe(e)}}function _fe(t,e,n){n?.createParent!==!1&&x6(UXe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(w6(t)?Nvn(t).mode&511:384);try{Lvn(r,e,{mode:i}),Ovn(r,i),n?.durable===!0&&Hvn(r),Qvn(r,t),n?.durable===!0&&jXe(UXe(t))}finally{w6(r)&&Pvn(r,{force:!0})}}function Gvn(t){return JSON.parse($Xe(t,"utf8"))}function $I(t){try{return Gvn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function WI(t){try{return JSON.parse($Xe(t,"utf8"))}catch{return null}}function kfe(t){return w6(t)}function Tfe(t){return w6(t)?Mvn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var Ol=y(()=>{"use strict"});import{homedir as qvn,userInfo as jvn}from"node:os";import{basename as zvn,dirname as Kyi,isAbsolute as Yyi,join as Vd,resolve as zXe}from"node:path";function C6(){let t=zXe(_g()||(process.platform==="linux"?"/":Vd(qvn(),".crouter")));if(Vvn()&&t===Kvn())throw new Error(`refusing to use the account's real crouter root ${t} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return t}function Vvn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function Kvn(){if(b6===void 0)try{b6=zXe(jvn().homedir,".crouter")}catch{b6=null}return b6}function Fl(){return Vd(C6(),"runtime")}function Rfe(){return Vd(C6(),"apps")}function q0(){return Vd(Fl(),"secrets")}function VXe(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=SF(t);return{dir:Vd(n.profiles,e),env:Vd(q0(),"env",zvn(n.root),e),home:n.home}}function Bfe(){return process.platform==="linux"?"/run/crtr":Fl()}function SF(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=Vd(Rfe(),e);return{root:n,profiles:Vd(n,"profiles"),conversations:Vd(n,"conversations"),nodes:Vd(n,"nodes"),files:Vd(n,"files"),home:Vd(n,"home"),cache:Vd(n,"cache")}}var b6,Xm=y(()=>{"use strict";Dc();Kd();JR();Ol()});import{chmodSync as rEi,chownSync as iEi,closeSync as pw,constants as I6,fchmodSync as oEi,fchownSync as sEi,fstatSync as XXe,fsyncSync as aEi,linkSync as cEi,lstatSync as uEi,mkdirSync as lEi,openSync as KXe,readdirSync as dEi,readFileSync as Yvn,readlinkSync as pEi,readSync as hEi,realpathSync as mEi,renameSync as fEi,rmdirSync as gEi,rmSync as AEi,statSync as yEi,symlinkSync as EEi,unlinkSync as wEi,writeSync as xEi}from"node:fs";import{basename as CEi,dirname as IEi,join as vEi,relative as ZXe,resolve as Pfe,sep as YXe}from"node:path";import{loadLinuxNative as Jvn,O_CLOEXEC as Nfe,O_PATH as Lfe,RESOLVE_BENEATH as Xvn,RESOLVE_NO_SYMLINKS as Zvn}from"../../native/linux.js";function eZe(){return Dfe===null&&(Dfe=Jvn()),Dfe}function tSn(t){return t.code}function nSn(t,e){switch(tSn(t)){case"ELOOP":case"EXDEV":return new HI(`path meets a symlink: ${e}`);case"ENXIO":return new HI(`path is not a regular file: ${e}`);case"EAGAIN":return new HI(`path is held by a lease: ${e}`);default:return t}}function Mfe(t,e,n,r,i){try{return t.openat2(e,n,r,eSn)}catch(o){throw nSn(o,i)}}function rSn(t,e,n){let r;try{r=XXe(t)}catch(i){throw pw(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw pw(t),new HI(`path is not a regular file: ${e}`)}function iSn(t,e){let n=ZXe(Pfe(t),Pfe(e));if(n===".."||n.startsWith(`..${YXe}`)||n.startsWith(YXe))throw new Error(`${e} is outside ${t}`);return n}function tZe(t,e,n){if(n&I6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=iSn(t,e),i=eZe();if(!i)return KXe(e,n);let o=KXe("/",JXe),s;try{s=Mfe(i,o,ZXe("/",Pfe(t))||".",JXe,t)}finally{pw(o)}try{return n&Lfe?Mfe(i,s,r||".",n|Nfe,e):rSn(Mfe(i,s,r||".",n|Nfe|I6.O_NONBLOCK,e),e,!0)}finally{pw(s)}}function Qfe(t,e){let n=tZe(t,e,I6.O_RDONLY);try{return Yvn(n)}finally{pw(n)}}function nZe(t,e){if(!eZe())return{path:e,release:()=>{}};let n=tZe(t,e,Lfe),r;try{r=XXe(n)}catch(o){throw pw(n),o}if(!r.isSocket())throw pw(n),new HI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,pw(n))}}}var eSn,JXe,Dfe,HI,_F=y(()=>{"use strict";eSn=Xvn|Zvn,JXe=Lfe|I6.O_DIRECTORY|Nfe,Dfe=null;HI=class extends Error{}});import{join as kg}from"node:path";function Ja(){return Fl()}function rZe(){return kg(Ja(),"on-disk-migration.lock")}function ZR(t){return kg(eB(t),"view.sock")}function oSn(){return kg(Ja(),"nodes")}function iZe(){return kg(Bfe(),"api.sock")}function oZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=sSn}function Ofe(t){if(!oZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function aSn(t){return Ofe(t),kg(oSn(),t)}function cSn(t,e){Ofe(t);let n=e??(Fme()===t?OYe():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return kg(SF(n).nodes,t)}function eB(t){return Ofe(t),process.platform==="linux"?kg(Bfe(),"nodes",t):kg(aSn(t),"run")}function cZe(t,e){return kg(cSn(t,e),"context")}function uZe(t){return kg(eB(t),"job")}var sSn,sZe,aZe,Ul=y(()=>{"use strict";Xm();Dc();_F();sSn=128;sZe="broker-released",aZe="cli-relay-generation"});import{join as uSn}from"node:path";function lSn(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function dSn(t){if(v6===void 0){v6=t;return}if(!lSn(v6,t))throw new Error("event source is already bound for this process")}function lZe(){dSn({component:"daemon",path:uSn(Ja(),"crtrd.log")})}function S6(){return v6}var v6,Ffe=y(()=>{"use strict";Ul()});function dZe(t){return t instanceof sn?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||t.code==="runtime_starting"||t.code==="northlight_unreachable")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}function Ufe(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var sn,hw=y(()=>{"use strict";sn=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}}});var se,$fe=y(()=>{"use strict";se={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonDrain:()=>"/v1/daemon/drain",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,executionStart:t=>`/v1/executions/${t}/start`,executionImportUnpacked:t=>`/v1/executions/${t}/import-unpacked`,environmentGitCredential:t=>`/v1/environments/${t}/git-credential`,feedback:()=>"/v1/feedback",nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeFiles:t=>`/v1/nodes/${t}/files`,nodeFileComplete:(t,e)=>`/v1/nodes/${t}/files/${encodeURIComponent(e)}/complete`,nodeUploads:t=>`/v1/nodes/${t}/uploads`,nodeUploadLink:(t,e)=>`/v1/nodes/${t}/uploads/${encodeURIComponent(e)}/link`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobReport:(t,e)=>`/v1/nodes/${t}/jobs/${e}/report`,nodeJobOutput:(t,e)=>`/v1/nodes/${t}/jobs/${e}/output`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeKick:t=>`/v1/nodes/${t}/kick`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerCycleStart:t=>`/v1/nodes/${t}/broker/cycle-start`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerCycle:t=>`/v1/nodes/${t}/broker/cycle`,nodeBrokerIdle:t=>`/v1/nodes/${t}/broker/idle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeSummaries:t=>`/v1/nodes/${t}/records/summaries`,nodeAttachments:t=>`/v1/nodes/${t}/attachments`,nodeAttachment:(t,e)=>`/v1/nodes/${t}/attachments/${e}`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerStructuredRequest:t=>`/v1/nodes/${t}/broker/structured-request`,nodeBrokerGoal:t=>`/v1/nodes/${t}/broker/goal`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,charges:()=>"/v1/charges",spendLimits:()=>"/v1/spend-limits",spendLimit:t=>`/v1/spend-limits/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",canvasView:t=>`/v1/canvas/view/${encodeURIComponent(t)}`,canvasBrowse:()=>"/v1/canvas/browse",canvasAnalytics:()=>"/v1/canvas/analytics",canvasGraph:()=>"/v1/canvas/graph",canvasPrune:()=>"/v1/canvas/prune",humanReviews:()=>"/v1/human/reviews",humanReview:t=>`/v1/human/reviews/${t}`,humanReviewSubmit:t=>`/v1/human/reviews/${t}/submit`,humanReviewCancel:t=>`/v1/human/reviews/${t}/cancel`,humanReviewDocument:t=>`/v1/human/reviews/${t}/document`,humanReviewComments:t=>`/v1/human/reviews/${t}/comments`,humanReviewCommentEvents:t=>`/v1/human/reviews/${t}/comment-events`,humanComment:t=>`/v1/human/comments/${t}`,humanCommentEdit:t=>`/v1/human/comments/${t}/edit`,humanCommentResolve:t=>`/v1/human/comments/${t}/resolve`,humanCommentReopen:t=>`/v1/human/comments/${t}/reopen`,humanCommentDelete:t=>`/v1/human/comments/${t}/delete`,humanCommentFork:t=>`/v1/human/comments/${t}/fork`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:t=>`/v1/human/inbox/${t}`,humanInboxRespond:t=>`/v1/human/inbox/${t}/respond`,humanInboxProgress:t=>`/v1/human/inbox/${t}/progress`,humanInboxResponse:t=>`/v1/human/inbox/${t}/response`,humanInboxCancel:t=>`/v1/human/inbox/${t}/cancel`,humanInboxFeedbackResolve:(t,e)=>`/v1/human/inbox/${t}/feedback-comments/${e}/resolve`,humanRequests:()=>"/v1/human/requests",humanComponents:()=>"/v1/human/components",humanRequest:t=>`/v1/human/requests/${t}`,humanRequestReplace:t=>`/v1/human/requests/${t}/replace`,humanRequestRespond:t=>`/v1/human/requests/${t}/respond`,humanRequestDismiss:t=>`/v1/human/requests/${t}/dismiss`,humanRequestCancel:t=>`/v1/human/requests/${t}/cancel`,profiles:()=>"/v1/profiles",profile:t=>`/v1/profiles/${t}`,profilePause:t=>`/v1/profiles/${t}/pause`,profileResume:t=>`/v1/profiles/${t}/resume`,profileMetadata:t=>`/v1/profiles/${t}/metadata`,appEnv:()=>"/v1/apps/self/env",appEnvVar:t=>`/v1/apps/self/env/${encodeURIComponent(t)}`,profileEnv:t=>`/v1/profiles/${t}/env`,profileEnvVar:(t,e)=>`/v1/profiles/${t}/env/${e}`,profileEnvironment:t=>`/v1/profiles/${t}/environment`,settings:()=>"/v1/settings",modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthAccount:(t,e)=>`/v1/model-auth/${t}/accounts/${encodeURIComponent(e)}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",exec:()=>"/v1/exec",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectShares:t=>`/v1/objects/${encodeURIComponent(t)}/shares`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",schemas:()=>"/v1/schemas",relations:()=>"/v1/relations",check:()=>"/v1/check",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"}});function hZe(t){pZe=t}function mZe(t){t!==null&&pZe?.(t)}var pZe,Wfe=y(()=>{"use strict"});function _6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Hfe=y(()=>{"use strict"});function fZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Gfe=y(()=>{"use strict"});function gZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var qfe=y(()=>{"use strict"});async function T6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=gSn,retry:i=()=>!0,now:o=Date.now,sleep:s=xZe}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}function tB(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new sn(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}function kr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function GI(t,e){let n=t.status>=200&&t.status<300,r=(await wZe(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new sn(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw Ufe(i)?new sn(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new sn(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function ySn(t){return t==="GET"||t==="HEAD"}async function ESn(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await wZe(t.clone(),Math.min(e??1/0,Date.now()+5e3)),r=JSON.parse(n).error;return r?.origin==="router"&&r.details?.forwarded===!1&&(r.details.runtime_state==="creating"||r.details.runtime_state==="recovering")}catch{return!1}}function wSn(t){return t===429||t>=500}async function jfe(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function wZe(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),tB(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(tB(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function AZe(t){return Math.min(2e3,250*2**(t-1))}function zfe(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function yZe(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function mw(t,e){if(e?.aborted)return new sn(0,"request_aborted","request aborted by caller signal");if(t instanceof sn)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new sn(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new sn(0,"request_aborted","request aborted by caller signal");let n=zfe(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new sn(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new sn(504,"request_timeout",`crtrd request timed out: ${r}`):new sn(503,"transport_error",r)}function xSn(t,e){return t==="GET"||t==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new sn(e.status,e.code,`${e.message}; the ${t} request was sent, so it may or may not have been applied`,{outcome:"unknown"},e.headers)}function EZe(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function k6(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new sn(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=tB(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return xZe(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new sn(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function bSn(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function xZe(t){return new Promise(e=>setTimeout(e,t))}function CSn(t){if(t!==void 0)try{return t()}catch{return}}var pSn,hSn,mSn,fSn,gSn,TF,kF,Tg,ASn,R6=y(()=>{"use strict";hw();$fe();Wfe();Hfe();Gfe();qfe();pSn=3e4,hSn=3e4,mSn=Symbol.for("@north-light/api/local-socket-fetch"),fSn=1e4,gSn=200;TF=2147483647;kF=t=>tB(t??Date.now()),Tg=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??pSn,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[mSn]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??fSn}healthz(){return this.request("GET",se.healthz())}async probeHealthz(e){let n=await this.transport("GET",se.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return GI(n)}async ready(){let e=await this.transport("GET",se.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return GI(e)}status(){return this.request("GET",se.status())}due(){return this.request("GET",se.due())}restartDaemon(){return this.request("POST",se.daemonRestart())}drainDaemon(e={}){let n=e.settle_limit_ms??0;return this.request("POST",se.daemonDrain(),e,{timeout:n+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",se.daemonDrain())}admitDaemon(){return this.request("POST",se.daemonAdmit())}migrateState(e){return this.request("POST",se.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",se.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",se.nodeTelemetry(this.nodePath(e)),n)}async putNodeSummaries(e,n){await this.request("PUT",se.nodeSummaries(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",se.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",kr(se.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}listNodeAttachments(e){return this.request("GET",se.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,n){let r=await this.send("GET",se.nodeAttachment(this.nodePath(e),n));return r.ok||await GI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",se.nodeFiles(this.nodePath(e)),n)}createNodeUpload(e,n){return this.request("POST",se.nodeUploads(this.nodePath(e)),n)}nodeUploadLink(e,n){return this.request("POST",se.nodeUploadLink(this.nodePath(e),n))}completeNodeFile(e,n){return this.request("POST",se.nodeFileComplete(this.nodePath(e),n))}readNodePassiveMessage(e,n){return this.request("GET",kr(se.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",se.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",se.nodes(),e,{timeout:12e4+this.timeoutMs})}listNodes(e){return this.request("GET",kr(se.nodes(),e))}getNode(e){return this.request("GET",se.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",kr(se.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",kr(se.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",kr(se.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await GI(i);return}if(i.body===null)throw new sn(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
89
+ `))!==-1;){let d=a.slice(0,l);a=a.slice(l+1),d!==""&&(yield JSON.parse(d))}}if(a+=s.decode(),a.trim()!=="")throw new sn(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,n){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,n):this.request("POST","/v1/structured-requests",e,n)}getStructuredRequest(e,{wait:n=0,budgetMs:r}={}){if(!Number.isInteger(n)||n<0||n>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",kr(`/v1/structured-requests/${this.requestPath(e)}`,{wait:n}),void 0,{budgetMs:r})}cancelStructuredRequest(e,n){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},n)}registerOutcomeDelivery(e,n){return this.request("PUT",se.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",se.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",se.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",se.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,n,r={}){let i=new URLSearchParams;r.tail_lines!==void 0&&i.set("tail_lines",String(r.tail_lines)),r.max_bytes!==void 0&&i.set("max_bytes",String(r.max_bytes));let o=i.size===0?"":`?${i.toString()}`;return this.request("GET",`${se.nodeJobOutput(this.nodePath(e),this.jobPath(n))}${o}`)}stopBashJob(e,n){return this.request("DELETE",se.nodeJob(this.nodePath(e),this.jobPath(n)))}async patchBashJob(e,n,r){await this.request("PATCH",se.nodeJob(this.nodePath(e),this.jobPath(n)),r)}async reportBashJob(e,n,r){await this.request("POST",se.nodeJobReport(this.nodePath(e),this.jobPath(n)),r)}sendMessage(e,n){return this.request("POST",se.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",se.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",se.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",se.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",se.nodeFork(this.nodePath(e)),{})}kickNode(e){return this.request("POST",se.nodeKick(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",se.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",se.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",se.nodeBrokerSessionBound(this.nodePath(e)),n)}cycleStartBroker(e,n,r){return this.request("POST",se.nodeBrokerCycleStart(this.nodePath(e)),n,r)}settleBroker(e,n){return this.request("POST",se.nodeBrokerSettle(this.nodePath(e)),n)}startBrokerCycle(e,n){return this.request("POST",se.nodeBrokerCycle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",se.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",se.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",se.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",se.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",se.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",se.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",se.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",se.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",se.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${se.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",se.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${se.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",se.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",se.executionStart(e))}executionImportUnpacked(e){return this.request("POST",se.executionImportUnpacked(e),{})}gitCredential(e,n){return this.request("POST",se.environmentGitCredential(e),n)}postFeedback(e){return this.request("POST",se.feedback(),e)}brokerExtensionState(e){return this.request("GET",se.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",se.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",se.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",se.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",se.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",se.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",se.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",se.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",se.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",se.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",se.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",se.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",se.kinds())}patchConfig(e,n){return this.request("PATCH",se.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",se.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",se.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",se.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",se.quarantinedWorktrees())}showLimits(){return this.request("GET",se.limits())}setAppLimits(e,n){return this.request("PUT",se.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(se.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(se.charges(),e))}listSpendLimits(){return this.request("GET",se.spendLimits())}setSpendLimit(e,n){return this.request("PUT",se.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",se.spendLimit(e))}listSpaces(){return this.request("GET",se.spaces())}subscribe(e,n){return this.request("POST",se.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",se.focuses())}focusOf(e){return this.request("GET",kr(se.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(se.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",se.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",se.focus(e),n)}async closeFocus(e){await this.request("DELETE",se.focus(e))}async unsubscribe(e,n){await this.request("DELETE",se.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",se.crons(),e)}listCrons(e){return this.request("GET",kr(se.crons(),e))}showCron(e,n){return this.request("GET",kr(se.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(se.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(se.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(se.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(se.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",se.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",se.nodeAttach(this.nodePath(e)),n??{},{timeout:hSn+this.timeoutMs})}getReports(e,n){return this.request("GET",kr(se.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",kr(se.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",se.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",se.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",kr(se.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",se.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",se.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",kr(se.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",se.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",kr(se.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",se.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",kr(se.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",se.bash(),e,n)}objects={read:(e,n)=>this.request("GET",kr(se.object(e),n)),list:e=>this.request("GET",kr(se.objects(),e)),search:e=>this.request("POST",se.objectsSearch(),e),watch:(e,n={})=>this.request("POST",se.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",kr(se.objectWatch(e),n)),edges:(e,n)=>this.request("GET",kr(se.objectEdges(e),n))};docs={write:e=>this.request("POST",se.docs(),e),edit:(e,n)=>this.request("PATCH",se.doc(e),n),move:(e,n)=>this.request("POST",se.docMove(e),n),delete:e=>this.request("DELETE",se.doc(e)),history:(e,n)=>this.request("GET",kr(se.docHistory(e),n)),lint:(e={})=>this.request("POST",se.docsLint(),e)};documents={browserAccess:()=>this.request("GET",se.documentsBrowserAccess()),reconcilePackages:e=>this.request("POST",se.documentsReconcilePackages(),e)};plugins={appToken:e=>this.request("GET",se.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",se.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",se.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",se.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",se.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",se.profile(e),n??{})}createProfile(e){return this.request("POST",se.profiles(),e)}listProfiles(){return this.request("GET",se.profiles())}updateProfile(e,n){return this.request("PATCH",se.profile(e),n)}listAppEnv(){return this.request("GET",se.appEnv())}setAppEnv(e,n){return this.request("PUT",se.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",se.appEnvVar(e))}listProfileEnv(e){return this.request("GET",se.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",se.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",se.profileEnvVar(e,n))}getProfileEnvironment(e){return this.request("GET",se.profileEnvironment(e))}setProfileEnvironment(e,n){return this.request("PUT",se.profileEnvironment(e),n)}getProfile(e){return this.request("GET",se.profile(e))}pauseProfile(e){return this.request("POST",se.profilePause(e),{})}resumeProfile(e){return this.request("POST",se.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",se.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",se.profile(e),n)}getSettings(){return this.request("GET",se.settings())}putSettings(e){return this.request("PUT",se.settings(),e)}listModelAuth(){return this.request("GET",se.modelAuths())}getModelAuthReadiness(e){return this.request("GET",kr(se.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",se.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",se.modelAuth(e))}patchModelAuthAccount(e,n,r){return this.request("PATCH",se.modelAuthAccount(e,n),r)}removeModelAuthAccount(e,n){return this.request("DELETE",se.modelAuthAccount(e,n))}startModelAuth(e){return this.request("POST",se.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",se.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",se.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",kr(se.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",se.humanReviews(),e)}listReviews(e){return this.request("GET",kr(se.humanReviews(),e))}getReview(e){return this.request("GET",se.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",se.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",se.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",se.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",se.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",kr(se.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",kr(se.humanReviewCommentEvents(this.reviewPath(e)),n))}getReviewComment(e){return this.request("GET",se.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",se.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",se.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",se.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",se.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",se.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",se.humanInbox())}getHumanInboxPage(e){return this.request("GET",se.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,n={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",kr(se.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",se.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",se.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",se.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",se.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",se.humanRequests(),e)}listPageComponents(){return this.request("GET",se.humanComponents())}getHumanRequest(e){return this.request("GET",se.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",se.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",se.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",se.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",se.humanRequestCancel(this.requestPath(e)),n)}resolvePageFeedbackComment(e,n,r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(n)}`);return this.request("POST",se.humanInboxFeedbackResolve(this.ticketId(e),n),{node_id:r})}async dashboard(e){let n=e?.under!==void 0?{under:e.under}:void 0,[r,i]=await Promise.all([this.listNodes(n),this.status()]);return{nodes:r,counts:i.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",se.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",se.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",se.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",se.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",kr(se.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",se.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",se.canvasSnapshot())}analytics(e){return this.request("GET",kr(se.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",se.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",kr(se.canvasLiveRoots(),e))}canvasView(e){return this.request("GET",se.canvasView(e))}canvasRoster(){return this.request("GET",se.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",se.canvasBrowse());return e.ok||await GI(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",se.canvasGraph())}prune(e){return this.request("POST",se.canvasPrune(),e)}async request(e,n,r,i){try{let o=i===void 0?void 0:this.resolveBudget(i),s=await this.send(e,n,r,o);return await GI(s,o?.deadlineAt)}catch(o){throw xSn(e,mw(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw mw(i,r?.signal)}}async send(e,n,r,i={}){let o=this.resolveBudget(i),s=e==="GET"||e==="HEAD"||e==="DELETE",a=o.maxRetries??this.maxRetries,c=Math.min(o.deadlineAt??1/0,Date.now()+ASn);for(let u=0;;u++){let l;try{l=await this.transport(e,n,r,o)}catch(d){if(this.isColdSocketError(d)||this.isInterruptedSocketError(d)){let p=this.availabilityFailure?.();if(p!==void 0)throw p}if(this.isColdSocketError(d))try{await this.handleColdSocket(d,o.deadlineAt),l=await this.transport(e,n,r,o)}catch(p){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!yZe(p,o.signal)?tB(o.deadlineAt):mw(p,o.signal)}else{if(this.isInterruptedSocketError(d)&&this.localSocketTransport&&(!s||u<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&u<a&&!yZe(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await k6(AZe(u+1),o);continue}else throw mw(d,o.signal)}}if(ySn(e)&&a>0&&l.status===503&&await ESn(l,o.deadlineAt)){let d=Math.max(250,(EZe(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await jfe(l,o.deadlineAt),await k6(d,{signal:o.signal});continue}if(s&&u<a&&wSn(l.status)){await jfe(l,o.deadlineAt),await k6(AZe(u+1),o,EZe(l));continue}return l}}resolveBudget(e){let{budgetMs:n,deadlineAt:r,...i}=e;if(n===void 0&&r===void 0)return i;if(n!==void 0&&(!Number.isFinite(n)||n<=0||n>TF))throw new RangeError(`budgetMs must be a positive finite number of at most ${TF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>TF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${TF} ms from now`);return{...i,deadlineAt:Math.min(r??1/0,n===void 0?1/0:Date.now()+n)}}async awaitWithinBudget(e,n){if(n===void 0)return e;let r=n-Date.now();if(r<=0)throw kF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(kF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await GI(await this.transport(e,n,r,o))}catch(s){throw mw(s,o.signal)}}nodePath(e){if(!_6(e))throw new sn(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!fZe(e))throw new sn(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!gZe(e))throw new sn(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!_6(e))throw new sn(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!_6(e))throw new sn(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new sn(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,n,r,i={}){let o=i.deadlineAt===void 0?void 0:i.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(kF(i.deadlineAt));let s=r===void 0?void 0:JSON.stringify(r),a={accept:"application/json",...this.headers,...i.headers};s!==void 0&&(a["content-type"]="application/json");let c=i.timeout??this.timeoutMs,u=o===void 0?c:c>0?Math.min(c,o):o,l=new AbortController,d=o!==void 0&&(c<=0||o<=c),p=u>0?setTimeout(()=>l.abort(d?kF(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,h=i.signal,m=()=>l.abort(h?.reason);h!==void 0&&(h.aborted?l.abort(h.reason):h.addEventListener("abort",m,{once:!0}));let f=()=>{p!==void 0&&clearTimeout(p),h?.removeEventListener("abort",m)};return bSn(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>(mZe(g.headers.get("server-timing")),this.retainRequestLifetime(g,f,()=>l.signal.aborted?l.signal.reason:void 0)),g=>{throw f(),g})}retainRequestLifetime(e,n,r){if(e.body===null)return n(),e;let i=e.body.getReader(),o=!1,s=()=>{o||(o=!0,n())},a=new ReadableStream({async pull(c){try{let{done:u,value:l}=await i.read();u?(s(),c.close()):c.enqueue(l)}catch(u){s(),c.error(r()??u)}},async cancel(c){s(),await i.cancel(c)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){let n=zfe(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=zfe(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw mw(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new sn(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,n,r,i)}catch(o){throw mw(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw kF(n);let i,o;try{await T6({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:s=>s!==i&&s!==o,probe:async s=>{let a=this.availabilityFailure?.();if(a!==void 0)throw o=a,a;let c=this.coldStartFailure?.();if(c!==void 0)throw i=new sn(503,"daemon_unavailable",`crtrd failed to start: ${c}`),i;let u=await this.transport("GET",se.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await jfe(u);return}let l=await u.text();try{if(typeof JSON.parse(l).startup_blocked=="string")return}catch{}throw new sn(u.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${u.status}: ${l.slice(0,500)}`)}})}catch(s){throw s===i&&(this.startupFailureReported=!0),s}}async handleColdSocket(e,n){let r=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;r&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),n));try{await this.awaitAvailability(e,n)}catch(i){if(r&&!this.startupFailureReported){let o=CSn(this.coldStartDiagnostic);if(o!==void 0){let s=mw(i);throw new sn(s.status,s.code,`${s.message}
90
90
  ${o}`)}}throw i}}};ASn=6e4});function bZe(){return ISn??void 0}var ISn,CZe=y(()=>{"use strict";ISn=null});import{request as vSn}from"node:http";import{homedir as SSn}from"node:os";import{join as Vfe}from"node:path";function RSn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:Vfe(SSn(),_Sn);return Vfe(process.platform==="linux"?"/run/crtr":Vfe(n,"runtime"),kSn)}function BSn(t){let e=function(n,r={}){let i=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=r.method??"GET",s={};if(r.headers!==void 0)for(let[c,u]of new Headers(r.headers).entries())s[c]=u;let a=typeof r.body=="string"?r.body:void 0;return a!==void 0&&(s["content-length"]=String(Buffer.byteLength(a))),new Promise((c,u)=>{let l=vSn({socketPath:t,path:i.pathname+i.search,method:o,headers:s},h=>{let m=new ReadableStream({start(A){h.on("data",x=>A.enqueue(new Uint8Array(x))),h.on("end",()=>A.close()),h.on("error",x=>A.error(x))},cancel(){h.destroy()}}),f=new Headers;for(let[A,x]of Object.entries(h.headers))if(x!==void 0)for(let b of Array.isArray(x)?x:[x])f.append(A,b);let g=h.statusCode??0;c(new Response(g===204?null:m,{status:g,statusText:h.statusMessage,headers:f}))});l.on("error",h=>u(new TypeError("fetch failed",{cause:h})));let d=r.signal,p=()=>{l.destroy(),u(d?.reason??new DOMException("The operation was aborted.","AbortError"))};if(d!=null){if(d.aborted){p();return}d.addEventListener("abort",p,{once:!0})}a!==void 0&&l.write(a),l.end()})};return e[TSn]=!0,e}function fw(t={}){let{socketPath:e,...n}=t;return new Tg({baseUrl:"http://localhost",fetch:BSn(e??RSn()),autostart:!0,...n})}var _Sn,kSn,TSn,B6=y(()=>{"use strict";R6();_Sn=".crouter",kSn="api.sock",TSn=Symbol.for("@north-light/api/local-socket-fetch")});import{readFileSync as DSn}from"node:fs";import{dirname as MSn,join as IZe}from"node:path";import{fileURLToPath as PSn}from"node:url";function Kfe(){if(D6!==null)return D6;let t=IZe(MSn(PSn(import.meta.url)),"..","..");return D6=JSON.parse(DSn(IZe(t,"package.json"),"utf8")).version,D6}var D6,Yfe=y(()=>{"use strict";D6=null});var vZe=y(()=>{"use strict";BF();hw()});var Xfe=Q(SZe=>{"use strict";SZe.parse=function(t,e){return new Jfe(t,e).parse()};var Jfe=class t{constructor(e,n){this.source=e,this.transform=n||NSn,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var n;(this.recorded.length>0||e)&&(n=this.recorded.join(""),n==="NULL"&&!e&&(n=null),n!==null&&(n=this.transform(n)),this.entries.push(n),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var n,r,i;for(this.consumeDimensions();!this.isEof();)if(n=this.nextCharacter(),n.value==="{"&&!i)this.dimension++,this.dimension>1&&(r=new t(this.source.substr(this.position-1),this.transform),this.entries.push(r.parse(!0)),this.position+=r.position-2);else if(n.value==="}"&&!i){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else n.value==='"'&&!n.escaped?(i&&this.newEntry(!0),i=!i):n.value===","&&!i?this.newEntry():this.record(n.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};function NSn(t){return t}});var Zfe=Q((dwi,_Ze)=>{var LSn=Xfe();_Ze.exports={create:function(t,e){return{parse:function(){return LSn.parse(t,e)}}}}});var RZe=Q((pwi,TZe)=>{"use strict";var QSn=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,OSn=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,FSn=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,USn=/^-?infinity$/;TZe.exports=function(e){if(USn.test(e))return Number(e.replace("i","I"));var n=QSn.exec(e);if(!n)return $Sn(e)||null;var r=!!n[8],i=parseInt(n[1],10);r&&(i=kZe(i));var o=parseInt(n[2],10)-1,s=n[3],a=parseInt(n[4],10),c=parseInt(n[5],10),u=parseInt(n[6],10),l=n[7];l=l?1e3*parseFloat(l):0;var d,p=WSn(e);return p!=null?(d=new Date(Date.UTC(i,o,s,a,c,u,l)),ege(i)&&d.setUTCFullYear(i),p!==0&&d.setTime(d.getTime()-p)):(d=new Date(i,o,s,a,c,u,l),ege(i)&&d.setFullYear(i)),d};function $Sn(t){var e=OSn.exec(t);if(e){var n=parseInt(e[1],10),r=!!e[4];r&&(n=kZe(n));var i=parseInt(e[2],10)-1,o=e[3],s=new Date(n,i,o);return ege(n)&&s.setFullYear(n),s}}function WSn(t){if(t.endsWith("+00"))return 0;var e=FSn.exec(t.split(" ")[1]);if(e){var n=e[1];if(n==="Z")return 0;var r=n==="-"?-1:1,i=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return i*r*1e3}}function kZe(t){return-(t-1)}function ege(t){return t>=0&&t<100}});var DZe=Q((hwi,BZe)=>{BZe.exports=GSn;var HSn=Object.prototype.hasOwnProperty;function GSn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)HSn.call(n,r)&&(t[r]=n[r])}return t}});var NZe=Q((mwi,PZe)=>{"use strict";var qSn=DZe();PZe.exports=nB;function nB(t){if(!(this instanceof nB))return new nB(t);qSn(this,r_n(t))}var jSn=["seconds","minutes","hours","days","months","years"];nB.prototype.toPostgres=function(){var t=jSn.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var n=this[e]||0;return e==="seconds"&&this.milliseconds&&(n=(n+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),n+" "+e},this).join(" ")};var zSn={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},VSn=["years","months","days"],KSn=["hours","minutes","seconds"];nB.prototype.toISOString=nB.prototype.toISO=function(){var t=VSn.map(n,this).join(""),e=KSn.map(n,this).join("");return"P"+t+"T"+e;function n(r){var i=this[r]||0;return r==="seconds"&&this.milliseconds&&(i=(i+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),i+zSn[r]}};var tge="([+-]?\\d+)",YSn=tge+"\\s+years?",JSn=tge+"\\s+mons?",XSn=tge+"\\s+days?",ZSn="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",e_n=new RegExp([YSn,JSn,XSn,ZSn].map(function(t){return"("+t+")?"}).join("\\s*")),MZe={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},t_n=["hours","minutes","seconds","milliseconds"];function n_n(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}function r_n(t){if(!t)return{};var e=e_n.exec(t),n=e[8]==="-";return Object.keys(MZe).reduce(function(r,i){var o=MZe[i],s=e[o];return!s||(s=i==="milliseconds"?n_n(s):parseInt(s,10),!s)||(n&&~t_n.indexOf(i)&&(s*=-1),r[i]=s),r},{})}});var OZe=Q((fwi,QZe)=>{"use strict";var LZe=Buffer.from||Buffer;QZe.exports=function(e){if(/^\\x/.test(e))return LZe(e.substr(2),"hex");for(var n="",r=0;r<e.length;)if(e[r]!=="\\")n+=e[r],++r;else if(/[0-7]{3}/.test(e.substr(r+1,3)))n+=String.fromCharCode(parseInt(e.substr(r+1,3),8)),r+=4;else{for(var i=1;r+i<e.length&&e[r+i]==="\\";)i++;for(var o=0;o<Math.floor(i/2);++o)n+="\\";r+=Math.floor(i/2)*2}return LZe(n,"binary")}});var qZe=Q((gwi,GZe)=>{var DF=Xfe(),MF=Zfe(),M6=RZe(),UZe=NZe(),$Ze=OZe();function P6(t){return function(n){return n===null?n:t(n)}}function WZe(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}function i_n(t){return t?DF.parse(t,WZe):null}function o_n(t){return parseInt(t,10)}function nge(t){return t?DF.parse(t,P6(o_n)):null}function s_n(t){return t?DF.parse(t,P6(function(e){return HZe(e).trim()})):null}var a_n=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=sge(n)),n});return e.parse()},rge=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=parseFloat(n)),n});return e.parse()},ph=function(t){if(!t)return null;var e=MF.create(t);return e.parse()},ige=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=M6(n)),n});return e.parse()},c_n=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=UZe(n)),n});return e.parse()},u_n=function(t){return t?DF.parse(t,P6($Ze)):null},oge=function(t){return parseInt(t,10)},HZe=function(t){var e=String(t);return/^\d+$/.test(e)?e:t},FZe=function(t){return t?DF.parse(t,P6(JSON.parse)):null},sge=function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},l_n=function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",n="",r=!1,i=2;i<t.length-1;i++){if(r||(e+=t[i]),t[i]===")"){r=!0;continue}else if(!r)continue;t[i]!==","&&(n+=t[i])}var o=sge(e);return o.radius=parseFloat(n),o},d_n=function(t){t(20,HZe),t(21,oge),t(23,oge),t(26,oge),t(700,parseFloat),t(701,parseFloat),t(16,WZe),t(1082,M6),t(1114,M6),t(1184,M6),t(600,sge),t(651,ph),t(718,l_n),t(1e3,i_n),t(1001,u_n),t(1005,nge),t(1007,nge),t(1028,nge),t(1016,s_n),t(1017,a_n),t(1021,rge),t(1022,rge),t(1231,rge),t(1014,ph),t(1015,ph),t(1008,ph),t(1009,ph),t(1040,ph),t(1041,ph),t(1115,ige),t(1182,ige),t(1185,ige),t(1186,UZe),t(1187,c_n),t(17,$Ze),t(114,JSON.parse.bind(JSON)),t(3802,JSON.parse.bind(JSON)),t(199,FZe),t(3807,FZe),t(3907,ph),t(2951,ph),t(791,ph),t(1183,ph),t(1270,ph)};GZe.exports={init:d_n}});var zZe=Q((Awi,jZe)=>{"use strict";var $l=1e6;function p_n(t){var e=t.readInt32BE(0),n=t.readUInt32BE(4),r="";e<0&&(e=~e+(n===0),n=~n+1>>>0,r="-");var i="",o,s,a,c,u,l;{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}return o=e%$l,s=4294967296*o+n,a=""+s%$l,r+a+i}jZe.exports=p_n});var XZe=Q((ywi,JZe)=>{var h_n=zZe(),ss=function(t,e,n,r,i){n=n||0,r=r||!1,i=i||function(h,m,f){return h*Math.pow(2,f)+m};var o=n>>3,s=function(h){return r?~h&255:h},a=255,c=8-n%8;e<c&&(a=255<<8-e&255,c=e),n&&(a=a>>n%8);var u=0;n%8+e>=8&&(u=i(0,s(t[o])&a,c));for(var l=e+n>>3,d=o+1;d<l;d++)u=i(u,s(t[d]),8);var p=(e+n)%8;return p>0&&(u=i(u,s(t[l])>>8-p,p)),u},YZe=function(t,e,n){var r=Math.pow(2,n-1)-1,i=ss(t,1),o=ss(t,n,1);if(o===0)return 0;var s=1,a=function(u,l,d){u===0&&(u=1);for(var p=1;p<=d;p++)s/=2,(l&1<<d-p)>0&&(u+=s);return u},c=ss(t,e,n+1,!1,a);return o==Math.pow(2,n+1)-1?c===0?i===0?1/0:-1/0:NaN:(i===0?1:-1)*Math.pow(2,o-r)*c},m_n=function(t){return ss(t,1)==1?-1*(ss(t,15,1,!0)+1):ss(t,15,1)},VZe=function(t){return ss(t,1)==1?-1*(ss(t,31,1,!0)+1):ss(t,31,1)},f_n=function(t){return YZe(t,23,8)},g_n=function(t){return YZe(t,52,11)},A_n=function(t){var e=ss(t,16,32);if(e==49152)return NaN;for(var n=Math.pow(1e4,ss(t,16,16)),r=0,i=[],o=ss(t,16),s=0;s<o;s++)r+=ss(t,16,64+16*s)*n,n/=1e4;var a=Math.pow(10,ss(t,16,48));return(e===0?1:-1)*Math.round(r*a)/a},KZe=function(t,e){var n=ss(e,1),r=ss(e,63,1),i=new Date((n===0?1:-1)*r/1e3+9466848e5);return t||i.setTime(i.getTime()+i.getTimezoneOffset()*6e4),i.usec=r%1e3,i.getMicroSeconds=function(){return this.usec},i.setMicroSeconds=function(o){this.usec=o},i.getUTCMicroSeconds=function(){return this.usec},i},PF=function(t){for(var e=ss(t,32),n=ss(t,32,32),r=ss(t,32,64),i=96,o=[],s=0;s<e;s++)o[s]=ss(t,32,i),i+=32,i+=32;var a=function(u){var l=ss(t,32,i);if(i+=32,l==4294967295)return null;var d;if(u==23||u==20)return d=ss(t,l*8,i),i+=l*8,d;if(u==25)return d=t.toString(this.encoding,i>>3,(i+=l<<3)>>3),d;console.log("ERROR: ElementType not implemented: "+u)},c=function(u,l){var d=[],p;if(u.length>1){var h=u.shift();for(p=0;p<h;p++)d[p]=c(u,l);u.unshift(h)}else for(p=0;p<u[0];p++)d[p]=a(l);return d};return c(o,r)},y_n=function(t){return t.toString("utf8")},E_n=function(t){return t===null?null:ss(t,8)>0},w_n=function(t){t(20,h_n),t(21,m_n),t(23,VZe),t(26,VZe),t(1700,A_n),t(700,f_n),t(701,g_n),t(16,E_n),t(1114,KZe.bind(null,!1)),t(1184,KZe.bind(null,!0)),t(1e3,PF),t(1007,PF),t(1016,PF),t(1008,PF),t(1009,PF),t(25,y_n)};JZe.exports={init:w_n}});var eet=Q((Ewi,ZZe)=>{ZZe.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var QF=Q(LF=>{var x_n=qZe(),b_n=XZe(),C_n=Zfe(),I_n=eet();LF.getTypeParser=v_n;LF.setTypeParser=S_n;LF.arrayParser=C_n;LF.builtins=I_n;var NF={text:{},binary:{}};function tet(t){return String(t)}function v_n(t,e){return e=e||"text",NF[e]&&NF[e][t]||tet}function S_n(t,e,n){typeof e=="function"&&(n=e,e="text"),NF[e][t]=n}x_n.init(function(t,e){NF.text[t]=e});b_n.init(function(t,e){NF.binary[t]=e})});var OF=Q((xwi,age)=>{"use strict";var net;try{net=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}age.exports={host:"localhost",user:net,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,sslnegotiation:void 0,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var rB=QF(),__n=rB.getTypeParser(20,"text"),k_n=rB.getTypeParser(1016,"text");age.exports.__defineSetter__("parseInt8",function(t){rB.setTypeParser(20,"text",t?rB.getTypeParser(23,"text"):__n),rB.setTypeParser(1016,"text",t?rB.getTypeParser(1007,"text"):k_n)})});var qI=Q((bwi,iet)=>{"use strict";var T_n=OF(),R_n=K("util"),{isDate:B_n}=K("util/types"),D_n=R_n.deprecate(()=>{},"Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.","PG_INVALID_DATE");function M_n(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function ret(t){let e="{";for(let n=0;n<t.length;n++){n>0&&(e+=",");let r=t[n];r==null?e+="NULL":Array.isArray(r)?e+=ret(r):ArrayBuffer.isView(r)?(r instanceof Buffer||(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),e+="\\\\x"+r.toString("hex")):e+=M_n(N6(r))}return e+="}",e}var N6=function(t,e){return t==null?null:typeof t=="object"?t instanceof Buffer?t:ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):B_n(t)?(isNaN(t.getTime())&&D_n(),T_n.parseInputDatesAsUTC?L_n(t):N_n(t)):Array.isArray(t)?ret(t):P_n(t,e):t.toString()};function P_n(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),N6(t.toPostgres(N6),e)}return JSON.stringify(t)}function N_n(t){let e=-t.getTimezoneOffset(),n=t.getFullYear(),r=n<1;r&&(n=Math.abs(n)+1);let i=String(n).padStart(4,"0")+"-"+String(t.getMonth()+1).padStart(2,"0")+"-"+String(t.getDate()).padStart(2,"0")+"T"+String(t.getHours()).padStart(2,"0")+":"+String(t.getMinutes()).padStart(2,"0")+":"+String(t.getSeconds()).padStart(2,"0")+"."+String(t.getMilliseconds()).padStart(3,"0");return e<0?(i+="-",e*=-1):i+="+",i+=String(Math.floor(e/60)).padStart(2,"0")+":"+String(e%60).padStart(2,"0"),r&&(i+=" BC"),i}function L_n(t){let e=t.getUTCFullYear(),n=e<1;n&&(e=Math.abs(e)+1);let r=String(e).padStart(4,"0")+"-"+String(t.getUTCMonth()+1).padStart(2,"0")+"-"+String(t.getUTCDate()).padStart(2,"0")+"T"+String(t.getUTCHours()).padStart(2,"0")+":"+String(t.getUTCMinutes()).padStart(2,"0")+":"+String(t.getUTCSeconds()).padStart(2,"0")+"."+String(t.getUTCMilliseconds()).padStart(3,"0");return r+="+00:00",n&&(r+=" BC"),r}function Q_n(t,e,n){return t=typeof t=="string"?{text:t}:O_n(t),e&&(typeof e=="function"?t.callback=e:t.values=e),n&&(t.callback=n),t}function O_n(t){return t==null?t:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),Object.getOwnPropertyDescriptors(t))}var F_n=function(t){return'"'+t.replace(/"/g,'""')+'"'},U_n=function(t){let e=!1,n="'";if(t==null||typeof t!="string")return"''";for(let r=0;r<t.length;r++){let i=t[r];i==="'"?n+=i+i:i==="\\"?(n+=i+i,e=!0):n+=i}return n+="'",e===!0&&(n=" E"+n),n};iet.exports={prepareValue:function(e){return N6(e)},normalizeQueryConfig:Q_n,escapeIdentifier:F_n,escapeLiteral:U_n}});var lge=Q((Cwi,aet)=>{var oet=K("crypto");aet.exports={postgresMd5PasswordHash:W_n,randomBytes:$_n,deriveKey:j_n,sha256:H_n,hashByName:G_n,hmacSha256:q_n,md5:cge};var set=oet.webcrypto||globalThis.crypto,jI=set.subtle,uge=new TextEncoder;function $_n(t){return set.getRandomValues(Buffer.alloc(t))}async function cge(t){try{return oet.createHash("md5").update(t,"utf-8").digest("hex")}catch{let n=typeof t=="string"?uge.encode(t):t,r=await jI.digest("MD5",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}}async function W_n(t,e,n){let r=await cge(e+t);return"md5"+await cge(Buffer.concat([Buffer.from(r),n]))}async function H_n(t){return await jI.digest("SHA-256",t)}async function G_n(t,e){return await jI.digest(t,e)}async function q_n(t,e){let n=await jI.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await jI.sign("HMAC",n,uge.encode(e))}async function j_n(t,e,n){let r=await jI.importKey("raw",uge.encode(t),"PBKDF2",!1,["deriveBits"]),i={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:n};return await jI.deriveBits(i,r,256,["deriveBits"])}});var det=Q((Iwi,uet)=>{function zI(t,e){return new Error("SASL channel binding: "+t+" when parsing public certificate "+e.toString("base64"))}function dge(t,e){let n=t[e++];if(n<128)return{length:n,index:e};let r=n&127;if(r>4)throw zI("bad length",t);n=0;for(let i=0;i<r;i++)n=n<<8|t[e++];return{length:n,index:e}}function cet(t,e){if(t[e++]!==6)throw zI("non-OID data",t);let{length:n,index:r}=dge(t,e);e=r;let i=e+n,o=t[e++],s=(o/40>>0)+"."+o%40;for(;e<i;){let a=0;for(;e<i;){let c=t[e++];if(a=a<<7|c&127,c<128)break}s+="."+a}return{oid:s,index:e}}function FF(t,e){if(t[e++]!==48)throw zI("non-sequence data",t);return dge(t,e)}function z_n(t,e){e===void 0&&(e=0),e=FF(t,e).index;let{length:n,index:r}=FF(t,e);e=r+n,e=FF(t,e).index;let{oid:i,index:o}=cet(t,e);switch(i){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(e=o,e=FF(t,e).index,t[e++]!==160)throw zI("non-tag data",t);e=dge(t,e).index,e=FF(t,e).index;let{oid:s}=cet(t,e);switch(s){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw zI("unknown hash OID "+s,t)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw zI("Ed448 certificate channel binding is not currently supported by Postgres")}throw zI("unknown OID "+i,t)}uet.exports={signatureAlgorithmHashFromCertificate:z_n}});var fet=Q((vwi,met)=>{"use strict";var gw=lge(),{signatureAlgorithmHashFromCertificate:V_n}=det();function K_n(t){let e=/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g,n=/[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g;return t.replace(e," ").replace(n,"").normalize("NFKC")}var pge=1e5;function Y_n(t,e,n=pge){let r=["SCRAM-SHA-256"];e&&r.unshift("SCRAM-SHA-256-PLUS");let i=r.find(a=>t.includes(a));if(!i)throw new Error("SASL: Only mechanism(s) "+r.join(" and ")+" are supported");if(i==="SCRAM-SHA-256-PLUS"&&typeof e.getPeerCertificate!="function")throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let o=gw.randomBytes(18).toString("base64");return{mechanism:i,clientNonce:o,response:(i==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":e?"y":"n")+",,n=*,r="+o,message:"SASLInitialResponse",scramMaxIterations:n}}async function J_n(t,e,n,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof n!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let i=ekn(n);if(i.nonce.startsWith(t.clientNonce)){if(i.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");let o=typeof t.scramMaxIterations=="number"?t.scramMaxIterations:pge;if(o!==0&&i.iteration>o)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count "+i.iteration+" exceeds scramMaxIterations of "+o);let s="n=*,r="+t.clientNonce,a="r="+i.nonce+",s="+i.salt+",i="+i.iteration,c=r?"eSws":"biws";if(t.mechanism==="SCRAM-SHA-256-PLUS"){let b=r.getPeerCertificate().raw,v=V_n(b);(v==="MD5"||v==="SHA-1")&&(v="SHA-256");let S=await gw.hashByName(v,b);c=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(S)]).toString("base64")}let u="c="+c+",r="+i.nonce,l=s+","+a+","+u,d=Buffer.from(i.salt,"base64"),p=await gw.deriveKey(K_n(e),d,i.iteration),h=await gw.hmacSha256(p,"Client Key"),m=await gw.sha256(h),f=await gw.hmacSha256(m,l),g=nkn(Buffer.from(h),Buffer.from(f)).toString("base64"),A=await gw.hmacSha256(p,"Server Key"),x=await gw.hmacSha256(A,l);t.message="SASLResponse",t.serverSignature=Buffer.from(x).toString("base64"),t.response=u+",p="+g}function X_n(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:n}=tkn(e);if(n!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function Z_n(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,n)=>t.charCodeAt(n)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function pet(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}function het(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let n=e[0],r=e.substring(2);return[n,r]}))}function ekn(t){let e=het(t),n=e.get("r");if(n){if(!Z_n(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let r=e.get("s");if(r){if(!pet(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let i=e.get("i");if(i){if(!/^[1-9][0-9]*$/.test(i))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let o=parseInt(i,10);return{nonce:n,salt:r,iteration:o}}function tkn(t){let e=het(t),n=e.get("e"),r=e.get("v");if(n)throw new Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${n}"`);if(r){if(!pet(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}function nkn(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((n,r)=>t[r]^e[r]))}met.exports={startSession:Y_n,continueSession:J_n,finalizeSession:X_n,DEFAULT_MAX_SCRAM_ITERATIONS:pge}});var Q6=Q((Swi,get)=>{"use strict";var rkn=QF();function L6(t){this._types=t||rkn,this.text={},this.binary={}}L6.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};L6.prototype.setTypeParser=function(t,e,n){typeof e=="function"&&(n=e,e="text"),this.getOverrides(e)[t]=n};L6.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};get.exports=L6});var Eet=Q((_wi,yet)=>{"use strict";function iB(t,e={}){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let n=Object.create(null),r,i=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/%25(\d\d)/g,"%$1"));try{try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),i=!0}}catch(c){throw c.input&&(c.input="*****REDACTED*****"),c}for(let c of r.searchParams.entries())n[c[0]]=c[1];if(n.user=n.user||decodeURIComponent(r.username),n.password=n.password||decodeURIComponent(r.password),r.protocol=="socket:")return n.host=decodeURI(r.pathname),n.database=r.searchParams.get("db"),n.client_encoding=r.searchParams.get("encoding"),n;let o=(i?"":r.hostname).replace(/^\[(.+)\]$/,"$1");n.host?o&&/^%2f/i.test(o)&&(r.pathname=o+r.pathname):n.host=decodeURIComponent(o),n.port||(n.port=r.port);let s=r.pathname.slice(1)||null;n.database=s?decodeURI(s):null,(n.ssl==="true"||n.ssl==="1")&&(n.ssl=!0),n.ssl==="0"&&(n.ssl=!1),(n.sslcert||n.sslkey||n.sslrootcert||n.sslmode)&&(n.ssl={}),n.sslnegotiation==="direct"&&n.ssl===void 0&&(n.ssl=!0);let a=n.sslcert||n.sslkey||n.sslrootcert?K("fs"):null;if(n.sslcert&&(n.ssl.cert=a.readFileSync(n.sslcert).toString()),n.sslkey&&(n.ssl.key=a.readFileSync(n.sslkey).toString()),n.sslrootcert&&(n.ssl.ca=a.readFileSync(n.sslrootcert).toString()),e.useLibpqCompat&&n.uselibpqcompat)throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(n.uselibpqcompat==="true"||e.useLibpqCompat)switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":{n.ssl.rejectUnauthorized=!1;break}case"require":{n.sslrootcert?n.ssl.checkServerIdentity=function(){}:n.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!n.ssl.ca)throw new Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");n.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{n.sslmode!=="verify-full"&&hge(n.sslmode);break}case"no-verify":{n.ssl.rejectUnauthorized=!1;break}}return n}function ikn(t){return Object.entries(t).reduce((n,[r,i])=>(i!=null&&(n[r]=i),n),Object.create(null))}function Aet(t){return Object.entries(t).reduce((n,[r,i])=>{if(r==="ssl"){let o=i;typeof o=="boolean"&&(n[r]=o),typeof o=="object"&&(n[r]=ikn(o))}else if(i!=null)if(r==="port"){if(i!==""){let o=parseInt(i,10);if(isNaN(o))throw new Error(`Invalid ${r}: ${i}`);n[r]=o}}else n[r]=i;return n},Object.create(null))}function okn(t){return Aet(iB(t))}function hge(t){!hge.warned&&typeof process<"u"&&process.emitWarning&&(hge.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
91
91
  In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
92
92
 
@@ -97,7 +97,7 @@ To prepare for this change:
97
97
  See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}yet.exports=iB;iB.parse=iB;iB.toClientConfig=Aet;iB.parseIntoClientConfig=okn});var fge=Q((kwi,bet)=>{"use strict";var skn=K("dns"),xet=OF(),wet=Eet().parse,ou=function(t,e,n){return e[t]?e[t]:(n===void 0?n=process.env["PG"+t.toUpperCase()]:n===!1||(n=process.env[n]),n||xet[t])},akn=function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return xet.ssl},oB=function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},Yd=function(t,e,n){let r=e[n];r!=null&&t.push(n+"="+oB(r))},mge=class{constructor(e){if(e=typeof e=="string"?wet(e):e||{},e.connectionString&&(e=Object.assign({},e,wet(e.connectionString))),this.user=ou("user",e),this.database=ou("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(ou("port",e),10),this.host=ou("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:ou("password",e)}),this.binary=ou("binary",e),this.options=ou("options",e),this.ssl=typeof e.ssl>"u"?akn():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.sslnegotiation=ou("sslnegotiation",e,"PGSSLNEGOTIATION"),this.sslnegotiation!==void 0&&this.sslnegotiation!=="postgres"&&this.sslnegotiation!=="direct")throw new Error(`Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`);if(this.sslnegotiation==="direct"&&!this.ssl)throw new Error("sslnegotiation=direct requires SSL to be enabled");this.client_encoding=ou("client_encoding",e),this.replication=ou("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=ou("application_name",e,"PGAPPNAME"),this.fallback_application_name=ou("fallback_application_name",e,!1),this.statement_timeout=ou("statement_timeout",e,!1),this.lock_timeout=ou("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=ou("idle_in_transaction_session_timeout",e,!1),this.query_timeout=ou("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){let n=[];Yd(n,this,"user"),Yd(n,this,"password"),Yd(n,this,"port"),Yd(n,this,"application_name"),Yd(n,this,"fallback_application_name"),Yd(n,this,"connect_timeout"),Yd(n,this,"options");let r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(Yd(n,r,"sslmode"),Yd(n,r,"sslca"),Yd(n,r,"sslkey"),Yd(n,r,"sslcert"),Yd(n,r,"sslrootcert"),Yd(n,this,"sslnegotiation"),this.database&&n.push("dbname="+oB(this.database)),this.replication&&n.push("replication="+oB(this.replication)),this.host&&n.push("host="+oB(this.host)),this.isDomainSocket)return e(null,n.join(" "));this.client_encoding&&n.push("client_encoding="+oB(this.client_encoding)),skn.lookup(this.host,function(i,o){return i?e(i,null):(n.push("hostaddr="+oB(o)),e(null,n.join(" ")))})}};bet.exports=mge});var Age=Q((Twi,Iet)=>{"use strict";var ckn=QF(),Cet=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,gge=class{constructor(e,n){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=n,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let n;e.text?n=Cet.exec(e.text):n=Cet.exec(e.command),n&&(this.command=n[1],n[3]?(this.oid=parseInt(n[2],10),this.rowCount=parseInt(n[3],10)):n[2]&&(this.rowCount=parseInt(n[2],10)))}_parseRowAsArray(e){let n=new Array(e.length);for(let r=0,i=e.length;r<i;r++){let o=e[r];o!==null?n[r]=this._parsers[r](o):n[r]=null}return n}parseRow(e){let n={...this._prebuiltEmptyResultObject};for(let r=0,i=e.length;r<i;r++){let o=e[r],s=this.fields[r].name;if(o!==null){let a=this.fields[r].format==="binary"?Buffer.from(o):o;n[s]=this._parsers[r](a)}else n[s]=null}return n}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));let n=Object.create(null);for(let r=0;r<e.length;r++){let i=e[r];n[i.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(i.dataTypeID,i.format||"text"):this._parsers[r]=ckn.getTypeParser(i.dataTypeID,i.format||"text")}this._prebuiltEmptyResultObject={...n}}};Iet.exports=gge});var Tet=Q((Rwi,ket)=>{"use strict";var{EventEmitter:ukn}=K("events"),vet=Age(),_et=qI(),yge=class extends ukn{constructor(e,n,r){super(),e=_et.normalizeQueryConfig(e,n,r),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new vet(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new vet(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let n;if(!this._canceledDueToError){try{n=this._result.parseRow(e.fields)}catch(r){this._canceledDueToError=r;return}this.emit("row",n,this._result),this._accumulateRows&&this._result.addRow(n)}}handleCommandComplete(e,n){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&n.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,n){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(n){process.nextTick(()=>{throw n})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let n=e.parsedStatements[this.name]||e.submittedNamedStatements[this.name];if(this.text&&n&&this.text!==n)return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return new Error("Query values must be an array");if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&(e.parsedStatements[this.name]!==void 0||e.submittedNamedStatements[this.name]!==void 0)}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,n){e.execute({portal:this.portal,rows:n}),n?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||(e.parse({text:this.text,name:this.name,types:this.types}),this.name&&(e.submittedNamedStatements[this.name]=this.text));try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:_et.prepareValue})}catch(n){e.close({type:"S",name:this.name}),e.sync(),this.handleError(n,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,n){}};ket.exports=yge});var Mge=Q($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.NoticeMessage=$n.DataRowMessage=$n.CommandCompleteMessage=$n.ReadyForQueryMessage=$n.NotificationResponseMessage=$n.BackendKeyDataMessage=$n.AuthenticationMD5Password=$n.ParameterStatusMessage=$n.ParameterDescriptionMessage=$n.RowDescriptionMessage=$n.Field=$n.CopyResponse=$n.CopyDataMessage=$n.DatabaseError=$n.copyDone=$n.emptyQuery=$n.replicationStart=$n.portalSuspended=$n.noData=$n.closeComplete=$n.bindComplete=$n.parseComplete=void 0;$n.parseComplete={name:"parseComplete",length:5};$n.bindComplete={name:"bindComplete",length:5};$n.closeComplete={name:"closeComplete",length:5};$n.noData={name:"noData",length:5};$n.portalSuspended={name:"portalSuspended",length:5};$n.replicationStart={name:"replicationStart",length:4};$n.emptyQuery={name:"emptyQuery",length:4};$n.copyDone={name:"copyDone",length:4};var Ege=class extends Error{constructor(e,n,r){super(e),this.length=n,this.name=r}};$n.DatabaseError=Ege;var wge=class{constructor(e,n){this.length=e,this.chunk=n,this.name="copyData"}};$n.CopyDataMessage=wge;var xge=class{constructor(e,n,r,i){this.length=e,this.name=n,this.binary=r,this.columnTypes=new Array(i)}};$n.CopyResponse=xge;var bge=class{constructor(e,n,r,i,o,s,a){this.name=e,this.tableID=n,this.columnID=r,this.dataTypeID=i,this.dataTypeSize=o,this.dataTypeModifier=s,this.format=a}};$n.Field=bge;var Cge=class{constructor(e,n){this.length=e,this.fieldCount=n,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};$n.RowDescriptionMessage=Cge;var Ige=class{constructor(e,n){this.length=e,this.parameterCount=n,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};$n.ParameterDescriptionMessage=Ige;var vge=class{constructor(e,n,r){this.length=e,this.parameterName=n,this.parameterValue=r,this.name="parameterStatus"}};$n.ParameterStatusMessage=vge;var Sge=class{constructor(e,n){this.length=e,this.salt=n,this.name="authenticationMD5Password"}};$n.AuthenticationMD5Password=Sge;var _ge=class{constructor(e,n,r){this.length=e,this.processID=n,this.secretKey=r,this.name="backendKeyData"}};$n.BackendKeyDataMessage=_ge;var kge=class{constructor(e,n,r,i){this.length=e,this.processId=n,this.channel=r,this.payload=i,this.name="notification"}};$n.NotificationResponseMessage=kge;var Tge=class{constructor(e,n){this.length=e,this.status=n,this.name="readyForQuery"}};$n.ReadyForQueryMessage=Tge;var Rge=class{constructor(e,n){this.length=e,this.text=n,this.name="commandComplete"}};$n.CommandCompleteMessage=Rge;var Bge=class{constructor(e,n){this.length=e,this.fields=n,this.name="dataRow",this.fieldCount=n.length}};$n.DataRowMessage=Bge;var Dge=class{constructor(e,n){this.length=e,this.message=n,this.name="notice"}};$n.NoticeMessage=Dge});var Ret=Q(O6=>{"use strict";Object.defineProperty(O6,"__esModule",{value:!0});O6.Writer=void 0;var Pge=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){if(this.buffer.length-this.offset<e){let r=this.buffer,i=r.length+(r.length>>1)+e;this.buffer=Buffer.allocUnsafe(i),r.copy(this.buffer,0,0,this.offset)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{let n=Buffer.byteLength(e);this.ensure(n+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=n}return this.buffer[this.offset++]=0,this}addString(e=""){let n=Buffer.byteLength(e);return this.ensure(n),this.buffer.write(e,this.offset),this.offset+=n,this}addInt32PrefixedString(e){let n=Buffer.byteLength(e);this.ensure(4+n);let r=this.buffer,i=this.offset;return r[i++]=n>>>24&255,r[i++]=n>>>16&255,r[i++]=n>>>8&255,r[i++]=n>>>0&255,r.write(e,i,"utf-8"),this.offset=i+n,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}reserveUnsafe(e){let n=this.offset;return this.ensure(e),this.offset+=e,n}join(e){if(e){this.buffer[this.headerPosition]=e;let n=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(n,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let n=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),n}clear(){this.offset=5,this.headerPosition=0}};O6.Writer=Pge});var Met=Q(U6=>{"use strict";Object.defineProperty(U6,"__esModule",{value:!0});U6.serialize=void 0;var Bet=Ret(),Vi=new Bet.Writer,lkn=t=>{Vi.addInt16(3).addInt16(0);for(let r of Object.keys(t))Vi.addCString(r).addCString(t[r]);Vi.addCString("client_encoding").addCString("UTF8");let e=Vi.addCString("").flush(),n=e.length+4;return new Bet.Writer().addInt32(n).add(e).flush()},dkn=()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},pkn=t=>Vi.addCString(t).flush(112),hkn=function(t,e){return Vi.addCString(t).addInt32PrefixedString(e),Vi.flush(112)},mkn=function(t){return Vi.addString(t).flush(112)},fkn=t=>Vi.addCString(t).flush(81),Det=[],gkn=t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let n=t.types||Det,r=n.length,i=Vi.addCString(e).addCString(t.text).addInt16(r);for(let o=0;o<r;o++)i.addInt32(n[o]);return Vi.flush(80)},Akn=function(t,e,n){let r=t.length;for(let i=0;i<r;i++){let o=e?e(t[i],i):t[i],s=0;o==null?Vi.addInt32(-1):o instanceof Buffer?(s=1,Vi.addInt32(o.length),Vi.add(o)):Vi.addInt32PrefixedString(o);let a=Vi.buffer;a[n++]=0,a[n++]=s}},ykn=(t={})=>{let e=t.portal||"",n=t.statement||"",r=t.binary||!1,i=t.values||Det,o=i.length;Vi.addCString(e).addCString(n),Vi.addInt16(o);let s=Vi.reserveUnsafe(o*2);Vi.addInt16(o);try{Akn(i,t.valueMapper,s)}catch(a){throw Vi.clear(),a}return Vi.addInt16(1),Vi.addInt16(r?1:0),Vi.flush(66)},Ekn=Buffer.from([69,0,0,0,9,0,0,0,0,0]),wkn=t=>{if(!t||!t.portal&&!t.rows)return Ekn;let e=t.portal||"",n=t.rows||0,r=Buffer.byteLength(e),i=4+r+1+4,o=Buffer.allocUnsafe(1+i);return o[0]=69,o.writeInt32BE(i,1),o.write(e,5,"utf-8"),o[r+5]=0,o.writeUInt32BE(n,o.length-4),o},xkn=(t,e)=>{let n=Buffer.allocUnsafe(16);return n.writeInt32BE(16,0),n.writeInt16BE(1234,4),n.writeInt16BE(5678,6),n.writeInt32BE(t,8),n.writeInt32BE(e,12),n},Nge=(t,e)=>{let r=4+Buffer.byteLength(e)+1,i=Buffer.allocUnsafe(1+r);return i[0]=t,i.writeInt32BE(r,1),i.write(e,5,"utf-8"),i[r]=0,i},bkn=Vi.addCString("P").flush(68),Ckn=Vi.addCString("S").flush(68),Ikn=t=>t.name?Nge(68,`${t.type}${t.name||""}`):t.type==="P"?bkn:Ckn,vkn=t=>{let e=`${t.type}${t.name||""}`;return Nge(67,e)},Skn=t=>Vi.add(t).flush(100),_kn=t=>Nge(102,t),F6=t=>Buffer.from([t,0,0,0,4]),kkn=F6(72),Tkn=F6(83),Rkn=F6(88),Bkn=F6(99),Dkn={startup:lkn,password:pkn,requestSsl:dkn,sendSASLInitialResponseMessage:hkn,sendSCRAMClientFinalMessage:mkn,query:fkn,parse:gkn,bind:ykn,execute:wkn,describe:Ikn,close:vkn,flush:()=>kkn,sync:()=>Tkn,end:()=>Rkn,copyData:Skn,copyDone:()=>Bkn,copyFail:_kn,cancel:xkn};U6.serialize=Dkn});var Pet=Q($6=>{"use strict";Object.defineProperty($6,"__esModule",{value:!0});$6.BufferReader=void 0;var Lge=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(e,n){this.offset=e,this.buffer=n}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let n=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,n}cstring(){let e=this.offset,n=e;for(;this.buffer[n++];);return this.offset=n,this.buffer.toString(this.encoding,e,n-1)}bytes(e){let n=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,n}};$6.BufferReader=Lge});var Oet=Q(W6=>{"use strict";Object.defineProperty(W6,"__esModule",{value:!0});W6.Parser=void 0;var as=Mge(),Mkn=Pet(),Oge=1,Pkn=4,Net=Oge+Pkn,Jd=-1,Qge=Buffer.allocUnsafe(0),Fge=class{constructor(e){if(this.buffer=Qge,this.bufferLength=0,this.bufferOffset=0,this.reader=new Mkn.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,n){this.mergeBuffer(e);let r=this.bufferOffset+this.bufferLength,i=this.bufferOffset;for(;i+Net<=r;){let o=this.buffer[i],s=this.buffer.readUInt32BE(i+Oge),a=Oge+s;if(a+i<=r){let c=this.handlePacket(i+Net,o,s,this.buffer);n(c),i+=a}else break}i===r?(this.buffer=Qge,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=r-i,this.bufferOffset=i)}mergeBuffer(e){if(this.bufferLength>0){let n=this.bufferLength+e.byteLength;if(n+this.bufferOffset>this.buffer.byteLength){let i;if(n<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)i=this.buffer;else{let o=this.buffer.byteLength*2;for(;n>=o;)o*=2;i=Buffer.allocUnsafe(o)}this.buffer.copy(i,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=i,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=n}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,n,r,i){let{reader:o}=this;o.setBuffer(e,i);let s;switch(n){case 50:s=as.bindComplete;break;case 49:s=as.parseComplete;break;case 51:s=as.closeComplete;break;case 110:s=as.noData;break;case 115:s=as.portalSuspended;break;case 99:s=as.copyDone;break;case 87:s=as.replicationStart;break;case 73:s=as.emptyQuery;break;case 68:s=Gkn(o);break;case 67:s=Lkn(o);break;case 90:s=Nkn(o);break;case 65:s=Ukn(o);break;case 82:s=zkn(o,r);break;case 83:s=qkn(o);break;case 75:s=jkn(o);break;case 69:s=Let(o,"error");break;case 78:s=Let(o,"notice");break;case 84:s=$kn(o);break;case 116:s=Hkn(o);break;case 71:s=Okn(o);break;case 72:s=Fkn(o);break;case 100:s=Qkn(o,r);break;default:return new as.DatabaseError("received invalid response: "+n.toString(16),r,"error")}return o.setBuffer(0,Qge),s.length=r,s}};W6.Parser=Fge;var Nkn=t=>{let e=t.string(1);return new as.ReadyForQueryMessage(Jd,e)},Lkn=t=>{let e=t.cstring();return new as.CommandCompleteMessage(Jd,e)},Qkn=(t,e)=>{let n=t.bytes(e-4);return new as.CopyDataMessage(Jd,n)},Okn=t=>Qet(t,"copyInResponse"),Fkn=t=>Qet(t,"copyOutResponse"),Qet=(t,e)=>{let n=t.byte()!==0,r=t.int16(),i=new as.CopyResponse(Jd,e,n,r);for(let o=0;o<r;o++)i.columnTypes[o]=t.int16();return i},Ukn=t=>{let e=t.int32(),n=t.cstring(),r=t.cstring();return new as.NotificationResponseMessage(Jd,e,n,r)},$kn=t=>{let e=t.int16(),n=new as.RowDescriptionMessage(Jd,e);for(let r=0;r<e;r++)n.fields[r]=Wkn(t);return n},Wkn=t=>{let e=t.cstring(),n=t.uint32(),r=t.int16(),i=t.uint32(),o=t.int16(),s=t.int32(),a=t.int16()===0?"text":"binary";return new as.Field(e,n,r,i,o,s,a)},Hkn=t=>{let e=t.int16(),n=new as.ParameterDescriptionMessage(Jd,e);for(let r=0;r<e;r++)n.dataTypeIDs[r]=t.uint32();return n},Gkn=t=>{let e=t.int16(),n=new Array(e);for(let r=0;r<e;r++){let i=t.int32();n[r]=i===-1?null:t.string(i)}return new as.DataRowMessage(Jd,n)},qkn=t=>{let e=t.cstring(),n=t.cstring();return new as.ParameterStatusMessage(Jd,e,n)},jkn=t=>{let e=t.int32(),n=t.int32();return new as.BackendKeyDataMessage(Jd,e,n)},zkn=(t,e)=>{let n=t.int32(),r={name:"authenticationOk",length:e};switch(n){case 0:break;case 3:r.length===8&&(r.name="authenticationCleartextPassword");break;case 5:if(r.length===12){r.name="authenticationMD5Password";let i=t.bytes(4);return new as.AuthenticationMD5Password(Jd,i)}break;case 10:{r.name="authenticationSASL",r.mechanisms=[];let i;do i=t.cstring(),i&&r.mechanisms.push(i);while(i)}break;case 11:r.name="authenticationSASLContinue",r.data=t.string(e-8);break;case 12:r.name="authenticationSASLFinal",r.data=t.string(e-8);break;default:throw new Error("Unknown authenticationOk message type "+n)}return r},Let=(t,e)=>{let n={},r=t.string(1);for(;r!=="\0";)n[r]=t.cstring(),r=t.string(1);let i=n.M,o=e==="notice"?new as.NoticeMessage(Jd,i):new as.DatabaseError(i,Jd,e);return o.severity=n.S,o.code=n.C,o.detail=n.D,o.hint=n.H,o.position=n.P,o.internalPosition=n.p,o.internalQuery=n.q,o.where=n.W,o.schema=n.s,o.table=n.t,o.column=n.c,o.dataType=n.d,o.constraint=n.n,o.file=n.F,o.line=n.L,o.routine=n.R,o}});var Uge=Q(VI=>{"use strict";Object.defineProperty(VI,"__esModule",{value:!0});VI.DatabaseError=VI.serialize=void 0;VI.parse=Jkn;var Vkn=Mge();Object.defineProperty(VI,"DatabaseError",{enumerable:!0,get:function(){return Vkn.DatabaseError}});var Kkn=Met();Object.defineProperty(VI,"serialize",{enumerable:!0,get:function(){return Kkn.serialize}});var Ykn=Oet();function Jkn(t,e){let n=new Ykn.Parser;return t.on("data",r=>n.parse(r,e)),new Promise(r=>t.on("end",()=>r()))}});var Fet=Q($ge=>{"use strict";Object.defineProperty($ge,"__esModule",{value:!0});$ge.default={}});var $et=Q((Owi,Uet)=>{var{getStream:Xkn,getSecureStream:Zkn}=rTn();Uet.exports={getStream:Xkn,getSecureStream:Zkn};function eTn(){function t(n){let r=K("net");return new r.Socket}function e(n){return K("tls").connect(n)}return{getStream:t,getSecureStream:e}}function tTn(){function t(n){let{CloudflareSocket:r}=Fet();return new r(n)}function e(n){return n.socket.startTls(n),n.socket}return{getStream:t,getSecureStream:e}}function nTn(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let t=new Response(null,{cf:{thing:!0}});if(typeof t.cf=="object"&&t.cf!==null&&t.cf.thing)return!0}return!1}function rTn(){return nTn()?tTn():eTn()}});var Hge=Q((Fwi,Het)=>{"use strict";var iTn=K("events").EventEmitter,{parse:oTn,serialize:Xa}=Uge(),Wet=$et(),{getStream:sTn}=Wet,aTn=Xa.flush(),cTn=Xa.sync(),uTn=Xa.end(),Wge=class extends iTn{constructor(e){super(),e=e||{},this.stream=e.stream||sTn(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.parsedStatements={},this.submittedNamedStatements={},this.ssl=e.ssl||!1,this.sslNegotiation=e.sslNegotiation||"postgres",this._ending=!1,this._emitMessage=!1;let n=this;this.on("newListener",function(r){r==="message"&&(n._emitMessage=!0)})}connect(e,n){let r=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,n),this.stream.once("connect",function(){r._keepAlive&&r.stream.setKeepAlive(!0,r._keepAliveInitialDelayMillis),r.emit("connect")});let i=function(o){r._ending&&(o.code==="ECONNRESET"||o.code==="EPIPE")||r.emit("error",o)};if(this.stream.on("error",i),this.stream.on("close",function(){r.emit("end")}),!this.ssl)return this.attachListeners(this.stream);if(this.sslNegotiation==="direct")return this.stream.once("connect",function(){r.upgradeToSSL(n,i)});this.stream.once("data",function(o){switch(o.toString("utf8")){case"S":break;case"N":return r.stream.end(),r.emit("error",new Error("The server does not support SSL connections"));default:return r.stream.end(),r.emit("error",new Error("There was an error establishing an SSL connection"))}r.upgradeToSSL(n,i)})}upgradeToSSL(e,n){let r=this,i={socket:r.stream,host:e};r.ssl!==!0&&(Object.assign(i,r.ssl),"key"in r.ssl&&(i.key=r.ssl.key)),r.sslNegotiation==="direct"&&(i.ALPNProtocols=["postgresql"]);let o=K("net");o.isIP&&o.isIP(e)===0&&(i.servername=e);try{r.stream=Wet.getSecureStream(i)}catch(s){return r.emit("error",s)}r.attachListeners(r.stream),r.stream.on("error",n),r.emit("sslconnect")}attachListeners(e){oTn(e,n=>{let r=n.name==="error"?"errorMessage":n.name;this._emitMessage&&this.emit("message",n),this.emit(r,n)})}requestSsl(){this.stream.write(Xa.requestSsl())}startup(e){this.stream.write(Xa.startup(e))}cancel(e,n){this._send(Xa.cancel(e,n))}password(e){this._send(Xa.password(e))}sendSASLInitialResponseMessage(e,n){this._send(Xa.sendSASLInitialResponseMessage(e,n))}sendSCRAMClientFinalMessage(e){this._send(Xa.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(Xa.query(e))}parse(e){this._send(Xa.parse(e))}bind(e){this._send(Xa.bind(e))}execute(e){this._send(Xa.execute(e))}flush(){this.stream.writable&&this.stream.write(aTn)}sync(){this._send(cTn)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(uTn,()=>{this.stream.end()})}close(e){this._send(Xa.close(e))}describe(e){this._send(Xa.describe(e))}sendCopyFromChunk(e){this._send(Xa.copyData(e))}endCopyFrom(){this._send(Xa.copyDone())}sendCopyFail(e){this._send(Xa.copyFail(e))}};Het.exports=Wge});var zet=Q((Uwi,jet)=>{"use strict";var{Transform:lTn}=K("stream"),{StringDecoder:dTn}=K("string_decoder"),Aw=Symbol("last"),H6=Symbol("decoder");function pTn(t,e,n){let r;if(this.overflow){if(r=this[H6].write(t).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[Aw]+=this[H6].write(t),r=this[Aw].split(this.matcher);this[Aw]=r.pop();for(let i=0;i<r.length;i++)try{qet(this,this.mapper(r[i]))}catch(o){return n(o)}if(this.overflow=this[Aw].length>this.maxLength,this.overflow&&!this.skipOverflow){n(new Error("maximum buffer reached"));return}n()}function hTn(t){if(this[Aw]+=this[H6].end(),this[Aw])try{qet(this,this.mapper(this[Aw]))}catch(e){return t(e)}t()}function qet(t,e){e!==void 0&&t.push(e)}function Get(t){return t}function mTn(t,e,n){switch(t=t||/\r?\n/,e=e||Get,n=n||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(n=t,t=/\r?\n/);break;case 2:typeof t=="function"?(n=e,e=t,t=/\r?\n/):typeof e=="object"&&(n=e,e=Get)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=pTn,n.flush=hTn,n.readableObjectMode=!0;let r=new lTn(n);return r[Aw]="",r[H6]=new dTn("utf8"),r.matcher=t,r.mapper=e,r.maxLength=n.maxLength,r.skipOverflow=n.skipOverflow||!1,r.overflow=!1,r._destroy=function(i,o){this._writableState.errorEmitted=!1,o(i)},r}jet.exports=mTn});var Yet=Q(($wi,j0)=>{"use strict";var Vet=K("path"),fTn=K("stream").Stream,gTn=zet(),Ket=K("util"),ATn=5432,G6=process.platform==="win32",UF=process.stderr,yTn=56,ETn=7,wTn=61440,xTn=32768;function bTn(t){return(t&wTn)==xTn}var sB=["host","port","database","user","password"],Gge=sB.length,CTn=sB[Gge-1];function qge(){var t=UF instanceof fTn&&UF.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(`
98
98
  `);UF.write(Ket.format.apply(Ket,e))}}Object.defineProperty(j0.exports,"isWin",{get:function(){return G6},set:function(t){G6=t}});j0.exports.warnTo=function(t){var e=UF;return UF=t,e};j0.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(G6?Vet.join(e.APPDATA||"./","postgresql","pgpass.conf"):Vet.join(e.HOME||"./",".pgpass"));return n};j0.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:G6?!0:(e=e||"<unkn>",bTn(t.mode)?t.mode&(yTn|ETn)?(qge('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(qge('WARNING: password file "%s" is not a plain file',e),!1))};var ITn=j0.exports.match=function(t,e){return sB.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||ATn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};j0.exports.getPassword=function(t,e,n){var r,i=e.pipe(gTn());function o(c){var u=vTn(c);u&&STn(u)&&ITn(t,u)&&(r=u[CTn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),qge("WARNING: error on reading file: %s",c),n(void 0)};e.on("error",a),i.on("data",o).on("end",s).on("error",a)};var vTn=j0.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",n="",r=0,i=0,o=0,s={},a=!1,c=function(l,d,p){var h=t.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(h=h.replace(/\\([:\\])/g,"$1")),s[sB[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==Gge-1,a){c(r,i);break}u>=0&&e==":"&&n!=="\\"&&(c(r,i,u+1),i=u+2,r+=1)}return s=Object.keys(s).length===Gge?s:null,s},STn=j0.exports.isValidEntry=function(t){for(var e={0:function(s){return s.length>0},1:function(s){return s==="*"?!0:(s=Number(s),isFinite(s)&&s>0&&s<9007199254740992&&Math.floor(s)===s)},2:function(s){return s.length>0},3:function(s){return s.length>0},4:function(s){return s.length>0}},n=0;n<sB.length;n+=1){var r=e[n],i=t[sB[n]]||"",o=r(i);if(!o)return!1}return!0}});var Xet=Q((Hwi,jge)=>{"use strict";var Wwi=K("path"),Jet=K("fs"),q6=Yet();jge.exports=function(t,e){var n=q6.getFileName();Jet.stat(n,function(r,i){if(r||!q6.usePgPass(i,n))return e(void 0);var o=Jet.createReadStream(n);q6.getPassword(t,o,e)})};jge.exports.warnTo=q6.warnTo});var ntt=Q((Gwi,ttt)=>{var _Tn=K("events").EventEmitter,Zet=qI(),$F=K("util"),j6=fet(),kTn=Q6(),TTn=fge(),zge=Tet(),RTn=OF(),BTn=Hge(),DTn=lge(),ett=$F.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),MTn=$F.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),PTn=$F.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),NTn=$F.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),LTn=$F.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");function QTn(t,e){if(typeof t=="number")return Number.isFinite(t)?t:e;if(typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isFinite(n)?n:e}return e}var z6=class extends _Tn{constructor(e){super(),this.connectionParameters=new TTn(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let n=e||{};n.Promise&&NTn(),this._Promise=n.Promise||global.Promise,this._types=new kTn(n.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!n.enableChannelBinding,this.scramMaxIterations=QTn(n.scramMaxIterations,j6.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new BTn({stream:n.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:n.keepAlive||!1,keepAliveInitialDelayMillis:n.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!n.pipeline,this.binary=n.binary||RTn.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||"postgres",this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=n.connectionTimeoutMillis||0}get activeQuery(){return ett(),this._activeQuery}set activeQuery(e){ett(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let n=i=>{process.nextTick(()=>{i.handleError(e,this.connection)})},r=this._getActiveQuery();r&&(n(r),this._activeQuery=null),this._sentQueryQueue.forEach(n),this._sentQueryQueue.length=0,this._queryQueue.forEach(n),this._queryQueue.length=0}_connect(e){let n=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let i=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(i)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){n.ssl?n.sslNegotiation!=="direct"&&r.requestSsl():r.startup(n.getStartupConf())}),r.on("sslconnect",function(){r.startup(n.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let i=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((n,r)=>{this._connect(i=>{i?r(i):n(this)})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_getPassword(e){let n=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(r=>{if(r!==void 0){if(typeof r!="string"){n.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{n.emit("error",r)});else if(this.password!==null)e();else try{Xet()(this.connectionParameters,i=>{i!==void 0&&(PTn(),this.connectionParameters.password=this.password=i),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let n=await DTn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=j6.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(n){this.connection.emit("error",n)}})}async _handleAuthSASLContinue(e){try{await j6.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(n){this.connection.emit("error",n)}}_handleAuthSASLFinal(e){try{j6.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(n){this.connection.emit("error",n)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let n=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,n&&n.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let n=this._getActiveQuery();if(!n){this._handleErrorEvent(e);return}this._activeQuery=null,n.name&&delete this.connection.submittedNamedStatements[n.name],n.handleError(e,this.connection)}_handleRowDescription(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(r);return}n.handleRowDescription(e)}_handleDataRow(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(r);return}n.handleDataRow(e)}_handlePortalSuspended(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(r);return}n.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(r);return}n.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(r);return}n.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let n=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(n);return}e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(r);return}n.handleCopyInResponse(this.connection)}_handleCopyData(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(r);return}n.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,n={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(n.application_name=r),e.replication&&(n.replication=""+e.replication),e.statement_timeout&&(n.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(n.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(n.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(n.options=e.options),n}cancel(e,n){if(e.activeQuery===n){let r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(n)!==-1?e._queryQueue.splice(e._queryQueue.indexOf(n),1):e._sentQueryQueue.indexOf(n)!==-1&&(n.callback=()=>{})}setTypeParser(e,n,r){return this._types.setTypeParser(e,n,r)}getTypeParser(e,n){return this._types.getTypeParser(e,n)}escapeIdentifier(e){return Zet.escapeIdentifier(e)}escapeLiteral(e){return Zet.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline){this._pulsePipelinedQueryQueue();return}if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let n=e.submit(this.connection);n&&process.nextTick(()=>{e.handleError(n,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}_pulsePipelinedQueryQueue(){if(!(!this._connected||!this._queryable)){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let n=e.submit(this.connection);if(n){process.nextTick(()=>{e.handleError(n,this.connection)});continue}this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit("drain")}}query(e,n,r){let i,o;if(e==null)throw new TypeError("Client was passed a null or undefined query");if(typeof e.submit=="function")o=i=e,i.callback||(typeof n=="function"?i.callback=n:r&&(i.callback=r));else if(i=new zge(e,n,r),!i.callback)o=new this._Promise((a,c)=>{i.callback=(u,l)=>u?c(u):a(l)}).catch(a=>{throw Error.captureStackTrace(a),a});else if(typeof i.callback!="function")throw new TypeError("callback is not a function");let s=e.query_timeout||this.connectionParameters.query_timeout;if(s){let a=i.callback||(()=>{}),c=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{i.handleError(u,this.connection)}),a(u),i.callback=()=>{};let l=this._queryQueue.indexOf(i);if(l>-1)this._queryQueue.splice(l,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},s);i.callback=(u,l)=>{clearTimeout(c),a(u,l)}}if(this.binary&&!i.binary&&(i.binary=!0),i._result&&!i._result._types&&(i._result._types=this._types),this.pipeline){let a=typeof e.submit=="function"&&!(i instanceof zge)?"Custom query classes such as pg-cursor and pg-query-stream are":i.rows?"The `rows` option is":null;if(a)return process.nextTick(()=>{i.handleError(new Error(`${a} not supported in pipeline mode`),this.connection)}),o}return this._queryable?this._ending?(process.nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"),this.connection)}),o):(this._queryQueue.length>0&&!this.pipeline&&LTn(),this._queryQueue.push(i),this._pulseQueryQueue(),o):(process.nextTick(()=>{i.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),o)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e){e();return}else return this._Promise.resolve();if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once("drain",()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once("end",e);else return new this._Promise(n=>{this.connection.once("end",n)})}get queryQueue(){return MTn(),this._queryQueue}};z6.Query=zge;ttt.exports=z6});var ott=Q((qwi,itt)=>{"use strict";var OTn=K("events").EventEmitter,Vge=function(){},rtt=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},Kge=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},aB=class{constructor(e){this.callback=e}};function FTn(){throw new Error("Release called on client which has already been released to the pool.")}function V6(t,e){if(e)return{callback:e,result:void 0};let n,r,i=function(s,a){s?n(s):r(a)},o=new t(function(s,a){r=s,n=a}).catch(s=>{throw Error.captureStackTrace(s),s});return{callback:i,result:o}}function UTn(t,e){return function n(r){r.client=e,e.removeListener("error",n),e.on("error",()=>{t.log("additional client error after disconnection due to error",r)}),t._remove(e),t.emit("error",r,e)}}var Yge=class extends OTn{constructor(e,n){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||n||Jge().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let n=this.Promise;return typeof n.try=="function"?n.try(e):new n(r=>r(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(n=>{this._remove(n.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let n=this._idle.pop();clearTimeout(n.timeoutId);let r=n.client;r.ref&&r.ref();let i=n.idleListener;return this._acquireClient(r,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,n){let r=rtt(this._idle,o=>o.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(o=>o!==e);let i=this;e.end(()=>{i.emit("remove",e),typeof n=="function"&&n()})}connect(e){if(this.ending){let i=new Error("Cannot use a pool after calling end on the pool");return e?e(i):this.Promise.reject(i)}let n=V6(this.Promise,e),r=n.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new aB(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new aB(i),s=setTimeout(()=>{rtt(this._pendingQueue,a=>a.callback===i),o.timedOut=!0,n.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return s.unref&&s.unref(),this._pendingQueue.push(o),r}return this.newClient(new aB(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=UTn(this,n);this.log("checking client timeout");let i,o=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{n.connection?(this.log("ending client due to timeout"),o=!0,n.connection.stream.destroy()):n.isConnected()||(this.log("ending client due to timeout"),o=!0,n.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),n.connect(s=>{if(i&&clearTimeout(i),n.on("error",r),s)this.log("client failed to connect",s),this._clients=this._clients.filter(a=>a!==n),o&&(s=new Error("Connection terminated due to connection timeout",{cause:s})),this._pulseQueue(),e.timedOut||e.callback(s,void 0,Vge);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(n)).then(()=>{this._afterConnect(n,e,r)},a=>{this._clients=this._clients.filter(c=>c!==n),n.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,Vge)})});return}return this._afterConnect(n,e,r)}})}_afterConnect(e,n,r){if(this.options.maxLifetimeSeconds!==0){let i=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(e),this._idle.findIndex(s=>s.client===e)!==-1&&this._acquireClient(e,new aB((s,a,c)=>c()),r,!1)},this.options.maxLifetimeSeconds*1e3);i.unref(),e.once("end",()=>clearTimeout(i))}return this._acquireClient(e,n,r,!0)}_acquireClient(e,n,r,i){i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),n.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,o=>{if(o)return e.release(o),n.callback(o,void 0,Vge);n.callback(void 0,e,e.release)}):n.callback(void 0,e,e.release)}_releaseOnce(e,n){let r=!1;return i=>{r&&FTn(),r=!0,this._release(e,n,i)}}_release(e,n,r){if(e.on("error",n),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log("remove expired client"),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let o;this.options.idleTimeoutMillis&&this._isAboveMin()&&(o=setTimeout(()=>{this._isAboveMin()&&(this.log("remove idle client"),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&o.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new Kge(e,n,o)),this._pulseQueue()}query(e,n,r){if(typeof e=="function"){let o=V6(this.Promise,e);return setImmediate(function(){return o.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),o.result}typeof n=="function"&&(r=n,n=void 0);let i=V6(this.Promise,r);return r=i.callback,this.connect((o,s)=>{if(o)return r(o);let a=!1,c=u=>{a||(a=!0,s.release(u),r(u))};s.once("error",c),this.log("dispatching query");try{s.query(e,n,(u,l)=>{if(this.log("query dispatched"),s.removeListener("error",c),!a)return a=!0,s.release(u),u?r(u):r(void 0,l)})}catch(u){return s.release(u),r(u)}}),i.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let n=V6(this.Promise,e);return this._endCallback=n.callback,this._pulseQueue(),n.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,n)=>e+(this._expired.has(n)?1:0),0)}get totalCount(){return this._clients.length}};itt.exports=Yge});var ctt=Q((jwi,att)=>{"use strict";var stt=K("events").EventEmitter,$Tn=K("util"),Xge=qI(),cB=att.exports=function(t,e,n){stt.call(this),t=Xge.normalizeQueryConfig(t,e,n),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};$Tn.inherits(cB,stt);var WTn={sqlState:"code",statementPosition:"position",messagePrimary:"message",messageDetail:"detail",messageHint:"hint",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};cB.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=WTn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};cB.prototype.then=function(t,e){return this._getPromise().then(t,e)};cB.prototype.catch=function(t){return this._getPromise().catch(t)};cB.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};cB.prototype.submit=function(t){this.state="running";let e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;let n=function(r,i,o){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),r)return e.handleError(r);e._emitRowEvents&&(o.length>1?i.forEach((s,a)=>{s.forEach(c=>{e.emit("row",c,o[a])})}):i.forEach(function(s){e.emit("row",s,o)})),e.state="end",e.emit("end",o),e.callback&&e.callback(null,o)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let r=(this.values||[]).map(Xge.prepareValue);if(t.namedQueries[this.name]!==void 0){if(this.text&&t.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(i)}return t.native.execute(this.name,r,n)}return t.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,r,n))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return n(i)}let r=this.values.map(Xge.prepareValue);t.native.query(this.text,r,n)}else this.queryMode==="extended"?t.native.query(this.text,[],n):t.native.query(this.text,n)}});var htt=Q((zwi,ptt)=>{var HTn=K("util"),utt;try{utt=K("pg-native")}catch(t){throw t}var GTn=Q6(),ltt=K("events").EventEmitter,qTn=K("util"),jTn=fge(),dtt=ctt(),zTn=HTn.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),Mc=ptt.exports=function(t){ltt.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new GTn(t.types),this.native=new utt({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!t.pipeline,this._pipelineInFlight=!1;let e=this.connectionParameters=new jTn(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};Mc.Query=dtt;qTn.inherits(Mc,ltt);Mc.prototype._errorAllQueries=function(t){let e=n=>{process.nextTick(()=>{n.native=this.native,n.handleError(t)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};Mc.prototype._connect=function(t){let e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),n)return t(n);e.native.connect(r,function(i){if(i)return e.native.end(),t(i);e._connected=!0,e.native.on("error",function(o){e._queryable=!1,e._errorAllQueries(o),e.emit("error",o)}),e.native.on("notification",function(o){e.emit("notification",{channel:o.relname,payload:o.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t(null,this)})})};Mc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};Mc.prototype.query=function(t,e,n){let r,i,o,s,a;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")o=t.query_timeout||this.connectionParameters.query_timeout,i=r=t,typeof e=="function"&&(t.callback=e);else if(o=t.query_timeout||this.connectionParameters.query_timeout,r=new dtt(t,e,n),!r.callback){let c,u;i=new this._Promise((l,d)=>{c=l,u=d}).catch(l=>{throw Error.captureStackTrace(l),l}),r.callback=(l,d)=>l?u(l):c(d)}return o&&(a=r.callback||(()=>{}),s=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{r.handleError(c,this.connection)}),a(c),r.callback=()=>{};let u=this._queryQueue.indexOf(r);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},o),r.callback=(c,u)=>{clearTimeout(s),a(c,u)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.length>0&&!this.pipeline&&zTn(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),i)};Mc.prototype.end=function(t){let e=this;this._ending=!0,this._connecting&&!this._connected&&this.once("connect",()=>{this.end(()=>{})});let n;t||(n=new this._Promise(function(i,o){t=s=>s?o(s):i()}));let r=function(){e.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once("drain",r):r(),n};Mc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Mc.prototype._pulseQueryQueue=function(t){if(!this._connected)return;if(this.pipeline&&!t)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);let n=this;e.once("_done",function(){n._pulseQueryQueue()})};Mc.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit("drain");return}this._pipelineInFlight=!0;let t=this,e=[],n=[],r=qI();for(;this._queryQueue.length>0;){let i=this._queryQueue.shift();this.hasExecuted=!0,n.push(i);let o=i.values?i.values.map(r.prepareValue):null,s={text:i.text,name:i.name,arrayMode:i._arrayMode};o&&(s.values=o),i.name&&this.namedQueries[i.name]&&(s._alreadyPrepared=!0),e.push(s)}this.native.pipeline(e,function(i,o){if(t._pipelineInFlight=!1,i){t._connected=!1,t._queryable=!1;for(let s=0;s<n.length;s++){let a=n[s];a.native=t.native,a.handleError(i)}t._errorAllQueries(i),t.emit("error",i),t.emit("end");return}for(let s=0;s<n.length;s++){let a=n[s],c=o[s];a.native=t.native,c.err?a.handleError(c.err):(a.name&&(t.namedQueries[a.name]=a.text),a.state="end",a.emit("end",c.result),a.callback&&a.callback(null,c.result)),setImmediate(function(){a.emit("_done")})}t._pulsePipelinedQueryQueue()})};Mc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};Mc.prototype.ref=function(){};Mc.prototype.unref=function(){};Mc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};Mc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};Mc.prototype.isConnected=function(){return this._connected};Mc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var Zge=Q((Vwi,mtt)=>{"use strict";mtt.exports=htt()});var Jge=Q((Ywi,K6)=>{"use strict";var VTn=ntt(),KTn=OF(),YTn=Hge(),JTn=Age(),XTn=qI(),ZTn=ott(),eRn=Q6(),{DatabaseError:tRn}=Uge(),{escapeIdentifier:nRn,escapeLiteral:rRn}=qI(),iRn=t=>class extends ZTn{constructor(n){super(n,t)}},ftt=function(t){this.defaults=KTn,this.Client=t,this.Query=this.Client.Query,this.Pool=iRn(this.Client),this._pools=[],this.Connection=YTn,this.types=QF(),this.DatabaseError=tRn,this.TypeOverrides=eRn,this.escapeIdentifier=nRn,this.escapeLiteral=rRn,this.Result=JTn,this.utils=XTn},gtt=VTn,Att=!1;try{Att=!!process.env.NODE_PG_FORCE_NATIVE}catch{}Att&&(gtt=Zge());K6.exports=new ftt(gtt);Object.defineProperty(K6.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new ftt(Zge())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(K6.exports,"native",{value:t}),t}})});var Xd,Jwi,Xwi,Zwi,exi,txi,nxi,rxi,ixi,oxi,sxi,axi,ytt,Ett=y(()=>{Xd=cn(Jge(),1),Jwi=Xd.default.Client,Xwi=Xd.default.Pool,Zwi=Xd.default.Connection,exi=Xd.default.types,txi=Xd.default.Query,nxi=Xd.default.DatabaseError,rxi=Xd.default.escapeIdentifier,ixi=Xd.default.escapeLiteral,oxi=Xd.default.Result,sxi=Xd.default.TypeOverrides,axi=Xd.default.defaults,ytt=Xd.default});var oRn,sRn,eAe,lxi,wtt=y(()=>{"use strict";Ett();oRn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","review","execution_exit"],sRn=new Set(oRn),eAe=class{dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){let r={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(r),this.listener!==void 0&&r.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(r)&&this.callListenStart(r)}),()=>{this.subscribers.delete(r)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){let r=`${e}:${n}`;this.dirty.has(r)||this.dirty.set(r,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty.values()];this.dirty.clear();for(let{id:n,kind:r}of e)for(let i of this.subscribers)if(i.kinds.has(r))try{i.listener(n,r)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){let e=new ytt.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",r=>{let i=r.payload??"",o=i.indexOf(":");if(o<0)return;let s=i.slice(0,o);sRn.has(s)&&this.mark(s,i.slice(o+1))});let n=()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())};e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(r){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),r}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(let r of[...this.subscribers])this.callListenStart(r)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let r,i=new Promise((o,s)=>{r=setTimeout(()=>s(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),i]).catch(()=>n()).finally(()=>clearTimeout(r))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();let e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}},lxi=new eAe});var xtt=y(()=>{"use strict";BF()});function dRn(t){switch(t){case uRn:return"context-nudge";case aRn:return"bearings";case lRn:return"review-boundary";case cRn:return"situational";default:return}}function nAe(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"})[e])}function tAe(t){let e={};Y6.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){Y6.lastIndex=n;let r=Y6.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=nAe(o??s??""),n=Y6.lastIndex}return e}function rAe(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function pRn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=tAe(r[1]??"");if(i?.id===void 0)continue;let o=[],s=r[2]??"",a=/<entry\b([^>]*)>([\s\S]*?)<\/entry>/g;for(let u of s.matchAll(a)){let l=tAe(u[1]??"");if(l?.kind===void 0)continue;let d=l.disposition==="human-answer"||l.disposition==="human-canceled"?l.disposition:"report";o.push({kind:l.kind,disposition:d,body:nAe(u[2]??""),...l.ref===void 0?{}:{ref:l.ref}})}let c=i.updates===void 0?Number.NaN:Number(i.updates);e.push({id:i.id,updates:Number.isFinite(c)?c:o.length,finished:i.finished==="true"||o.some(u=>u.kind==="final"),entries:o})}return e}function hRn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function Stt(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=tAe(e[1]??"");if(n?.kind===void 0)return null;let r=t.slice(e[0].length,-10),{kind:i,...o}=n,s=Object.freeze(o),a=i.includes(":")?nAe(r):r;return hRn(i,s,a,i==="inbox"?pRn(a):[])}function uB(t){let e=rAe(t),n=Stt(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=dRn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function KI(t){return t.disposition==="human-answer"&&Stt(t.body.trim())===null}var aRn,cRn,uRn,lRn,btt,Ctt,Itt,vtt,Y6,YI=y(()=>{"use strict";aRn="crtr-context",cRn="crtr-situational-context",uRn="crtr-context-nudge",lRn="crtr-review-boundary",btt="Provider credentials were just updated (a new login landed). Your previous turn stopped on a provider authentication failure. Continue from where you left off and retry the work that failed.",Ctt="The network connection is back online. Your previous turn stopped on a connection error (the network was down). Continue from where you left off and retry the work that failed.",Itt="Your previous turn stopped on a connection error reaching the model provider. Retrying now: continue from where you left off and retry the work that failed.",vtt="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";Y6=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var _tt=y(()=>{"use strict";YI()});function mRn(){let t=process.env.CRTR_API_URL;if(!(t===void 0||t==="")){if(!/^https?:\/\//.test(t))throw new Error(`CRTR_API_URL must be an http(s) URL: ${t}`);return t}}function RF(){let t=mRn();if(t===void 0)return fw({autostart:!1});let e=bZe();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new Tg({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function ktt(t,e){return RF().appendNodeLog(t,{record:e,expected_execution_id:fRn()})}function fRn(){let t=FYe();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function Ttt(t,e){return RF().recordNodeFault(t,e)}async function Rtt(t,e={}){return RF().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var BF=y(()=>{"use strict";R6();CZe();B6();hw();Yfe();Dc();vZe();JI();wtt();xtt();_tt()});function ARn(t,e){Btt=Btt.then(async()=>{try{let{appended:n}=await ktt(t,e);n||process.stderr.write(`[broker] log.jsonl refused record: ${e}
99
99
  `)}catch(n){process.stderr.write(`[broker] log.jsonl append failed (${n instanceof Error?n.message:String(n)}): ${e}
100
- `)}})}function Wl(t){let e=S6();if(e===void 0)return!1;if(e.component==="broker"&&e.node_id!==void 0&&t.node_id!==void 0&&t.node_id!==e.node_id)throw new TypeError(`broker event target node_id must match bound node_id; received ${t.node_id}`);if(t.level==="debug"&&process.env.CRTR_LOG!=="debug")return!1;let n=PXe({...t,component:e.component,...e.node_id===void 0?{}:{node_id:e.node_id},...e.stream_id===void 0?{}:{stream_id:e.stream_id}}),r=LXe(n);return e.component==="broker"&&e.node_id!==void 0&&(gRn??=DI())?(ARn(e.node_id,r),!0):e.component==="daemon"?_Xe(e.path,r):m6(e.path,r)}var gRn,Btt,JI=y(()=>{"use strict";xfe();NXe();QXe();Ffe();Dc();BF();Btt=Promise.resolve()});var Dtt,Mtt=y(()=>{"use strict";JI();Dtt={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",sandboxDiskUsdPerGbMonth:"CRTR_LEDGER_SANDBOX_DISK_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});function J6(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var WF=y(()=>{"use strict"});var Ptt=y(()=>{"use strict"});import{createHash as yRn}from"node:crypto";function Qtt(t){return t===void 0?"absent":yRn("sha256").update(JSON.stringify(t)).digest("hex")}function Ott(t,e){Ltt.set(t,e)}function z0(){let t;try{t=E6()}catch(n){if(n instanceof vF)return Ntt();if(n instanceof IF)return iAe??Ntt();throw n}let e=Ltt.get(t);if(e!==void 0)return e;if(iAe!==void 0)return iAe;throw new oAe(t)}function Ftt(t){ERn=t}function Utt(t){wRn=t}function GF(t){let e=z0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:Qtt(e)}}function $tt(t){let e=z0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function Wtt(){return structuredClone(z0().profiles)}function Htt(t){let e=z0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var HF,oAe,Ltt,Ntt,iAe,ERn,wRn,lB=y(()=>{"use strict";JR();HF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},oAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},Ltt=new Map;Ntt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});ERn=async()=>{throw new Error("no settings transport installed in this process")}});var Gtt=y(()=>{"use strict"});import{chmodSync as Yxi,existsSync as qtt,mkdirSync as Jxi,readFileSync as jtt,rmSync as Xxi,writeFileSync as Zxi}from"node:fs";import{dirname as tbi,join as ztt}from"node:path";function yw(){let t=xRn();if(!qtt(t))return;let e=JSON.parse(jtt(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, runId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,runId:e.runId,directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}function CRn(){let t=bRn();if(!qtt(t))return;let e=JSON.parse(jtt(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var xRn,bRn,Vtt,Ktt,qF=y(()=>{"use strict";Xm();jd();Ol();iu();xRn=()=>ztt(Fl(),"machine.json");bRn=()=>ztt(Fl(),"import","move.json");Vtt=()=>CRn()?.state==="committed",Ktt=t=>new os("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,ji.USAGE,{next:"Run `crtr sys signin` to finish."})});function vRn(t){return t.grantee??"app:terminal"}function SRn(t){if(!Ytt.test(t))throw dw(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function X6(t){SRn(t);let e=Htt(t);if(e===null)throw p6(`profile not found: ${t}`,{received:t});return VXe(vRn(e.manifest),t).dir}function _Rn(){return{entries:Wtt(),unreadableIds:[]}}function Z6(){return _Rn().entries}function kRn(t){let e=Z6(),n=TRn(e,t,Jtt);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function TRn(t,e,n){if(Ytt.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw EXe(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function RRn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return p6(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function Rg(t){let e=kRn(t);if(e.kind==="resolved")return e.entry;throw RRn(Z6(),t,Jtt)}var Ytt,Jtt,XI=y(()=>{"use strict";iu();Xm();WF();Ol();lB();jd();Gtt();JR();qF();Ytt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Jtt=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Xtt}from"node:os";import{existsSync as BRn,statSync as DRn}from"node:fs";import{join as eV,resolve as Ztt,dirname as MRn,sep as sAe}from"node:path";function Zd(){return eV(Fl(),"scope")}function PRn(t,e){if(!BRn(t)||Jm(t)===Jm(eV(Xtt(),LI))||Jm(t).startsWith(`${Jm(Rfe())}${sAe}`)&&t.endsWith(`${sAe}home${sAe}${LI}`)||!DI()&&(Jm(t)===Jm(e)||Jm(t)===Jm(C6())))return!1;try{return DRn(t).isDirectory()}catch{return!1}}function NRn(t=process.cwd()){return ent(t)[0]??null}function LRn(t,e){let n=[],r=Jm(Xtt()),i=Ztt(t);for(;;){let o=eV(i,LI);if(PRn(o,e)&&n.push(o),Jm(i)===r)return n;let s=MRn(i);if(s===i)return n;i=s}}function ent(t=process.cwd(),e=Ume()||null){return QRn(t,e)}function QRn(t,e){let n=Ztt(t),r=Zd(),i=[n];if(!DI()&&e!==null&&e!=="")try{let{manifest:a}=Rg(e);i.push(...J6(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of LRn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function tnt(t){return NRn(t)}function V0(t){return t==="builtin"?null:t==="user"?Zd():tnt()}function nnt(t){let e=t==="user"?Fl():V0(t);return e?eV(e,"plugins"):null}var ZI=y(()=>{"use strict";Dc();WF();iu();Ptt();jd();XI();Ol();Xm()});import{join as ORn}from"node:path";function FRn(t){return ORn(t,gXe,AXe)}function URn(t){let e;try{e=$I(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function $Rn(t){return URn(FRn(t))}function rnt(t){let e=$Rn(t);return e.status==="ok"?e.manifest:null}var aAe=y(()=>{"use strict";iu();Ol()});import{existsSync as WRn,mkdirSync as HRn,readdirSync as ont,rmSync as snt,rmdirSync as GRn,statSync as qRn,unlinkSync as jRn,writeFileSync as zRn}from"node:fs";import{randomUUID as VRn}from"node:crypto";function cnt(t){return Math.min(t*2,KRn)}function unt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function uAe(t,e){return`${t}/${cAe}${e}`}function lAe(t){try{return ont(t).find(e=>e.startsWith(cAe))?.slice(cAe.length)??null}catch{return null}}function lnt(t){let e=Number(t.split(".",1)[0]);if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function XRn(t){try{return ont(t).length===0}catch{return!1}}function ZRn(t){try{return Date.now()-qRn(t).mtimeMs}catch{return 0}}function eBn(t,e){let n=lAe(t);if(n!==null){if(lnt(n))return;try{jRn(uAe(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(ZRn(t)<=e)return;if(!XRn(t)){snt(t,{recursive:!0,force:!0});return}}try{GRn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function dB(t){let e=lAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function dnt(t,e){let n=Date.now()+e,r=ant;for(;;){let i=lAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!lnt(i))return;let o=n-Date.now();if(o<=0)return;unt(Math.min(r,o)),r=cnt(r)}}function int(t,e){let n=`${process.pid}.${VRn()}`;try{return HRn(t,{mode:448}),zRn(uAe(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return eBn(t,e),null}}function ev(t,e,n={}){let r=n.staleMs??YRn,i=Date.now()+(n.timeoutMs??JRn),o=ant,s=int(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);unt(Math.min(o,Math.max(0,i-Date.now()))),o=cnt(o),s=int(t,r)}try{return e()}finally{WRn(uAe(s.path,s.token))&&snt(s.path,{recursive:!0,force:!0})}}var cAe,ant,KRn,YRn,JRn,Ew=y(()=>{"use strict";cAe="owner.",ant=10,KRn=250,YRn=3e4,JRn=5e3});import{join as tBn}from"node:path";function pnt(t,e){return tBn(t,"tmp",`${e}.swap.lock`)}function hnt(t,e){let n=dB(pnt(t,e));return n!==null&&n!==process.pid}function mnt(t,e){dnt(pnt(t,e),nBn)}var nBn,fnt=y(()=>{"use strict";Ew();nBn=2e3});function tV(t,e){let n=t.apps[rBn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var rBn,dAe=y(()=>{"use strict";Dc();lB();rBn="app:terminal"});import{join as pAe}from"node:path";function iBn(t,e){let n=t==="user"?hF()?tV(z0(),GF("user").settings):GF("user").settings:$I(pAe(e,u6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function oBn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&hnt(t,i))}function nV(t,e){if(t==="user"&&y6())return[];let n=t!=="user"?pAe(e,"plugins"):nnt("user");if(n===void 0||!kfe(n))return[];let r=iBn(t,e),i=gnt(t,n,r),o=oBn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)mnt(e,s);return gnt(t,n,r)}function gnt(t,e,n){let r=[];for(let i of Tfe(e)){let o=pAe(e,i),s=rnt(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var rV=y(()=>{"use strict";iu();Ol();aAe();fnt();JR();lB();dAe();ZI()});import{existsSync as sBn,realpathSync as aBn}from"node:fs";import{basename as cBn,dirname as uBn,join as lCi,resolve as Ant}from"node:path";function pB(t){let e=Ant(t),n=e,r=[];for(;!sBn(n);){let i=uBn(n);if(i===n)return e;r.unshift(cBn(n)),n=i}return Ant(aBn(n),...r)}var ynt=y(()=>{"use strict"});function lBn(t){let e=zi.indexOf(t);return`less ${zi.map((r,i)=>i===e?"\u25CF":"\u25CB").map((r,i)=>i===0?r:`${i<=e?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${r}`).join("")} more ${oV[t]}`}function iV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Ent(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function tv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function bnt(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function dBn(t,e){let n=bnt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function xnt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function fBn(){let t=[];for(let e of Object.values(Cnt))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var oV,wnt,pBn,hBn,jF,Cnt,mBn,hCi,hAe=y(()=>{"use strict";iu();oV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};wnt=[!1,"notify","apply"],pBn=[0,1,6,12,24,48,72,168],hBn=[1,2,3,4,5,6,8,10,12],jF="openai-codex";Cnt={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=iV(wnt,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=iV(wnt,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=Ent(pBn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=bnt(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=Ent(hBn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=dBn(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=tv(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=tv(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=tv(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=tv(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:QI.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=iV(QI,t.whip_message_mode,e)},setFromString:(t,e)=>QI.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${QI.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:OI.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=iV(OI,t.mouse_mode_default,e)},setFromString:(t,e)=>OI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${OI.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=tv(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:zi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>lBn(t.verbosity),cycle:(t,e)=>{let n=zi.indexOf(t.verbosity)+e;t.verbosity=zi[Math.max(0,Math.min(zi.length-1,n))]},setFromString:(t,e)=>zi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${zi.join("|")}`}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:t=>String(t.document_port),cycle:(t,e)=>{t.document_port=Math.max(1,Math.min(65535,t.document_port+e))},setFromString:(t,e)=>{let n=Number(e);return!/^\d+$/.test(e)||!Number.isInteger(n)||n<1||n>65535?"document_port must be an integer from 1 to 65535":(t.document_port=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=tv(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${jF}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[jF]?.fastMode?"on":"off",cycle:t=>{let e=xnt(t,jF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=tv(e,`providerOptions.${jF}.fastMode`);return typeof n=="string"?n:(xnt(t,jF).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},mBn=Object.keys(Cnt);hCi=fBn()});function zF(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function mB(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function hB(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${mB(t)}`);return t.trim()}}function AAe(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${mB(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${mB(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${mB(i)}`);s={kind:u.kind.trim(),...hB(u.description,"description",e,o)===void 0?{}:{description:hB(u.description,"description",e,o)},...hB(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:hB(u.useWhen,"useWhen",e,o)},...hB(u.doc,"doc",e,o)===void 0?{}:{doc:hB(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${mB(i)}`);let a=s.kind;if(!ABn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${mB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(yBn.has(a)||gBn.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=zF(a);if(sV.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function vnt(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=zF(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function Snt(t,e){return e.find(n=>n.kind===t)}var mAe,gBn,ABn,yBn,Int,fAe,sV,gAe,VF=y(()=>{"use strict";mAe=["options","text","table","cards","chart"],gBn=["page","step"],ABn=/^[a-z][a-z0-9-]{0,63}$/,yBn=new Set(mAe),Int=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];fAe=Object.fromEntries(Int.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),sV=new Set(Int.map(t=>t.tag)),gAe=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as Bnt,join as Dnt}from"node:path";import{existsSync as wBn,mkdirSync as xCi,statSync as bCi}from"node:fs";function xBn(t){return Dnt(t,u6)}function bBn(t){return Dnt(t,yXe)}function Mnt(t){let e=pB(t),n=pB(Zd());if(e===n)return{key:"user",kind:"user",root:n};if(Bnt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of Z6()){let i=pB(X6(r.profileId));if(e===i)return{key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function Pnt(t){if(Bnt(t)===".crouter"){let r;try{r=pB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==pB(Zd()))return $I(xBn(t))}let e=Mnt(t).key,n=GF(e).settings;return e==="user"&&hF()?tV(z0(),n):n}function dh(t){let e=CBn[IBn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=V0(t);return n?vBn(n):d6()}function vBn(t){let e=Pnt(t);return e?XBn(e):d6()}function SBn(t){let e=$I(bBn(t));return{marketplaces:e?.marketplaces??{},plugins:e?.plugins??{},activeCanvas:e?.activeCanvas??null,...e?.last_self_check===void 0?{}:{last_self_check:e.last_self_check}}}function Nnt(t){let e=V0(t);return e?t==="project"?wBn(e)?SBn(e):wfe():$tt(Mnt(e).key):wfe()}function _Bn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function fB(t){return t===void 0?[...TBn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&NI.has(e)&&kBn.has(e)))]:[]}function RBn(t,e=Efe()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function Lnt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function yAe(){return Object.create(null)}function aV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function DBn(t){let e=yAe();for(let[n,r]of Object.entries(t??{}))aV(e,n,r);return e}function KF(t,e){Wl({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function MBn(t,e={}){let n=DBn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){KF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){KF(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!Lnt(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){KF(r,c);continue}aV(n,r,a)}return n}function PBn(t){let e=yAe(),n=yAe();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){KF(r,"route must include family, credentialSource, providerId, and models");continue}let o=BBn.filter(s=>i.models[s]===void 0);if(o.length>0){KF(r,`incomplete route; missing strengths: ${o.join(", ")}`),aV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}aV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function NBn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>Lnt(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function LBn(t){return t!==""&&t.replace(/\*/g,"")===""}function QBn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(LBn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function OBn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function UBn(t,e){if(e==="bin"&&FBn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!_nt.test(t))return`${e}.${t} is not a safe bare command name (expected ${_nt.source})`}function $Bn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))UBn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function WBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(knt.test(n)||i.push(`action name must match ${knt.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function HBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(WBn(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function GBn(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function qBn(t,e=yfe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=GBn(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function uV(){let t=[{origin:"config.json",components:dh("user").page_components}],e=V0("user");if(e!==null){let n=nV("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:AAe(r.manifest.page_components,i)})}}return vnt(t)}function jBn(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function zBn(t,e=Afe()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=jBn(o);s!==null&&(n[i]=s)}}return{targets:n}}function Tnt(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function cV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function VBn(t,e){let n=t!==null&&typeof t=="object"?t:{},r=cV(n.warning,e.warning),i=cV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function KBn(t,e){return{unattendedParkMs:cV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function YBn(t){if(!Array.isArray(t))return[...l6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...l6]}function JBn(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function XBn(t){!Rnt&&t.ledger!==void 0&&(Rnt=!0,Wl({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Dtt)}}));let e=d6(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:Tnt(o?.crtr,e.auto_update.crtr),content:Tnt(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=cV(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=VBn(t.brokerThresholds,e.brokerThresholds),h=KBn(t.lifecycle,e.lifecycle),m=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,f=t.working_gerunds===void 0?[...e.working_gerunds]:mXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,A=AAe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=YBn(t.whip_messages),v=QI.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=OI.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,_=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,T=zi.includes(t.verbosity)?t.verbosity:e.verbosity,B=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,R=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,P=_Bn(t.keybindings),O=fB(t.tmux_passthrough),$=RBn(t.modelLadders),j=OBn(t.providerOptions,e.providerOptions),H=PBn(MBn(t.modelRoutes)),le=H.complete,ee=NBn(t.modelRouting,void 0),ge=qBn(t.kinds),Ie=zBn(t.remoteCanvas),$e=JBn(t.api,e.api),wt=t.paths;if(wt?.user_files!==void 0&&(typeof wt.user_files!="string"||!wt.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,xt=t.runtime;if(xt?.person_uids!==void 0&&(!Array.isArray(xt.person_uids)||!xt.person_uids.every(et=>Number.isSafeInteger(et)&&et>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let re=QBn(t.spawnEnv,e.spawnEnv?.allow),ot=$Bn(t.bin),ke=HBn(t.humanActions);return{bin:ot,humanActions:ke,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:h,completion_bell:m,working_gerunds:f,whip_mode:g,page_components:A,page_surface:x,whip_messages:b,whip_message_mode:v,mouse_mode_default:S,bash_tool_purpose:_,verbosity:T,detailed_tool_recaps:B,document_port:R,keybindings:P,tmux_passthrough:O,modelLadders:$,providerOptions:j,...Object.keys(le).length>0?{modelRoutes:le}:{},...Object.keys(H.legacy).length>0?{legacyModelRoutes:H.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:ge,remoteCanvas:Ie,api:$e,...wt?{paths:wt}:{},...Ze?{store:Ze}:{},...xt?{runtime:xt}:{},spawnEnv:re}}function ZBn(t){return Pnt(t)}function Qnt(t){let e=V0(t);return e?ZBn(e):null}var CBn,IBn,kBn,TBn,BBn,_nt,FBn,knt,Rnt,Kd=y(()=>{"use strict";Dc();iu();s6();jd();JI();Mtt();Ol();ZI();rV();XI();ynt();lB();dAe();Ew();hAe();c6();VF();CBn=globalThis,IBn=Symbol.for("crtr.broker.config-snapshot");kBn=new Set(qd.filter(xF).map(t=>t.id)),TBn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);BBn=["ultra","strong","medium","light"];_nt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,FBn=new Set(["crtr","crtrd"]);knt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Rnt=!1});var Y0=Q((FIi,rrt)=>{"use strict";var trt=["nodebuffer","arraybuffer","fragments"],nrt=typeof Blob<"u";nrt&&trt.push("blob");rrt.exports={BINARY_TYPES:trt,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:nrt,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var nU=Q((UIi,hV)=>{"use strict";var{EMPTY_BUFFER:j1n}=Y0(),GAe=Buffer[Symbol.species];function z1n(t,e){if(t.length===0)return j1n;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new GAe(n.buffer,n.byteOffset,r):n}function irt(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function ort(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function V1n(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function qAe(t){if(qAe.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new GAe(t):ArrayBuffer.isView(t)?e=new GAe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),qAe.readOnly=!1),e}hV.exports={concat:z1n,mask:irt,toArrayBuffer:V1n,toBuffer:qAe,unmask:ort};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=K("bufferutil");hV.exports.mask=function(e,n,r,i,o){o<48?irt(e,n,r,i,o):t.mask(e,n,r,i,o)},hV.exports.unmask=function(e,n){e.length<32?ort(e,n):t.unmask(e,n)}}catch{}});var crt=Q(($Ii,art)=>{"use strict";var srt=Symbol("kDone"),jAe=Symbol("kRun"),zAe=class{constructor(e){this[srt]=()=>{this.pending--,this[jAe]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[jAe]()}[jAe](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[srt])}}};art.exports=zAe});var CB=Q((WIi,prt)=>{"use strict";var rU=K("zlib"),urt=nU(),K1n=crt(),{kStatusCode:lrt}=Y0(),Y1n=Buffer[Symbol.species],J1n=Buffer.from([0,0,255,255]),fV=Symbol("permessage-deflate"),J0=Symbol("total-length"),xB=Symbol("callback"),bw=Symbol("buffers"),bB=Symbol("error"),mV,VAe=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!mV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;mV=new K1n(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[xB];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){mV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){mV.add(i=>{this._compress(e,n,(o,s)=>{i(),r(o,s)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?rU.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=rU.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[fV]=this,this._inflate[J0]=0,this._inflate[bw]=[],this._inflate.on("error",Z1n),this._inflate.on("data",drt)}this._inflate[xB]=r,this._inflate.write(e),n&&this._inflate.write(J1n),this._inflate.flush(()=>{let o=this._inflate[bB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=urt.concat(this._inflate[bw],this._inflate[J0]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[J0]=0,this._inflate[bw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?rU.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=rU.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[J0]=0,this._deflate[bw]=[],this._deflate.on("data",X1n)}this._deflate[xB]=r,this._deflate.write(e),this._deflate.flush(rU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=urt.concat(this._deflate[bw],this._deflate[J0]);n&&(o=new Y1n(o.buffer,o.byteOffset,o.length-4)),this._deflate[xB]=null,this._deflate[J0]=0,this._deflate[bw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};prt.exports=VAe;function X1n(t){this[bw].push(t),this[J0]+=t.length}function drt(t){if(this[J0]+=t.length,this[fV]._maxPayload<1||this[J0]<=this[fV]._maxPayload){this[bw].push(t);return}this[bB]=new RangeError("Max payload size exceeded"),this[bB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[bB][lrt]=1009,this.removeListener("data",drt),this.reset()}function Z1n(t){if(this[fV]._inflate=null,this[bB]){this[xB](this[bB]);return}t[lrt]=1007,this[xB](t)}});var IB=Q((HIi,gV)=>{"use strict";var{isUtf8:hrt}=K("buffer"),{hasBlob:eDn}=Y0(),tDn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function nDn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function KAe(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function rDn(t){return eDn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}gV.exports={isBlob:rDn,isValidStatusCode:nDn,isValidUTF8:KAe,tokenChars:tDn};if(hrt)gV.exports.isValidUTF8=function(t){return t.length<24?KAe(t):hrt(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=K("utf-8-validate");gV.exports.isValidUTF8=function(e){return e.length<32?KAe(e):t(e)}}catch{}});var e0e=Q((GIi,wrt)=>{"use strict";var{Writable:iDn}=K("stream"),mrt=CB(),{BINARY_TYPES:oDn,EMPTY_BUFFER:frt,kStatusCode:sDn,kWebSocket:aDn}=Y0(),{concat:YAe,toArrayBuffer:cDn,unmask:uDn}=nU(),{isValidStatusCode:lDn,isValidUTF8:grt}=IB(),AV=Buffer[Symbol.species],hh=0,Art=1,yrt=2,Ert=3,JAe=4,XAe=5,yV=6,ZAe=class extends iDn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||oDn[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[aDn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=hh}_write(e,n,r){if(this._opcode===8&&this._state==hh)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e),new AV(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case hh:this.getInfo(e);break;case Art:this.getPayloadLength16(e);break;case yrt:this.getPayloadLength64(e);break;case Ert:this.getMask();break;case JAe:this.getData(e);break;case XAe:case yV:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[mrt.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Art:this._payloadLength===127?this._state=yrt:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Ert:this._state=JAe}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=JAe}getData(e){let n=frt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&uDn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=XAe,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[mrt.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===hh&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=hh;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=YAe(r,n):this._binaryType==="arraybuffer"?i=cDn(YAe(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=hh):(this._state=yV,setImmediate(()=>{this.emit("message",i,!0),this._state=hh,this.startLoop(e)}))}else{let i=YAe(r,n);if(!this._skipUTF8Validation&&!grt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===XAe||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=hh):(this._state=yV,setImmediate(()=>{this.emit("message",i,!1),this._state=hh,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,frt),this.end();else{let r=e.readUInt16BE(0);if(!lDn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new AV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!grt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=hh;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=hh):(this._state=yV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=hh,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[sDn]=i,s}};wrt.exports=ZAe});var r0e=Q((jIi,Crt)=>{"use strict";var{Duplex:qIi}=K("stream"),{randomFillSync:dDn}=K("crypto"),{types:{isUint8Array:pDn}}=K("util"),xrt=CB(),{EMPTY_BUFFER:hDn,kWebSocket:mDn,NOOP:fDn}=Y0(),{isBlob:vB,isValidStatusCode:gDn}=IB(),{mask:brt,toBuffer:ov}=nU(),mh=Symbol("kByteLength"),ADn=Buffer.alloc(4),EV=8*1024,sv,SB=EV,ef=0,yDn=1,EDn=2,t0e=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ef,this.onerror=fDn,this[mDn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||ADn,n.generateMask?n.generateMask(r):(SB===EV&&(sv===void 0&&(sv=Buffer.alloc(EV)),dDn(sv,0,EV),SB=0),r[0]=sv[SB++],r[1]=sv[SB++],r[2]=sv[SB++],r[3]=sv[SB++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[mh]!==void 0?a=n[mh]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[o-4]=r[0],u[o-3]=r[1],u[o-2]=r[2],u[o-1]=r[3],s?[u,e]:i?(brt(e,r,u,o,a),[u]):(brt(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=hDn;else{if(typeof e!="number"||!gDn(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(pDn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[mh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ef?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(t.frame(o,s),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):vB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[mh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};vB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):vB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[mh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};vB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[xrt.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):vB(e)?(a=e.size,c=!1):(e=ov(e),a=e.length,c=ov.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let u={[mh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};vB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==ef?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[mh],this._state=EDn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(n0e,this,a,i);return}this._bufferedBytes-=r[mh];let s=ov(o);n?this.dispatch(s,n,r,i):(this._state=ef,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(wDn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[xrt.extensionName];this._bufferedBytes+=r[mh],this._state=yDn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");n0e(this,c,i);return}this._bufferedBytes-=r[mh],this._state=ef,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===ef&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][mh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][mh],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Crt.exports=t0e;function n0e(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function wDn(t,e,n){n0e(t,e,n),t.onerror(e)}});var Drt=Q((zIi,Brt)=>{"use strict";var{kForOnEventAttribute:iU,kListener:i0e}=Y0(),Irt=Symbol("kCode"),vrt=Symbol("kData"),Srt=Symbol("kError"),_rt=Symbol("kMessage"),krt=Symbol("kReason"),_B=Symbol("kTarget"),Trt=Symbol("kType"),Rrt=Symbol("kWasClean"),X0=class{constructor(e){this[_B]=null,this[Trt]=e}get target(){return this[_B]}get type(){return this[Trt]}};Object.defineProperty(X0.prototype,"target",{enumerable:!0});Object.defineProperty(X0.prototype,"type",{enumerable:!0});var av=class extends X0{constructor(e,n={}){super(e),this[Irt]=n.code===void 0?0:n.code,this[krt]=n.reason===void 0?"":n.reason,this[Rrt]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Irt]}get reason(){return this[krt]}get wasClean(){return this[Rrt]}};Object.defineProperty(av.prototype,"code",{enumerable:!0});Object.defineProperty(av.prototype,"reason",{enumerable:!0});Object.defineProperty(av.prototype,"wasClean",{enumerable:!0});var kB=class extends X0{constructor(e,n={}){super(e),this[Srt]=n.error===void 0?null:n.error,this[_rt]=n.message===void 0?"":n.message}get error(){return this[Srt]}get message(){return this[_rt]}};Object.defineProperty(kB.prototype,"error",{enumerable:!0});Object.defineProperty(kB.prototype,"message",{enumerable:!0});var oU=class extends X0{constructor(e,n={}){super(e),this[vrt]=n.data===void 0?null:n.data}get data(){return this[vrt]}};Object.defineProperty(oU.prototype,"data",{enumerable:!0});var xDn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[iU]&&i[i0e]===e&&!i[iU])return;let r;if(t==="message")r=function(o,s){let a=new oU("message",{data:s?o:o.toString()});a[_B]=this,wV(e,this,a)};else if(t==="close")r=function(o,s){let a=new av("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[_B]=this,wV(e,this,a)};else if(t==="error")r=function(o){let s=new kB("error",{error:o,message:o.message});s[_B]=this,wV(e,this,s)};else if(t==="open")r=function(){let o=new X0("open");o[_B]=this,wV(e,this,o)};else return;r[iU]=!!n[iU],r[i0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[i0e]===e&&!n[iU]){this.removeListener(t,n);break}}};Brt.exports={CloseEvent:av,ErrorEvent:kB,Event:X0,EventTarget:xDn,MessageEvent:oU};function wV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var xV=Q((VIi,Mrt)=>{"use strict";var{tokenChars:sU}=IB();function Mg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function bDn(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,s,a,c=-1,u=-1,l=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),s===void 0)if(l===-1&&sU[u]===1)c===-1&&(c=d);else if(d!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);u===44?(Mg(e,h,n),n=Object.create(null)):s=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&sU[u]===1)c===-1&&(c=d);else if(u===32||u===9)l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),Mg(n,t.slice(c,l),!0),u===44&&(Mg(e,s,n),n=Object.create(null),s=void 0),c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,d),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(sU[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(sU[u]===1)c===-1&&(c=d);else if(u===34&&c!==-1)o=!1,l=d;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&sU[u]===1)c===-1&&(c=d);else if(c!==-1&&(u===32||u===9))l===-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);r&&(h=h.replace(/\\/g,""),r=!1),Mg(n,a,h),u===44&&(Mg(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let p=t.slice(c,l);return s===void 0?Mg(e,p,n):(a===void 0?Mg(n,p,!0):r?Mg(n,a,p.replace(/\\/g,"")):Mg(n,a,p),Mg(e,s,n)),e}function CDn(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Mrt.exports={format:CDn,parse:bDn}});var vV=Q((JIi,qrt)=>{"use strict";var IDn=K("events"),vDn=K("https"),SDn=K("http"),Lrt=K("net"),_Dn=K("tls"),{randomBytes:kDn,createHash:TDn}=K("crypto"),{Duplex:KIi,Readable:YIi}=K("stream"),{URL:o0e}=K("url"),Cw=CB(),RDn=e0e(),BDn=r0e(),{isBlob:DDn}=IB(),{BINARY_TYPES:Prt,CLOSE_TIMEOUT:MDn,EMPTY_BUFFER:bV,GUID:PDn,kForOnEventAttribute:s0e,kListener:NDn,kStatusCode:LDn,kWebSocket:ec,NOOP:Qrt}=Y0(),{EventTarget:{addEventListener:QDn,removeEventListener:ODn}}=Drt(),{format:FDn,parse:UDn}=xV(),{toBuffer:$Dn}=nU(),Ort=Symbol("kAborted"),a0e=[8,13],Z0=["CONNECTING","OPEN","CLOSING","CLOSED"],WDn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Go=class t extends IDn{constructor(e,n,r){super(),this._binaryType=Prt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=bV,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Frt(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Prt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new RDn({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new BDn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[ec]=this,o[ec]=this,e[ec]=this,i.on("conclude",qDn),i.on("drain",jDn),i.on("error",zDn),i.on("message",VDn),i.on("ping",KDn),i.on("pong",YDn),o.onerror=JDn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Wrt),e.on("data",IV),e.on("end",Hrt),e.on("error",Grt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Cw.extensionName]&&this._extensions[Cw.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$rt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){c0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||bV,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){c0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||bV,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){c0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Cw.extensionName]||(i.compress=!1),this._sender.send(e||bV,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Go,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go.prototype,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go.prototype,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go.prototype,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});Object.defineProperty(Go.prototype,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Go.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Go.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[s0e])return e[NDn];return null},set(e){for(let n of this.listeners(t))if(n[s0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[s0e]:!0})}})});Go.prototype.addEventListener=QDn;Go.prototype.removeEventListener=ODn;qrt.exports=Go;function Frt(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:MDn,protocolVersion:a0e[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!a0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${a0e.join(", ")})`);let o;if(e instanceof o0e)o=e;else try{o=new o0e(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let f=new SyntaxError(c);if(t._redirects===0)throw f;CV(t,f);return}let u=s?443:80,l=kDn(16).toString("base64"),d=s?vDn.request:SDn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?GDn:HDn),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new Cw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=FDn({[Cw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!WDn.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let f=i.path.split(":");i.socketPath=f[0],i.path=f[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?i.socketPath:o.host;let f=r&&r.headers;if(r={...r,headers:{}},f)for(let[g,A]of Object.entries(f))r.headers[g.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let f=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!f||t._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,f||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=d(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=d(i);i.timeout&&m.on("timeout",()=>{ep(t,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[Ort]||(m=t._req=null,CV(t,f))}),m.on("response",f=>{let g=f.headers.location,A=f.statusCode;if(g&&i.followRedirects&&A>=300&&A<400){if(++t._redirects>i.maxRedirects){ep(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new o0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);CV(t,v);return}Frt(t,x,n,r)}else t.emit("unexpected-response",m,f)||ep(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,A)=>{if(t.emit("upgrade",f),t.readyState!==Go.CONNECTING)return;m=t._req=null;let x=f.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){ep(t,g,"Invalid Upgrade header");return}let b=TDn("sha1").update(l+PDn).digest("base64");if(f.headers["sec-websocket-accept"]!==b){ep(t,g,"Invalid Sec-WebSocket-Accept header");return}let v=f.headers["sec-websocket-protocol"],S;if(v!==void 0?p.size?p.has(v)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":p.size&&(S="Server sent no subprotocol"),S){ep(t,g,S);return}v&&(t._protocol=v);let _=f.headers["sec-websocket-extensions"];if(_!==void 0){if(!h){ep(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=UDn(_)}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==Cw.extensionName){ep(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[Cw.extensionName])}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cw.extensionName]=h}t.setSocket(g,A,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function CV(t,e){t._readyState=Go.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function HDn(t){return t.path=t.socketPath,Lrt.connect(t)}function GDn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Lrt.isIP(t.host)?"":t.host),_Dn.connect(t)}function ep(t,e,n){t._readyState=Go.CLOSING;let r=new Error(n);Error.captureStackTrace(r,ep),e.setHeader?(e[Ort]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(CV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function c0e(t,e,n){if(e){let r=DDn(e)?e.size:$Dn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Z0[t.readyState]})`);process.nextTick(n,r)}}function qDn(t,e){let n=this[ec];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ec]!==void 0&&(n._socket.removeListener("data",IV),process.nextTick(Urt,n._socket),t===1005?n.close():n.close(t,e))}function jDn(){let t=this[ec];t.isPaused||t._socket.resume()}function zDn(t){let e=this[ec];e._socket[ec]!==void 0&&(e._socket.removeListener("data",IV),process.nextTick(Urt,e._socket),e.close(t[LDn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Nrt(){this[ec].emitClose()}function VDn(t,e){this[ec].emit("message",t,e)}function KDn(t){let e=this[ec];e._autoPong&&e.pong(t,!this._isServer,Qrt),e.emit("ping",t)}function YDn(t){this[ec].emit("pong",t)}function Urt(t){t.resume()}function JDn(t){let e=this[ec];e.readyState!==Go.CLOSED&&(e.readyState===Go.OPEN&&(e._readyState=Go.CLOSING,$rt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $rt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Wrt(){let t=this[ec];if(this.removeListener("close",Wrt),this.removeListener("data",IV),this.removeListener("end",Hrt),t._readyState=Go.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ec]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Nrt),t._receiver.on("finish",Nrt))}function IV(t){this[ec]._receiver.write(t)||this.pause()}function Hrt(){let t=this[ec];t._readyState=Go.CLOSING,t._receiver.end(),this.end()}function Grt(){let t=this[ec];this.removeListener("error",Grt),this.on("error",Qrt),t&&(t._readyState=Go.CLOSING,this.destroy())}});var Krt=Q((ZIi,Vrt)=>{"use strict";var XIi=vV(),{Duplex:XDn}=K("stream");function jrt(t){t.emit("close")}function ZDn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function zrt(t){this.removeListener("error",zrt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function eMn(t,e){let n=!0,r=new XDn({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&r._readableState.objectMode?o.toString():o;r.push(a)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(jrt,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(jrt,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,s)});return}t.send(i,s)},r.on("end",ZDn),r.on("error",zrt),r}Vrt.exports=eMn});var u0e=Q((evi,Yrt)=>{"use strict";var{tokenChars:tMn}=IB();function nMn(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let s=t.charCodeAt(i);if(r===-1&&tMn[s]===1)n===-1&&(n=i);else if(i!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=i);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Yrt.exports={parse:nMn}});var rit=Q((nvi,nit)=>{"use strict";var rMn=K("events"),SV=K("http"),{Duplex:tvi}=K("stream"),{createHash:iMn}=K("crypto"),Jrt=xV(),cv=CB(),oMn=u0e(),sMn=vV(),{CLOSE_TIMEOUT:aMn,GUID:cMn,kWebSocket:uMn}=Y0(),lMn=/^[+/0-9A-Za-z]{22}==$/,Xrt=0,Zrt=1,tit=2,l0e=class extends rMn{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:aMn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:sMn,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=SV.createServer((r,i)=>{let o=SV.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=dMn(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Xrt}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===tit){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(aU,this);return}if(e&&this.once("close",e),this._state!==Zrt)if(this._state=Zrt,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(aU,this):process.nextTick(aU,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{aU(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",eit);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){uv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){uv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!lMn.test(o)){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){cU(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=oMn.parse(c)}catch{uv(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let p=new cv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Jrt.parse(l);h[cv.extensionName]&&(p.accept(h[cv.extensionName]),d[cv.extensionName]=p)}catch{uv(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,m,f,g)=>{if(!h)return cU(n,m||401,f,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return cU(n,401)}this.completeUpgrade(d,o,u,e,n,r,i)}completeUpgrade(e,n,r,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[uMn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xrt)return cU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${iMn("sha1").update(n+cMn).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[cv.extensionName]){let d=e[cv.extensionName].params,p=Jrt.format({[cv.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
100
+ `)}})}function Wl(t){let e=S6();if(e===void 0)return!1;if(e.component==="broker"&&e.node_id!==void 0&&t.node_id!==void 0&&t.node_id!==e.node_id)throw new TypeError(`broker event target node_id must match bound node_id; received ${t.node_id}`);if(t.level==="debug"&&process.env.CRTR_LOG!=="debug")return!1;let n=PXe({...t,component:e.component,...e.node_id===void 0?{}:{node_id:e.node_id},...e.stream_id===void 0?{}:{stream_id:e.stream_id}}),r=LXe(n);return e.component==="broker"&&e.node_id!==void 0&&(gRn??=DI())?(ARn(e.node_id,r),!0):e.component==="daemon"?_Xe(e.path,r):m6(e.path,r)}var gRn,Btt,JI=y(()=>{"use strict";xfe();NXe();QXe();Ffe();Dc();BF();Btt=Promise.resolve()});var Dtt,Mtt=y(()=>{"use strict";JI();Dtt={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});function J6(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var WF=y(()=>{"use strict"});var Ptt=y(()=>{"use strict"});import{createHash as yRn}from"node:crypto";function Qtt(t){return t===void 0?"absent":yRn("sha256").update(JSON.stringify(t)).digest("hex")}function Ott(t,e){Ltt.set(t,e)}function z0(){let t;try{t=E6()}catch(n){if(n instanceof vF)return Ntt();if(n instanceof IF)return iAe??Ntt();throw n}let e=Ltt.get(t);if(e!==void 0)return e;if(iAe!==void 0)return iAe;throw new oAe(t)}function Ftt(t){ERn=t}function Utt(t){wRn=t}function GF(t){let e=z0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:Qtt(e)}}function $tt(t){let e=z0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function Wtt(){return structuredClone(z0().profiles)}function Htt(t){let e=z0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var HF,oAe,Ltt,Ntt,iAe,ERn,wRn,lB=y(()=>{"use strict";JR();HF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},oAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},Ltt=new Map;Ntt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});ERn=async()=>{throw new Error("no settings transport installed in this process")}});var Gtt=y(()=>{"use strict"});import{chmodSync as Yxi,existsSync as qtt,mkdirSync as Jxi,readFileSync as jtt,rmSync as Xxi,writeFileSync as Zxi}from"node:fs";import{dirname as tbi,join as ztt}from"node:path";function yw(){let t=xRn();if(!qtt(t))return;let e=JSON.parse(jtt(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, runId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,runId:e.runId,directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}function CRn(){let t=bRn();if(!qtt(t))return;let e=JSON.parse(jtt(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var xRn,bRn,Vtt,Ktt,qF=y(()=>{"use strict";Xm();jd();Ol();iu();xRn=()=>ztt(Fl(),"machine.json");bRn=()=>ztt(Fl(),"import","move.json");Vtt=()=>CRn()?.state==="committed",Ktt=t=>new os("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,ji.USAGE,{next:"Run `crtr sys signin` to finish."})});function vRn(t){return t.grantee??"app:terminal"}function SRn(t){if(!Ytt.test(t))throw dw(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function X6(t){SRn(t);let e=Htt(t);if(e===null)throw p6(`profile not found: ${t}`,{received:t});return VXe(vRn(e.manifest),t).dir}function _Rn(){return{entries:Wtt(),unreadableIds:[]}}function Z6(){return _Rn().entries}function kRn(t){let e=Z6(),n=TRn(e,t,Jtt);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function TRn(t,e,n){if(Ytt.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw EXe(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function RRn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return p6(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function Rg(t){let e=kRn(t);if(e.kind==="resolved")return e.entry;throw RRn(Z6(),t,Jtt)}var Ytt,Jtt,XI=y(()=>{"use strict";iu();Xm();WF();Ol();lB();jd();Gtt();JR();qF();Ytt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Jtt=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Xtt}from"node:os";import{existsSync as BRn,statSync as DRn}from"node:fs";import{join as eV,resolve as Ztt,dirname as MRn,sep as sAe}from"node:path";function Zd(){return eV(Fl(),"scope")}function PRn(t,e){if(!BRn(t)||Jm(t)===Jm(eV(Xtt(),LI))||Jm(t).startsWith(`${Jm(Rfe())}${sAe}`)&&t.endsWith(`${sAe}home${sAe}${LI}`)||!DI()&&(Jm(t)===Jm(e)||Jm(t)===Jm(C6())))return!1;try{return DRn(t).isDirectory()}catch{return!1}}function NRn(t=process.cwd()){return ent(t)[0]??null}function LRn(t,e){let n=[],r=Jm(Xtt()),i=Ztt(t);for(;;){let o=eV(i,LI);if(PRn(o,e)&&n.push(o),Jm(i)===r)return n;let s=MRn(i);if(s===i)return n;i=s}}function ent(t=process.cwd(),e=Ume()||null){return QRn(t,e)}function QRn(t,e){let n=Ztt(t),r=Zd(),i=[n];if(!DI()&&e!==null&&e!=="")try{let{manifest:a}=Rg(e);i.push(...J6(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of LRn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function tnt(t){return NRn(t)}function V0(t){return t==="builtin"?null:t==="user"?Zd():tnt()}function nnt(t){let e=t==="user"?Fl():V0(t);return e?eV(e,"plugins"):null}var ZI=y(()=>{"use strict";Dc();WF();iu();Ptt();jd();XI();Ol();Xm()});import{join as ORn}from"node:path";function FRn(t){return ORn(t,gXe,AXe)}function URn(t){let e;try{e=$I(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function $Rn(t){return URn(FRn(t))}function rnt(t){let e=$Rn(t);return e.status==="ok"?e.manifest:null}var aAe=y(()=>{"use strict";iu();Ol()});import{existsSync as WRn,mkdirSync as HRn,readdirSync as ont,rmSync as snt,rmdirSync as GRn,statSync as qRn,unlinkSync as jRn,writeFileSync as zRn}from"node:fs";import{randomUUID as VRn}from"node:crypto";function cnt(t){return Math.min(t*2,KRn)}function unt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function uAe(t,e){return`${t}/${cAe}${e}`}function lAe(t){try{return ont(t).find(e=>e.startsWith(cAe))?.slice(cAe.length)??null}catch{return null}}function lnt(t){let e=Number(t.split(".",1)[0]);if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function XRn(t){try{return ont(t).length===0}catch{return!1}}function ZRn(t){try{return Date.now()-qRn(t).mtimeMs}catch{return 0}}function eBn(t,e){let n=lAe(t);if(n!==null){if(lnt(n))return;try{jRn(uAe(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(ZRn(t)<=e)return;if(!XRn(t)){snt(t,{recursive:!0,force:!0});return}}try{GRn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function dB(t){let e=lAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function dnt(t,e){let n=Date.now()+e,r=ant;for(;;){let i=lAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!lnt(i))return;let o=n-Date.now();if(o<=0)return;unt(Math.min(r,o)),r=cnt(r)}}function int(t,e){let n=`${process.pid}.${VRn()}`;try{return HRn(t,{mode:448}),zRn(uAe(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return eBn(t,e),null}}function ev(t,e,n={}){let r=n.staleMs??YRn,i=Date.now()+(n.timeoutMs??JRn),o=ant,s=int(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);unt(Math.min(o,Math.max(0,i-Date.now()))),o=cnt(o),s=int(t,r)}try{return e()}finally{WRn(uAe(s.path,s.token))&&snt(s.path,{recursive:!0,force:!0})}}var cAe,ant,KRn,YRn,JRn,Ew=y(()=>{"use strict";cAe="owner.",ant=10,KRn=250,YRn=3e4,JRn=5e3});import{join as tBn}from"node:path";function pnt(t,e){return tBn(t,"tmp",`${e}.swap.lock`)}function hnt(t,e){let n=dB(pnt(t,e));return n!==null&&n!==process.pid}function mnt(t,e){dnt(pnt(t,e),nBn)}var nBn,fnt=y(()=>{"use strict";Ew();nBn=2e3});function tV(t,e){let n=t.apps[rBn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var rBn,dAe=y(()=>{"use strict";Dc();lB();rBn="app:terminal"});import{join as pAe}from"node:path";function iBn(t,e){let n=t==="user"?hF()?tV(z0(),GF("user").settings):GF("user").settings:$I(pAe(e,u6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function oBn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&hnt(t,i))}function nV(t,e){if(t==="user"&&y6())return[];let n=t!=="user"?pAe(e,"plugins"):nnt("user");if(n===void 0||!kfe(n))return[];let r=iBn(t,e),i=gnt(t,n,r),o=oBn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)mnt(e,s);return gnt(t,n,r)}function gnt(t,e,n){let r=[];for(let i of Tfe(e)){let o=pAe(e,i),s=rnt(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var rV=y(()=>{"use strict";iu();Ol();aAe();fnt();JR();lB();dAe();ZI()});import{existsSync as sBn,realpathSync as aBn}from"node:fs";import{basename as cBn,dirname as uBn,join as lCi,resolve as Ant}from"node:path";function pB(t){let e=Ant(t),n=e,r=[];for(;!sBn(n);){let i=uBn(n);if(i===n)return e;r.unshift(cBn(n)),n=i}return Ant(aBn(n),...r)}var ynt=y(()=>{"use strict"});function lBn(t){let e=zi.indexOf(t);return`less ${zi.map((r,i)=>i===e?"\u25CF":"\u25CB").map((r,i)=>i===0?r:`${i<=e?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${r}`).join("")} more ${oV[t]}`}function iV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Ent(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function tv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function bnt(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function dBn(t,e){let n=bnt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function xnt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function fBn(){let t=[];for(let e of Object.values(Cnt))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var oV,wnt,pBn,hBn,jF,Cnt,mBn,hCi,hAe=y(()=>{"use strict";iu();oV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};wnt=[!1,"notify","apply"],pBn=[0,1,6,12,24,48,72,168],hBn=[1,2,3,4,5,6,8,10,12],jF="openai-codex";Cnt={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=iV(wnt,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=iV(wnt,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=Ent(pBn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=bnt(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=Ent(hBn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=dBn(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=tv(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=tv(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=tv(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=tv(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:QI.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=iV(QI,t.whip_message_mode,e)},setFromString:(t,e)=>QI.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${QI.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:OI.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=iV(OI,t.mouse_mode_default,e)},setFromString:(t,e)=>OI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${OI.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=tv(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:zi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>lBn(t.verbosity),cycle:(t,e)=>{let n=zi.indexOf(t.verbosity)+e;t.verbosity=zi[Math.max(0,Math.min(zi.length-1,n))]},setFromString:(t,e)=>zi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${zi.join("|")}`}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:t=>String(t.document_port),cycle:(t,e)=>{t.document_port=Math.max(1,Math.min(65535,t.document_port+e))},setFromString:(t,e)=>{let n=Number(e);return!/^\d+$/.test(e)||!Number.isInteger(n)||n<1||n>65535?"document_port must be an integer from 1 to 65535":(t.document_port=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=tv(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${jF}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[jF]?.fastMode?"on":"off",cycle:t=>{let e=xnt(t,jF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=tv(e,`providerOptions.${jF}.fastMode`);return typeof n=="string"?n:(xnt(t,jF).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},mBn=Object.keys(Cnt);hCi=fBn()});function zF(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function mB(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function hB(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${mB(t)}`);return t.trim()}}function AAe(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${mB(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${mB(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${mB(i)}`);s={kind:u.kind.trim(),...hB(u.description,"description",e,o)===void 0?{}:{description:hB(u.description,"description",e,o)},...hB(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:hB(u.useWhen,"useWhen",e,o)},...hB(u.doc,"doc",e,o)===void 0?{}:{doc:hB(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${mB(i)}`);let a=s.kind;if(!ABn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${mB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(yBn.has(a)||gBn.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=zF(a);if(sV.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function vnt(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=zF(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function Snt(t,e){return e.find(n=>n.kind===t)}var mAe,gBn,ABn,yBn,Int,fAe,sV,gAe,VF=y(()=>{"use strict";mAe=["options","text","table","cards","chart"],gBn=["page","step"],ABn=/^[a-z][a-z0-9-]{0,63}$/,yBn=new Set(mAe),Int=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];fAe=Object.fromEntries(Int.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),sV=new Set(Int.map(t=>t.tag)),gAe=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as Bnt,join as Dnt}from"node:path";import{existsSync as wBn,mkdirSync as xCi,statSync as bCi}from"node:fs";function xBn(t){return Dnt(t,u6)}function bBn(t){return Dnt(t,yXe)}function Mnt(t){let e=pB(t),n=pB(Zd());if(e===n)return{key:"user",kind:"user",root:n};if(Bnt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of Z6()){let i=pB(X6(r.profileId));if(e===i)return{key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function Pnt(t){if(Bnt(t)===".crouter"){let r;try{r=pB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==pB(Zd()))return $I(xBn(t))}let e=Mnt(t).key,n=GF(e).settings;return e==="user"&&hF()?tV(z0(),n):n}function dh(t){let e=CBn[IBn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=V0(t);return n?vBn(n):d6()}function vBn(t){let e=Pnt(t);return e?XBn(e):d6()}function SBn(t){let e=$I(bBn(t));return{marketplaces:e?.marketplaces??{},plugins:e?.plugins??{},activeCanvas:e?.activeCanvas??null,...e?.last_self_check===void 0?{}:{last_self_check:e.last_self_check}}}function Nnt(t){let e=V0(t);return e?t==="project"?wBn(e)?SBn(e):wfe():$tt(Mnt(e).key):wfe()}function _Bn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function fB(t){return t===void 0?[...TBn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&NI.has(e)&&kBn.has(e)))]:[]}function RBn(t,e=Efe()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function Lnt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function yAe(){return Object.create(null)}function aV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function DBn(t){let e=yAe();for(let[n,r]of Object.entries(t??{}))aV(e,n,r);return e}function KF(t,e){Wl({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function MBn(t,e={}){let n=DBn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){KF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){KF(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!Lnt(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){KF(r,c);continue}aV(n,r,a)}return n}function PBn(t){let e=yAe(),n=yAe();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){KF(r,"route must include family, credentialSource, providerId, and models");continue}let o=BBn.filter(s=>i.models[s]===void 0);if(o.length>0){KF(r,`incomplete route; missing strengths: ${o.join(", ")}`),aV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}aV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function NBn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>Lnt(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function LBn(t){return t!==""&&t.replace(/\*/g,"")===""}function QBn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(LBn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function OBn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function UBn(t,e){if(e==="bin"&&FBn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!_nt.test(t))return`${e}.${t} is not a safe bare command name (expected ${_nt.source})`}function $Bn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))UBn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function WBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(knt.test(n)||i.push(`action name must match ${knt.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function HBn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(WBn(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function GBn(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function qBn(t,e=yfe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=GBn(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function uV(){let t=[{origin:"config.json",components:dh("user").page_components}],e=V0("user");if(e!==null){let n=nV("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:AAe(r.manifest.page_components,i)})}}return vnt(t)}function jBn(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function zBn(t,e=Afe()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=jBn(o);s!==null&&(n[i]=s)}}return{targets:n}}function Tnt(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function cV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function VBn(t,e){let n=t!==null&&typeof t=="object"?t:{},r=cV(n.warning,e.warning),i=cV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function KBn(t,e){return{unattendedParkMs:cV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function YBn(t){if(!Array.isArray(t))return[...l6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...l6]}function JBn(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function XBn(t){!Rnt&&t.ledger!==void 0&&(Rnt=!0,Wl({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Dtt)}}));let e=d6(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:Tnt(o?.crtr,e.auto_update.crtr),content:Tnt(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=cV(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=VBn(t.brokerThresholds,e.brokerThresholds),h=KBn(t.lifecycle,e.lifecycle),m=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,f=t.working_gerunds===void 0?[...e.working_gerunds]:mXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,A=AAe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=YBn(t.whip_messages),v=QI.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=OI.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,_=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,T=zi.includes(t.verbosity)?t.verbosity:e.verbosity,B=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,R=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,P=_Bn(t.keybindings),O=fB(t.tmux_passthrough),$=RBn(t.modelLadders),j=OBn(t.providerOptions,e.providerOptions),H=PBn(MBn(t.modelRoutes)),le=H.complete,ee=NBn(t.modelRouting,void 0),ge=qBn(t.kinds),Ie=zBn(t.remoteCanvas),$e=JBn(t.api,e.api),wt=t.paths;if(wt?.user_files!==void 0&&(typeof wt.user_files!="string"||!wt.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,xt=t.runtime;if(xt?.person_uids!==void 0&&(!Array.isArray(xt.person_uids)||!xt.person_uids.every(et=>Number.isSafeInteger(et)&&et>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let re=QBn(t.spawnEnv,e.spawnEnv?.allow),ot=$Bn(t.bin),ke=HBn(t.humanActions);return{bin:ot,humanActions:ke,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:h,completion_bell:m,working_gerunds:f,whip_mode:g,page_components:A,page_surface:x,whip_messages:b,whip_message_mode:v,mouse_mode_default:S,bash_tool_purpose:_,verbosity:T,detailed_tool_recaps:B,document_port:R,keybindings:P,tmux_passthrough:O,modelLadders:$,providerOptions:j,...Object.keys(le).length>0?{modelRoutes:le}:{},...Object.keys(H.legacy).length>0?{legacyModelRoutes:H.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:ge,remoteCanvas:Ie,api:$e,...wt?{paths:wt}:{},...Ze?{store:Ze}:{},...xt?{runtime:xt}:{},spawnEnv:re}}function ZBn(t){return Pnt(t)}function Qnt(t){let e=V0(t);return e?ZBn(e):null}var CBn,IBn,kBn,TBn,BBn,_nt,FBn,knt,Rnt,Kd=y(()=>{"use strict";Dc();iu();s6();jd();JI();Mtt();Ol();ZI();rV();XI();ynt();lB();dAe();Ew();hAe();c6();VF();CBn=globalThis,IBn=Symbol.for("crtr.broker.config-snapshot");kBn=new Set(qd.filter(xF).map(t=>t.id)),TBn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);BBn=["ultra","strong","medium","light"];_nt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,FBn=new Set(["crtr","crtrd"]);knt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Rnt=!1});var Y0=Q((FIi,rrt)=>{"use strict";var trt=["nodebuffer","arraybuffer","fragments"],nrt=typeof Blob<"u";nrt&&trt.push("blob");rrt.exports={BINARY_TYPES:trt,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:nrt,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var nU=Q((UIi,hV)=>{"use strict";var{EMPTY_BUFFER:j1n}=Y0(),GAe=Buffer[Symbol.species];function z1n(t,e){if(t.length===0)return j1n;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new GAe(n.buffer,n.byteOffset,r):n}function irt(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function ort(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function V1n(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function qAe(t){if(qAe.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new GAe(t):ArrayBuffer.isView(t)?e=new GAe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),qAe.readOnly=!1),e}hV.exports={concat:z1n,mask:irt,toArrayBuffer:V1n,toBuffer:qAe,unmask:ort};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=K("bufferutil");hV.exports.mask=function(e,n,r,i,o){o<48?irt(e,n,r,i,o):t.mask(e,n,r,i,o)},hV.exports.unmask=function(e,n){e.length<32?ort(e,n):t.unmask(e,n)}}catch{}});var crt=Q(($Ii,art)=>{"use strict";var srt=Symbol("kDone"),jAe=Symbol("kRun"),zAe=class{constructor(e){this[srt]=()=>{this.pending--,this[jAe]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[jAe]()}[jAe](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[srt])}}};art.exports=zAe});var CB=Q((WIi,prt)=>{"use strict";var rU=K("zlib"),urt=nU(),K1n=crt(),{kStatusCode:lrt}=Y0(),Y1n=Buffer[Symbol.species],J1n=Buffer.from([0,0,255,255]),fV=Symbol("permessage-deflate"),J0=Symbol("total-length"),xB=Symbol("callback"),bw=Symbol("buffers"),bB=Symbol("error"),mV,VAe=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!mV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;mV=new K1n(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[xB];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){mV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){mV.add(i=>{this._compress(e,n,(o,s)=>{i(),r(o,s)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?rU.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=rU.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[fV]=this,this._inflate[J0]=0,this._inflate[bw]=[],this._inflate.on("error",Z1n),this._inflate.on("data",drt)}this._inflate[xB]=r,this._inflate.write(e),n&&this._inflate.write(J1n),this._inflate.flush(()=>{let o=this._inflate[bB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=urt.concat(this._inflate[bw],this._inflate[J0]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[J0]=0,this._inflate[bw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?rU.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=rU.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[J0]=0,this._deflate[bw]=[],this._deflate.on("data",X1n)}this._deflate[xB]=r,this._deflate.write(e),this._deflate.flush(rU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=urt.concat(this._deflate[bw],this._deflate[J0]);n&&(o=new Y1n(o.buffer,o.byteOffset,o.length-4)),this._deflate[xB]=null,this._deflate[J0]=0,this._deflate[bw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};prt.exports=VAe;function X1n(t){this[bw].push(t),this[J0]+=t.length}function drt(t){if(this[J0]+=t.length,this[fV]._maxPayload<1||this[J0]<=this[fV]._maxPayload){this[bw].push(t);return}this[bB]=new RangeError("Max payload size exceeded"),this[bB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[bB][lrt]=1009,this.removeListener("data",drt),this.reset()}function Z1n(t){if(this[fV]._inflate=null,this[bB]){this[xB](this[bB]);return}t[lrt]=1007,this[xB](t)}});var IB=Q((HIi,gV)=>{"use strict";var{isUtf8:hrt}=K("buffer"),{hasBlob:eDn}=Y0(),tDn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function nDn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function KAe(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function rDn(t){return eDn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}gV.exports={isBlob:rDn,isValidStatusCode:nDn,isValidUTF8:KAe,tokenChars:tDn};if(hrt)gV.exports.isValidUTF8=function(t){return t.length<24?KAe(t):hrt(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=K("utf-8-validate");gV.exports.isValidUTF8=function(e){return e.length<32?KAe(e):t(e)}}catch{}});var e0e=Q((GIi,wrt)=>{"use strict";var{Writable:iDn}=K("stream"),mrt=CB(),{BINARY_TYPES:oDn,EMPTY_BUFFER:frt,kStatusCode:sDn,kWebSocket:aDn}=Y0(),{concat:YAe,toArrayBuffer:cDn,unmask:uDn}=nU(),{isValidStatusCode:lDn,isValidUTF8:grt}=IB(),AV=Buffer[Symbol.species],hh=0,Art=1,yrt=2,Ert=3,JAe=4,XAe=5,yV=6,ZAe=class extends iDn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||oDn[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[aDn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=hh}_write(e,n,r){if(this._opcode===8&&this._state==hh)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e),new AV(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new AV(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case hh:this.getInfo(e);break;case Art:this.getPayloadLength16(e);break;case yrt:this.getPayloadLength64(e);break;case Ert:this.getMask();break;case JAe:this.getData(e);break;case XAe:case yV:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[mrt.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Art:this._payloadLength===127?this._state=yrt:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Ert:this._state=JAe}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=JAe}getData(e){let n=frt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&uDn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=XAe,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[mrt.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===hh&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=hh;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=YAe(r,n):this._binaryType==="arraybuffer"?i=cDn(YAe(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=hh):(this._state=yV,setImmediate(()=>{this.emit("message",i,!0),this._state=hh,this.startLoop(e)}))}else{let i=YAe(r,n);if(!this._skipUTF8Validation&&!grt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===XAe||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=hh):(this._state=yV,setImmediate(()=>{this.emit("message",i,!1),this._state=hh,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,frt),this.end();else{let r=e.readUInt16BE(0);if(!lDn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new AV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!grt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=hh;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=hh):(this._state=yV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=hh,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[sDn]=i,s}};wrt.exports=ZAe});var r0e=Q((jIi,Crt)=>{"use strict";var{Duplex:qIi}=K("stream"),{randomFillSync:dDn}=K("crypto"),{types:{isUint8Array:pDn}}=K("util"),xrt=CB(),{EMPTY_BUFFER:hDn,kWebSocket:mDn,NOOP:fDn}=Y0(),{isBlob:vB,isValidStatusCode:gDn}=IB(),{mask:brt,toBuffer:ov}=nU(),mh=Symbol("kByteLength"),ADn=Buffer.alloc(4),EV=8*1024,sv,SB=EV,ef=0,yDn=1,EDn=2,t0e=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ef,this.onerror=fDn,this[mDn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||ADn,n.generateMask?n.generateMask(r):(SB===EV&&(sv===void 0&&(sv=Buffer.alloc(EV)),dDn(sv,0,EV),SB=0),r[0]=sv[SB++],r[1]=sv[SB++],r[2]=sv[SB++],r[3]=sv[SB++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[mh]!==void 0?a=n[mh]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[o-4]=r[0],u[o-3]=r[1],u[o-2]=r[2],u[o-1]=r[3],s?[u,e]:i?(brt(e,r,u,o,a),[u]):(brt(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=hDn;else{if(typeof e!="number"||!gDn(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(pDn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[mh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ef?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(t.frame(o,s),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):vB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[mh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};vB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):vB(e)?(i=e.size,o=!1):(e=ov(e),i=e.length,o=ov.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[mh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};vB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[xrt.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):vB(e)?(a=e.size,c=!1):(e=ov(e),a=e.length,c=ov.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let u={[mh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};vB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==ef?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[mh],this._state=EDn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(n0e,this,a,i);return}this._bufferedBytes-=r[mh];let s=ov(o);n?this.dispatch(s,n,r,i):(this._state=ef,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(wDn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[xrt.extensionName];this._bufferedBytes+=r[mh],this._state=yDn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");n0e(this,c,i);return}this._bufferedBytes-=r[mh],this._state=ef,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===ef&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][mh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][mh],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Crt.exports=t0e;function n0e(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function wDn(t,e,n){n0e(t,e,n),t.onerror(e)}});var Drt=Q((zIi,Brt)=>{"use strict";var{kForOnEventAttribute:iU,kListener:i0e}=Y0(),Irt=Symbol("kCode"),vrt=Symbol("kData"),Srt=Symbol("kError"),_rt=Symbol("kMessage"),krt=Symbol("kReason"),_B=Symbol("kTarget"),Trt=Symbol("kType"),Rrt=Symbol("kWasClean"),X0=class{constructor(e){this[_B]=null,this[Trt]=e}get target(){return this[_B]}get type(){return this[Trt]}};Object.defineProperty(X0.prototype,"target",{enumerable:!0});Object.defineProperty(X0.prototype,"type",{enumerable:!0});var av=class extends X0{constructor(e,n={}){super(e),this[Irt]=n.code===void 0?0:n.code,this[krt]=n.reason===void 0?"":n.reason,this[Rrt]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Irt]}get reason(){return this[krt]}get wasClean(){return this[Rrt]}};Object.defineProperty(av.prototype,"code",{enumerable:!0});Object.defineProperty(av.prototype,"reason",{enumerable:!0});Object.defineProperty(av.prototype,"wasClean",{enumerable:!0});var kB=class extends X0{constructor(e,n={}){super(e),this[Srt]=n.error===void 0?null:n.error,this[_rt]=n.message===void 0?"":n.message}get error(){return this[Srt]}get message(){return this[_rt]}};Object.defineProperty(kB.prototype,"error",{enumerable:!0});Object.defineProperty(kB.prototype,"message",{enumerable:!0});var oU=class extends X0{constructor(e,n={}){super(e),this[vrt]=n.data===void 0?null:n.data}get data(){return this[vrt]}};Object.defineProperty(oU.prototype,"data",{enumerable:!0});var xDn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[iU]&&i[i0e]===e&&!i[iU])return;let r;if(t==="message")r=function(o,s){let a=new oU("message",{data:s?o:o.toString()});a[_B]=this,wV(e,this,a)};else if(t==="close")r=function(o,s){let a=new av("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[_B]=this,wV(e,this,a)};else if(t==="error")r=function(o){let s=new kB("error",{error:o,message:o.message});s[_B]=this,wV(e,this,s)};else if(t==="open")r=function(){let o=new X0("open");o[_B]=this,wV(e,this,o)};else return;r[iU]=!!n[iU],r[i0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[i0e]===e&&!n[iU]){this.removeListener(t,n);break}}};Brt.exports={CloseEvent:av,ErrorEvent:kB,Event:X0,EventTarget:xDn,MessageEvent:oU};function wV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var xV=Q((VIi,Mrt)=>{"use strict";var{tokenChars:sU}=IB();function Mg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function bDn(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,s,a,c=-1,u=-1,l=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),s===void 0)if(l===-1&&sU[u]===1)c===-1&&(c=d);else if(d!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);u===44?(Mg(e,h,n),n=Object.create(null)):s=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&sU[u]===1)c===-1&&(c=d);else if(u===32||u===9)l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),Mg(n,t.slice(c,l),!0),u===44&&(Mg(e,s,n),n=Object.create(null),s=void 0),c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,d),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(sU[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(sU[u]===1)c===-1&&(c=d);else if(u===34&&c!==-1)o=!1,l=d;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&sU[u]===1)c===-1&&(c=d);else if(c!==-1&&(u===32||u===9))l===-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);r&&(h=h.replace(/\\/g,""),r=!1),Mg(n,a,h),u===44&&(Mg(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let p=t.slice(c,l);return s===void 0?Mg(e,p,n):(a===void 0?Mg(n,p,!0):r?Mg(n,a,p.replace(/\\/g,"")):Mg(n,a,p),Mg(e,s,n)),e}function CDn(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Mrt.exports={format:CDn,parse:bDn}});var vV=Q((JIi,qrt)=>{"use strict";var IDn=K("events"),vDn=K("https"),SDn=K("http"),Lrt=K("net"),_Dn=K("tls"),{randomBytes:kDn,createHash:TDn}=K("crypto"),{Duplex:KIi,Readable:YIi}=K("stream"),{URL:o0e}=K("url"),Cw=CB(),RDn=e0e(),BDn=r0e(),{isBlob:DDn}=IB(),{BINARY_TYPES:Prt,CLOSE_TIMEOUT:MDn,EMPTY_BUFFER:bV,GUID:PDn,kForOnEventAttribute:s0e,kListener:NDn,kStatusCode:LDn,kWebSocket:ec,NOOP:Qrt}=Y0(),{EventTarget:{addEventListener:QDn,removeEventListener:ODn}}=Drt(),{format:FDn,parse:UDn}=xV(),{toBuffer:$Dn}=nU(),Ort=Symbol("kAborted"),a0e=[8,13],Z0=["CONNECTING","OPEN","CLOSING","CLOSED"],WDn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Go=class t extends IDn{constructor(e,n,r){super(),this._binaryType=Prt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=bV,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Frt(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Prt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new RDn({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new BDn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[ec]=this,o[ec]=this,e[ec]=this,i.on("conclude",qDn),i.on("drain",jDn),i.on("error",zDn),i.on("message",VDn),i.on("ping",KDn),i.on("pong",YDn),o.onerror=JDn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Wrt),e.on("data",IV),e.on("end",Hrt),e.on("error",Grt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Cw.extensionName]&&this._extensions[Cw.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),$rt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){c0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||bV,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){c0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||bV,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){c0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Cw.extensionName]||(i.compress=!1),this._sender.send(e||bV,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ep(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Go,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go.prototype,"CONNECTING",{enumerable:!0,value:Z0.indexOf("CONNECTING")});Object.defineProperty(Go,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go.prototype,"OPEN",{enumerable:!0,value:Z0.indexOf("OPEN")});Object.defineProperty(Go,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go.prototype,"CLOSING",{enumerable:!0,value:Z0.indexOf("CLOSING")});Object.defineProperty(Go,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});Object.defineProperty(Go.prototype,"CLOSED",{enumerable:!0,value:Z0.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Go.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Go.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[s0e])return e[NDn];return null},set(e){for(let n of this.listeners(t))if(n[s0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[s0e]:!0})}})});Go.prototype.addEventListener=QDn;Go.prototype.removeEventListener=ODn;qrt.exports=Go;function Frt(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:MDn,protocolVersion:a0e[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!a0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${a0e.join(", ")})`);let o;if(e instanceof o0e)o=e;else try{o=new o0e(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let f=new SyntaxError(c);if(t._redirects===0)throw f;CV(t,f);return}let u=s?443:80,l=kDn(16).toString("base64"),d=s?vDn.request:SDn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?GDn:HDn),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new Cw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=FDn({[Cw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!WDn.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let f=i.path.split(":");i.socketPath=f[0],i.path=f[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?i.socketPath:o.host;let f=r&&r.headers;if(r={...r,headers:{}},f)for(let[g,A]of Object.entries(f))r.headers[g.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let f=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!f||t._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,f||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=d(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=d(i);i.timeout&&m.on("timeout",()=>{ep(t,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[Ort]||(m=t._req=null,CV(t,f))}),m.on("response",f=>{let g=f.headers.location,A=f.statusCode;if(g&&i.followRedirects&&A>=300&&A<400){if(++t._redirects>i.maxRedirects){ep(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new o0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);CV(t,v);return}Frt(t,x,n,r)}else t.emit("unexpected-response",m,f)||ep(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,A)=>{if(t.emit("upgrade",f),t.readyState!==Go.CONNECTING)return;m=t._req=null;let x=f.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){ep(t,g,"Invalid Upgrade header");return}let b=TDn("sha1").update(l+PDn).digest("base64");if(f.headers["sec-websocket-accept"]!==b){ep(t,g,"Invalid Sec-WebSocket-Accept header");return}let v=f.headers["sec-websocket-protocol"],S;if(v!==void 0?p.size?p.has(v)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":p.size&&(S="Server sent no subprotocol"),S){ep(t,g,S);return}v&&(t._protocol=v);let _=f.headers["sec-websocket-extensions"];if(_!==void 0){if(!h){ep(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=UDn(_)}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==Cw.extensionName){ep(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[Cw.extensionName])}catch{ep(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Cw.extensionName]=h}t.setSocket(g,A,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function CV(t,e){t._readyState=Go.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function HDn(t){return t.path=t.socketPath,Lrt.connect(t)}function GDn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Lrt.isIP(t.host)?"":t.host),_Dn.connect(t)}function ep(t,e,n){t._readyState=Go.CLOSING;let r=new Error(n);Error.captureStackTrace(r,ep),e.setHeader?(e[Ort]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(CV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function c0e(t,e,n){if(e){let r=DDn(e)?e.size:$Dn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${Z0[t.readyState]})`);process.nextTick(n,r)}}function qDn(t,e){let n=this[ec];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ec]!==void 0&&(n._socket.removeListener("data",IV),process.nextTick(Urt,n._socket),t===1005?n.close():n.close(t,e))}function jDn(){let t=this[ec];t.isPaused||t._socket.resume()}function zDn(t){let e=this[ec];e._socket[ec]!==void 0&&(e._socket.removeListener("data",IV),process.nextTick(Urt,e._socket),e.close(t[LDn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Nrt(){this[ec].emitClose()}function VDn(t,e){this[ec].emit("message",t,e)}function KDn(t){let e=this[ec];e._autoPong&&e.pong(t,!this._isServer,Qrt),e.emit("ping",t)}function YDn(t){this[ec].emit("pong",t)}function Urt(t){t.resume()}function JDn(t){let e=this[ec];e.readyState!==Go.CLOSED&&(e.readyState===Go.OPEN&&(e._readyState=Go.CLOSING,$rt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function $rt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Wrt(){let t=this[ec];if(this.removeListener("close",Wrt),this.removeListener("data",IV),this.removeListener("end",Hrt),t._readyState=Go.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ec]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Nrt),t._receiver.on("finish",Nrt))}function IV(t){this[ec]._receiver.write(t)||this.pause()}function Hrt(){let t=this[ec];t._readyState=Go.CLOSING,t._receiver.end(),this.end()}function Grt(){let t=this[ec];this.removeListener("error",Grt),this.on("error",Qrt),t&&(t._readyState=Go.CLOSING,this.destroy())}});var Krt=Q((ZIi,Vrt)=>{"use strict";var XIi=vV(),{Duplex:XDn}=K("stream");function jrt(t){t.emit("close")}function ZDn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function zrt(t){this.removeListener("error",zrt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function eMn(t,e){let n=!0,r=new XDn({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&r._readableState.objectMode?o.toString():o;r.push(a)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(jrt,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(jrt,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,s)});return}t.send(i,s)},r.on("end",ZDn),r.on("error",zrt),r}Vrt.exports=eMn});var u0e=Q((evi,Yrt)=>{"use strict";var{tokenChars:tMn}=IB();function nMn(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let s=t.charCodeAt(i);if(r===-1&&tMn[s]===1)n===-1&&(n=i);else if(i!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=i);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Yrt.exports={parse:nMn}});var rit=Q((nvi,nit)=>{"use strict";var rMn=K("events"),SV=K("http"),{Duplex:tvi}=K("stream"),{createHash:iMn}=K("crypto"),Jrt=xV(),cv=CB(),oMn=u0e(),sMn=vV(),{CLOSE_TIMEOUT:aMn,GUID:cMn,kWebSocket:uMn}=Y0(),lMn=/^[+/0-9A-Za-z]{22}==$/,Xrt=0,Zrt=1,tit=2,l0e=class extends rMn{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:aMn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:sMn,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=SV.createServer((r,i)=>{let o=SV.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=dMn(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Xrt}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===tit){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(aU,this);return}if(e&&this.once("close",e),this._state!==Zrt)if(this._state=Zrt,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(aU,this):process.nextTick(aU,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{aU(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",eit);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){uv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){uv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!lMn.test(o)){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){uv(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){cU(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=oMn.parse(c)}catch{uv(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let p=new cv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Jrt.parse(l);h[cv.extensionName]&&(p.accept(h[cv.extensionName]),d[cv.extensionName]=p)}catch{uv(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,m,f,g)=>{if(!h)return cU(n,m||401,f,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return cU(n,401)}this.completeUpgrade(d,o,u,e,n,r,i)}completeUpgrade(e,n,r,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[uMn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xrt)return cU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${iMn("sha1").update(n+cMn).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[cv.extensionName]){let d=e[cv.extensionName].params,p=Jrt.format({[cv.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
101
101
  `).join(`\r
102
102
  `)),o.removeListener("error",eit),l.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(aU,this)})),a(l,i)}};nit.exports=l0e;function dMn(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function aU(t){t._state=tit,t.emit("close")}function eit(){this.destroy()}function cU(t,e,n,r){n=n||SV.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${SV.STATUS_CODES[e]}\r
103
103
  `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r