@north-light/cli 0.3.769 → 0.3.771
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +0 -2
- package/dist/api/client.js +2 -2
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/execution-start.d.ts +0 -12
- package/dist/api/routes.d.ts +0 -1
- package/dist/api/routes.js +1 -1
- package/dist/clients/attach/viewer.js +2 -2
- package/dist/core/runtime/interactive-deliver.d.ts +2 -1
- package/dist/core/runtime/interactive-deliver.js +1 -1
- package/dist/daemon/api/handlers/execution-start.js +2 -2
- package/dist/daemon/api/handlers/node-events.js +3 -3
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/review-page.js +4 -4
- package/dist/doc-editor/review.css +1 -1
- package/dist/doc-editor/review.js +49 -47
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +0 -4
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/routes.js +0 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/sandbox-start.mjs +1 -184
|
@@ -85,8 +85,8 @@ ${i}`);return e.join(`
|
|
|
85
85
|
`)||e.includes("\r")||Buffer.byteLength(e,"utf8")+1>OXe?!1:LXe(t,[e])}function QXe(t,e){if(e.includes(`
|
|
86
86
|
`)||e.includes("\r"))return!1;let n=Buffer.byteLength(e,"utf8")+1;return n>OXe?!1:(Vd!==void 0&&Vd.path!==t&&f6(),Vd===void 0&&(Vd={path:t,records:[],bytes:0},NXe||(process.on("exit",f6),NXe=!0)),Vd.path=t,Vd.records.push(e),Vd.bytes+=n,Vd.bytes>=hSn?f6():Vd.timer===void 0&&(Vd.timer=setTimeout(f6,mSn),Vd.timer.unref()),!0)}function f6(){let t=Vd;if(!(t===void 0||t.records.length===0)&&(t.timer!==void 0&&clearTimeout(t.timer),Vd=void 0,!LXe(t.path,t.records,pSn)))for(let e of t.records)process.stderr.write(`[crtrd] event log append failed: ${e}
|
|
87
87
|
`)}var OXe,dSn,pSn,hSn,mSn,Vd,NXe,Tfe=A(()=>{"use strict";OXe=65536,dSn=5*1024*1024,pSn=16*1024*1024,hSn=128*1024,mSn=200;NXe=!1});var Rfe,FXe=A(()=>{"use strict";Rfe=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"]});function fSn(t){return typeof t=="object"&&t!==null?t:void 0}function UXe(t){return typeof t=="string"?t:""}function $Xe(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=fSn(t);return{type:UXe(e?.name)||"Error",message:UXe(e?.message)||String(t)}}var WXe=A(()=>{"use strict";FXe()});import{AsyncLocalStorage as gSn}from"node:async_hooks";import{randomBytes as ASn}from"node:crypto";function A6(t){if(typeof t!="string"||!ySn.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function Dfe(){let t;do t=ASn(16).toString("hex");while(t==="00000000000000000000000000000000");return A6(t)}var ySn,Bfe,HXe,GXe=A(()=>{"use strict";ySn=/^(?!0{32}$)[0-9a-f]{32}$/,Bfe=new gSn;HXe={current:()=>Bfe.getStore(),run:(t,e)=>Bfe.run(A6(t),e),fresh:t=>{let e=Dfe();return Bfe.run(e,()=>t(e))}}});function vSn(t){return Buffer.byteLength(t,"utf8")}function y6(t,e,n=128){if(typeof t!="string"||t===""||vSn(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function SSn(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 _Sn(t){if(!ISn.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=y6(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!CSn.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function qXe(t){if(!wSn.has(t.level))throw new TypeError("level is invalid");if(!xSn.has(t.component))throw new TypeError("component is invalid");let e=y6(t.event,"event");if(!ESn.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?HXe.current()??Dfe():A6(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():SSn(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=y6(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=y6(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(!bSn.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=_Sn(t.error_class)),t.error!==void 0&&(r.error=$Xe(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}var ESn,wSn,xSn,bSn,CSn,ISn,jXe=A(()=>{"use strict";WXe();GXe();ESn=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,wSn=new Set(["error","warn","info","debug"]),xSn=new Set(["daemon","broker","control-plane","front","sentinel"]),bSn=new Set(["succeeded","failed","skipped"]),CSn=new Set(["auto","manual","fatal"]),ISn=new Set(Rfe)});function HI(t){return Buffer.byteLength(t,"utf8")}function WI(t,e){if(HI(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-HI(n),i=0,o="";for(let s of t){let a=HI(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function kSn(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 Mfe(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=WI(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:kSn(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=Mfe(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=WI(l,128),p;try{p=Mfe(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 TSn(t){let e=WI(String(t.type),128),n=WI(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=WI(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=WI(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function E6(t){return JSON.stringify(t)}function CF(t){return HI(E6(t))+1}function zXe(t){let e=t.fields===void 0?void 0:Mfe(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:TSn(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=HI(E6(u[p]))-HI(E6(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=WI(a.message,64).value);let c=E6(r);if(HI(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}var VXe=A(()=>{"use strict"});import{AsyncLocalStorage as RSn}from"node:async_hooks";function YXe(t){Pfe=t}function w6(){return KXe}function x6(){let t=BSn.getStore();if(t!==void 0)return t;if(KXe)throw new vF;if(Pfe===void 0)throw new IF;return Pfe}var IF,vF,Pfe,KXe,BSn,JR=A(()=>{"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"}},KXe=!1,BSn=new RSn});import{existsSync as b6,lstatSync as FEi,mkdirSync as DSn,readdirSync as MSn,readFileSync as XXe,rmSync as PSn,statSync as NSn,symlinkSync as UEi,writeFileSync as OSn,cpSync as $Ei,readlinkSync as WEi,renameSync as LSn,chmodSync as QSn,realpathSync as FSn,closeSync as ZXe,fsyncSync as eZe,openSync as tZe,linkSync as HEi,unlinkSync as GEi,writeSync as qEi}from"node:fs";import{dirname as JXe,join as USn,relative as zEi,sep as VEi}from"node:path";import{homedir as $Sn,platform as WSn}from"node:os";function ef(t){try{return FSn(t)}catch{return t}}function nZe(t,e=$Sn()){return t==="~"?e:t.startsWith("~/")||WSn()==="win32"&&t.startsWith("~\\")?USn(e,t.slice(2)):t}function C6(t){DSn(t,{recursive:!0})}function XR(t,e,n){Nfe(t,JSON.stringify(e,null,2)+`
|
|
88
|
-
`,n)}function HSn(t){let e=tZe(t,"r");try{eZe(e)}finally{ZXe(e)}}function rZe(t){let e=tZe(t,"r");try{eZe(e)}finally{ZXe(e)}}function Nfe(t,e,n){n?.createParent!==!1&&C6(JXe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(b6(t)?NSn(t).mode&511:384);try{OSn(r,e,{mode:i}),QSn(r,i),n?.durable===!0&&HSn(r),LSn(r,t),n?.durable===!0&&rZe(JXe(t))}finally{b6(r)&&PSn(r,{force:!0})}}function GSn(t){return JSON.parse(XXe(t,"utf8"))}function j0(t){try{return GSn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function GI(t){try{return JSON.parse(XXe(t,"utf8"))}catch{return null}}function Ofe(t){return b6(t)}function Lfe(t){return b6(t)?MSn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var $l=A(()=>{"use strict"});import{homedir as qSn,userInfo as jSn}from"node:os";import{basename as zSn,dirname as ewi,isAbsolute as twi,join as Kd,resolve as iZe}from"node:path";function v6(){let t=iZe(kg()||(process.platform==="linux"?"/":Kd(qSn(),".crouter")));if(VSn()&&t===KSn())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 VSn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function KSn(){if(I6===void 0)try{I6=iZe(jSn().homedir,".crouter")}catch{I6=null}return I6}function Wl(){return Kd(v6(),"runtime")}function Qfe(){return Kd(v6(),"apps")}function lh(){return Kd(Wl(),"secrets")}function oZe(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:Kd(n.profiles,e),env:Kd(lh(),"env",zSn(n.root),e),home:n.home}}function Ffe(){return process.platform==="linux"?"/run/crtr":Wl()}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=Kd(Qfe(),e);return{root:n,profiles:Kd(n,"profiles"),conversations:Kd(n,"conversations"),nodes:Kd(n,"nodes"),files:Kd(n,"files"),home:Kd(n,"home"),cache:Kd(n,"cache")}}var I6,dh=A(()=>{"use strict";Rc();Yd();JR();$l()});import{chmodSync as cwi,chownSync as uwi,closeSync as fw,constants as S6,fchmodSync as lwi,fchownSync as dwi,fstatSync as uZe,fsyncSync as pwi,linkSync as hwi,lstatSync as mwi,mkdirSync as fwi,openSync as sZe,readdirSync as gwi,readFileSync as YSn,readlinkSync as Awi,readSync as ywi,realpathSync as Ewi,renameSync as wwi,rmdirSync as xwi,rmSync as bwi,statSync as Cwi,symlinkSync as Iwi,unlinkSync as vwi,writeSync as Swi}from"node:fs";import{basename as kwi,dirname as Twi,join as Rwi,relative as lZe,resolve as Wfe,sep as aZe}from"node:path";import{loadLinuxNative as JSn,O_CLOEXEC as Hfe,O_PATH as Gfe,RESOLVE_BENEATH as XSn,RESOLVE_NO_SYMLINKS as ZSn}from"../../native/linux.js";function dZe(){return Ufe===null&&(Ufe=JSn()),Ufe}function t_n(t){return t.code}function n_n(t,e){switch(t_n(t)){case"ELOOP":case"EXDEV":return new qI(`path meets a symlink: ${e}`);case"ENXIO":return new qI(`path is not a regular file: ${e}`);case"EAGAIN":return new qI(`path is held by a lease: ${e}`);default:return t}}function $fe(t,e,n,r,i){try{return t.openat2(e,n,r,e_n)}catch(o){throw n_n(o,i)}}function r_n(t,e,n){let r;try{r=uZe(t)}catch(i){throw fw(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw fw(t),new qI(`path is not a regular file: ${e}`)}function i_n(t,e){let n=lZe(Wfe(t),Wfe(e));if(n===".."||n.startsWith(`..${aZe}`)||n.startsWith(aZe))throw new Error(`${e} is outside ${t}`);return n}function pZe(t,e,n){if(n&S6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=i_n(t,e),i=dZe();if(!i)return sZe(e,n);let o=sZe("/",cZe),s;try{s=$fe(i,o,lZe("/",Wfe(t))||".",cZe,t)}finally{fw(o)}try{return n&Gfe?$fe(i,s,r||".",n|Hfe,e):r_n($fe(i,s,r||".",n|Hfe|S6.O_NONBLOCK,e),e,!0)}finally{fw(s)}}function qfe(t,e){let n=pZe(t,e,S6.O_RDONLY);try{return YSn(n)}finally{fw(n)}}function hZe(t,e){if(!dZe())return{path:e,release:()=>{}};let n=pZe(t,e,Gfe),r;try{r=uZe(n)}catch(o){throw fw(n),o}if(!r.isSocket())throw fw(n),new qI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,fw(n))}}}var e_n,cZe,Ufe,qI,_F=A(()=>{"use strict";e_n=XSn|ZSn,cZe=Gfe|S6.O_DIRECTORY|Hfe,Ufe=null;qI=class extends Error{}});import{join as Tg}from"node:path";function nu(){return Wl()}function mZe(){return Tg(nu(),"on-disk-migration.lock")}function ZR(t){return Tg(eB(t),"view.sock")}function o_n(){return Tg(nu(),"nodes")}function kF(){return Tg(Ffe(),"api.sock")}function fZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=s_n}function jfe(t){if(!fZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function a_n(t){return jfe(t),Tg(o_n(),t)}function c_n(t,e){jfe(t);let n=e??(zme()===t?KYe():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return Tg(SF(n).nodes,t)}function eB(t){return jfe(t),process.platform==="linux"?Tg(Ffe(),"nodes",t):Tg(a_n(t),"run")}function yZe(t,e){return Tg(c_n(t,e),"context")}function EZe(t){return Tg(eB(t),"job")}var s_n,gZe,AZe,Hl=A(()=>{"use strict";dh();Rc();_F();s_n=128;gZe="broker-released",AZe="cli-relay-generation"});import{join as u_n}from"node:path";function l_n(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function d_n(t){if(_6===void 0){_6=t;return}if(!l_n(_6,t))throw new Error("event source is already bound for this process")}function wZe(){d_n({component:"daemon",path:u_n(nu(),"crtrd.log")})}function k6(){return _6}var _6,zfe=A(()=>{"use strict";Hl()});function xZe(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 Vfe(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,gw=A(()=>{"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 ae,Kfe=A(()=>{"use strict";ae={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",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}`,environments:()=>"/v1/environments",environment:t=>`/v1/environments/${t}`,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 CZe(t){bZe=t}function IZe(t){t!==null&&bZe?.(t)}var bZe,Yfe=A(()=>{"use strict"});function T6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Jfe=A(()=>{"use strict"});function vZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Xfe=A(()=>{"use strict"});function SZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Zfe=A(()=>{"use strict"});async function B6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=g_n,retry:i=()=>!0,now:o=Date.now,sleep:s=BZe}){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 jI(t,e){let n=t.status>=200&&t.status<300,r=(await RZe(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 Vfe(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 y_n(t){return t==="GET"||t==="HEAD"}async function E_n(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await RZe(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 w_n(t){return t===429||t>=500}async function ege(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 RZe(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 _Ze(t){return Math.min(2e3,250*2**(t-1))}function tge(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 kZe(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function Aw(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=tge(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 x_n(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 TZe(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function R6(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 BZe(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 b_n(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 BZe(t){return new Promise(e=>setTimeout(e,t))}function C_n(t){if(t!==void 0)try{return t()}catch{return}}var p_n,h_n,m_n,f_n,g_n,RF,TF,Rg,A_n,D6=A(()=>{"use strict";gw();Kfe();Yfe();Jfe();Xfe();Zfe();p_n=3e4,h_n=3e4,m_n=Symbol.for("@north-light/api/local-socket-fetch"),f_n=1e4,g_n=200;RF=2147483647;TF=t=>tB(t??Date.now()),Rg=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??p_n,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[m_n]===!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??f_n}healthz(){return this.request("GET",ae.healthz())}async probeHealthz(e){let n=await this.transport("GET",ae.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 jI(n)}async ready(){let e=await this.transport("GET",ae.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return jI(e)}status(){return this.request("GET",ae.status())}due(){return this.request("GET",ae.due())}restartDaemon(){return this.request("POST",ae.daemonRestart())}drainDaemon(e={}){let n=e.settle_limit_ms??0;return this.request("POST",ae.daemonDrain(),e,{timeout:n+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",ae.daemonDrain())}admitDaemon(){return this.request("POST",ae.daemonAdmit())}appendNodeLog(e,n){return this.request("POST",ae.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",ae.nodeTelemetry(this.nodePath(e)),n)}async putNodeSummaries(e,n){await this.request("PUT",ae.nodeSummaries(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",ae.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",kr(ae.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}listNodeAttachments(e){return this.request("GET",ae.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,n){let r=await this.send("GET",ae.nodeAttachment(this.nodePath(e),n));return r.ok||await jI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",ae.nodeFiles(this.nodePath(e)),n)}createNodeUpload(e,n){return this.request("POST",ae.nodeUploads(this.nodePath(e)),n)}nodeUploadLink(e,n){return this.request("POST",ae.nodeUploadLink(this.nodePath(e),n))}completeNodeFile(e,n){return this.request("POST",ae.nodeFileComplete(this.nodePath(e),n))}readNodePassiveMessage(e,n){return this.request("GET",kr(ae.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",ae.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",ae.nodes(),e,{timeout:12e4+this.timeoutMs})}listNodes(e){return this.request("GET",kr(ae.nodes(),e))}getNode(e){return this.request("GET",ae.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(ae.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(ae.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(ae.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await jI(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",ae.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",ae.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",ae.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",ae.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",`${ae.nodeJobOutput(this.nodePath(e),this.jobPath(n))}${o}`)}stopBashJob(e,n){return this.request("DELETE",ae.nodeJob(this.nodePath(e),this.jobPath(n)))}async patchBashJob(e,n,r){await this.request("PATCH",ae.nodeJob(this.nodePath(e),this.jobPath(n)),r)}async reportBashJob(e,n,r){await this.request("POST",ae.nodeJobReport(this.nodePath(e),this.jobPath(n)),r)}sendMessage(e,n){return this.request("POST",ae.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",ae.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",ae.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",ae.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",ae.nodeFork(this.nodePath(e)),{})}kickNode(e){return this.request("POST",ae.nodeKick(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",ae.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",ae.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",ae.nodeBrokerSessionBound(this.nodePath(e)),n)}cycleStartBroker(e,n,r){return this.request("POST",ae.nodeBrokerCycleStart(this.nodePath(e)),n,r)}settleBroker(e,n){return this.request("POST",ae.nodeBrokerSettle(this.nodePath(e)),n)}startBrokerCycle(e,n){return this.request("POST",ae.nodeBrokerCycle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",ae.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",ae.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",ae.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",ae.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",ae.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",ae.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",ae.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",ae.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",ae.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${ae.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",ae.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",`${ae.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",ae.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",ae.executionStart(e))}executionImportUnpacked(e){return this.request("POST",ae.executionImportUnpacked(e),{})}gitCredential(e,n){return this.request("POST",ae.environmentGitCredential(e),n)}postFeedback(e){return this.request("POST",ae.feedback(),e)}brokerExtensionState(e){return this.request("GET",ae.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",ae.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",ae.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",ae.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",ae.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",ae.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",ae.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",ae.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",ae.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",ae.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",ae.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",ae.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",ae.kinds())}patchConfig(e,n){return this.request("PATCH",ae.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",ae.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",ae.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",ae.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",ae.quarantinedWorktrees())}showLimits(){return this.request("GET",ae.limits())}setAppLimits(e,n){return this.request("PUT",ae.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(ae.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(ae.charges(),e))}listSpendLimits(){return this.request("GET",ae.spendLimits())}setSpendLimit(e,n){return this.request("PUT",ae.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",ae.spendLimit(e))}listSpaces(){return this.request("GET",ae.spaces())}subscribe(e,n){return this.request("POST",ae.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",ae.focuses())}focusOf(e){return this.request("GET",kr(ae.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(ae.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",ae.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",ae.focus(e),n)}async closeFocus(e){await this.request("DELETE",ae.focus(e))}async unsubscribe(e,n){await this.request("DELETE",ae.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",ae.crons(),e)}listCrons(e){return this.request("GET",kr(ae.crons(),e))}showCron(e,n){return this.request("GET",kr(ae.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(ae.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(ae.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(ae.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(ae.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",ae.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",ae.nodeAttach(this.nodePath(e)),n??{},{timeout:h_n+this.timeoutMs})}getReports(e,n){return this.request("GET",kr(ae.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",kr(ae.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",ae.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",ae.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",kr(ae.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",ae.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",ae.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",kr(ae.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",ae.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",kr(ae.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",ae.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",kr(ae.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",ae.bash(),e,n)}objects={read:(e,n)=>this.request("GET",kr(ae.object(e),n)),list:e=>this.request("GET",kr(ae.objects(),e)),search:e=>this.request("POST",ae.objectsSearch(),e),watch:(e,n={})=>this.request("POST",ae.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",kr(ae.objectWatch(e),n)),edges:(e,n)=>this.request("GET",kr(ae.objectEdges(e),n))};docs={write:e=>this.request("POST",ae.docs(),e),edit:(e,n)=>this.request("PATCH",ae.doc(e),n),move:(e,n)=>this.request("POST",ae.docMove(e),n),delete:e=>this.request("DELETE",ae.doc(e)),history:(e,n)=>this.request("GET",kr(ae.docHistory(e),n)),lint:(e={})=>this.request("POST",ae.docsLint(),e)};documents={browserAccess:()=>this.request("GET",ae.documentsBrowserAccess()),reconcilePackages:e=>this.request("POST",ae.documentsReconcilePackages(),e)};plugins={appToken:e=>this.request("GET",ae.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",ae.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",ae.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",ae.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",ae.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",ae.profile(e),n??{})}createProfile(e){return this.request("POST",ae.profiles(),e)}listProfiles(){return this.request("GET",ae.profiles())}updateProfile(e,n){return this.request("PATCH",ae.profile(e),n)}listAppEnv(){return this.request("GET",ae.appEnv())}setAppEnv(e,n){return this.request("PUT",ae.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",ae.appEnvVar(e))}listProfileEnv(e){return this.request("GET",ae.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",ae.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",ae.profileEnvVar(e,n))}getProfileEnvironment(e){return this.request("GET",ae.profileEnvironment(e))}setProfileEnvironment(e,n){return this.request("PUT",ae.profileEnvironment(e),n)}getProfile(e){return this.request("GET",ae.profile(e))}pauseProfile(e){return this.request("POST",ae.profilePause(e),{})}resumeProfile(e){return this.request("POST",ae.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",ae.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",ae.profile(e),n)}getSettings(){return this.request("GET",ae.settings())}putSettings(e){return this.request("PUT",ae.settings(),e)}listModelAuth(){return this.request("GET",ae.modelAuths())}getModelAuthReadiness(e){return this.request("GET",kr(ae.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",ae.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",ae.modelAuth(e))}patchModelAuthAccount(e,n,r){return this.request("PATCH",ae.modelAuthAccount(e,n),r)}removeModelAuthAccount(e,n){return this.request("DELETE",ae.modelAuthAccount(e,n))}startModelAuth(e){return this.request("POST",ae.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",ae.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",ae.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",kr(ae.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",ae.humanReviews(),e)}listReviews(e){return this.request("GET",kr(ae.humanReviews(),e))}getReview(e){return this.request("GET",ae.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",ae.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",ae.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",ae.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",ae.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",kr(ae.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",kr(ae.humanReviewCommentEvents(this.reviewPath(e)),n))}getReviewComment(e){return this.request("GET",ae.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",ae.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",ae.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",ae.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",ae.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",ae.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",ae.humanInbox())}getHumanInboxPage(e){return this.request("GET",ae.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(ae.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",ae.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",ae.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",ae.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",ae.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",ae.humanRequests(),e)}listPageComponents(){return this.request("GET",ae.humanComponents())}getHumanRequest(e){return this.request("GET",ae.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",ae.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",ae.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",ae.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",ae.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",ae.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",ae.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",ae.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",ae.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",ae.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",kr(ae.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",ae.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",ae.canvasSnapshot())}analytics(e){return this.request("GET",kr(ae.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",ae.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",kr(ae.canvasLiveRoots(),e))}canvasView(e){return this.request("GET",ae.canvasView(e))}canvasRoster(){return this.request("GET",ae.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",ae.canvasBrowse());return e.ok||await jI(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(e){return this.request("GET",e===void 0?ae.canvasGraph():`${ae.canvasGraph()}?root=${encodeURIComponent(e)}`)}prune(e){return this.request("POST",ae.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 jI(s,o?.deadlineAt)}catch(o){throw x_n(e,Aw(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw Aw(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()+A_n);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&&!kZe(p,o.signal)?tB(o.deadlineAt):Aw(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&&!kZe(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await R6(_Ze(u+1),o);continue}else throw Aw(d,o.signal)}}if(y_n(e)&&a>0&&l.status===503&&await E_n(l,o.deadlineAt)){let d=Math.max(250,(TZe(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await ege(l,o.deadlineAt),await R6(d,{signal:o.signal});continue}if(s&&u<a&&w_n(l.status)){await ege(l,o.deadlineAt),await R6(_Ze(u+1),o,TZe(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>RF))throw new RangeError(`budgetMs must be a positive finite number of at most ${RF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>RF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${RF} 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 TF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(TF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await jI(await this.transport(e,n,r,o))}catch(s){throw Aw(s,o.signal)}}nodePath(e){if(!T6(e))throw new sn(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!vZe(e))throw new sn(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!SZe(e))throw new sn(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!T6(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(!T6(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(TF(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?TF(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 b_n(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>(IZe(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=tge(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=tge(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw Aw(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 Aw(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw TF(n);let i,o;try{await B6({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",ae.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await ege(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=C_n(this.coldStartDiagnostic);if(o!==void 0){let s=Aw(i);throw new sn(s.status,s.code,`${s.message}
|
|
88
|
+
`,n)}function HSn(t){let e=tZe(t,"r");try{eZe(e)}finally{ZXe(e)}}function rZe(t){let e=tZe(t,"r");try{eZe(e)}finally{ZXe(e)}}function Nfe(t,e,n){n?.createParent!==!1&&C6(JXe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(b6(t)?NSn(t).mode&511:384);try{OSn(r,e,{mode:i}),QSn(r,i),n?.durable===!0&&HSn(r),LSn(r,t),n?.durable===!0&&rZe(JXe(t))}finally{b6(r)&&PSn(r,{force:!0})}}function GSn(t){return JSON.parse(XXe(t,"utf8"))}function j0(t){try{return GSn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function GI(t){try{return JSON.parse(XXe(t,"utf8"))}catch{return null}}function Ofe(t){return b6(t)}function Lfe(t){return b6(t)?MSn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var $l=A(()=>{"use strict"});import{homedir as qSn,userInfo as jSn}from"node:os";import{basename as zSn,dirname as ewi,isAbsolute as twi,join as Kd,resolve as iZe}from"node:path";function v6(){let t=iZe(kg()||(process.platform==="linux"?"/":Kd(qSn(),".crouter")));if(VSn()&&t===KSn())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 VSn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function KSn(){if(I6===void 0)try{I6=iZe(jSn().homedir,".crouter")}catch{I6=null}return I6}function Wl(){return Kd(v6(),"runtime")}function Qfe(){return Kd(v6(),"apps")}function lh(){return Kd(Wl(),"secrets")}function oZe(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:Kd(n.profiles,e),env:Kd(lh(),"env",zSn(n.root),e),home:n.home}}function Ffe(){return process.platform==="linux"?"/run/crtr":Wl()}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=Kd(Qfe(),e);return{root:n,profiles:Kd(n,"profiles"),conversations:Kd(n,"conversations"),nodes:Kd(n,"nodes"),files:Kd(n,"files"),home:Kd(n,"home"),cache:Kd(n,"cache")}}var I6,dh=A(()=>{"use strict";Rc();Yd();JR();$l()});import{chmodSync as cwi,chownSync as uwi,closeSync as fw,constants as S6,fchmodSync as lwi,fchownSync as dwi,fstatSync as uZe,fsyncSync as pwi,linkSync as hwi,lstatSync as mwi,mkdirSync as fwi,openSync as sZe,readdirSync as gwi,readFileSync as YSn,readlinkSync as Awi,readSync as ywi,realpathSync as Ewi,renameSync as wwi,rmdirSync as xwi,rmSync as bwi,statSync as Cwi,symlinkSync as Iwi,unlinkSync as vwi,writeSync as Swi}from"node:fs";import{basename as kwi,dirname as Twi,join as Rwi,relative as lZe,resolve as Wfe,sep as aZe}from"node:path";import{loadLinuxNative as JSn,O_CLOEXEC as Hfe,O_PATH as Gfe,RESOLVE_BENEATH as XSn,RESOLVE_NO_SYMLINKS as ZSn}from"../../native/linux.js";function dZe(){return Ufe===null&&(Ufe=JSn()),Ufe}function t_n(t){return t.code}function n_n(t,e){switch(t_n(t)){case"ELOOP":case"EXDEV":return new qI(`path meets a symlink: ${e}`);case"ENXIO":return new qI(`path is not a regular file: ${e}`);case"EAGAIN":return new qI(`path is held by a lease: ${e}`);default:return t}}function $fe(t,e,n,r,i){try{return t.openat2(e,n,r,e_n)}catch(o){throw n_n(o,i)}}function r_n(t,e,n){let r;try{r=uZe(t)}catch(i){throw fw(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw fw(t),new qI(`path is not a regular file: ${e}`)}function i_n(t,e){let n=lZe(Wfe(t),Wfe(e));if(n===".."||n.startsWith(`..${aZe}`)||n.startsWith(aZe))throw new Error(`${e} is outside ${t}`);return n}function pZe(t,e,n){if(n&S6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=i_n(t,e),i=dZe();if(!i)return sZe(e,n);let o=sZe("/",cZe),s;try{s=$fe(i,o,lZe("/",Wfe(t))||".",cZe,t)}finally{fw(o)}try{return n&Gfe?$fe(i,s,r||".",n|Hfe,e):r_n($fe(i,s,r||".",n|Hfe|S6.O_NONBLOCK,e),e,!0)}finally{fw(s)}}function qfe(t,e){let n=pZe(t,e,S6.O_RDONLY);try{return YSn(n)}finally{fw(n)}}function hZe(t,e){if(!dZe())return{path:e,release:()=>{}};let n=pZe(t,e,Gfe),r;try{r=uZe(n)}catch(o){throw fw(n),o}if(!r.isSocket())throw fw(n),new qI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,fw(n))}}}var e_n,cZe,Ufe,qI,_F=A(()=>{"use strict";e_n=XSn|ZSn,cZe=Gfe|S6.O_DIRECTORY|Hfe,Ufe=null;qI=class extends Error{}});import{join as Tg}from"node:path";function nu(){return Wl()}function mZe(){return Tg(nu(),"on-disk-migration.lock")}function ZR(t){return Tg(eB(t),"view.sock")}function o_n(){return Tg(nu(),"nodes")}function kF(){return Tg(Ffe(),"api.sock")}function fZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=s_n}function jfe(t){if(!fZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function a_n(t){return jfe(t),Tg(o_n(),t)}function c_n(t,e){jfe(t);let n=e??(zme()===t?KYe():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return Tg(SF(n).nodes,t)}function eB(t){return jfe(t),process.platform==="linux"?Tg(Ffe(),"nodes",t):Tg(a_n(t),"run")}function yZe(t,e){return Tg(c_n(t,e),"context")}function EZe(t){return Tg(eB(t),"job")}var s_n,gZe,AZe,Hl=A(()=>{"use strict";dh();Rc();_F();s_n=128;gZe="broker-released",AZe="cli-relay-generation"});import{join as u_n}from"node:path";function l_n(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function d_n(t){if(_6===void 0){_6=t;return}if(!l_n(_6,t))throw new Error("event source is already bound for this process")}function wZe(){d_n({component:"daemon",path:u_n(nu(),"crtrd.log")})}function k6(){return _6}var _6,zfe=A(()=>{"use strict";Hl()});function xZe(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 Vfe(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,gw=A(()=>{"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 ae,Kfe=A(()=>{"use strict";ae={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",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`,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}`,environments:()=>"/v1/environments",environment:t=>`/v1/environments/${t}`,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 CZe(t){bZe=t}function IZe(t){t!==null&&bZe?.(t)}var bZe,Yfe=A(()=>{"use strict"});function T6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Jfe=A(()=>{"use strict"});function vZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Xfe=A(()=>{"use strict"});function SZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Zfe=A(()=>{"use strict"});async function B6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=g_n,retry:i=()=>!0,now:o=Date.now,sleep:s=BZe}){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 jI(t,e){let n=t.status>=200&&t.status<300,r=(await RZe(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 Vfe(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 y_n(t){return t==="GET"||t==="HEAD"}async function E_n(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await RZe(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 w_n(t){return t===429||t>=500}async function ege(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 RZe(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 _Ze(t){return Math.min(2e3,250*2**(t-1))}function tge(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 kZe(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function Aw(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=tge(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 x_n(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 TZe(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function R6(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 BZe(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 b_n(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 BZe(t){return new Promise(e=>setTimeout(e,t))}function C_n(t){if(t!==void 0)try{return t()}catch{return}}var p_n,h_n,m_n,f_n,g_n,RF,TF,Rg,A_n,D6=A(()=>{"use strict";gw();Kfe();Yfe();Jfe();Xfe();Zfe();p_n=3e4,h_n=3e4,m_n=Symbol.for("@north-light/api/local-socket-fetch"),f_n=1e4,g_n=200;RF=2147483647;TF=t=>tB(t??Date.now()),Rg=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??p_n,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[m_n]===!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??f_n}healthz(){return this.request("GET",ae.healthz())}async probeHealthz(e){let n=await this.transport("GET",ae.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 jI(n)}async ready(){let e=await this.transport("GET",ae.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return jI(e)}status(){return this.request("GET",ae.status())}due(){return this.request("GET",ae.due())}restartDaemon(){return this.request("POST",ae.daemonRestart())}drainDaemon(e={}){let n=e.settle_limit_ms??0;return this.request("POST",ae.daemonDrain(),e,{timeout:n+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",ae.daemonDrain())}admitDaemon(){return this.request("POST",ae.daemonAdmit())}appendNodeLog(e,n){return this.request("POST",ae.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",ae.nodeTelemetry(this.nodePath(e)),n)}async putNodeSummaries(e,n){await this.request("PUT",ae.nodeSummaries(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",ae.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",kr(ae.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}listNodeAttachments(e){return this.request("GET",ae.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,n){let r=await this.send("GET",ae.nodeAttachment(this.nodePath(e),n));return r.ok||await jI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",ae.nodeFiles(this.nodePath(e)),n)}createNodeUpload(e,n){return this.request("POST",ae.nodeUploads(this.nodePath(e)),n)}nodeUploadLink(e,n){return this.request("POST",ae.nodeUploadLink(this.nodePath(e),n))}completeNodeFile(e,n){return this.request("POST",ae.nodeFileComplete(this.nodePath(e),n))}readNodePassiveMessage(e,n){return this.request("GET",kr(ae.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",ae.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",ae.nodes(),e,{timeout:12e4+this.timeoutMs})}listNodes(e){return this.request("GET",kr(ae.nodes(),e))}getNode(e){return this.request("GET",ae.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(ae.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(ae.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(ae.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await jI(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",ae.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",ae.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",ae.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",ae.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",`${ae.nodeJobOutput(this.nodePath(e),this.jobPath(n))}${o}`)}stopBashJob(e,n){return this.request("DELETE",ae.nodeJob(this.nodePath(e),this.jobPath(n)))}async patchBashJob(e,n,r){await this.request("PATCH",ae.nodeJob(this.nodePath(e),this.jobPath(n)),r)}async reportBashJob(e,n,r){await this.request("POST",ae.nodeJobReport(this.nodePath(e),this.jobPath(n)),r)}sendMessage(e,n){return this.request("POST",ae.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",ae.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",ae.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",ae.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",ae.nodeFork(this.nodePath(e)),{})}kickNode(e){return this.request("POST",ae.nodeKick(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",ae.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",ae.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",ae.nodeBrokerSessionBound(this.nodePath(e)),n)}cycleStartBroker(e,n,r){return this.request("POST",ae.nodeBrokerCycleStart(this.nodePath(e)),n,r)}settleBroker(e,n){return this.request("POST",ae.nodeBrokerSettle(this.nodePath(e)),n)}startBrokerCycle(e,n){return this.request("POST",ae.nodeBrokerCycle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",ae.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",ae.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",ae.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",ae.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",ae.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",ae.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",ae.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",ae.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",ae.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${ae.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",ae.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",`${ae.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",ae.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",ae.executionStart(e))}gitCredential(e,n){return this.request("POST",ae.environmentGitCredential(e),n)}postFeedback(e){return this.request("POST",ae.feedback(),e)}brokerExtensionState(e){return this.request("GET",ae.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",ae.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",ae.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",ae.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",ae.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",ae.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",ae.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",ae.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",ae.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",ae.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",ae.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",ae.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",ae.kinds())}patchConfig(e,n){return this.request("PATCH",ae.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",ae.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",ae.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",ae.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",ae.quarantinedWorktrees())}showLimits(){return this.request("GET",ae.limits())}setAppLimits(e,n){return this.request("PUT",ae.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(ae.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(ae.charges(),e))}listSpendLimits(){return this.request("GET",ae.spendLimits())}setSpendLimit(e,n){return this.request("PUT",ae.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",ae.spendLimit(e))}listSpaces(){return this.request("GET",ae.spaces())}subscribe(e,n){return this.request("POST",ae.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",ae.focuses())}focusOf(e){return this.request("GET",kr(ae.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(ae.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",ae.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",ae.focus(e),n)}async closeFocus(e){await this.request("DELETE",ae.focus(e))}async unsubscribe(e,n){await this.request("DELETE",ae.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",ae.crons(),e)}listCrons(e){return this.request("GET",kr(ae.crons(),e))}showCron(e,n){return this.request("GET",kr(ae.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(ae.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(ae.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(ae.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(ae.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",ae.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",ae.nodeAttach(this.nodePath(e)),n??{},{timeout:h_n+this.timeoutMs})}getReports(e,n){return this.request("GET",kr(ae.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",kr(ae.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",ae.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",ae.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",kr(ae.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",ae.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",ae.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",kr(ae.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",ae.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",kr(ae.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",ae.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",kr(ae.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",ae.bash(),e,n)}objects={read:(e,n)=>this.request("GET",kr(ae.object(e),n)),list:e=>this.request("GET",kr(ae.objects(),e)),search:e=>this.request("POST",ae.objectsSearch(),e),watch:(e,n={})=>this.request("POST",ae.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",kr(ae.objectWatch(e),n)),edges:(e,n)=>this.request("GET",kr(ae.objectEdges(e),n))};docs={write:e=>this.request("POST",ae.docs(),e),edit:(e,n)=>this.request("PATCH",ae.doc(e),n),move:(e,n)=>this.request("POST",ae.docMove(e),n),delete:e=>this.request("DELETE",ae.doc(e)),history:(e,n)=>this.request("GET",kr(ae.docHistory(e),n)),lint:(e={})=>this.request("POST",ae.docsLint(),e)};documents={browserAccess:()=>this.request("GET",ae.documentsBrowserAccess()),reconcilePackages:e=>this.request("POST",ae.documentsReconcilePackages(),e)};plugins={appToken:e=>this.request("GET",ae.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",ae.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",ae.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",ae.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",ae.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",ae.profile(e),n??{})}createProfile(e){return this.request("POST",ae.profiles(),e)}listProfiles(){return this.request("GET",ae.profiles())}updateProfile(e,n){return this.request("PATCH",ae.profile(e),n)}listAppEnv(){return this.request("GET",ae.appEnv())}setAppEnv(e,n){return this.request("PUT",ae.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",ae.appEnvVar(e))}listProfileEnv(e){return this.request("GET",ae.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",ae.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",ae.profileEnvVar(e,n))}getProfileEnvironment(e){return this.request("GET",ae.profileEnvironment(e))}setProfileEnvironment(e,n){return this.request("PUT",ae.profileEnvironment(e),n)}getProfile(e){return this.request("GET",ae.profile(e))}pauseProfile(e){return this.request("POST",ae.profilePause(e),{})}resumeProfile(e){return this.request("POST",ae.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",ae.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",ae.profile(e),n)}getSettings(){return this.request("GET",ae.settings())}putSettings(e){return this.request("PUT",ae.settings(),e)}listModelAuth(){return this.request("GET",ae.modelAuths())}getModelAuthReadiness(e){return this.request("GET",kr(ae.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",ae.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",ae.modelAuth(e))}patchModelAuthAccount(e,n,r){return this.request("PATCH",ae.modelAuthAccount(e,n),r)}removeModelAuthAccount(e,n){return this.request("DELETE",ae.modelAuthAccount(e,n))}startModelAuth(e){return this.request("POST",ae.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",ae.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",ae.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",kr(ae.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",ae.humanReviews(),e)}listReviews(e){return this.request("GET",kr(ae.humanReviews(),e))}getReview(e){return this.request("GET",ae.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",ae.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",ae.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",ae.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",ae.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",kr(ae.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",kr(ae.humanReviewCommentEvents(this.reviewPath(e)),n))}getReviewComment(e){return this.request("GET",ae.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",ae.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",ae.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",ae.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",ae.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",ae.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",ae.humanInbox())}getHumanInboxPage(e){return this.request("GET",ae.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(ae.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",ae.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",ae.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",ae.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",ae.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",ae.humanRequests(),e)}listPageComponents(){return this.request("GET",ae.humanComponents())}getHumanRequest(e){return this.request("GET",ae.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",ae.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",ae.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",ae.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",ae.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",ae.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",ae.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",ae.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",ae.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",ae.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",kr(ae.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",ae.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",ae.canvasSnapshot())}analytics(e){return this.request("GET",kr(ae.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",ae.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",kr(ae.canvasLiveRoots(),e))}canvasView(e){return this.request("GET",ae.canvasView(e))}canvasRoster(){return this.request("GET",ae.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",ae.canvasBrowse());return e.ok||await jI(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(e){return this.request("GET",e===void 0?ae.canvasGraph():`${ae.canvasGraph()}?root=${encodeURIComponent(e)}`)}prune(e){return this.request("POST",ae.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 jI(s,o?.deadlineAt)}catch(o){throw x_n(e,Aw(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw Aw(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()+A_n);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&&!kZe(p,o.signal)?tB(o.deadlineAt):Aw(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&&!kZe(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await R6(_Ze(u+1),o);continue}else throw Aw(d,o.signal)}}if(y_n(e)&&a>0&&l.status===503&&await E_n(l,o.deadlineAt)){let d=Math.max(250,(TZe(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await ege(l,o.deadlineAt),await R6(d,{signal:o.signal});continue}if(s&&u<a&&w_n(l.status)){await ege(l,o.deadlineAt),await R6(_Ze(u+1),o,TZe(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>RF))throw new RangeError(`budgetMs must be a positive finite number of at most ${RF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>RF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${RF} 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 TF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(TF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await jI(await this.transport(e,n,r,o))}catch(s){throw Aw(s,o.signal)}}nodePath(e){if(!T6(e))throw new sn(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!vZe(e))throw new sn(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!SZe(e))throw new sn(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!T6(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(!T6(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(TF(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?TF(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 b_n(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>(IZe(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=tge(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=tge(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw Aw(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 Aw(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw TF(n);let i,o;try{await B6({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",ae.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await ege(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=C_n(this.coldStartDiagnostic);if(o!==void 0){let s=Aw(i);throw new sn(s.status,s.code,`${s.message}
|
|
90
90
|
${o}`)}}throw i}}};A_n=6e4});function DZe(){return I_n??void 0}var I_n,MZe=A(()=>{"use strict";I_n=null});import{request as v_n}from"node:http";import{homedir as S_n}from"node:os";import{join as nge}from"node:path";function R_n(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:nge(S_n(),__n);return nge(process.platform==="linux"?"/run/crtr":nge(n,"runtime"),k_n)}function B_n(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=v_n({socketPath:t,path:i.pathname+i.search,method:o,headers:s,agent:!1},h=>{let m=new ReadableStream({start(y){h.on("data",x=>y.enqueue(new Uint8Array(x))),h.on("end",()=>y.close()),h.on("error",x=>y.error(x))},cancel(){h.destroy()}}),f=new Headers;for(let[y,x]of Object.entries(h.headers))if(x!==void 0)for(let b of Array.isArray(x)?x:[x])f.append(y,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[T_n]=!0,e}function yw(t={}){let{socketPath:e,...n}=t;return new Rg({baseUrl:"http://localhost",fetch:B_n(e??R_n()),autostart:!0,...n})}var __n,k_n,T_n,M6=A(()=>{"use strict";D6();__n=".crouter",k_n="api.sock",T_n=Symbol.for("@north-light/api/local-socket-fetch")});import{readFileSync as D_n}from"node:fs";import{dirname as M_n,join as PZe}from"node:path";import{fileURLToPath as P_n}from"node:url";function N6(){if(P6!==null)return P6;let t=PZe(M_n(P_n(import.meta.url)),"..","..");return P6=JSON.parse(D_n(PZe(t,"package.json"),"utf8")).version,P6}var P6,O6=A(()=>{"use strict";P6=null});var NZe=A(()=>{"use strict";DF();gw()});var ige=L(OZe=>{"use strict";OZe.parse=function(t,e){return new rge(t,e).parse()};var rge=class t{constructor(e,n){this.source=e,this.transform=n||N_n,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 N_n(t){return t}});var oge=L((gxi,LZe)=>{var O_n=ige();LZe.exports={create:function(t,e){return{parse:function(){return O_n.parse(t,e)}}}}});var UZe=L((Axi,FZe)=>{"use strict";var L_n=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,Q_n=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,F_n=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,U_n=/^-?infinity$/;FZe.exports=function(e){if(U_n.test(e))return Number(e.replace("i","I"));var n=L_n.exec(e);if(!n)return $_n(e)||null;var r=!!n[8],i=parseInt(n[1],10);r&&(i=QZe(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=W_n(e);return p!=null?(d=new Date(Date.UTC(i,o,s,a,c,u,l)),sge(i)&&d.setUTCFullYear(i),p!==0&&d.setTime(d.getTime()-p)):(d=new Date(i,o,s,a,c,u,l),sge(i)&&d.setFullYear(i)),d};function $_n(t){var e=Q_n.exec(t);if(e){var n=parseInt(e[1],10),r=!!e[4];r&&(n=QZe(n));var i=parseInt(e[2],10)-1,o=e[3],s=new Date(n,i,o);return sge(n)&&s.setFullYear(n),s}}function W_n(t){if(t.endsWith("+00"))return 0;var e=F_n.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 QZe(t){return-(t-1)}function sge(t){return t>=0&&t<100}});var WZe=L((yxi,$Ze)=>{$Ze.exports=G_n;var H_n=Object.prototype.hasOwnProperty;function G_n(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)H_n.call(n,r)&&(t[r]=n[r])}return t}});var qZe=L((Exi,GZe)=>{"use strict";var q_n=WZe();GZe.exports=nB;function nB(t){if(!(this instanceof nB))return new nB(t);q_n(this,rkn(t))}var j_n=["seconds","minutes","hours","days","months","years"];nB.prototype.toPostgres=function(){var t=j_n.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 z_n={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},V_n=["years","months","days"],K_n=["hours","minutes","seconds"];nB.prototype.toISOString=nB.prototype.toISO=function(){var t=V_n.map(n,this).join(""),e=K_n.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+z_n[r]}};var age="([+-]?\\d+)",Y_n=age+"\\s+years?",J_n=age+"\\s+mons?",X_n=age+"\\s+days?",Z_n="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",ekn=new RegExp([Y_n,J_n,X_n,Z_n].map(function(t){return"("+t+")?"}).join("\\s*")),HZe={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},tkn=["hours","minutes","seconds","milliseconds"];function nkn(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}function rkn(t){if(!t)return{};var e=ekn.exec(t),n=e[8]==="-";return Object.keys(HZe).reduce(function(r,i){var o=HZe[i],s=e[o];return!s||(s=i==="milliseconds"?nkn(s):parseInt(s,10),!s)||(n&&~tkn.indexOf(i)&&(s*=-1),r[i]=s),r},{})}});var VZe=L((wxi,zZe)=>{"use strict";var jZe=Buffer.from||Buffer;zZe.exports=function(e){if(/^\\x/.test(e))return jZe(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 jZe(n,"binary")}});var tet=L((xxi,eet)=>{var MF=ige(),PF=oge(),L6=UZe(),YZe=qZe(),JZe=VZe();function Q6(t){return function(n){return n===null?n:t(n)}}function XZe(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}function ikn(t){return t?MF.parse(t,XZe):null}function okn(t){return parseInt(t,10)}function cge(t){return t?MF.parse(t,Q6(okn)):null}function skn(t){return t?MF.parse(t,Q6(function(e){return ZZe(e).trim()})):null}var akn=function(t){if(!t)return null;var e=PF.create(t,function(n){return n!==null&&(n=pge(n)),n});return e.parse()},uge=function(t){if(!t)return null;var e=PF.create(t,function(n){return n!==null&&(n=parseFloat(n)),n});return e.parse()},hh=function(t){if(!t)return null;var e=PF.create(t);return e.parse()},lge=function(t){if(!t)return null;var e=PF.create(t,function(n){return n!==null&&(n=L6(n)),n});return e.parse()},ckn=function(t){if(!t)return null;var e=PF.create(t,function(n){return n!==null&&(n=YZe(n)),n});return e.parse()},ukn=function(t){return t?MF.parse(t,Q6(JZe)):null},dge=function(t){return parseInt(t,10)},ZZe=function(t){var e=String(t);return/^\d+$/.test(e)?e:t},KZe=function(t){return t?MF.parse(t,Q6(JSON.parse)):null},pge=function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},lkn=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=pge(e);return o.radius=parseFloat(n),o},dkn=function(t){t(20,ZZe),t(21,dge),t(23,dge),t(26,dge),t(700,parseFloat),t(701,parseFloat),t(16,XZe),t(1082,L6),t(1114,L6),t(1184,L6),t(600,pge),t(651,hh),t(718,lkn),t(1e3,ikn),t(1001,ukn),t(1005,cge),t(1007,cge),t(1028,cge),t(1016,skn),t(1017,akn),t(1021,uge),t(1022,uge),t(1231,uge),t(1014,hh),t(1015,hh),t(1008,hh),t(1009,hh),t(1040,hh),t(1041,hh),t(1115,lge),t(1182,lge),t(1185,lge),t(1186,YZe),t(1187,ckn),t(17,JZe),t(114,JSON.parse.bind(JSON)),t(3802,JSON.parse.bind(JSON)),t(199,KZe),t(3807,KZe),t(3907,hh),t(2951,hh),t(791,hh),t(1183,hh),t(1270,hh)};eet.exports={init:dkn}});var ret=L((bxi,net)=>{"use strict";var Gl=1e6;function pkn(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%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*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%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*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%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*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%Gl,s=4294967296*o+n,a=""+s%Gl,r+a+i}net.exports=pkn});var cet=L((Cxi,aet)=>{var hkn=ret(),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},set=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},mkn=function(t){return ss(t,1)==1?-1*(ss(t,15,1,!0)+1):ss(t,15,1)},iet=function(t){return ss(t,1)==1?-1*(ss(t,31,1,!0)+1):ss(t,31,1)},fkn=function(t){return set(t,23,8)},gkn=function(t){return set(t,52,11)},Akn=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},oet=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},NF=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)},ykn=function(t){return t.toString("utf8")},Ekn=function(t){return t===null?null:ss(t,8)>0},wkn=function(t){t(20,hkn),t(21,mkn),t(23,iet),t(26,iet),t(1700,Akn),t(700,fkn),t(701,gkn),t(16,Ekn),t(1114,oet.bind(null,!1)),t(1184,oet.bind(null,!0)),t(1e3,NF),t(1007,NF),t(1016,NF),t(1008,NF),t(1009,NF),t(25,ykn)};aet.exports={init:wkn}});var det=L((Ixi,uet)=>{uet.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=L(LF=>{var xkn=tet(),bkn=cet(),Ckn=oge(),Ikn=det();LF.getTypeParser=vkn;LF.setTypeParser=Skn;LF.arrayParser=Ckn;LF.builtins=Ikn;var OF={text:{},binary:{}};function pet(t){return String(t)}function vkn(t,e){return e=e||"text",OF[e]&&OF[e][t]||pet}function Skn(t,e,n){typeof e=="function"&&(n=e,e="text"),OF[e][t]=n}xkn.init(function(t,e){OF.text[t]=e});bkn.init(function(t,e){OF.binary[t]=e})});var FF=L((Sxi,hge)=>{"use strict";var het;try{het=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}hge.exports={host:"localhost",user:het,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(),_kn=rB.getTypeParser(20,"text"),kkn=rB.getTypeParser(1016,"text");hge.exports.__defineSetter__("parseInt8",function(t){rB.setTypeParser(20,"text",t?rB.getTypeParser(23,"text"):_kn),rB.setTypeParser(1016,"text",t?rB.getTypeParser(1007,"text"):kkn)})});var zI=L((_xi,fet)=>{"use strict";var Tkn=FF(),Rkn=Y("util"),{isDate:Bkn}=Y("util/types"),Dkn=Rkn.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 Mkn(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function met(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+=met(r):ArrayBuffer.isView(r)?(r instanceof Buffer||(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),e+="\\\\x"+r.toString("hex")):e+=Mkn(F6(r))}return e+="}",e}var F6=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):Bkn(t)?(isNaN(t.getTime())&&Dkn(),Tkn.parseInputDatesAsUTC?Okn(t):Nkn(t)):Array.isArray(t)?met(t):Pkn(t,e):t.toString()};function Pkn(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),F6(t.toPostgres(F6),e)}return JSON.stringify(t)}function Nkn(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 Okn(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 Lkn(t,e,n){return t=typeof t=="string"?{text:t}:Qkn(t),e&&(typeof e=="function"?t.callback=e:t.values=e),n&&(t.callback=n),t}function Qkn(t){return t==null?t:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),Object.getOwnPropertyDescriptors(t))}var Fkn=function(t){return'"'+t.replace(/"/g,'""')+'"'},Ukn=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};fet.exports={prepareValue:function(e){return F6(e)},normalizeQueryConfig:Lkn,escapeIdentifier:Fkn,escapeLiteral:Ukn}});var gge=L((kxi,yet)=>{var get=Y("crypto");yet.exports={postgresMd5PasswordHash:Wkn,randomBytes:$kn,deriveKey:jkn,sha256:Hkn,hashByName:Gkn,hmacSha256:qkn,md5:mge};var Aet=get.webcrypto||globalThis.crypto,VI=Aet.subtle,fge=new TextEncoder;function $kn(t){return Aet.getRandomValues(Buffer.alloc(t))}async function mge(t){try{return get.createHash("md5").update(t,"utf-8").digest("hex")}catch{let n=typeof t=="string"?fge.encode(t):t,r=await VI.digest("MD5",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}}async function Wkn(t,e,n){let r=await mge(e+t);return"md5"+await mge(Buffer.concat([Buffer.from(r),n]))}async function Hkn(t){return await VI.digest("SHA-256",t)}async function Gkn(t,e){return await VI.digest(t,e)}async function qkn(t,e){let n=await VI.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await VI.sign("HMAC",n,fge.encode(e))}async function jkn(t,e,n){let r=await VI.importKey("raw",fge.encode(t),"PBKDF2",!1,["deriveBits"]),i={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:n};return await VI.deriveBits(i,r,256,["deriveBits"])}});var xet=L((Txi,wet)=>{function KI(t,e){return new Error("SASL channel binding: "+t+" when parsing public certificate "+e.toString("base64"))}function Age(t,e){let n=t[e++];if(n<128)return{length:n,index:e};let r=n&127;if(r>4)throw KI("bad length",t);n=0;for(let i=0;i<r;i++)n=n<<8|t[e++];return{length:n,index:e}}function Eet(t,e){if(t[e++]!==6)throw KI("non-OID data",t);let{length:n,index:r}=Age(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 UF(t,e){if(t[e++]!==48)throw KI("non-sequence data",t);return Age(t,e)}function zkn(t,e){e===void 0&&(e=0),e=UF(t,e).index;let{length:n,index:r}=UF(t,e);e=r+n,e=UF(t,e).index;let{oid:i,index:o}=Eet(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=UF(t,e).index,t[e++]!==160)throw KI("non-tag data",t);e=Age(t,e).index,e=UF(t,e).index;let{oid:s}=Eet(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 KI("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 KI("Ed448 certificate channel binding is not currently supported by Postgres")}throw KI("unknown OID "+i,t)}wet.exports={signatureAlgorithmHashFromCertificate:zkn}});var vet=L((Rxi,Iet)=>{"use strict";var Ew=gge(),{signatureAlgorithmHashFromCertificate:Vkn}=xet();function Kkn(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 yge=1e5;function Ykn(t,e,n=yge){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=Ew.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 Jkn(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=eTn(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:yge;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=Vkn(b);(v==="MD5"||v==="SHA-1")&&(v="SHA-256");let S=await Ew.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 Ew.deriveKey(Kkn(e),d,i.iteration),h=await Ew.hmacSha256(p,"Client Key"),m=await Ew.sha256(h),f=await Ew.hmacSha256(m,l),g=nTn(Buffer.from(h),Buffer.from(f)).toString("base64"),y=await Ew.hmacSha256(p,"Server Key"),x=await Ew.hmacSha256(y,l);t.message="SASLResponse",t.serverSignature=Buffer.from(x).toString("base64"),t.response=u+",p="+g}function Xkn(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}=tTn(e);if(n!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function Zkn(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 bet(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}function Cet(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 eTn(t){let e=Cet(t),n=e.get("r");if(n){if(!Zkn(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(!bet(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 tTn(t){let e=Cet(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(!bet(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 nTn(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]))}Iet.exports={startSession:Ykn,continueSession:Jkn,finalizeSession:Xkn,DEFAULT_MAX_SCRAM_ITERATIONS:yge}});var $6=L((Bxi,_et)=>{"use strict";var rTn=QF();function U6(t){this._types=t||rTn,this.text={},this.binary={}}U6.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};U6.prototype.setTypeParser=function(t,e,n){typeof e=="function"&&(n=e,e="text"),this.getOverrides(e)[t]=n};U6.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};_et.exports=U6});var Ret=L((Dxi,Tet)=>{"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?Y("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"&&Ege(n.sslmode);break}case"no-verify":{n.ssl.rejectUnauthorized=!1;break}}return n}function iTn(t){return Object.entries(t).reduce((n,[r,i])=>(i!=null&&(n[r]=i),n),Object.create(null))}function ket(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]=iTn(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 oTn(t){return ket(iB(t))}function Ege(t){!Ege.warned&&typeof process<"u"&&process.emitWarning&&(Ege.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
|
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Transport } from '../broker-client/index.js';
|
|
1
2
|
import type { MessageOrigin } from './stamp/protocol.js';
|
|
2
3
|
/** Which engine call the broker routed a live deliver to (its ack `detail`):
|
|
3
4
|
* idle → `prompt`, turn in flight → `steer`. */
|
|
@@ -19,4 +20,4 @@ export declare function deliverLive(nodeId: string, text: string, opts?: {
|
|
|
19
20
|
* once the broker has PROCESSED the abort — which, on the single frame loop,
|
|
20
21
|
* also implies every earlier-accepted deliver was already routed (so a
|
|
21
22
|
* just-delivered send cannot start its turn after this resolves un-aborted). */
|
|
22
|
-
export declare function interruptLive(nodeId: string): Promise<LiveInterruptOutcome>;
|
|
23
|
+
export declare function interruptLive(nodeId: string, transport?: Transport): Promise<LiveInterruptOutcome>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var r=(i,t)=>a(i,"name",{value:t,configurable:!0});import{oneShotControllerRequest as u}from"./broker-request.js";function l(i,t,e={}){const o=e.cards??[];return u({nodeId:i,what:"the interactive delivery",ackFor:"deliver",correlated:!0,frame:r(n=>({type:"deliver",id:n,text:t,...o.length>0?{cards:[...o]}:{},...e.origin!==void 0?{origin:e.origin}:{}}),"frame"),result:r(n=>n==="steer"?"steer":"prompt","result")})}r(l,"deliverLive");function f(i,t){return u({nodeId:i,...t===void 0?{}:{transport:t},what:"the interrupt",ackFor:"abort",correlated:!0,frame:r(e=>({type:"abort",id:e}),"frame"),result:r(e=>e==="turn"||e==="bash"?e:"idle","result")})}r(f,"interruptLive");export{l as deliverLive,f as interruptLive};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var p=Object.defineProperty;var
|
|
2
|
-
WHERE person = ? AND enabled = 1 AND owner_key = ? ORDER BY name`).all(
|
|
1
|
+
var p=Object.defineProperty;var s=(e,i)=>p(e,"name",{value:i,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{getNode as _}from"../../../core/canvas/canvas.js";import{openDb as d}from"../../../core/canvas/db.js";import{grantedProviderIds as m,isProviderBundleRow as w}from"../../../core/grants/mirror.js";import{profileMetadataEnv as f}from"../../../core/runtime/spawn-env.js";import{localEnvironmentSecrets as h}from"../../../core/secrets/environment-owner.js";import{environmentOfNode as g,recipeOf as x}from"../environment-of.js";import{mintInstallationToken as E}from"./git-credential.js";async function b(e,i){const o=await d(),a=new Map((await o.prepare(`SELECT owner_key, name, version, source_marketplace, source_path FROM scope_plugins
|
|
2
|
+
WHERE person = ? AND enabled = 1 AND owner_key = ? ORDER BY name`).all(e,i)).map(t=>[t.name,t])),n=[],c=await m(e);for(const t of a.values()){if(w(t,c))continue;if(t.source_path!==null){n.push({name:t.name,source:{path:t.source_path},version:t.version});continue}if(t.source_marketplace===null)throw new r(500,"plugin_source_missing",`plugin ${t.name} names neither a marketplace nor a path`);const u=await o.prepare("SELECT url, ref FROM scope_marketplaces WHERE person = ? AND owner_key = ? AND name = ?").get(e,t.owner_key,t.source_marketplace);n.push({name:t.name,source:{marketplace:{url:u?.url??null,ref:u?.ref??null}},version:t.version})}return n}s(b,"plugins");async function A(e){const{principal:i}=e;if(i.class!=="broker")throw new r(403,"broker_only","this route is called with a node token");const o=e.params.execution_id??"",n=await(await d()).prepare("SELECT node_id, state FROM executions WHERE execution_id = ?").get(o);if(n===void 0||n.node_id!==i.node)throw new r(403,"not_your_execution",`execution ${o} is not an execution of this node`);if(n.state!=="launching"&&n.state!=="running")throw new r(403,"execution_ended",`execution ${o} is ${n.state}`);return i.node}s(A,"ownedExecution");async function k(e){const i=await d(),o=await _(e.nodeId);if(o===null)throw new r(404,"node_not_found",`no node ${e.nodeId}`);const a=await i.prepare("SELECT plugins_revision FROM person_settings WHERE person = ?").get(e.sub),n=await g(o.profile_id??null),c=await x(n),t=c?.repositories.map(l=>l.github_full_name)??[],u=t.length===0?null:(await E(e.sub,t)).author;return{launch:JSON.parse(e.launchJson),node:{id:o.node_id,app:e.app,cwd:o.cwd,profile:o.profile_id??null,isolated:o.isolated===!0,environment_id:n},recipe:c,git_identity:u,plugins_revision:a===void 0?0:Number(a.plugins_revision),plugins:await b(e.sub,e.app),...e.runner==="machine"?{machine_env:{...f(o.profile_id??null),...await h(o.profile_id??null,e.app)}}:{}}}s(k,"buildStartBundle");async function v(e){const{principal:i}=e;if(i.class!=="broker")throw new r(403,"broker_only","the start bundle is read with a node token");const o=e.params.execution_id??"",n=await(await d()).prepare("SELECT node_id, state, launch_json, runner FROM executions WHERE execution_id = ?").get(o);if(n===void 0||n.node_id!==i.node)throw new r(403,"not_your_execution",`execution ${o} is not an execution of this node`);if(n.state!=="launching"&&n.state!=="running")throw new r(403,"execution_ended",`execution ${o} is ${n.state}`);if(n.launch_json===null)throw new r(409,"launch_missing",`execution ${o} carries no launch recipe`);return{status:200,body:await k({nodeId:i.node,app:i.app,sub:i.sub,launchJson:n.launch_json,runner:n.runner})}}s(v,"handleStart");const C=[{method:"GET",pattern:"/v1/executions/:execution_id/start",handler:v}];export{k as buildStartBundle,C as executionStartRoutes,b as plugins};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var C=Object.defineProperty;var o=(r,e)=>C(r,"name",{value:e,configurable:!0});import{randomUUID as k}from"node:crypto";import{ApiError as E}from"../../../api/errors.js";import{BrokerClient as B}from"../../../core/broker-client/client.js";import{getNode as p}from"../../../core/canvas/canvas.js";import{emitEvent as w}from"../../../core/events/emit.js";import{isPidAlive as L}from"../../../core/canvas/pid.js";import{BROKER_VIEW_SOCKET_WAIT_MS as D}from"../../../core/runtime/view-socket.js";import{openDb as M}from"../../../core/canvas/db.js";import{brokerSignalBus as $}from"../../broker-signals/bus.js";import{toNodeOutcomeDTO as P}from"../map.js";import{reportsForNode as x}from"./reports.js";import{runAsPerson as j}from"../../../core/canvas/person.js";const G=15e3,V=6e4,T=250,z=512,A=256*1024,H=1e3,J=32*1024*1024;class W{static{o(this,"NodeEventRing")}events=[];bytes=0;nextSequence=1;earliestAvailable=1;append(e){const t={...e,sequence_number:this.nextSequence++},s=Buffer.byteLength(JSON.stringify(t),"utf8");if(s>A)return this.events=[],this.bytes=0,this.earliestAvailable=this.nextSequence,t;for(this.events.push(t),this.bytes+=s;this.events.length>z||this.bytes>A;){const n=this.events.shift();if(n===void 0)break;this.bytes-=Buffer.byteLength(JSON.stringify(n),"utf8"),this.earliestAvailable=n.sequence_number+1}return t}replay(e){if(e===void 0)return{gap:null,events:this.events};const t=e<this.earliestAvailable-1||e>=this.nextSequence?R(this.earliestAvailable):null;return{gap:t,events:t===null?this.events.filter(s=>s.sequence_number>e):this.events}}get empty(){return this.events.length===0}}function R(r){return{type:"error",error:{code:"stream_gap",message:"the requested event cursor is older than this daemon can resume",details:{earliest_sequence:r}}}}o(R,"streamGap");function F(r){return r===null?"arguments: null":Array.isArray(r)?`arguments: array (${r.length} items)`:typeof r=="object"?`arguments: object (${Object.keys(r).length} fields)`:`arguments: ${typeof r}`}o(F,"toolSummary");function m(r){if(typeof r!="object"||r===null)return"";const e=r.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(""):""}o(m,"assistantText");class N{static{o(this,"NodeEventTranslationState")}toolSummaries=new Map;emittedAssistantText="";resetAssistantText(){this.emittedAssistantText=""}emitAssistantTextDelta(e){const t=m(e),s=t.startsWith(this.emittedAssistantText)?t.slice(this.emittedAssistantText.length):t;return this.emittedAssistantText=t,s}seedAssistantText(e){const t=m(e);return this.emittedAssistantText=t,t}}function K(r,e,t=new N){switch(e.type){case"message_start":return e.message.role==="assistant"&&t.resetAssistantText(),[];case"message_update":{if(e.message.role!=="assistant")return[];const s=t.emitAssistantTextDelta(e.message);return s===""?[]:[{type:"node.output_text.delta",node_id:r,delta:s}]}case"message_end":{if(e.message.role!=="assistant")return[];const s=m(e.message);return t.resetAssistantText(),[{type:"node.output_text.done",node_id:r,text:s}]}case"tool_execution_start":{const s=F(e.args);return t.toolSummaries.set(e.toolCallId,s),[{type:"node.tool_call.started",node_id:r,tool_call_id:e.toolCallId,tool:e.toolName,summary:s}]}case"tool_execution_end":{const s=t.toolSummaries.get(e.toolCallId)??"[arguments unavailable]";return t.toolSummaries.delete(e.toolCallId),[{type:"node.tool_call.completed",node_id:r,tool_call_id:e.toolCallId,tool:e.toolName,status:e.isError?"error":"ok",summary:s}]}case"turn_start":return[{type:"node.turn.started",node_id:r}];case"turn_end":return[{type:"node.turn.completed",node_id:r}];default:return[]}}o(K,"translateBrokerFrame");class U{static{o(this,"NodeEventHub")}nodeId;remove;ring=new W;subscribers=new Set;observer;observerErrorAt;poll;reconnect;idleClose;status;settledRevision;settledOutcome;settledSequence;snapshotSeeded=!1;reportsSeeded=!1;publishedReports=new Set;translationState=new N;fresh=!0;constructor(e,t){this.nodeId=e,this.remove=t}async subscribe(e,t){const s=this.fresh&&e!==void 0;this.fresh=!1,await this.start();const n=this.settledOutcome!==void 0,a=s?{gap:R(1),events:this.ring.replay(void 0).events}:this.ring.replay(e);n||(this.subscribers.add(t),this.status!=="dormant"&&await this.openObserver());let h=!1;return queueMicrotask(()=>{if(!h){a.gap!==null&&t(a.gap);for(const u of a.events)t(u)}}),n&&this.scheduleIdleClose(),{unsubscribe:o(()=>{h=!0,n||this.unsubscribe(t)},"unsubscribe"),terminal:n}}report(e){this.settledRevision!==void 0||this.publishedReports.has(e.id)||(this.publishedReports.add(e.id),this.publish({type:"node.report.pushed",node_id:this.nodeId,report:e}))}async start(){this.idleClose!==void 0&&(clearTimeout(this.idleClose),this.idleClose=void 0),this.poll===void 0&&(await this.check(),this.settledRevision===void 0&&(await this.seedReports(),this.poll=setInterval(()=>this.checkDetached(),T)))}async seedReports(){if(!this.reportsSeeded){this.reportsSeeded=!0;for(const e of(await this.storedReports()).reverse())this.report(e)}}async storedReports(){const e=(await p(this.nodeId))?.sub;return e?await j(e,()=>x(this.nodeId)):await x(this.nodeId)}async refreshReports(){if(!(!this.reportsSeeded||this.settledRevision!==void 0))for(const e of(await this.storedReports()).reverse())this.report(e)}async check(){const e=await p(this.nodeId);if(e===null){this.fail("stream_error",`node ${this.nodeId} no longer exists`);return}const t=await P(e);if(t!==null){this.settledRevision!==t.revision&&(this.settledRevision=t.revision,this.settledOutcome=t,this.settledSequence=this.publish({type:"node.settled",node_id:this.nodeId,outcome:t}).sequence_number,this.stopObserver(),this.stopPoll());return}const s=e.pi_pid===null?"dormant":e.status;if(s==="dormant"){this.observerErrorAt=void 0,this.status!=="dormant"&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s}));return}this.status===void 0?this.status=s:this.status!=="dormant"&&this.status!==s&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s})),await this.openObserver()}async openObserver(){if(this.observer!==void 0||this.subscribers.size===0)return;const e=new B(this.nodeId);this.observer=e,e.on("connect",()=>{(async()=>{this.observerErrorAt=void 0;const t=await p(this.nodeId);this.status==="dormant"&&t!==null&&t.pi_pid!==null&&(this.status=t.status,this.publish({type:"node.status.changed",node_id:this.nodeId,status:t.status})),e.send({type:"hello",role:"observer",client_id:k(),attends:!1})})().catch(t=>this.fail("stream_error",t instanceof Error?t.message:String(t)))}),e.on("frame",t=>{try{t.type==="welcome"&&this.seedSnapshot(t.snapshot);for(const s of K(this.nodeId,t,this.translationState))this.publish(s)}catch(s){this.fail("stream_error",s instanceof Error?s.message:String(s))}}),e.on("error",()=>{(async()=>{const t=await p(this.nodeId),s=Date.now();if(t!==null&&t.pi_pid!==null&&L(t.pi_pid)){if(this.observerErrorAt??=s,s-this.observerErrorAt<D)return;this.fail("stream_error","observer connection failed");return}this.observerErrorAt=void 0})().catch(t=>this.fail("stream_error",t instanceof Error?t.message:String(t)))}),e.on("close",()=>{this.observer===e&&(this.observer=void 0,!(this.subscribers.size===0||this.settledRevision!==void 0)&&(this.status!=="dormant"&&(this.publish({type:"node.status.changed",node_id:this.nodeId,status:"dormant"}),this.status="dormant"),this.scheduleReconnect()))}),e.connect()}seedSnapshot(e){if(this.snapshotSeeded)return;this.snapshotSeeded=!0;const t=e.messages.filter(n=>n.role==="assistant"),s=e.state.isStreaming?t.pop():void 0;for(const n of t)this.publish({type:"node.output_text.done",node_id:this.nodeId,text:m(n)});s!==void 0&&this.publish({type:"node.output_text.delta",node_id:this.nodeId,delta:this.translationState.seedAssistantText(s)})}scheduleReconnect(){this.reconnect===void 0&&(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.checkDetached()},T))}checkDetached(){this.check().catch(e=>w({level:"error",event:"api.node_events.check_failed",node_id:this.nodeId,error:e}))}publish(e){const t=this.ring.append(e);for(const s of[...this.subscribers])s(t);return t}fail(e,t){const s={type:"error",error:{code:e,message:t}};for(const n of[...this.subscribers])n(s);this.stopObserver(),this.stopPoll()}unsubscribe(e){this.subscribers.delete(e),this.subscribers.size===0&&this.scheduleIdleClose()}scheduleIdleClose(){this.idleClose===void 0&&(this.idleClose=setTimeout(()=>{this.stopObserver(),this.stopPoll(),this.remove()},V))}stopObserver(){this.reconnect!==void 0&&(clearTimeout(this.reconnect),this.reconnect=void 0);const e=this.observer;this.observer=void 0,e?.close()}stopPoll(){this.poll!==void 0&&(clearInterval(this.poll),this.poll=void 0)}}class Y{static{o(this,"NodeEventStreams")}hubs=new Map;unsubscribeBus;refresh(e){this.hubs.get(e)?.refreshReports().catch(t=>w({level:"error",event:"api.node_events.report_refresh_failed",node_id:e,error:t}))}listen(){this.unsubscribeBus??=$.subscribe(e=>this.refresh(e),{kinds:["report"],onListenStart:o(()=>{for(const e of[...this.hubs.keys()])this.refresh(e)},"onListenStart")})}remove(e){if(this.hubs.delete(e),this.hubs.size===0){const t=this.unsubscribeBus;this.unsubscribeBus=void 0,t?.then(s=>s())}}async subscribe(e,t,s){let n=this.hubs.get(e);return n===void 0&&(n=new U(e,()=>this.remove(e)),this.hubs.set(e,n),this.listen()),await n.subscribe(t,s)}report(e,t){this.hubs.get(e)?.report(t),M().then(s=>s.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`report:${e}`)).catch(s=>w({level:"error",event:"api.node_events.report_signal_failed",node_id:e,error:s}))}}const Q=new Y;function X(r){const e=r.get("after");if(e===null||e==="")return{};if(!/^(?:0|[1-9]\d*)$/.test(e))throw new E(400,"invalid_request","`after` must be a non-negative integer");const t=Number(e);if(!Number.isSafeInteger(t))throw new E(400,"invalid_request","`after` must be a safe integer");return{after:t}}o(X,"parseQuery");function I(r){const{type:e,...t}=r;return`event: ${e}
|
|
1
|
+
var C=Object.defineProperty;var o=(n,e)=>C(n,"name",{value:e,configurable:!0});import{randomUUID as k}from"node:crypto";import{ApiError as E}from"../../../api/errors.js";import{BrokerClient as B}from"../../../core/broker-client/client.js";import{viewTransport as L}from"../../runs/observer.js";import{getNode as p}from"../../../core/canvas/canvas.js";import{emitEvent as w}from"../../../core/events/emit.js";import{isPidAlive as D}from"../../../core/canvas/pid.js";import{BROKER_VIEW_SOCKET_WAIT_MS as M}from"../../../core/runtime/view-socket.js";import{openDb as $}from"../../../core/canvas/db.js";import{brokerSignalBus as P}from"../../broker-signals/bus.js";import{toNodeOutcomeDTO as j}from"../map.js";import{reportsForNode as x}from"./reports.js";import{runAsPerson as G}from"../../../core/canvas/person.js";const z=15e3,V=6e4,T=250,H=512,A=256*1024,J=1e3,W=32*1024*1024;class F{static{o(this,"NodeEventRing")}events=[];bytes=0;nextSequence=1;earliestAvailable=1;append(e){const t={...e,sequence_number:this.nextSequence++},s=Buffer.byteLength(JSON.stringify(t),"utf8");if(s>A)return this.events=[],this.bytes=0,this.earliestAvailable=this.nextSequence,t;for(this.events.push(t),this.bytes+=s;this.events.length>H||this.bytes>A;){const r=this.events.shift();if(r===void 0)break;this.bytes-=Buffer.byteLength(JSON.stringify(r),"utf8"),this.earliestAvailable=r.sequence_number+1}return t}replay(e){if(e===void 0)return{gap:null,events:this.events};const t=e<this.earliestAvailable-1||e>=this.nextSequence?R(this.earliestAvailable):null;return{gap:t,events:t===null?this.events.filter(s=>s.sequence_number>e):this.events}}get empty(){return this.events.length===0}}function R(n){return{type:"error",error:{code:"stream_gap",message:"the requested event cursor is older than this daemon can resume",details:{earliest_sequence:n}}}}o(R,"streamGap");function K(n){return n===null?"arguments: null":Array.isArray(n)?`arguments: array (${n.length} items)`:typeof n=="object"?`arguments: object (${Object.keys(n).length} fields)`:`arguments: ${typeof n}`}o(K,"toolSummary");function m(n){if(typeof n!="object"||n===null)return"";const e=n.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(""):""}o(m,"assistantText");class N{static{o(this,"NodeEventTranslationState")}toolSummaries=new Map;emittedAssistantText="";resetAssistantText(){this.emittedAssistantText=""}emitAssistantTextDelta(e){const t=m(e),s=t.startsWith(this.emittedAssistantText)?t.slice(this.emittedAssistantText.length):t;return this.emittedAssistantText=t,s}seedAssistantText(e){const t=m(e);return this.emittedAssistantText=t,t}}function U(n,e,t=new N){switch(e.type){case"message_start":return e.message.role==="assistant"&&t.resetAssistantText(),[];case"message_update":{if(e.message.role!=="assistant")return[];const s=t.emitAssistantTextDelta(e.message);return s===""?[]:[{type:"node.output_text.delta",node_id:n,delta:s}]}case"message_end":{if(e.message.role!=="assistant")return[];const s=m(e.message);return t.resetAssistantText(),[{type:"node.output_text.done",node_id:n,text:s}]}case"tool_execution_start":{const s=K(e.args);return t.toolSummaries.set(e.toolCallId,s),[{type:"node.tool_call.started",node_id:n,tool_call_id:e.toolCallId,tool:e.toolName,summary:s}]}case"tool_execution_end":{const s=t.toolSummaries.get(e.toolCallId)??"[arguments unavailable]";return t.toolSummaries.delete(e.toolCallId),[{type:"node.tool_call.completed",node_id:n,tool_call_id:e.toolCallId,tool:e.toolName,status:e.isError?"error":"ok",summary:s}]}case"turn_start":return[{type:"node.turn.started",node_id:n}];case"turn_end":return[{type:"node.turn.completed",node_id:n}];default:return[]}}o(U,"translateBrokerFrame");class Y{static{o(this,"NodeEventHub")}nodeId;remove;ring=new F;subscribers=new Set;observer;opening=!1;observerErrorAt;poll;reconnect;idleClose;status;settledRevision;settledOutcome;settledSequence;snapshotSeeded=!1;reportsSeeded=!1;publishedReports=new Set;translationState=new N;fresh=!0;constructor(e,t){this.nodeId=e,this.remove=t}async subscribe(e,t){const s=this.fresh&&e!==void 0;this.fresh=!1,await this.start();const r=this.settledOutcome!==void 0,a=s?{gap:R(1),events:this.ring.replay(void 0).events}:this.ring.replay(e);r||(this.subscribers.add(t),this.status!=="dormant"&&await this.openObserver());let h=!1;return queueMicrotask(()=>{if(!h){a.gap!==null&&t(a.gap);for(const u of a.events)t(u)}}),r&&this.scheduleIdleClose(),{unsubscribe:o(()=>{h=!0,r||this.unsubscribe(t)},"unsubscribe"),terminal:r}}report(e){this.settledRevision!==void 0||this.publishedReports.has(e.id)||(this.publishedReports.add(e.id),this.publish({type:"node.report.pushed",node_id:this.nodeId,report:e}))}async start(){this.idleClose!==void 0&&(clearTimeout(this.idleClose),this.idleClose=void 0),this.poll===void 0&&(await this.check(),this.settledRevision===void 0&&(await this.seedReports(),this.poll=setInterval(()=>this.checkDetached(),T)))}async seedReports(){if(!this.reportsSeeded){this.reportsSeeded=!0;for(const e of(await this.storedReports()).reverse())this.report(e)}}async storedReports(){const e=(await p(this.nodeId))?.sub;return e?await G(e,()=>x(this.nodeId)):await x(this.nodeId)}async refreshReports(){if(!(!this.reportsSeeded||this.settledRevision!==void 0))for(const e of(await this.storedReports()).reverse())this.report(e)}async check(){const e=await p(this.nodeId);if(e===null){this.fail("stream_error",`node ${this.nodeId} no longer exists`);return}const t=await j(e);if(t!==null){this.settledRevision!==t.revision&&(this.settledRevision=t.revision,this.settledOutcome=t,this.settledSequence=this.publish({type:"node.settled",node_id:this.nodeId,outcome:t}).sequence_number,this.stopObserver(),this.stopPoll());return}const s=e.pi_pid===null?"dormant":e.status;if(s==="dormant"){this.observerErrorAt=void 0,this.status!=="dormant"&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s}));return}this.status===void 0?this.status=s:this.status!=="dormant"&&this.status!==s&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s})),await this.openObserver()}async openObserver(){if(this.observer!==void 0||this.subscribers.size===0||this.opening)return;this.opening=!0;let e;try{e=await L(this.nodeId)}finally{this.opening=!1}if(this.observer!==void 0||this.subscribers.size===0){e.destroy();return}const t=new B(this.nodeId,{transport:e});this.observer=t,t.on("connect",()=>{(async()=>{this.observerErrorAt=void 0;const s=await p(this.nodeId);this.status==="dormant"&&s!==null&&s.pi_pid!==null&&(this.status=s.status,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s.status})),t.send({type:"hello",role:"observer",client_id:k(),attends:!1})})().catch(s=>this.fail("stream_error",s instanceof Error?s.message:String(s)))}),t.on("frame",s=>{try{s.type==="welcome"&&this.seedSnapshot(s.snapshot);for(const r of U(this.nodeId,s,this.translationState))this.publish(r)}catch(r){this.fail("stream_error",r instanceof Error?r.message:String(r))}}),t.on("error",()=>{(async()=>{const s=await p(this.nodeId),r=Date.now();if(s!==null&&s.pi_pid!==null&&D(s.pi_pid)){if(this.observerErrorAt??=r,r-this.observerErrorAt<M)return;this.fail("stream_error","observer connection failed");return}this.observerErrorAt=void 0})().catch(s=>this.fail("stream_error",s instanceof Error?s.message:String(s)))}),t.on("close",()=>{this.observer===t&&(this.observer=void 0,!(this.subscribers.size===0||this.settledRevision!==void 0)&&(this.status!=="dormant"&&(this.publish({type:"node.status.changed",node_id:this.nodeId,status:"dormant"}),this.status="dormant"),this.scheduleReconnect()))}),t.connect()}seedSnapshot(e){if(this.snapshotSeeded)return;this.snapshotSeeded=!0;const t=e.messages.filter(r=>r.role==="assistant"),s=e.state.isStreaming?t.pop():void 0;for(const r of t)this.publish({type:"node.output_text.done",node_id:this.nodeId,text:m(r)});s!==void 0&&this.publish({type:"node.output_text.delta",node_id:this.nodeId,delta:this.translationState.seedAssistantText(s)})}scheduleReconnect(){this.reconnect===void 0&&(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.checkDetached()},T))}checkDetached(){this.check().catch(e=>w({level:"error",event:"api.node_events.check_failed",node_id:this.nodeId,error:e}))}publish(e){const t=this.ring.append(e);for(const s of[...this.subscribers])s(t);return t}fail(e,t){const s={type:"error",error:{code:e,message:t}};for(const r of[...this.subscribers])r(s);this.stopObserver(),this.stopPoll()}unsubscribe(e){this.subscribers.delete(e),this.subscribers.size===0&&this.scheduleIdleClose()}scheduleIdleClose(){this.idleClose===void 0&&(this.idleClose=setTimeout(()=>{this.stopObserver(),this.stopPoll(),this.remove()},V))}stopObserver(){this.reconnect!==void 0&&(clearTimeout(this.reconnect),this.reconnect=void 0);const e=this.observer;this.observer=void 0,e?.close()}stopPoll(){this.poll!==void 0&&(clearInterval(this.poll),this.poll=void 0)}}class Q{static{o(this,"NodeEventStreams")}hubs=new Map;unsubscribeBus;refresh(e){this.hubs.get(e)?.refreshReports().catch(t=>w({level:"error",event:"api.node_events.report_refresh_failed",node_id:e,error:t}))}listen(){this.unsubscribeBus??=P.subscribe(e=>this.refresh(e),{kinds:["report"],onListenStart:o(()=>{for(const e of[...this.hubs.keys()])this.refresh(e)},"onListenStart")})}remove(e){if(this.hubs.delete(e),this.hubs.size===0){const t=this.unsubscribeBus;this.unsubscribeBus=void 0,t?.then(s=>s())}}async subscribe(e,t,s){let r=this.hubs.get(e);return r===void 0&&(r=new Y(e,()=>this.remove(e)),this.hubs.set(e,r),this.listen()),await r.subscribe(t,s)}report(e,t){this.hubs.get(e)?.report(t),$().then(s=>s.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`report:${e}`)).catch(s=>w({level:"error",event:"api.node_events.report_signal_failed",node_id:e,error:s}))}}const X=new Q;function Z(n){const e=n.get("after");if(e===null||e==="")return{};if(!/^(?:0|[1-9]\d*)$/.test(e))throw new E(400,"invalid_request","`after` must be a non-negative integer");const t=Number(e);if(!Number.isSafeInteger(t))throw new E(400,"invalid_request","`after` must be a safe integer");return{after:t}}o(Z,"parseQuery");function I(n){const{type:e,...t}=n;return`event: ${e}
|
|
2
2
|
data: ${JSON.stringify(t)}
|
|
3
3
|
|
|
4
|
-
`}o(I,"sseRecord");async function
|
|
4
|
+
`}o(I,"sseRecord");async function ee(n){const e=n.params.id??"";if(await p(e)===null)throw new E(404,"node_not_found",`no node ${e}`);const{after:t}=Z(n.query),{req:s,res:r}=n;r.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"});let a=!1,h=!1,u=!1,c=0;const d=[];let v,f;const _=o(()=>{r.writableEnded||r.end()},"finish"),b=o(()=>{if(!a){if(a=!0,f!==void 0&&clearInterval(f),v?.(),r.destroyed){d.length=0,c=0,_();return}if(u||d.length>0){h=!0;return}_()}},"close"),g=o(()=>{for(u=!1;d.length>0;){const i=d.shift();if(c-=Buffer.byteLength(i,"utf8"),!r.write(i)){u=!0,r.once("drain",g);return}}h&&_()},"flush"),O=o(()=>{if(a)return;d.length=0,c=0;const i=I({type:"error",error:{code:"stream_dropped",message:"stream reader is too slow"}});d.push(i),c=Buffer.byteLength(i,"utf8"),a=!0,h=!0,f!==void 0&&clearInterval(f),v?.(),u||g()},"dropSlowReader"),y=o(i=>{if(a)return!1;if(u||d.length>0){const l=Buffer.byteLength(i,"utf8");return d.length>=J||c+l>W?(O(),!1):(d.push(i),c+=l,!0)}return r.write(i)||(u=!0,r.once("drain",g)),!0},"write"),S=o((i,l)=>{a||y(I({type:"error",error:{code:i,message:l}})),b()},"fail"),q=o(i=>{try{if(!y(I(i)))return;(i.type==="node.settled"||i.type==="error"&&i.error.code!=="stream_gap")&&b()}catch(l){S("stream_error",l instanceof Error?l.message:String(l))}},"onEvent");f=setInterval(()=>{try{a||y(`: keepalive
|
|
5
5
|
|
|
6
|
-
`)}catch(i){S("stream_error",i instanceof Error?i.message:String(i))}},
|
|
6
|
+
`)}catch(i){S("stream_error",i instanceof Error?i.message:String(i))}},z),s.once("close",b);try{const i=await X.subscribe(e,t,q);v=i.unsubscribe,i.terminal&&queueMicrotask(b)}catch(i){S("stream_error",i instanceof Error?i.message:String(i))}return{status:200}}o(ee,"handleEvents");const be=[{method:"GET",pattern:"/v1/nodes/:id/events",handler:ee}];export{F as NodeEventRing,N as NodeEventTranslationState,be as nodeEventRoutes,X as nodeEventStreams,U as translateBrokerFrame};
|