@north-light/cli 0.3.717 → 0.3.718

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.
@@ -1 +1 @@
1
- var T=Object.defineProperty;var a=(n,e)=>T(n,"name",{value:e,configurable:!0});import{request as g}from"node:http";import{homedir as A}from"node:os";import{join as p}from"node:path";import{CrtrClient as S}from"./client.js";const O=".crouter",_="api.sock",v=Symbol.for("@north-light/api/local-socket-fetch");function k(){const n=process.env.CRTR_API_SOCKET;if(n)return n;const e=process.env.CRTR_HOME,t=e!==void 0&&e!==""?e:p(A(),O);return p(process.platform==="linux"?"/run/crtr":p(t,"runtime"),_)}a(k,"defaultSocketPath");function x(n){const e=a(function(t,s={}){const m=t instanceof URL?t:new URL(typeof t=="string"?t:t.url),w=s.method??"GET",l={};if(s.headers!==void 0)for(const[h,u]of new Headers(s.headers).entries())l[h]=u;const f=typeof s.body=="string"?s.body:void 0;return f!==void 0&&(l["content-length"]=String(Buffer.byteLength(f))),new Promise((h,u)=>{const i=g({socketPath:n,path:m.pathname+m.search,method:w,headers:l},o=>{const C=new ReadableStream({start(d){o.on("data",r=>d.enqueue(new Uint8Array(r))),o.on("end",()=>d.close()),o.on("error",r=>d.error(r))},cancel(){o.destroy()}}),b=new Headers;for(const[d,r]of Object.entries(o.headers))if(r!==void 0)for(const R of Array.isArray(r)?r:[r])b.append(d,R);const E=o.statusCode??0;h(new Response(E===204?null:C,{status:E,statusText:o.statusMessage,headers:b}))});i.on("error",o=>u(new TypeError("fetch failed",{cause:o})));const c=s.signal,y=a(()=>{i.destroy(),u(c?.reason??new DOMException("The operation was aborted.","AbortError"))},"abort");if(c!=null){if(c.aborted){y();return}c.addEventListener("abort",y,{once:!0})}f!==void 0&&i.write(f),i.end()})},"fetchOverSocket");return e[v]=!0,e}a(x,"socketFetch");function U(n={}){const{socketPath:e,...t}=n;return new S({baseUrl:"http://localhost",fetch:x(e??k()),autostart:!0,...t})}a(U,"localClient");export{k as defaultSocketPath,U as localClient,x as socketFetch};
1
+ var T=Object.defineProperty;var a=(n,e)=>T(n,"name",{value:e,configurable:!0});import{request as g}from"node:http";import{homedir as A}from"node:os";import{join as p}from"node:path";import{CrtrClient as S}from"./client.js";const O=".crouter",_="api.sock",v=Symbol.for("@north-light/api/local-socket-fetch");function k(){const n=process.env.CRTR_API_SOCKET;if(n)return n;const e=process.env.CRTR_HOME,t=e!==void 0&&e!==""?e:p(A(),O);return p(process.platform==="linux"?"/run/crtr":p(t,"runtime"),_)}a(k,"defaultSocketPath");function x(n){const e=a(function(t,s={}){const m=t instanceof URL?t:new URL(typeof t=="string"?t:t.url),w=s.method??"GET",l={};if(s.headers!==void 0)for(const[h,u]of new Headers(s.headers).entries())l[h]=u;const f=typeof s.body=="string"?s.body:void 0;return f!==void 0&&(l["content-length"]=String(Buffer.byteLength(f))),new Promise((h,u)=>{const i=g({socketPath:n,path:m.pathname+m.search,method:w,headers:l,agent:!1},o=>{const C=new ReadableStream({start(d){o.on("data",r=>d.enqueue(new Uint8Array(r))),o.on("end",()=>d.close()),o.on("error",r=>d.error(r))},cancel(){o.destroy()}}),b=new Headers;for(const[d,r]of Object.entries(o.headers))if(r!==void 0)for(const R of Array.isArray(r)?r:[r])b.append(d,R);const E=o.statusCode??0;h(new Response(E===204?null:C,{status:E,statusText:o.statusMessage,headers:b}))});i.on("error",o=>u(new TypeError("fetch failed",{cause:o})));const c=s.signal,y=a(()=>{i.destroy(),u(c?.reason??new DOMException("The operation was aborted.","AbortError"))},"abort");if(c!=null){if(c.aborted){y();return}c.addEventListener("abort",y,{once:!0})}f!==void 0&&i.write(f),i.end()})},"fetchOverSocket");return e[v]=!0,e}a(x,"socketFetch");function U(n={}){const{socketPath:e,...t}=n;return new S({baseUrl:"http://localhost",fetch:x(e??k()),autostart:!0,...t})}a(U,"localClient");export{k as defaultSocketPath,U as localClient,x as socketFetch};
@@ -87,7 +87,7 @@ ${i}`);return e.join(`
87
87
  `)}var vXe,dvn,pvn,hvn,mvn,zd,IXe,xfe=y(()=>{"use strict";vXe=65536,dvn=5*1024*1024,pvn=16*1024*1024,hvn=128*1024,mvn=200;IXe=!1});var bfe,kXe=y(()=>{"use strict";bfe=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"]});function fvn(t){return typeof t=="object"&&t!==null?t:void 0}function TXe(t){return typeof t=="string"?t:""}function RXe(t){if(t instanceof Error){let n={type:t.name||"Error",message:t.message};return typeof t.stack=="string"&&(n.stack=t.stack),t.cause!==void 0&&(n.cause=t.cause instanceof Error?t.cause.message:String(t.cause)),n}if(typeof t=="string")return{type:"Error",message:t};let e=fvn(t);return{type:TXe(e?.name)||"Error",message:TXe(e?.message)||String(t)}}var BXe=y(()=>{"use strict";kXe()});import{AsyncLocalStorage as gvn}from"node:async_hooks";import{randomBytes as Avn}from"node:crypto";function f6(t){if(typeof t!="string"||!yvn.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function Ife(){let t;do t=Avn(16).toString("hex");while(t==="00000000000000000000000000000000");return f6(t)}var yvn,Cfe,DXe,MXe=y(()=>{"use strict";yvn=/^(?!0{32}$)[0-9a-f]{32}$/,Cfe=new gvn;DXe={current:()=>Cfe.getStore(),run:(t,e)=>Cfe.run(f6(t),e),fresh:t=>{let e=Ife();return Cfe.run(e,()=>t(e))}}});function vvn(t){return Buffer.byteLength(t,"utf8")}function g6(t,e,n=128){if(typeof t!="string"||t===""||vvn(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function Svn(t){if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(t))throw new TypeError("ts must be an ISO 8601 timestamp");let e=new Date(t);if(Number.isNaN(e.getTime()))throw new TypeError("ts must be an ISO 8601 timestamp");return e.toISOString()}function _vn(t){if(!Ivn.has(t.class))throw new TypeError("error_class.class is invalid");let e={class:t.class};if(t.status!==void 0){if(!Number.isInteger(t.status))throw new TypeError("error_class.status must be an integer");e.status=t.status}if(t.provider!==void 0&&(e.provider=g6(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!Cvn.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function PXe(t){if(!wvn.has(t.level))throw new TypeError("level is invalid");if(!xvn.has(t.component))throw new TypeError("component is invalid");let e=g6(t.event,"event");if(!Evn.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?DXe.current()??Ife():f6(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():Svn(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=g6(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=g6(t.stream_id,"stream_id")),t.duration_ms!==void 0){if(!Number.isFinite(t.duration_ms)||t.duration_ms<0)throw new TypeError("duration_ms must be finite and non-negative");r.duration_ms=t.duration_ms}if(t.outcome!==void 0){if(!bvn.has(t.outcome))throw new TypeError("outcome is invalid");r.outcome=t.outcome}if(t.attempt!==void 0){if(!Number.isInteger(t.attempt)||t.attempt<=0)throw new TypeError("attempt must be a positive integer");r.attempt=t.attempt}return t.error_class!==void 0&&(r.error_class=_vn(t.error_class)),t.error!==void 0&&(r.error=RXe(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}var Evn,wvn,xvn,bvn,Cvn,Ivn,NXe=y(()=>{"use strict";BXe();MXe();Evn=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,wvn=new Set(["error","warn","info","debug"]),xvn=new Set(["daemon","broker","control-plane","front","sentinel"]),bvn=new Set(["succeeded","failed","skipped"]),Cvn=new Set(["auto","manual","fatal"]),Ivn=new Set(bfe)});function UI(t){return Buffer.byteLength(t,"utf8")}function FI(t,e){if(UI(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-UI(n),i=0,o="";for(let s of t){let a=UI(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function kvn(t){return t===void 0?"[Unsupported undefined]":typeof t=="function"?`[Unsupported function${t.name?` ${t.name}`:""}]`:typeof t=="symbol"?`[Unsupported ${String(t)}]`:`[Unsupported ${t?.constructor?.name??typeof t}]`}function vfe(t,e,n,r){if(r.remaining<=0)return{value:"[Omitted]",altered:!0,dropped:0};if(r.remaining-=1,t===null||typeof t=="boolean")return{value:t,altered:!1,dropped:0};if(typeof t=="string"){let i=FI(t,4096);return{value:i.value,altered:i.altered,dropped:0}}if(typeof t=="number")return Number.isFinite(t)?{value:t,altered:!1,dropped:0}:{value:String(t),altered:!0,dropped:0};if(typeof t=="bigint")return{value:t.toString(),altered:!0,dropped:0};if(t instanceof Date)return{value:Number.isNaN(t.getTime())?"Invalid Date":t.toISOString(),altered:!0,dropped:0};if(typeof t!="object"||t===void 0)return{value:kvn(t),altered:!0,dropped:0};if(n.has(t))return{value:"[Circular]",altered:!0,dropped:0};if(e>=4)return{value:"[Max depth]",altered:!0,dropped:0};n.add(t);try{if(Array.isArray(t)){let u=Math.min(t.length,64),l=[],d=t.length>u,p=t.length-u;for(let h=0;h<u;h+=1){if(r.remaining<=0){d=!0,p+=u-h;break}let m=vfe(t[h],e+1,n,r);l.push(m.value),d||=m.altered,p+=m.dropped}return{value:l,altered:d,dropped:p}}let i;try{i=Object.keys(t).sort()}catch{return{value:"[Unsupported object]",altered:!0,dropped:0}}let o=i.slice(0,64),s={},a=i.length>o.length,c=i.length-o.length;for(let u=0;u<o.length;u+=1){let l=o[u];if(r.remaining<=0){a=!0,c+=o.length-u;break}let d=FI(l,128),p;try{p=vfe(t[l],e+1,n,r)}catch{p={value:"[Unsupported property]",altered:!0,dropped:0}}if(Object.prototype.hasOwnProperty.call(s,d.value)){a=!0,c+=1;continue}s[d.value]=p.value,a||=d.altered||p.altered,c+=p.dropped}return{value:s,altered:a,dropped:c}}finally{n.delete(t)}}function Tvn(t){let e=FI(String(t.type),128),n=FI(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=FI(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=FI(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function A6(t){return JSON.stringify(t)}function CF(t){return UI(A6(t))+1}function LXe(t){let e=t.fields===void 0?void 0:vfe(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:Tvn(t.error),r={v:1,ts:t.ts,level:t.level,event:t.event,component:t.component,operation_id:t.operation_id,...t.node_id===void 0?{}:{node_id:t.node_id},...t.stream_id===void 0?{}:{stream_id:t.stream_id},...t.duration_ms===void 0?{}:{duration_ms:t.duration_ms},...t.outcome===void 0?{}:{outcome:t.outcome},...t.attempt===void 0?{}:{attempt:t.attempt},...t.error_class===void 0?{}:{error_class:t.error_class},...n===void 0?{}:{error:n.value},...e===void 0?{}:{fields:e.value}},i=CF(r),o=e?.altered===!0||n?.altered===!0||i>65536,s=e?.dropped??0;for(o&&Object.assign(r,{record_truncated:!0,original_bytes:i,dropped_fields_count:s});CF(r)>65536&&r.fields!==void 0;){let u=r.fields,l=Object.keys(u);if(l.length===0){delete r.fields;break}l.sort((d,p)=>{let h=UI(A6(u[p]))-UI(A6(u[d]));return h!==0?h:p<d?-1:p>d?1:0}),delete u[l[0]],s+=1,r.record_truncated=!0,r.original_bytes=i,r.dropped_fields_count=s}let a=r.error;CF(r)>65536&&a?.stack!==void 0&&delete a.stack,CF(r)>65536&&a?.cause!==void 0&&delete a.cause,CF(r)>65536&&a!==void 0&&(a.message=FI(a.message,64).value);let c=A6(r);if(UI(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}var QXe=y(()=>{"use strict"});import{AsyncLocalStorage as Rvn}from"node:async_hooks";function FXe(t){Sfe=t}function y6(){return OXe}function E6(){let t=Bvn.getStore();if(t!==void 0)return t;if(OXe)throw new vF;if(Sfe===void 0)throw new IF;return Sfe}var IF,vF,Sfe,OXe,Bvn,JR=y(()=>{"use strict";IF=class extends Error{code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}},vF=class extends Error{code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}},OXe=!1,Bvn=new Rvn});import{existsSync as w6,lstatSync as Pyi,mkdirSync as Dvn,readdirSync as Mvn,readFileSync as $Xe,rmSync as Pvn,statSync as Nvn,symlinkSync as Nyi,writeFileSync as Lvn,cpSync as Lyi,readlinkSync as Qyi,renameSync as Qvn,chmodSync as Ovn,realpathSync as Fvn,closeSync as WXe,fsyncSync as HXe,openSync as GXe,linkSync as Oyi,unlinkSync as Fyi,writeSync as Uyi}from"node:fs";import{dirname as UXe,join as Uvn,relative as Wyi,sep as Hyi}from"node:path";import{homedir as $vn,platform as Wvn}from"node:os";function Jm(t){try{return Fvn(t)}catch{return t}}function qXe(t,e=$vn()){return t==="~"?e:t.startsWith("~/")||Wvn()==="win32"&&t.startsWith("~\\")?Uvn(e,t.slice(2)):t}function x6(t){Dvn(t,{recursive:!0})}function XR(t,e,n){_fe(t,JSON.stringify(e,null,2)+`
88
88
  `,n)}function Hvn(t){let e=GXe(t,"r");try{HXe(e)}finally{WXe(e)}}function jXe(t){let e=GXe(t,"r");try{HXe(e)}finally{WXe(e)}}function _fe(t,e,n){n?.createParent!==!1&&x6(UXe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(w6(t)?Nvn(t).mode&511:384);try{Lvn(r,e,{mode:i}),Ovn(r,i),n?.durable===!0&&Hvn(r),Qvn(r,t),n?.durable===!0&&jXe(UXe(t))}finally{w6(r)&&Pvn(r,{force:!0})}}function Gvn(t){return JSON.parse($Xe(t,"utf8"))}function $I(t){try{return Gvn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function WI(t){try{return JSON.parse($Xe(t,"utf8"))}catch{return null}}function kfe(t){return w6(t)}function Tfe(t){return w6(t)?Mvn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var Ol=y(()=>{"use strict"});import{homedir as qvn,userInfo as jvn}from"node:os";import{basename as zvn,dirname as Kyi,isAbsolute as Yyi,join as Vd,resolve as zXe}from"node:path";function C6(){let t=zXe(_g()||(process.platform==="linux"?"/":Vd(qvn(),".crouter")));if(Vvn()&&t===Kvn())throw new Error(`refusing to use the account's real crouter root ${t} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return t}function Vvn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function Kvn(){if(b6===void 0)try{b6=zXe(jvn().homedir,".crouter")}catch{b6=null}return b6}function Fl(){return Vd(C6(),"runtime")}function Rfe(){return Vd(C6(),"apps")}function q0(){return Vd(Fl(),"secrets")}function VXe(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=SF(t);return{dir:Vd(n.profiles,e),env:Vd(q0(),"env",zvn(n.root),e),home:n.home}}function Bfe(){return process.platform==="linux"?"/run/crtr":Fl()}function SF(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=Vd(Rfe(),e);return{root:n,profiles:Vd(n,"profiles"),conversations:Vd(n,"conversations"),nodes:Vd(n,"nodes"),files:Vd(n,"files"),home:Vd(n,"home"),cache:Vd(n,"cache")}}var b6,Xm=y(()=>{"use strict";Dc();Kd();JR();Ol()});import{chmodSync as rEi,chownSync as iEi,closeSync as pw,constants as I6,fchmodSync as oEi,fchownSync as sEi,fstatSync as XXe,fsyncSync as aEi,linkSync as cEi,lstatSync as uEi,mkdirSync as lEi,openSync as KXe,readdirSync as dEi,readFileSync as Yvn,readlinkSync as pEi,readSync as hEi,realpathSync as mEi,renameSync as fEi,rmdirSync as gEi,rmSync as AEi,statSync as yEi,symlinkSync as EEi,unlinkSync as wEi,writeSync as xEi}from"node:fs";import{basename as CEi,dirname as IEi,join as vEi,relative as ZXe,resolve as Pfe,sep as YXe}from"node:path";import{loadLinuxNative as Jvn,O_CLOEXEC as Nfe,O_PATH as Lfe,RESOLVE_BENEATH as Xvn,RESOLVE_NO_SYMLINKS as Zvn}from"../../native/linux.js";function eZe(){return Dfe===null&&(Dfe=Jvn()),Dfe}function tSn(t){return t.code}function nSn(t,e){switch(tSn(t)){case"ELOOP":case"EXDEV":return new HI(`path meets a symlink: ${e}`);case"ENXIO":return new HI(`path is not a regular file: ${e}`);case"EAGAIN":return new HI(`path is held by a lease: ${e}`);default:return t}}function Mfe(t,e,n,r,i){try{return t.openat2(e,n,r,eSn)}catch(o){throw nSn(o,i)}}function rSn(t,e,n){let r;try{r=XXe(t)}catch(i){throw pw(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw pw(t),new HI(`path is not a regular file: ${e}`)}function iSn(t,e){let n=ZXe(Pfe(t),Pfe(e));if(n===".."||n.startsWith(`..${YXe}`)||n.startsWith(YXe))throw new Error(`${e} is outside ${t}`);return n}function tZe(t,e,n){if(n&I6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=iSn(t,e),i=eZe();if(!i)return KXe(e,n);let o=KXe("/",JXe),s;try{s=Mfe(i,o,ZXe("/",Pfe(t))||".",JXe,t)}finally{pw(o)}try{return n&Lfe?Mfe(i,s,r||".",n|Nfe,e):rSn(Mfe(i,s,r||".",n|Nfe|I6.O_NONBLOCK,e),e,!0)}finally{pw(s)}}function Qfe(t,e){let n=tZe(t,e,I6.O_RDONLY);try{return Yvn(n)}finally{pw(n)}}function nZe(t,e){if(!eZe())return{path:e,release:()=>{}};let n=tZe(t,e,Lfe),r;try{r=XXe(n)}catch(o){throw pw(n),o}if(!r.isSocket())throw pw(n),new HI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,pw(n))}}}var eSn,JXe,Dfe,HI,_F=y(()=>{"use strict";eSn=Xvn|Zvn,JXe=Lfe|I6.O_DIRECTORY|Nfe,Dfe=null;HI=class extends Error{}});import{join as kg}from"node:path";function Ja(){return Fl()}function rZe(){return kg(Ja(),"on-disk-migration.lock")}function ZR(t){return kg(eB(t),"view.sock")}function oSn(){return kg(Ja(),"nodes")}function iZe(){return kg(Bfe(),"api.sock")}function oZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=sSn}function Ofe(t){if(!oZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function aSn(t){return Ofe(t),kg(oSn(),t)}function cSn(t,e){Ofe(t);let n=e??(Fme()===t?OYe():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return kg(SF(n).nodes,t)}function eB(t){return Ofe(t),process.platform==="linux"?kg(Bfe(),"nodes",t):kg(aSn(t),"run")}function cZe(t,e){return kg(cSn(t,e),"context")}function uZe(t){return kg(eB(t),"job")}var sSn,sZe,aZe,Ul=y(()=>{"use strict";Xm();Dc();_F();sSn=128;sZe="broker-released",aZe="cli-relay-generation"});import{join as uSn}from"node:path";function lSn(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function dSn(t){if(v6===void 0){v6=t;return}if(!lSn(v6,t))throw new Error("event source is already bound for this process")}function lZe(){dSn({component:"daemon",path:uSn(Ja(),"crtrd.log")})}function S6(){return v6}var v6,Ffe=y(()=>{"use strict";Ul()});function dZe(t){return t instanceof sn?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||t.code==="runtime_starting"||t.code==="northlight_unreachable")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}function Ufe(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var sn,hw=y(()=>{"use strict";sn=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}}});var se,$fe=y(()=>{"use strict";se={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonDrain:()=>"/v1/daemon/drain",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,executionStart:t=>`/v1/executions/${t}/start`,executionImportUnpacked:t=>`/v1/executions/${t}/import-unpacked`,environmentGitCredential:t=>`/v1/environments/${t}/git-credential`,feedback:()=>"/v1/feedback",nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeFiles:t=>`/v1/nodes/${t}/files`,nodeFileComplete:(t,e)=>`/v1/nodes/${t}/files/${encodeURIComponent(e)}/complete`,nodeUploads:t=>`/v1/nodes/${t}/uploads`,nodeUploadLink:(t,e)=>`/v1/nodes/${t}/uploads/${encodeURIComponent(e)}/link`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobReport:(t,e)=>`/v1/nodes/${t}/jobs/${e}/report`,nodeJobOutput:(t,e)=>`/v1/nodes/${t}/jobs/${e}/output`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeKick:t=>`/v1/nodes/${t}/kick`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerCycleStart:t=>`/v1/nodes/${t}/broker/cycle-start`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerCycle:t=>`/v1/nodes/${t}/broker/cycle`,nodeBrokerIdle:t=>`/v1/nodes/${t}/broker/idle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeSummaries:t=>`/v1/nodes/${t}/records/summaries`,nodeAttachments:t=>`/v1/nodes/${t}/attachments`,nodeAttachment:(t,e)=>`/v1/nodes/${t}/attachments/${e}`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerStructuredRequest:t=>`/v1/nodes/${t}/broker/structured-request`,nodeBrokerGoal:t=>`/v1/nodes/${t}/broker/goal`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,charges:()=>"/v1/charges",spendLimits:()=>"/v1/spend-limits",spendLimit:t=>`/v1/spend-limits/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",canvasView:t=>`/v1/canvas/view/${encodeURIComponent(t)}`,canvasBrowse:()=>"/v1/canvas/browse",canvasAnalytics:()=>"/v1/canvas/analytics",canvasGraph:()=>"/v1/canvas/graph",canvasPrune:()=>"/v1/canvas/prune",humanReviews:()=>"/v1/human/reviews",humanReview:t=>`/v1/human/reviews/${t}`,humanReviewSubmit:t=>`/v1/human/reviews/${t}/submit`,humanReviewCancel:t=>`/v1/human/reviews/${t}/cancel`,humanReviewDocument:t=>`/v1/human/reviews/${t}/document`,humanReviewComments:t=>`/v1/human/reviews/${t}/comments`,humanReviewCommentEvents:t=>`/v1/human/reviews/${t}/comment-events`,humanComment:t=>`/v1/human/comments/${t}`,humanCommentEdit:t=>`/v1/human/comments/${t}/edit`,humanCommentResolve:t=>`/v1/human/comments/${t}/resolve`,humanCommentReopen:t=>`/v1/human/comments/${t}/reopen`,humanCommentDelete:t=>`/v1/human/comments/${t}/delete`,humanCommentFork:t=>`/v1/human/comments/${t}/fork`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:t=>`/v1/human/inbox/${t}`,humanInboxRespond:t=>`/v1/human/inbox/${t}/respond`,humanInboxProgress:t=>`/v1/human/inbox/${t}/progress`,humanInboxResponse:t=>`/v1/human/inbox/${t}/response`,humanInboxCancel:t=>`/v1/human/inbox/${t}/cancel`,humanInboxFeedbackResolve:(t,e)=>`/v1/human/inbox/${t}/feedback-comments/${e}/resolve`,humanRequests:()=>"/v1/human/requests",humanComponents:()=>"/v1/human/components",humanRequest:t=>`/v1/human/requests/${t}`,humanRequestReplace:t=>`/v1/human/requests/${t}/replace`,humanRequestRespond:t=>`/v1/human/requests/${t}/respond`,humanRequestDismiss:t=>`/v1/human/requests/${t}/dismiss`,humanRequestCancel:t=>`/v1/human/requests/${t}/cancel`,profiles:()=>"/v1/profiles",profile:t=>`/v1/profiles/${t}`,profilePause:t=>`/v1/profiles/${t}/pause`,profileResume:t=>`/v1/profiles/${t}/resume`,profileMetadata:t=>`/v1/profiles/${t}/metadata`,appEnv:()=>"/v1/apps/self/env",appEnvVar:t=>`/v1/apps/self/env/${encodeURIComponent(t)}`,profileEnv:t=>`/v1/profiles/${t}/env`,profileEnvVar:(t,e)=>`/v1/profiles/${t}/env/${e}`,profileEnvironment:t=>`/v1/profiles/${t}/environment`,settings:()=>"/v1/settings",modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthAccount:(t,e)=>`/v1/model-auth/${t}/accounts/${encodeURIComponent(e)}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",exec:()=>"/v1/exec",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectShares:t=>`/v1/objects/${encodeURIComponent(t)}/shares`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",schemas:()=>"/v1/schemas",relations:()=>"/v1/relations",check:()=>"/v1/check",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"}});function hZe(t){pZe=t}function mZe(t){t!==null&&pZe?.(t)}var pZe,Wfe=y(()=>{"use strict"});function _6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Hfe=y(()=>{"use strict"});function fZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Gfe=y(()=>{"use strict"});function gZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var qfe=y(()=>{"use strict"});async function T6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=gSn,retry:i=()=>!0,now:o=Date.now,sleep:s=xZe}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}function tB(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new sn(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}function kr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function GI(t,e){let n=t.status>=200&&t.status<300,r=(await wZe(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new sn(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw Ufe(i)?new sn(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new sn(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function ySn(t){return t==="GET"||t==="HEAD"}async function ESn(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await wZe(t.clone(),Math.min(e??1/0,Date.now()+5e3)),r=JSON.parse(n).error;return r?.origin==="router"&&r.details?.forwarded===!1&&(r.details.runtime_state==="creating"||r.details.runtime_state==="recovering")}catch{return!1}}function wSn(t){return t===429||t>=500}async function jfe(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function wZe(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),tB(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(tB(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function AZe(t){return Math.min(2e3,250*2**(t-1))}function zfe(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function yZe(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function mw(t,e){if(e?.aborted)return new sn(0,"request_aborted","request aborted by caller signal");if(t instanceof sn)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new sn(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new sn(0,"request_aborted","request aborted by caller signal");let n=zfe(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new sn(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new sn(504,"request_timeout",`crtrd request timed out: ${r}`):new sn(503,"transport_error",r)}function xSn(t,e){return t==="GET"||t==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new sn(e.status,e.code,`${e.message}; the ${t} request was sent, so it may or may not have been applied`,{outcome:"unknown"},e.headers)}function EZe(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function k6(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new sn(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=tB(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return xZe(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new sn(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function bSn(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function xZe(t){return new Promise(e=>setTimeout(e,t))}function CSn(t){if(t!==void 0)try{return t()}catch{return}}var pSn,hSn,mSn,fSn,gSn,TF,kF,Tg,ASn,R6=y(()=>{"use strict";hw();$fe();Wfe();Hfe();Gfe();qfe();pSn=3e4,hSn=3e4,mSn=Symbol.for("@north-light/api/local-socket-fetch"),fSn=1e4,gSn=200;TF=2147483647;kF=t=>tB(t??Date.now()),Tg=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??pSn,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[mSn]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??fSn}healthz(){return this.request("GET",se.healthz())}async probeHealthz(e){let n=await this.transport("GET",se.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return GI(n)}async ready(){let e=await this.transport("GET",se.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return GI(e)}status(){return this.request("GET",se.status())}due(){return this.request("GET",se.due())}restartDaemon(){return this.request("POST",se.daemonRestart())}drainDaemon(e={}){let n=e.settle_limit_ms??0;return this.request("POST",se.daemonDrain(),e,{timeout:n+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",se.daemonDrain())}admitDaemon(){return this.request("POST",se.daemonAdmit())}migrateState(e){return this.request("POST",se.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",se.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",se.nodeTelemetry(this.nodePath(e)),n)}async putNodeSummaries(e,n){await this.request("PUT",se.nodeSummaries(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",se.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",kr(se.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}listNodeAttachments(e){return this.request("GET",se.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,n){let r=await this.send("GET",se.nodeAttachment(this.nodePath(e),n));return r.ok||await GI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",se.nodeFiles(this.nodePath(e)),n)}createNodeUpload(e,n){return this.request("POST",se.nodeUploads(this.nodePath(e)),n)}nodeUploadLink(e,n){return this.request("POST",se.nodeUploadLink(this.nodePath(e),n))}completeNodeFile(e,n){return this.request("POST",se.nodeFileComplete(this.nodePath(e),n))}readNodePassiveMessage(e,n){return this.request("GET",kr(se.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",se.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",se.nodes(),e,{timeout:12e4+this.timeoutMs})}listNodes(e){return this.request("GET",kr(se.nodes(),e))}getNode(e){return this.request("GET",se.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",kr(se.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",kr(se.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",kr(se.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await GI(i);return}if(i.body===null)throw new sn(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
89
89
  `))!==-1;){let d=a.slice(0,l);a=a.slice(l+1),d!==""&&(yield JSON.parse(d))}}if(a+=s.decode(),a.trim()!=="")throw new sn(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,n){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,n):this.request("POST","/v1/structured-requests",e,n)}getStructuredRequest(e,{wait:n=0,budgetMs:r}={}){if(!Number.isInteger(n)||n<0||n>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",kr(`/v1/structured-requests/${this.requestPath(e)}`,{wait:n}),void 0,{budgetMs:r})}cancelStructuredRequest(e,n){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},n)}registerOutcomeDelivery(e,n){return this.request("PUT",se.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",se.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",se.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",se.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,n,r={}){let i=new URLSearchParams;r.tail_lines!==void 0&&i.set("tail_lines",String(r.tail_lines)),r.max_bytes!==void 0&&i.set("max_bytes",String(r.max_bytes));let o=i.size===0?"":`?${i.toString()}`;return this.request("GET",`${se.nodeJobOutput(this.nodePath(e),this.jobPath(n))}${o}`)}stopBashJob(e,n){return this.request("DELETE",se.nodeJob(this.nodePath(e),this.jobPath(n)))}async patchBashJob(e,n,r){await this.request("PATCH",se.nodeJob(this.nodePath(e),this.jobPath(n)),r)}async reportBashJob(e,n,r){await this.request("POST",se.nodeJobReport(this.nodePath(e),this.jobPath(n)),r)}sendMessage(e,n){return this.request("POST",se.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",se.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",se.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",se.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",se.nodeFork(this.nodePath(e)),{})}kickNode(e){return this.request("POST",se.nodeKick(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",se.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",se.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",se.nodeBrokerSessionBound(this.nodePath(e)),n)}cycleStartBroker(e,n,r){return this.request("POST",se.nodeBrokerCycleStart(this.nodePath(e)),n,r)}settleBroker(e,n){return this.request("POST",se.nodeBrokerSettle(this.nodePath(e)),n)}startBrokerCycle(e,n){return this.request("POST",se.nodeBrokerCycle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",se.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",se.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",se.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",se.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",se.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",se.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",se.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",se.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",se.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${se.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",se.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${se.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",se.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",se.executionStart(e))}executionImportUnpacked(e){return this.request("POST",se.executionImportUnpacked(e),{})}gitCredential(e,n){return this.request("POST",se.environmentGitCredential(e),n)}postFeedback(e){return this.request("POST",se.feedback(),e)}brokerExtensionState(e){return this.request("GET",se.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",se.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",se.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",se.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",se.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",se.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",se.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",se.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",se.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",se.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",se.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",se.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",se.kinds())}patchConfig(e,n){return this.request("PATCH",se.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",se.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",se.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",se.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",se.quarantinedWorktrees())}showLimits(){return this.request("GET",se.limits())}setAppLimits(e,n){return this.request("PUT",se.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(se.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(se.charges(),e))}listSpendLimits(){return this.request("GET",se.spendLimits())}setSpendLimit(e,n){return this.request("PUT",se.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",se.spendLimit(e))}listSpaces(){return this.request("GET",se.spaces())}subscribe(e,n){return this.request("POST",se.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",se.focuses())}focusOf(e){return this.request("GET",kr(se.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(se.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",se.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",se.focus(e),n)}async closeFocus(e){await this.request("DELETE",se.focus(e))}async unsubscribe(e,n){await this.request("DELETE",se.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",se.crons(),e)}listCrons(e){return this.request("GET",kr(se.crons(),e))}showCron(e,n){return this.request("GET",kr(se.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(se.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(se.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(se.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(se.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",se.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",se.nodeAttach(this.nodePath(e)),n??{},{timeout:hSn+this.timeoutMs})}getReports(e,n){return this.request("GET",kr(se.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",kr(se.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",se.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",se.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",kr(se.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",se.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",se.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",kr(se.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",se.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",kr(se.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",se.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",kr(se.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",se.bash(),e,n)}objects={read:(e,n)=>this.request("GET",kr(se.object(e),n)),list:e=>this.request("GET",kr(se.objects(),e)),search:e=>this.request("POST",se.objectsSearch(),e),watch:(e,n={})=>this.request("POST",se.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",kr(se.objectWatch(e),n)),edges:(e,n)=>this.request("GET",kr(se.objectEdges(e),n))};docs={write:e=>this.request("POST",se.docs(),e),edit:(e,n)=>this.request("PATCH",se.doc(e),n),move:(e,n)=>this.request("POST",se.docMove(e),n),delete:e=>this.request("DELETE",se.doc(e)),history:(e,n)=>this.request("GET",kr(se.docHistory(e),n)),lint:(e={})=>this.request("POST",se.docsLint(),e)};documents={browserAccess:()=>this.request("GET",se.documentsBrowserAccess()),reconcilePackages:e=>this.request("POST",se.documentsReconcilePackages(),e)};plugins={appToken:e=>this.request("GET",se.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",se.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",se.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",se.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",se.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",se.profile(e),n??{})}createProfile(e){return this.request("POST",se.profiles(),e)}listProfiles(){return this.request("GET",se.profiles())}updateProfile(e,n){return this.request("PATCH",se.profile(e),n)}listAppEnv(){return this.request("GET",se.appEnv())}setAppEnv(e,n){return this.request("PUT",se.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",se.appEnvVar(e))}listProfileEnv(e){return this.request("GET",se.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",se.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",se.profileEnvVar(e,n))}getProfileEnvironment(e){return this.request("GET",se.profileEnvironment(e))}setProfileEnvironment(e,n){return this.request("PUT",se.profileEnvironment(e),n)}getProfile(e){return this.request("GET",se.profile(e))}pauseProfile(e){return this.request("POST",se.profilePause(e),{})}resumeProfile(e){return this.request("POST",se.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",se.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",se.profile(e),n)}getSettings(){return this.request("GET",se.settings())}putSettings(e){return this.request("PUT",se.settings(),e)}listModelAuth(){return this.request("GET",se.modelAuths())}getModelAuthReadiness(e){return this.request("GET",kr(se.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",se.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",se.modelAuth(e))}patchModelAuthAccount(e,n,r){return this.request("PATCH",se.modelAuthAccount(e,n),r)}removeModelAuthAccount(e,n){return this.request("DELETE",se.modelAuthAccount(e,n))}startModelAuth(e){return this.request("POST",se.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",se.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",se.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",kr(se.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",se.humanReviews(),e)}listReviews(e){return this.request("GET",kr(se.humanReviews(),e))}getReview(e){return this.request("GET",se.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",se.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",se.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",se.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",se.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",kr(se.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",kr(se.humanReviewCommentEvents(this.reviewPath(e)),n))}getReviewComment(e){return this.request("GET",se.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",se.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",se.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",se.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",se.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",se.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",se.humanInbox())}getHumanInboxPage(e){return this.request("GET",se.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,n={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",kr(se.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",se.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",se.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",se.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",se.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",se.humanRequests(),e)}listPageComponents(){return this.request("GET",se.humanComponents())}getHumanRequest(e){return this.request("GET",se.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",se.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",se.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",se.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",se.humanRequestCancel(this.requestPath(e)),n)}resolvePageFeedbackComment(e,n,r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(n)}`);return this.request("POST",se.humanInboxFeedbackResolve(this.ticketId(e),n),{node_id:r})}async dashboard(e){let n=e?.under!==void 0?{under:e.under}:void 0,[r,i]=await Promise.all([this.listNodes(n),this.status()]);return{nodes:r,counts:i.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",se.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",se.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",se.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",se.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",kr(se.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",se.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",se.canvasSnapshot())}analytics(e){return this.request("GET",kr(se.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",se.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",kr(se.canvasLiveRoots(),e))}canvasView(e){return this.request("GET",se.canvasView(e))}canvasRoster(){return this.request("GET",se.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",se.canvasBrowse());return e.ok||await GI(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",se.canvasGraph())}prune(e){return this.request("POST",se.canvasPrune(),e)}async request(e,n,r,i){try{let o=i===void 0?void 0:this.resolveBudget(i),s=await this.send(e,n,r,o);return await GI(s,o?.deadlineAt)}catch(o){throw xSn(e,mw(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw mw(i,r?.signal)}}async send(e,n,r,i={}){let o=this.resolveBudget(i),s=e==="GET"||e==="HEAD"||e==="DELETE",a=o.maxRetries??this.maxRetries,c=Math.min(o.deadlineAt??1/0,Date.now()+ASn);for(let u=0;;u++){let l;try{l=await this.transport(e,n,r,o)}catch(d){if(this.isColdSocketError(d)||this.isInterruptedSocketError(d)){let p=this.availabilityFailure?.();if(p!==void 0)throw p}if(this.isColdSocketError(d))try{await this.handleColdSocket(d,o.deadlineAt),l=await this.transport(e,n,r,o)}catch(p){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!yZe(p,o.signal)?tB(o.deadlineAt):mw(p,o.signal)}else{if(this.isInterruptedSocketError(d)&&this.localSocketTransport&&(!s||u<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&u<a&&!yZe(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await k6(AZe(u+1),o);continue}else throw mw(d,o.signal)}}if(ySn(e)&&a>0&&l.status===503&&await ESn(l,o.deadlineAt)){let d=Math.max(250,(EZe(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await jfe(l,o.deadlineAt),await k6(d,{signal:o.signal});continue}if(s&&u<a&&wSn(l.status)){await jfe(l,o.deadlineAt),await k6(AZe(u+1),o,EZe(l));continue}return l}}resolveBudget(e){let{budgetMs:n,deadlineAt:r,...i}=e;if(n===void 0&&r===void 0)return i;if(n!==void 0&&(!Number.isFinite(n)||n<=0||n>TF))throw new RangeError(`budgetMs must be a positive finite number of at most ${TF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>TF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${TF} ms from now`);return{...i,deadlineAt:Math.min(r??1/0,n===void 0?1/0:Date.now()+n)}}async awaitWithinBudget(e,n){if(n===void 0)return e;let r=n-Date.now();if(r<=0)throw kF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(kF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await GI(await this.transport(e,n,r,o))}catch(s){throw mw(s,o.signal)}}nodePath(e){if(!_6(e))throw new sn(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!fZe(e))throw new sn(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!gZe(e))throw new sn(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!_6(e))throw new sn(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!_6(e))throw new sn(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new sn(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,n,r,i={}){let o=i.deadlineAt===void 0?void 0:i.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(kF(i.deadlineAt));let s=r===void 0?void 0:JSON.stringify(r),a={accept:"application/json",...this.headers,...i.headers};s!==void 0&&(a["content-type"]="application/json");let c=i.timeout??this.timeoutMs,u=o===void 0?c:c>0?Math.min(c,o):o,l=new AbortController,d=o!==void 0&&(c<=0||o<=c),p=u>0?setTimeout(()=>l.abort(d?kF(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,h=i.signal,m=()=>l.abort(h?.reason);h!==void 0&&(h.aborted?l.abort(h.reason):h.addEventListener("abort",m,{once:!0}));let f=()=>{p!==void 0&&clearTimeout(p),h?.removeEventListener("abort",m)};return bSn(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>(mZe(g.headers.get("server-timing")),this.retainRequestLifetime(g,f,()=>l.signal.aborted?l.signal.reason:void 0)),g=>{throw f(),g})}retainRequestLifetime(e,n,r){if(e.body===null)return n(),e;let i=e.body.getReader(),o=!1,s=()=>{o||(o=!0,n())},a=new ReadableStream({async pull(c){try{let{done:u,value:l}=await i.read();u?(s(),c.close()):c.enqueue(l)}catch(u){s(),c.error(r()??u)}},async cancel(c){s(),await i.cancel(c)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){let n=zfe(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=zfe(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw mw(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new sn(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,n,r,i)}catch(o){throw mw(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw kF(n);let i,o;try{await T6({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:s=>s!==i&&s!==o,probe:async s=>{let a=this.availabilityFailure?.();if(a!==void 0)throw o=a,a;let c=this.coldStartFailure?.();if(c!==void 0)throw i=new sn(503,"daemon_unavailable",`crtrd failed to start: ${c}`),i;let u=await this.transport("GET",se.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await jfe(u);return}let l=await u.text();try{if(typeof JSON.parse(l).startup_blocked=="string")return}catch{}throw new sn(u.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${u.status}: ${l.slice(0,500)}`)}})}catch(s){throw s===i&&(this.startupFailureReported=!0),s}}async handleColdSocket(e,n){let r=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;r&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),n));try{await this.awaitAvailability(e,n)}catch(i){if(r&&!this.startupFailureReported){let o=CSn(this.coldStartDiagnostic);if(o!==void 0){let s=mw(i);throw new sn(s.status,s.code,`${s.message}
90
- ${o}`)}}throw i}}};ASn=6e4});function bZe(){return ISn??void 0}var ISn,CZe=y(()=>{"use strict";ISn=null});import{request as vSn}from"node:http";import{homedir as SSn}from"node:os";import{join as Vfe}from"node:path";function RSn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:Vfe(SSn(),_Sn);return Vfe(process.platform==="linux"?"/run/crtr":Vfe(n,"runtime"),kSn)}function BSn(t){let e=function(n,r={}){let i=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=r.method??"GET",s={};if(r.headers!==void 0)for(let[c,u]of new Headers(r.headers).entries())s[c]=u;let a=typeof r.body=="string"?r.body:void 0;return a!==void 0&&(s["content-length"]=String(Buffer.byteLength(a))),new Promise((c,u)=>{let l=vSn({socketPath:t,path:i.pathname+i.search,method:o,headers:s},h=>{let m=new ReadableStream({start(A){h.on("data",x=>A.enqueue(new Uint8Array(x))),h.on("end",()=>A.close()),h.on("error",x=>A.error(x))},cancel(){h.destroy()}}),f=new Headers;for(let[A,x]of Object.entries(h.headers))if(x!==void 0)for(let b of Array.isArray(x)?x:[x])f.append(A,b);let g=h.statusCode??0;c(new Response(g===204?null:m,{status:g,statusText:h.statusMessage,headers:f}))});l.on("error",h=>u(new TypeError("fetch failed",{cause:h})));let d=r.signal,p=()=>{l.destroy(),u(d?.reason??new DOMException("The operation was aborted.","AbortError"))};if(d!=null){if(d.aborted){p();return}d.addEventListener("abort",p,{once:!0})}a!==void 0&&l.write(a),l.end()})};return e[TSn]=!0,e}function fw(t={}){let{socketPath:e,...n}=t;return new Tg({baseUrl:"http://localhost",fetch:BSn(e??RSn()),autostart:!0,...n})}var _Sn,kSn,TSn,B6=y(()=>{"use strict";R6();_Sn=".crouter",kSn="api.sock",TSn=Symbol.for("@north-light/api/local-socket-fetch")});import{readFileSync as DSn}from"node:fs";import{dirname as MSn,join as IZe}from"node:path";import{fileURLToPath as PSn}from"node:url";function Kfe(){if(D6!==null)return D6;let t=IZe(MSn(PSn(import.meta.url)),"..","..");return D6=JSON.parse(DSn(IZe(t,"package.json"),"utf8")).version,D6}var D6,Yfe=y(()=>{"use strict";D6=null});var vZe=y(()=>{"use strict";BF();hw()});var Xfe=Q(SZe=>{"use strict";SZe.parse=function(t,e){return new Jfe(t,e).parse()};var Jfe=class t{constructor(e,n){this.source=e,this.transform=n||NSn,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var n;(this.recorded.length>0||e)&&(n=this.recorded.join(""),n==="NULL"&&!e&&(n=null),n!==null&&(n=this.transform(n)),this.entries.push(n),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var n,r,i;for(this.consumeDimensions();!this.isEof();)if(n=this.nextCharacter(),n.value==="{"&&!i)this.dimension++,this.dimension>1&&(r=new t(this.source.substr(this.position-1),this.transform),this.entries.push(r.parse(!0)),this.position+=r.position-2);else if(n.value==="}"&&!i){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else n.value==='"'&&!n.escaped?(i&&this.newEntry(!0),i=!i):n.value===","&&!i?this.newEntry():this.record(n.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};function NSn(t){return t}});var Zfe=Q((dwi,_Ze)=>{var LSn=Xfe();_Ze.exports={create:function(t,e){return{parse:function(){return LSn.parse(t,e)}}}}});var RZe=Q((pwi,TZe)=>{"use strict";var QSn=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,OSn=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,FSn=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,USn=/^-?infinity$/;TZe.exports=function(e){if(USn.test(e))return Number(e.replace("i","I"));var n=QSn.exec(e);if(!n)return $Sn(e)||null;var r=!!n[8],i=parseInt(n[1],10);r&&(i=kZe(i));var o=parseInt(n[2],10)-1,s=n[3],a=parseInt(n[4],10),c=parseInt(n[5],10),u=parseInt(n[6],10),l=n[7];l=l?1e3*parseFloat(l):0;var d,p=WSn(e);return p!=null?(d=new Date(Date.UTC(i,o,s,a,c,u,l)),ege(i)&&d.setUTCFullYear(i),p!==0&&d.setTime(d.getTime()-p)):(d=new Date(i,o,s,a,c,u,l),ege(i)&&d.setFullYear(i)),d};function $Sn(t){var e=OSn.exec(t);if(e){var n=parseInt(e[1],10),r=!!e[4];r&&(n=kZe(n));var i=parseInt(e[2],10)-1,o=e[3],s=new Date(n,i,o);return ege(n)&&s.setFullYear(n),s}}function WSn(t){if(t.endsWith("+00"))return 0;var e=FSn.exec(t.split(" ")[1]);if(e){var n=e[1];if(n==="Z")return 0;var r=n==="-"?-1:1,i=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return i*r*1e3}}function kZe(t){return-(t-1)}function ege(t){return t>=0&&t<100}});var DZe=Q((hwi,BZe)=>{BZe.exports=GSn;var HSn=Object.prototype.hasOwnProperty;function GSn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)HSn.call(n,r)&&(t[r]=n[r])}return t}});var NZe=Q((mwi,PZe)=>{"use strict";var qSn=DZe();PZe.exports=nB;function nB(t){if(!(this instanceof nB))return new nB(t);qSn(this,r_n(t))}var jSn=["seconds","minutes","hours","days","months","years"];nB.prototype.toPostgres=function(){var t=jSn.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var n=this[e]||0;return e==="seconds"&&this.milliseconds&&(n=(n+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),n+" "+e},this).join(" ")};var zSn={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},VSn=["years","months","days"],KSn=["hours","minutes","seconds"];nB.prototype.toISOString=nB.prototype.toISO=function(){var t=VSn.map(n,this).join(""),e=KSn.map(n,this).join("");return"P"+t+"T"+e;function n(r){var i=this[r]||0;return r==="seconds"&&this.milliseconds&&(i=(i+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),i+zSn[r]}};var tge="([+-]?\\d+)",YSn=tge+"\\s+years?",JSn=tge+"\\s+mons?",XSn=tge+"\\s+days?",ZSn="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",e_n=new RegExp([YSn,JSn,XSn,ZSn].map(function(t){return"("+t+")?"}).join("\\s*")),MZe={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},t_n=["hours","minutes","seconds","milliseconds"];function n_n(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}function r_n(t){if(!t)return{};var e=e_n.exec(t),n=e[8]==="-";return Object.keys(MZe).reduce(function(r,i){var o=MZe[i],s=e[o];return!s||(s=i==="milliseconds"?n_n(s):parseInt(s,10),!s)||(n&&~t_n.indexOf(i)&&(s*=-1),r[i]=s),r},{})}});var OZe=Q((fwi,QZe)=>{"use strict";var LZe=Buffer.from||Buffer;QZe.exports=function(e){if(/^\\x/.test(e))return LZe(e.substr(2),"hex");for(var n="",r=0;r<e.length;)if(e[r]!=="\\")n+=e[r],++r;else if(/[0-7]{3}/.test(e.substr(r+1,3)))n+=String.fromCharCode(parseInt(e.substr(r+1,3),8)),r+=4;else{for(var i=1;r+i<e.length&&e[r+i]==="\\";)i++;for(var o=0;o<Math.floor(i/2);++o)n+="\\";r+=Math.floor(i/2)*2}return LZe(n,"binary")}});var qZe=Q((gwi,GZe)=>{var DF=Xfe(),MF=Zfe(),M6=RZe(),UZe=NZe(),$Ze=OZe();function P6(t){return function(n){return n===null?n:t(n)}}function WZe(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}function i_n(t){return t?DF.parse(t,WZe):null}function o_n(t){return parseInt(t,10)}function nge(t){return t?DF.parse(t,P6(o_n)):null}function s_n(t){return t?DF.parse(t,P6(function(e){return HZe(e).trim()})):null}var a_n=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=sge(n)),n});return e.parse()},rge=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=parseFloat(n)),n});return e.parse()},ph=function(t){if(!t)return null;var e=MF.create(t);return e.parse()},ige=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=M6(n)),n});return e.parse()},c_n=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=UZe(n)),n});return e.parse()},u_n=function(t){return t?DF.parse(t,P6($Ze)):null},oge=function(t){return parseInt(t,10)},HZe=function(t){var e=String(t);return/^\d+$/.test(e)?e:t},FZe=function(t){return t?DF.parse(t,P6(JSON.parse)):null},sge=function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},l_n=function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",n="",r=!1,i=2;i<t.length-1;i++){if(r||(e+=t[i]),t[i]===")"){r=!0;continue}else if(!r)continue;t[i]!==","&&(n+=t[i])}var o=sge(e);return o.radius=parseFloat(n),o},d_n=function(t){t(20,HZe),t(21,oge),t(23,oge),t(26,oge),t(700,parseFloat),t(701,parseFloat),t(16,WZe),t(1082,M6),t(1114,M6),t(1184,M6),t(600,sge),t(651,ph),t(718,l_n),t(1e3,i_n),t(1001,u_n),t(1005,nge),t(1007,nge),t(1028,nge),t(1016,s_n),t(1017,a_n),t(1021,rge),t(1022,rge),t(1231,rge),t(1014,ph),t(1015,ph),t(1008,ph),t(1009,ph),t(1040,ph),t(1041,ph),t(1115,ige),t(1182,ige),t(1185,ige),t(1186,UZe),t(1187,c_n),t(17,$Ze),t(114,JSON.parse.bind(JSON)),t(3802,JSON.parse.bind(JSON)),t(199,FZe),t(3807,FZe),t(3907,ph),t(2951,ph),t(791,ph),t(1183,ph),t(1270,ph)};GZe.exports={init:d_n}});var zZe=Q((Awi,jZe)=>{"use strict";var $l=1e6;function p_n(t){var e=t.readInt32BE(0),n=t.readUInt32BE(4),r="";e<0&&(e=~e+(n===0),n=~n+1>>>0,r="-");var i="",o,s,a,c,u,l;{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}return o=e%$l,s=4294967296*o+n,a=""+s%$l,r+a+i}jZe.exports=p_n});var XZe=Q((ywi,JZe)=>{var h_n=zZe(),ss=function(t,e,n,r,i){n=n||0,r=r||!1,i=i||function(h,m,f){return h*Math.pow(2,f)+m};var o=n>>3,s=function(h){return r?~h&255:h},a=255,c=8-n%8;e<c&&(a=255<<8-e&255,c=e),n&&(a=a>>n%8);var u=0;n%8+e>=8&&(u=i(0,s(t[o])&a,c));for(var l=e+n>>3,d=o+1;d<l;d++)u=i(u,s(t[d]),8);var p=(e+n)%8;return p>0&&(u=i(u,s(t[l])>>8-p,p)),u},YZe=function(t,e,n){var r=Math.pow(2,n-1)-1,i=ss(t,1),o=ss(t,n,1);if(o===0)return 0;var s=1,a=function(u,l,d){u===0&&(u=1);for(var p=1;p<=d;p++)s/=2,(l&1<<d-p)>0&&(u+=s);return u},c=ss(t,e,n+1,!1,a);return o==Math.pow(2,n+1)-1?c===0?i===0?1/0:-1/0:NaN:(i===0?1:-1)*Math.pow(2,o-r)*c},m_n=function(t){return ss(t,1)==1?-1*(ss(t,15,1,!0)+1):ss(t,15,1)},VZe=function(t){return ss(t,1)==1?-1*(ss(t,31,1,!0)+1):ss(t,31,1)},f_n=function(t){return YZe(t,23,8)},g_n=function(t){return YZe(t,52,11)},A_n=function(t){var e=ss(t,16,32);if(e==49152)return NaN;for(var n=Math.pow(1e4,ss(t,16,16)),r=0,i=[],o=ss(t,16),s=0;s<o;s++)r+=ss(t,16,64+16*s)*n,n/=1e4;var a=Math.pow(10,ss(t,16,48));return(e===0?1:-1)*Math.round(r*a)/a},KZe=function(t,e){var n=ss(e,1),r=ss(e,63,1),i=new Date((n===0?1:-1)*r/1e3+9466848e5);return t||i.setTime(i.getTime()+i.getTimezoneOffset()*6e4),i.usec=r%1e3,i.getMicroSeconds=function(){return this.usec},i.setMicroSeconds=function(o){this.usec=o},i.getUTCMicroSeconds=function(){return this.usec},i},PF=function(t){for(var e=ss(t,32),n=ss(t,32,32),r=ss(t,32,64),i=96,o=[],s=0;s<e;s++)o[s]=ss(t,32,i),i+=32,i+=32;var a=function(u){var l=ss(t,32,i);if(i+=32,l==4294967295)return null;var d;if(u==23||u==20)return d=ss(t,l*8,i),i+=l*8,d;if(u==25)return d=t.toString(this.encoding,i>>3,(i+=l<<3)>>3),d;console.log("ERROR: ElementType not implemented: "+u)},c=function(u,l){var d=[],p;if(u.length>1){var h=u.shift();for(p=0;p<h;p++)d[p]=c(u,l);u.unshift(h)}else for(p=0;p<u[0];p++)d[p]=a(l);return d};return c(o,r)},y_n=function(t){return t.toString("utf8")},E_n=function(t){return t===null?null:ss(t,8)>0},w_n=function(t){t(20,h_n),t(21,m_n),t(23,VZe),t(26,VZe),t(1700,A_n),t(700,f_n),t(701,g_n),t(16,E_n),t(1114,KZe.bind(null,!1)),t(1184,KZe.bind(null,!0)),t(1e3,PF),t(1007,PF),t(1016,PF),t(1008,PF),t(1009,PF),t(25,y_n)};JZe.exports={init:w_n}});var eet=Q((Ewi,ZZe)=>{ZZe.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var QF=Q(LF=>{var x_n=qZe(),b_n=XZe(),C_n=Zfe(),I_n=eet();LF.getTypeParser=v_n;LF.setTypeParser=S_n;LF.arrayParser=C_n;LF.builtins=I_n;var NF={text:{},binary:{}};function tet(t){return String(t)}function v_n(t,e){return e=e||"text",NF[e]&&NF[e][t]||tet}function S_n(t,e,n){typeof e=="function"&&(n=e,e="text"),NF[e][t]=n}x_n.init(function(t,e){NF.text[t]=e});b_n.init(function(t,e){NF.binary[t]=e})});var OF=Q((xwi,age)=>{"use strict";var net;try{net=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}age.exports={host:"localhost",user:net,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,sslnegotiation:void 0,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var rB=QF(),__n=rB.getTypeParser(20,"text"),k_n=rB.getTypeParser(1016,"text");age.exports.__defineSetter__("parseInt8",function(t){rB.setTypeParser(20,"text",t?rB.getTypeParser(23,"text"):__n),rB.setTypeParser(1016,"text",t?rB.getTypeParser(1007,"text"):k_n)})});var qI=Q((bwi,iet)=>{"use strict";var T_n=OF(),R_n=K("util"),{isDate:B_n}=K("util/types"),D_n=R_n.deprecate(()=>{},"Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.","PG_INVALID_DATE");function M_n(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function ret(t){let e="{";for(let n=0;n<t.length;n++){n>0&&(e+=",");let r=t[n];r==null?e+="NULL":Array.isArray(r)?e+=ret(r):ArrayBuffer.isView(r)?(r instanceof Buffer||(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),e+="\\\\x"+r.toString("hex")):e+=M_n(N6(r))}return e+="}",e}var N6=function(t,e){return t==null?null:typeof t=="object"?t instanceof Buffer?t:ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):B_n(t)?(isNaN(t.getTime())&&D_n(),T_n.parseInputDatesAsUTC?L_n(t):N_n(t)):Array.isArray(t)?ret(t):P_n(t,e):t.toString()};function P_n(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),N6(t.toPostgres(N6),e)}return JSON.stringify(t)}function N_n(t){let e=-t.getTimezoneOffset(),n=t.getFullYear(),r=n<1;r&&(n=Math.abs(n)+1);let i=String(n).padStart(4,"0")+"-"+String(t.getMonth()+1).padStart(2,"0")+"-"+String(t.getDate()).padStart(2,"0")+"T"+String(t.getHours()).padStart(2,"0")+":"+String(t.getMinutes()).padStart(2,"0")+":"+String(t.getSeconds()).padStart(2,"0")+"."+String(t.getMilliseconds()).padStart(3,"0");return e<0?(i+="-",e*=-1):i+="+",i+=String(Math.floor(e/60)).padStart(2,"0")+":"+String(e%60).padStart(2,"0"),r&&(i+=" BC"),i}function L_n(t){let e=t.getUTCFullYear(),n=e<1;n&&(e=Math.abs(e)+1);let r=String(e).padStart(4,"0")+"-"+String(t.getUTCMonth()+1).padStart(2,"0")+"-"+String(t.getUTCDate()).padStart(2,"0")+"T"+String(t.getUTCHours()).padStart(2,"0")+":"+String(t.getUTCMinutes()).padStart(2,"0")+":"+String(t.getUTCSeconds()).padStart(2,"0")+"."+String(t.getUTCMilliseconds()).padStart(3,"0");return r+="+00:00",n&&(r+=" BC"),r}function Q_n(t,e,n){return t=typeof t=="string"?{text:t}:O_n(t),e&&(typeof e=="function"?t.callback=e:t.values=e),n&&(t.callback=n),t}function O_n(t){return t==null?t:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),Object.getOwnPropertyDescriptors(t))}var F_n=function(t){return'"'+t.replace(/"/g,'""')+'"'},U_n=function(t){let e=!1,n="'";if(t==null||typeof t!="string")return"''";for(let r=0;r<t.length;r++){let i=t[r];i==="'"?n+=i+i:i==="\\"?(n+=i+i,e=!0):n+=i}return n+="'",e===!0&&(n=" E"+n),n};iet.exports={prepareValue:function(e){return N6(e)},normalizeQueryConfig:Q_n,escapeIdentifier:F_n,escapeLiteral:U_n}});var lge=Q((Cwi,aet)=>{var oet=K("crypto");aet.exports={postgresMd5PasswordHash:W_n,randomBytes:$_n,deriveKey:j_n,sha256:H_n,hashByName:G_n,hmacSha256:q_n,md5:cge};var set=oet.webcrypto||globalThis.crypto,jI=set.subtle,uge=new TextEncoder;function $_n(t){return set.getRandomValues(Buffer.alloc(t))}async function cge(t){try{return oet.createHash("md5").update(t,"utf-8").digest("hex")}catch{let n=typeof t=="string"?uge.encode(t):t,r=await jI.digest("MD5",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}}async function W_n(t,e,n){let r=await cge(e+t);return"md5"+await cge(Buffer.concat([Buffer.from(r),n]))}async function H_n(t){return await jI.digest("SHA-256",t)}async function G_n(t,e){return await jI.digest(t,e)}async function q_n(t,e){let n=await jI.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await jI.sign("HMAC",n,uge.encode(e))}async function j_n(t,e,n){let r=await jI.importKey("raw",uge.encode(t),"PBKDF2",!1,["deriveBits"]),i={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:n};return await jI.deriveBits(i,r,256,["deriveBits"])}});var det=Q((Iwi,uet)=>{function zI(t,e){return new Error("SASL channel binding: "+t+" when parsing public certificate "+e.toString("base64"))}function dge(t,e){let n=t[e++];if(n<128)return{length:n,index:e};let r=n&127;if(r>4)throw zI("bad length",t);n=0;for(let i=0;i<r;i++)n=n<<8|t[e++];return{length:n,index:e}}function cet(t,e){if(t[e++]!==6)throw zI("non-OID data",t);let{length:n,index:r}=dge(t,e);e=r;let i=e+n,o=t[e++],s=(o/40>>0)+"."+o%40;for(;e<i;){let a=0;for(;e<i;){let c=t[e++];if(a=a<<7|c&127,c<128)break}s+="."+a}return{oid:s,index:e}}function FF(t,e){if(t[e++]!==48)throw zI("non-sequence data",t);return dge(t,e)}function z_n(t,e){e===void 0&&(e=0),e=FF(t,e).index;let{length:n,index:r}=FF(t,e);e=r+n,e=FF(t,e).index;let{oid:i,index:o}=cet(t,e);switch(i){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(e=o,e=FF(t,e).index,t[e++]!==160)throw zI("non-tag data",t);e=dge(t,e).index,e=FF(t,e).index;let{oid:s}=cet(t,e);switch(s){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw zI("unknown hash OID "+s,t)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw zI("Ed448 certificate channel binding is not currently supported by Postgres")}throw zI("unknown OID "+i,t)}uet.exports={signatureAlgorithmHashFromCertificate:z_n}});var fet=Q((vwi,met)=>{"use strict";var gw=lge(),{signatureAlgorithmHashFromCertificate:V_n}=det();function K_n(t){let e=/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g,n=/[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g;return t.replace(e," ").replace(n,"").normalize("NFKC")}var pge=1e5;function Y_n(t,e,n=pge){let r=["SCRAM-SHA-256"];e&&r.unshift("SCRAM-SHA-256-PLUS");let i=r.find(a=>t.includes(a));if(!i)throw new Error("SASL: Only mechanism(s) "+r.join(" and ")+" are supported");if(i==="SCRAM-SHA-256-PLUS"&&typeof e.getPeerCertificate!="function")throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let o=gw.randomBytes(18).toString("base64");return{mechanism:i,clientNonce:o,response:(i==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":e?"y":"n")+",,n=*,r="+o,message:"SASLInitialResponse",scramMaxIterations:n}}async function J_n(t,e,n,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof n!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let i=ekn(n);if(i.nonce.startsWith(t.clientNonce)){if(i.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");let o=typeof t.scramMaxIterations=="number"?t.scramMaxIterations:pge;if(o!==0&&i.iteration>o)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count "+i.iteration+" exceeds scramMaxIterations of "+o);let s="n=*,r="+t.clientNonce,a="r="+i.nonce+",s="+i.salt+",i="+i.iteration,c=r?"eSws":"biws";if(t.mechanism==="SCRAM-SHA-256-PLUS"){let b=r.getPeerCertificate().raw,v=V_n(b);(v==="MD5"||v==="SHA-1")&&(v="SHA-256");let S=await gw.hashByName(v,b);c=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(S)]).toString("base64")}let u="c="+c+",r="+i.nonce,l=s+","+a+","+u,d=Buffer.from(i.salt,"base64"),p=await gw.deriveKey(K_n(e),d,i.iteration),h=await gw.hmacSha256(p,"Client Key"),m=await gw.sha256(h),f=await gw.hmacSha256(m,l),g=nkn(Buffer.from(h),Buffer.from(f)).toString("base64"),A=await gw.hmacSha256(p,"Server Key"),x=await gw.hmacSha256(A,l);t.message="SASLResponse",t.serverSignature=Buffer.from(x).toString("base64"),t.response=u+",p="+g}function X_n(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:n}=tkn(e);if(n!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function Z_n(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,n)=>t.charCodeAt(n)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function pet(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}function het(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let n=e[0],r=e.substring(2);return[n,r]}))}function ekn(t){let e=het(t),n=e.get("r");if(n){if(!Z_n(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let r=e.get("s");if(r){if(!pet(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let i=e.get("i");if(i){if(!/^[1-9][0-9]*$/.test(i))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let o=parseInt(i,10);return{nonce:n,salt:r,iteration:o}}function tkn(t){let e=het(t),n=e.get("e"),r=e.get("v");if(n)throw new Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${n}"`);if(r){if(!pet(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}function nkn(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((n,r)=>t[r]^e[r]))}met.exports={startSession:Y_n,continueSession:J_n,finalizeSession:X_n,DEFAULT_MAX_SCRAM_ITERATIONS:pge}});var Q6=Q((Swi,get)=>{"use strict";var rkn=QF();function L6(t){this._types=t||rkn,this.text={},this.binary={}}L6.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};L6.prototype.setTypeParser=function(t,e,n){typeof e=="function"&&(n=e,e="text"),this.getOverrides(e)[t]=n};L6.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};get.exports=L6});var Eet=Q((_wi,yet)=>{"use strict";function iB(t,e={}){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let n=Object.create(null),r,i=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/%25(\d\d)/g,"%$1"));try{try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),i=!0}}catch(c){throw c.input&&(c.input="*****REDACTED*****"),c}for(let c of r.searchParams.entries())n[c[0]]=c[1];if(n.user=n.user||decodeURIComponent(r.username),n.password=n.password||decodeURIComponent(r.password),r.protocol=="socket:")return n.host=decodeURI(r.pathname),n.database=r.searchParams.get("db"),n.client_encoding=r.searchParams.get("encoding"),n;let o=(i?"":r.hostname).replace(/^\[(.+)\]$/,"$1");n.host?o&&/^%2f/i.test(o)&&(r.pathname=o+r.pathname):n.host=decodeURIComponent(o),n.port||(n.port=r.port);let s=r.pathname.slice(1)||null;n.database=s?decodeURI(s):null,(n.ssl==="true"||n.ssl==="1")&&(n.ssl=!0),n.ssl==="0"&&(n.ssl=!1),(n.sslcert||n.sslkey||n.sslrootcert||n.sslmode)&&(n.ssl={}),n.sslnegotiation==="direct"&&n.ssl===void 0&&(n.ssl=!0);let a=n.sslcert||n.sslkey||n.sslrootcert?K("fs"):null;if(n.sslcert&&(n.ssl.cert=a.readFileSync(n.sslcert).toString()),n.sslkey&&(n.ssl.key=a.readFileSync(n.sslkey).toString()),n.sslrootcert&&(n.ssl.ca=a.readFileSync(n.sslrootcert).toString()),e.useLibpqCompat&&n.uselibpqcompat)throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(n.uselibpqcompat==="true"||e.useLibpqCompat)switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":{n.ssl.rejectUnauthorized=!1;break}case"require":{n.sslrootcert?n.ssl.checkServerIdentity=function(){}:n.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!n.ssl.ca)throw new Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");n.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{n.sslmode!=="verify-full"&&hge(n.sslmode);break}case"no-verify":{n.ssl.rejectUnauthorized=!1;break}}return n}function ikn(t){return Object.entries(t).reduce((n,[r,i])=>(i!=null&&(n[r]=i),n),Object.create(null))}function Aet(t){return Object.entries(t).reduce((n,[r,i])=>{if(r==="ssl"){let o=i;typeof o=="boolean"&&(n[r]=o),typeof o=="object"&&(n[r]=ikn(o))}else if(i!=null)if(r==="port"){if(i!==""){let o=parseInt(i,10);if(isNaN(o))throw new Error(`Invalid ${r}: ${i}`);n[r]=o}}else n[r]=i;return n},Object.create(null))}function okn(t){return Aet(iB(t))}function hge(t){!hge.warned&&typeof process<"u"&&process.emitWarning&&(hge.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
90
+ ${o}`)}}throw i}}};ASn=6e4});function bZe(){return ISn??void 0}var ISn,CZe=y(()=>{"use strict";ISn=null});import{request as vSn}from"node:http";import{homedir as SSn}from"node:os";import{join as Vfe}from"node:path";function RSn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:Vfe(SSn(),_Sn);return Vfe(process.platform==="linux"?"/run/crtr":Vfe(n,"runtime"),kSn)}function BSn(t){let e=function(n,r={}){let i=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=r.method??"GET",s={};if(r.headers!==void 0)for(let[c,u]of new Headers(r.headers).entries())s[c]=u;let a=typeof r.body=="string"?r.body:void 0;return a!==void 0&&(s["content-length"]=String(Buffer.byteLength(a))),new Promise((c,u)=>{let l=vSn({socketPath:t,path:i.pathname+i.search,method:o,headers:s,agent:!1},h=>{let m=new ReadableStream({start(A){h.on("data",x=>A.enqueue(new Uint8Array(x))),h.on("end",()=>A.close()),h.on("error",x=>A.error(x))},cancel(){h.destroy()}}),f=new Headers;for(let[A,x]of Object.entries(h.headers))if(x!==void 0)for(let b of Array.isArray(x)?x:[x])f.append(A,b);let g=h.statusCode??0;c(new Response(g===204?null:m,{status:g,statusText:h.statusMessage,headers:f}))});l.on("error",h=>u(new TypeError("fetch failed",{cause:h})));let d=r.signal,p=()=>{l.destroy(),u(d?.reason??new DOMException("The operation was aborted.","AbortError"))};if(d!=null){if(d.aborted){p();return}d.addEventListener("abort",p,{once:!0})}a!==void 0&&l.write(a),l.end()})};return e[TSn]=!0,e}function fw(t={}){let{socketPath:e,...n}=t;return new Tg({baseUrl:"http://localhost",fetch:BSn(e??RSn()),autostart:!0,...n})}var _Sn,kSn,TSn,B6=y(()=>{"use strict";R6();_Sn=".crouter",kSn="api.sock",TSn=Symbol.for("@north-light/api/local-socket-fetch")});import{readFileSync as DSn}from"node:fs";import{dirname as MSn,join as IZe}from"node:path";import{fileURLToPath as PSn}from"node:url";function Kfe(){if(D6!==null)return D6;let t=IZe(MSn(PSn(import.meta.url)),"..","..");return D6=JSON.parse(DSn(IZe(t,"package.json"),"utf8")).version,D6}var D6,Yfe=y(()=>{"use strict";D6=null});var vZe=y(()=>{"use strict";BF();hw()});var Xfe=Q(SZe=>{"use strict";SZe.parse=function(t,e){return new Jfe(t,e).parse()};var Jfe=class t{constructor(e,n){this.source=e,this.transform=n||NSn,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var n;(this.recorded.length>0||e)&&(n=this.recorded.join(""),n==="NULL"&&!e&&(n=null),n!==null&&(n=this.transform(n)),this.entries.push(n),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var n,r,i;for(this.consumeDimensions();!this.isEof();)if(n=this.nextCharacter(),n.value==="{"&&!i)this.dimension++,this.dimension>1&&(r=new t(this.source.substr(this.position-1),this.transform),this.entries.push(r.parse(!0)),this.position+=r.position-2);else if(n.value==="}"&&!i){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else n.value==='"'&&!n.escaped?(i&&this.newEntry(!0),i=!i):n.value===","&&!i?this.newEntry():this.record(n.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};function NSn(t){return t}});var Zfe=Q((dwi,_Ze)=>{var LSn=Xfe();_Ze.exports={create:function(t,e){return{parse:function(){return LSn.parse(t,e)}}}}});var RZe=Q((pwi,TZe)=>{"use strict";var QSn=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,OSn=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,FSn=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,USn=/^-?infinity$/;TZe.exports=function(e){if(USn.test(e))return Number(e.replace("i","I"));var n=QSn.exec(e);if(!n)return $Sn(e)||null;var r=!!n[8],i=parseInt(n[1],10);r&&(i=kZe(i));var o=parseInt(n[2],10)-1,s=n[3],a=parseInt(n[4],10),c=parseInt(n[5],10),u=parseInt(n[6],10),l=n[7];l=l?1e3*parseFloat(l):0;var d,p=WSn(e);return p!=null?(d=new Date(Date.UTC(i,o,s,a,c,u,l)),ege(i)&&d.setUTCFullYear(i),p!==0&&d.setTime(d.getTime()-p)):(d=new Date(i,o,s,a,c,u,l),ege(i)&&d.setFullYear(i)),d};function $Sn(t){var e=OSn.exec(t);if(e){var n=parseInt(e[1],10),r=!!e[4];r&&(n=kZe(n));var i=parseInt(e[2],10)-1,o=e[3],s=new Date(n,i,o);return ege(n)&&s.setFullYear(n),s}}function WSn(t){if(t.endsWith("+00"))return 0;var e=FSn.exec(t.split(" ")[1]);if(e){var n=e[1];if(n==="Z")return 0;var r=n==="-"?-1:1,i=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return i*r*1e3}}function kZe(t){return-(t-1)}function ege(t){return t>=0&&t<100}});var DZe=Q((hwi,BZe)=>{BZe.exports=GSn;var HSn=Object.prototype.hasOwnProperty;function GSn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)HSn.call(n,r)&&(t[r]=n[r])}return t}});var NZe=Q((mwi,PZe)=>{"use strict";var qSn=DZe();PZe.exports=nB;function nB(t){if(!(this instanceof nB))return new nB(t);qSn(this,r_n(t))}var jSn=["seconds","minutes","hours","days","months","years"];nB.prototype.toPostgres=function(){var t=jSn.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var n=this[e]||0;return e==="seconds"&&this.milliseconds&&(n=(n+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),n+" "+e},this).join(" ")};var zSn={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},VSn=["years","months","days"],KSn=["hours","minutes","seconds"];nB.prototype.toISOString=nB.prototype.toISO=function(){var t=VSn.map(n,this).join(""),e=KSn.map(n,this).join("");return"P"+t+"T"+e;function n(r){var i=this[r]||0;return r==="seconds"&&this.milliseconds&&(i=(i+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),i+zSn[r]}};var tge="([+-]?\\d+)",YSn=tge+"\\s+years?",JSn=tge+"\\s+mons?",XSn=tge+"\\s+days?",ZSn="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",e_n=new RegExp([YSn,JSn,XSn,ZSn].map(function(t){return"("+t+")?"}).join("\\s*")),MZe={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},t_n=["hours","minutes","seconds","milliseconds"];function n_n(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}function r_n(t){if(!t)return{};var e=e_n.exec(t),n=e[8]==="-";return Object.keys(MZe).reduce(function(r,i){var o=MZe[i],s=e[o];return!s||(s=i==="milliseconds"?n_n(s):parseInt(s,10),!s)||(n&&~t_n.indexOf(i)&&(s*=-1),r[i]=s),r},{})}});var OZe=Q((fwi,QZe)=>{"use strict";var LZe=Buffer.from||Buffer;QZe.exports=function(e){if(/^\\x/.test(e))return LZe(e.substr(2),"hex");for(var n="",r=0;r<e.length;)if(e[r]!=="\\")n+=e[r],++r;else if(/[0-7]{3}/.test(e.substr(r+1,3)))n+=String.fromCharCode(parseInt(e.substr(r+1,3),8)),r+=4;else{for(var i=1;r+i<e.length&&e[r+i]==="\\";)i++;for(var o=0;o<Math.floor(i/2);++o)n+="\\";r+=Math.floor(i/2)*2}return LZe(n,"binary")}});var qZe=Q((gwi,GZe)=>{var DF=Xfe(),MF=Zfe(),M6=RZe(),UZe=NZe(),$Ze=OZe();function P6(t){return function(n){return n===null?n:t(n)}}function WZe(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}function i_n(t){return t?DF.parse(t,WZe):null}function o_n(t){return parseInt(t,10)}function nge(t){return t?DF.parse(t,P6(o_n)):null}function s_n(t){return t?DF.parse(t,P6(function(e){return HZe(e).trim()})):null}var a_n=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=sge(n)),n});return e.parse()},rge=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=parseFloat(n)),n});return e.parse()},ph=function(t){if(!t)return null;var e=MF.create(t);return e.parse()},ige=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=M6(n)),n});return e.parse()},c_n=function(t){if(!t)return null;var e=MF.create(t,function(n){return n!==null&&(n=UZe(n)),n});return e.parse()},u_n=function(t){return t?DF.parse(t,P6($Ze)):null},oge=function(t){return parseInt(t,10)},HZe=function(t){var e=String(t);return/^\d+$/.test(e)?e:t},FZe=function(t){return t?DF.parse(t,P6(JSON.parse)):null},sge=function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},l_n=function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",n="",r=!1,i=2;i<t.length-1;i++){if(r||(e+=t[i]),t[i]===")"){r=!0;continue}else if(!r)continue;t[i]!==","&&(n+=t[i])}var o=sge(e);return o.radius=parseFloat(n),o},d_n=function(t){t(20,HZe),t(21,oge),t(23,oge),t(26,oge),t(700,parseFloat),t(701,parseFloat),t(16,WZe),t(1082,M6),t(1114,M6),t(1184,M6),t(600,sge),t(651,ph),t(718,l_n),t(1e3,i_n),t(1001,u_n),t(1005,nge),t(1007,nge),t(1028,nge),t(1016,s_n),t(1017,a_n),t(1021,rge),t(1022,rge),t(1231,rge),t(1014,ph),t(1015,ph),t(1008,ph),t(1009,ph),t(1040,ph),t(1041,ph),t(1115,ige),t(1182,ige),t(1185,ige),t(1186,UZe),t(1187,c_n),t(17,$Ze),t(114,JSON.parse.bind(JSON)),t(3802,JSON.parse.bind(JSON)),t(199,FZe),t(3807,FZe),t(3907,ph),t(2951,ph),t(791,ph),t(1183,ph),t(1270,ph)};GZe.exports={init:d_n}});var zZe=Q((Awi,jZe)=>{"use strict";var $l=1e6;function p_n(t){var e=t.readInt32BE(0),n=t.readUInt32BE(4),r="";e<0&&(e=~e+(n===0),n=~n+1>>>0,r="-");var i="",o,s,a,c,u,l;{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%$l,e=e/$l>>>0,s=4294967296*o+n,n=s/$l>>>0,a=""+(s-$l*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}return o=e%$l,s=4294967296*o+n,a=""+s%$l,r+a+i}jZe.exports=p_n});var XZe=Q((ywi,JZe)=>{var h_n=zZe(),ss=function(t,e,n,r,i){n=n||0,r=r||!1,i=i||function(h,m,f){return h*Math.pow(2,f)+m};var o=n>>3,s=function(h){return r?~h&255:h},a=255,c=8-n%8;e<c&&(a=255<<8-e&255,c=e),n&&(a=a>>n%8);var u=0;n%8+e>=8&&(u=i(0,s(t[o])&a,c));for(var l=e+n>>3,d=o+1;d<l;d++)u=i(u,s(t[d]),8);var p=(e+n)%8;return p>0&&(u=i(u,s(t[l])>>8-p,p)),u},YZe=function(t,e,n){var r=Math.pow(2,n-1)-1,i=ss(t,1),o=ss(t,n,1);if(o===0)return 0;var s=1,a=function(u,l,d){u===0&&(u=1);for(var p=1;p<=d;p++)s/=2,(l&1<<d-p)>0&&(u+=s);return u},c=ss(t,e,n+1,!1,a);return o==Math.pow(2,n+1)-1?c===0?i===0?1/0:-1/0:NaN:(i===0?1:-1)*Math.pow(2,o-r)*c},m_n=function(t){return ss(t,1)==1?-1*(ss(t,15,1,!0)+1):ss(t,15,1)},VZe=function(t){return ss(t,1)==1?-1*(ss(t,31,1,!0)+1):ss(t,31,1)},f_n=function(t){return YZe(t,23,8)},g_n=function(t){return YZe(t,52,11)},A_n=function(t){var e=ss(t,16,32);if(e==49152)return NaN;for(var n=Math.pow(1e4,ss(t,16,16)),r=0,i=[],o=ss(t,16),s=0;s<o;s++)r+=ss(t,16,64+16*s)*n,n/=1e4;var a=Math.pow(10,ss(t,16,48));return(e===0?1:-1)*Math.round(r*a)/a},KZe=function(t,e){var n=ss(e,1),r=ss(e,63,1),i=new Date((n===0?1:-1)*r/1e3+9466848e5);return t||i.setTime(i.getTime()+i.getTimezoneOffset()*6e4),i.usec=r%1e3,i.getMicroSeconds=function(){return this.usec},i.setMicroSeconds=function(o){this.usec=o},i.getUTCMicroSeconds=function(){return this.usec},i},PF=function(t){for(var e=ss(t,32),n=ss(t,32,32),r=ss(t,32,64),i=96,o=[],s=0;s<e;s++)o[s]=ss(t,32,i),i+=32,i+=32;var a=function(u){var l=ss(t,32,i);if(i+=32,l==4294967295)return null;var d;if(u==23||u==20)return d=ss(t,l*8,i),i+=l*8,d;if(u==25)return d=t.toString(this.encoding,i>>3,(i+=l<<3)>>3),d;console.log("ERROR: ElementType not implemented: "+u)},c=function(u,l){var d=[],p;if(u.length>1){var h=u.shift();for(p=0;p<h;p++)d[p]=c(u,l);u.unshift(h)}else for(p=0;p<u[0];p++)d[p]=a(l);return d};return c(o,r)},y_n=function(t){return t.toString("utf8")},E_n=function(t){return t===null?null:ss(t,8)>0},w_n=function(t){t(20,h_n),t(21,m_n),t(23,VZe),t(26,VZe),t(1700,A_n),t(700,f_n),t(701,g_n),t(16,E_n),t(1114,KZe.bind(null,!1)),t(1184,KZe.bind(null,!0)),t(1e3,PF),t(1007,PF),t(1016,PF),t(1008,PF),t(1009,PF),t(25,y_n)};JZe.exports={init:w_n}});var eet=Q((Ewi,ZZe)=>{ZZe.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var QF=Q(LF=>{var x_n=qZe(),b_n=XZe(),C_n=Zfe(),I_n=eet();LF.getTypeParser=v_n;LF.setTypeParser=S_n;LF.arrayParser=C_n;LF.builtins=I_n;var NF={text:{},binary:{}};function tet(t){return String(t)}function v_n(t,e){return e=e||"text",NF[e]&&NF[e][t]||tet}function S_n(t,e,n){typeof e=="function"&&(n=e,e="text"),NF[e][t]=n}x_n.init(function(t,e){NF.text[t]=e});b_n.init(function(t,e){NF.binary[t]=e})});var OF=Q((xwi,age)=>{"use strict";var net;try{net=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}age.exports={host:"localhost",user:net,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,sslnegotiation:void 0,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var rB=QF(),__n=rB.getTypeParser(20,"text"),k_n=rB.getTypeParser(1016,"text");age.exports.__defineSetter__("parseInt8",function(t){rB.setTypeParser(20,"text",t?rB.getTypeParser(23,"text"):__n),rB.setTypeParser(1016,"text",t?rB.getTypeParser(1007,"text"):k_n)})});var qI=Q((bwi,iet)=>{"use strict";var T_n=OF(),R_n=K("util"),{isDate:B_n}=K("util/types"),D_n=R_n.deprecate(()=>{},"Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.","PG_INVALID_DATE");function M_n(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function ret(t){let e="{";for(let n=0;n<t.length;n++){n>0&&(e+=",");let r=t[n];r==null?e+="NULL":Array.isArray(r)?e+=ret(r):ArrayBuffer.isView(r)?(r instanceof Buffer||(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),e+="\\\\x"+r.toString("hex")):e+=M_n(N6(r))}return e+="}",e}var N6=function(t,e){return t==null?null:typeof t=="object"?t instanceof Buffer?t:ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):B_n(t)?(isNaN(t.getTime())&&D_n(),T_n.parseInputDatesAsUTC?L_n(t):N_n(t)):Array.isArray(t)?ret(t):P_n(t,e):t.toString()};function P_n(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),N6(t.toPostgres(N6),e)}return JSON.stringify(t)}function N_n(t){let e=-t.getTimezoneOffset(),n=t.getFullYear(),r=n<1;r&&(n=Math.abs(n)+1);let i=String(n).padStart(4,"0")+"-"+String(t.getMonth()+1).padStart(2,"0")+"-"+String(t.getDate()).padStart(2,"0")+"T"+String(t.getHours()).padStart(2,"0")+":"+String(t.getMinutes()).padStart(2,"0")+":"+String(t.getSeconds()).padStart(2,"0")+"."+String(t.getMilliseconds()).padStart(3,"0");return e<0?(i+="-",e*=-1):i+="+",i+=String(Math.floor(e/60)).padStart(2,"0")+":"+String(e%60).padStart(2,"0"),r&&(i+=" BC"),i}function L_n(t){let e=t.getUTCFullYear(),n=e<1;n&&(e=Math.abs(e)+1);let r=String(e).padStart(4,"0")+"-"+String(t.getUTCMonth()+1).padStart(2,"0")+"-"+String(t.getUTCDate()).padStart(2,"0")+"T"+String(t.getUTCHours()).padStart(2,"0")+":"+String(t.getUTCMinutes()).padStart(2,"0")+":"+String(t.getUTCSeconds()).padStart(2,"0")+"."+String(t.getUTCMilliseconds()).padStart(3,"0");return r+="+00:00",n&&(r+=" BC"),r}function Q_n(t,e,n){return t=typeof t=="string"?{text:t}:O_n(t),e&&(typeof e=="function"?t.callback=e:t.values=e),n&&(t.callback=n),t}function O_n(t){return t==null?t:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),Object.getOwnPropertyDescriptors(t))}var F_n=function(t){return'"'+t.replace(/"/g,'""')+'"'},U_n=function(t){let e=!1,n="'";if(t==null||typeof t!="string")return"''";for(let r=0;r<t.length;r++){let i=t[r];i==="'"?n+=i+i:i==="\\"?(n+=i+i,e=!0):n+=i}return n+="'",e===!0&&(n=" E"+n),n};iet.exports={prepareValue:function(e){return N6(e)},normalizeQueryConfig:Q_n,escapeIdentifier:F_n,escapeLiteral:U_n}});var lge=Q((Cwi,aet)=>{var oet=K("crypto");aet.exports={postgresMd5PasswordHash:W_n,randomBytes:$_n,deriveKey:j_n,sha256:H_n,hashByName:G_n,hmacSha256:q_n,md5:cge};var set=oet.webcrypto||globalThis.crypto,jI=set.subtle,uge=new TextEncoder;function $_n(t){return set.getRandomValues(Buffer.alloc(t))}async function cge(t){try{return oet.createHash("md5").update(t,"utf-8").digest("hex")}catch{let n=typeof t=="string"?uge.encode(t):t,r=await jI.digest("MD5",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}}async function W_n(t,e,n){let r=await cge(e+t);return"md5"+await cge(Buffer.concat([Buffer.from(r),n]))}async function H_n(t){return await jI.digest("SHA-256",t)}async function G_n(t,e){return await jI.digest(t,e)}async function q_n(t,e){let n=await jI.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await jI.sign("HMAC",n,uge.encode(e))}async function j_n(t,e,n){let r=await jI.importKey("raw",uge.encode(t),"PBKDF2",!1,["deriveBits"]),i={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:n};return await jI.deriveBits(i,r,256,["deriveBits"])}});var det=Q((Iwi,uet)=>{function zI(t,e){return new Error("SASL channel binding: "+t+" when parsing public certificate "+e.toString("base64"))}function dge(t,e){let n=t[e++];if(n<128)return{length:n,index:e};let r=n&127;if(r>4)throw zI("bad length",t);n=0;for(let i=0;i<r;i++)n=n<<8|t[e++];return{length:n,index:e}}function cet(t,e){if(t[e++]!==6)throw zI("non-OID data",t);let{length:n,index:r}=dge(t,e);e=r;let i=e+n,o=t[e++],s=(o/40>>0)+"."+o%40;for(;e<i;){let a=0;for(;e<i;){let c=t[e++];if(a=a<<7|c&127,c<128)break}s+="."+a}return{oid:s,index:e}}function FF(t,e){if(t[e++]!==48)throw zI("non-sequence data",t);return dge(t,e)}function z_n(t,e){e===void 0&&(e=0),e=FF(t,e).index;let{length:n,index:r}=FF(t,e);e=r+n,e=FF(t,e).index;let{oid:i,index:o}=cet(t,e);switch(i){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(e=o,e=FF(t,e).index,t[e++]!==160)throw zI("non-tag data",t);e=dge(t,e).index,e=FF(t,e).index;let{oid:s}=cet(t,e);switch(s){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw zI("unknown hash OID "+s,t)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw zI("Ed448 certificate channel binding is not currently supported by Postgres")}throw zI("unknown OID "+i,t)}uet.exports={signatureAlgorithmHashFromCertificate:z_n}});var fet=Q((vwi,met)=>{"use strict";var gw=lge(),{signatureAlgorithmHashFromCertificate:V_n}=det();function K_n(t){let e=/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g,n=/[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g;return t.replace(e," ").replace(n,"").normalize("NFKC")}var pge=1e5;function Y_n(t,e,n=pge){let r=["SCRAM-SHA-256"];e&&r.unshift("SCRAM-SHA-256-PLUS");let i=r.find(a=>t.includes(a));if(!i)throw new Error("SASL: Only mechanism(s) "+r.join(" and ")+" are supported");if(i==="SCRAM-SHA-256-PLUS"&&typeof e.getPeerCertificate!="function")throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let o=gw.randomBytes(18).toString("base64");return{mechanism:i,clientNonce:o,response:(i==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":e?"y":"n")+",,n=*,r="+o,message:"SASLInitialResponse",scramMaxIterations:n}}async function J_n(t,e,n,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof n!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let i=ekn(n);if(i.nonce.startsWith(t.clientNonce)){if(i.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");let o=typeof t.scramMaxIterations=="number"?t.scramMaxIterations:pge;if(o!==0&&i.iteration>o)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count "+i.iteration+" exceeds scramMaxIterations of "+o);let s="n=*,r="+t.clientNonce,a="r="+i.nonce+",s="+i.salt+",i="+i.iteration,c=r?"eSws":"biws";if(t.mechanism==="SCRAM-SHA-256-PLUS"){let b=r.getPeerCertificate().raw,v=V_n(b);(v==="MD5"||v==="SHA-1")&&(v="SHA-256");let S=await gw.hashByName(v,b);c=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(S)]).toString("base64")}let u="c="+c+",r="+i.nonce,l=s+","+a+","+u,d=Buffer.from(i.salt,"base64"),p=await gw.deriveKey(K_n(e),d,i.iteration),h=await gw.hmacSha256(p,"Client Key"),m=await gw.sha256(h),f=await gw.hmacSha256(m,l),g=nkn(Buffer.from(h),Buffer.from(f)).toString("base64"),A=await gw.hmacSha256(p,"Server Key"),x=await gw.hmacSha256(A,l);t.message="SASLResponse",t.serverSignature=Buffer.from(x).toString("base64"),t.response=u+",p="+g}function X_n(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:n}=tkn(e);if(n!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function Z_n(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,n)=>t.charCodeAt(n)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function pet(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}function het(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let n=e[0],r=e.substring(2);return[n,r]}))}function ekn(t){let e=het(t),n=e.get("r");if(n){if(!Z_n(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let r=e.get("s");if(r){if(!pet(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let i=e.get("i");if(i){if(!/^[1-9][0-9]*$/.test(i))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let o=parseInt(i,10);return{nonce:n,salt:r,iteration:o}}function tkn(t){let e=het(t),n=e.get("e"),r=e.get("v");if(n)throw new Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${n}"`);if(r){if(!pet(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}function nkn(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((n,r)=>t[r]^e[r]))}met.exports={startSession:Y_n,continueSession:J_n,finalizeSession:X_n,DEFAULT_MAX_SCRAM_ITERATIONS:pge}});var Q6=Q((Swi,get)=>{"use strict";var rkn=QF();function L6(t){this._types=t||rkn,this.text={},this.binary={}}L6.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};L6.prototype.setTypeParser=function(t,e,n){typeof e=="function"&&(n=e,e="text"),this.getOverrides(e)[t]=n};L6.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};get.exports=L6});var Eet=Q((_wi,yet)=>{"use strict";function iB(t,e={}){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let n=Object.create(null),r,i=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/%25(\d\d)/g,"%$1"));try{try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),i=!0}}catch(c){throw c.input&&(c.input="*****REDACTED*****"),c}for(let c of r.searchParams.entries())n[c[0]]=c[1];if(n.user=n.user||decodeURIComponent(r.username),n.password=n.password||decodeURIComponent(r.password),r.protocol=="socket:")return n.host=decodeURI(r.pathname),n.database=r.searchParams.get("db"),n.client_encoding=r.searchParams.get("encoding"),n;let o=(i?"":r.hostname).replace(/^\[(.+)\]$/,"$1");n.host?o&&/^%2f/i.test(o)&&(r.pathname=o+r.pathname):n.host=decodeURIComponent(o),n.port||(n.port=r.port);let s=r.pathname.slice(1)||null;n.database=s?decodeURI(s):null,(n.ssl==="true"||n.ssl==="1")&&(n.ssl=!0),n.ssl==="0"&&(n.ssl=!1),(n.sslcert||n.sslkey||n.sslrootcert||n.sslmode)&&(n.ssl={}),n.sslnegotiation==="direct"&&n.ssl===void 0&&(n.ssl=!0);let a=n.sslcert||n.sslkey||n.sslrootcert?K("fs"):null;if(n.sslcert&&(n.ssl.cert=a.readFileSync(n.sslcert).toString()),n.sslkey&&(n.ssl.key=a.readFileSync(n.sslkey).toString()),n.sslrootcert&&(n.ssl.ca=a.readFileSync(n.sslrootcert).toString()),e.useLibpqCompat&&n.uselibpqcompat)throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(n.uselibpqcompat==="true"||e.useLibpqCompat)switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":{n.ssl.rejectUnauthorized=!1;break}case"require":{n.sslrootcert?n.ssl.checkServerIdentity=function(){}:n.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!n.ssl.ca)throw new Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");n.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{n.sslmode!=="verify-full"&&hge(n.sslmode);break}case"no-verify":{n.ssl.rejectUnauthorized=!1;break}}return n}function ikn(t){return Object.entries(t).reduce((n,[r,i])=>(i!=null&&(n[r]=i),n),Object.create(null))}function Aet(t){return Object.entries(t).reduce((n,[r,i])=>{if(r==="ssl"){let o=i;typeof o=="boolean"&&(n[r]=o),typeof o=="object"&&(n[r]=ikn(o))}else if(i!=null)if(r==="port"){if(i!==""){let o=parseInt(i,10);if(isNaN(o))throw new Error(`Invalid ${r}: ${i}`);n[r]=o}}else n[r]=i;return n},Object.create(null))}function okn(t){return Aet(iB(t))}function hge(t){!hge.warned&&typeof process<"u"&&process.emitWarning&&(hge.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
91
91
  In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
92
92
 
93
93
  To prepare for this change:
@@ -1 +1 @@
1
- var E=Object.defineProperty;var s=(e,t)=>E(e,"name",{value:t,configurable:!0});import{parentPort as M,workerData as N}from"node:worker_threads";import{request as v}from"node:http";import{request as $}from"node:https";const{address:l,token:b}=N,r=[],m=new Set;let w=!1,d=0,c=500,y;const I=Number(process.env.CRTR_CONVERSATION_COMMIT_DEADLINE_MS??15*6e4),k=process.env.CRTR_NODE_DEADLINE_AT?Date.parse(process.env.CRTR_NODE_DEADLINE_AT):1/0,O=s(()=>Math.max(1e3,Math.min(6e4,k-Date.now())),"requestTimeoutMs");function P(e){return new Promise(t=>setTimeout(t,e))}s(P,"wait");function _(e){return new Promise(t=>{const i=`/v1${e.path}`,n=l.startsWith("http")?new URL(l.replace(/\/$/,"")+i):null,u=e.data===void 0?void 0:JSON.stringify(e.data);let g=!1;const f=s(o=>{g||(g=!0,t(o))},"finish"),T=s(o=>{const D=[];o.on("data",h=>D.push(h)),o.on("aborted",()=>f({error:"conversation store response ended before completion"})),o.on("error",h=>f({error:h.message})),o.on("end",()=>f({status:o.statusCode,body:Buffer.concat(D).toString("utf8"),path:o.headers["x-conversation-path"],tail:o.headers["x-conversation-tail"]}))},"onResponse"),a=n?(n.protocol==="https:"?$:v)(n,{method:e.method},T):v({socketPath:l,path:i,method:e.method},T);a.on("error",o=>f({error:o.message})),a.setTimeout(O(),()=>{f({error:"conversation store request timed out"}),a.destroy()}),e.reply?.on("message",o=>{o==="cancel"&&a.destroy()}),b&&a.setHeader("authorization",`Bearer ${b}`),u!==void 0?(a.setHeader("content-type","application/json"),a.end(u)):a.end()})}s(_,"send");function p(e,t){e.reply?.postMessage(t),e.signal&&(Atomics.store(new Int32Array(e.signal),0,1),Atomics.notify(new Int32Array(e.signal),0)),e.reply?.close()}s(p,"answer");function q(e){y=e;for(const t of r.splice(0))t.kind!=="append"&&p(t,{error:`conversation_write_failed: ${e}`});d=0,c=500}s(q,"giveUp");const A=s(e=>!!e.error||!e.status||e.status>=400,"failed");async function R(e){if(d||(d=Date.now()),Date.now()-d>=I||Date.now()>=k){q(e);return}await P(c),c=Math.min(c*2,3e4)}s(R,"backoff");async function S(){if(!w){w=!0;try{for(;r.length;){const e=r[0];if(e.kind==="append"){const t=[];for(;r[t.length]?.kind==="append"&&r[t.length]?.path===e.path;)t.push(r[t.length]);const i=t.flatMap(u=>u.data.entries),n=await _({method:"POST",path:e.path,data:{entries:i}});if(A(n)){await R(n.error??n.body??`HTTP ${n.status}`);continue}d=0,c=500,m.add(e.path.replace(/\/entries$/,"")),r.splice(0,t.length);continue}if(e.kind==="flush"){if(y){p(e,{error:`conversation_write_failed: ${y}`}),r.shift();continue}let t;for(const i of m){const n=await _({method:"POST",path:`${i}/commit`});if(A(n)){t=n.error??n.body??`HTTP ${n.status}`;break}m.delete(i)}if(t){await R(t);continue}d=0,c=500,p(e,{status:200}),r.shift();continue}p(e,await _(e)),r.shift()}}finally{w=!1}}}s(S,"drain"),M?.on("message",e=>{r.push(e),S()});
1
+ var E=Object.defineProperty;var s=(e,t)=>E(e,"name",{value:t,configurable:!0});import{parentPort as M,workerData as N}from"node:worker_threads";import{request as v}from"node:http";import{request as $}from"node:https";const{address:l,token:b}=N,r=[],m=new Set;let w=!1,d=0,c=500,y;const I=Number(process.env.CRTR_CONVERSATION_COMMIT_DEADLINE_MS??15*6e4),k=process.env.CRTR_NODE_DEADLINE_AT?Date.parse(process.env.CRTR_NODE_DEADLINE_AT):1/0,O=s(()=>Math.max(1e3,Math.min(6e4,k-Date.now())),"requestTimeoutMs");function P(e){return new Promise(t=>setTimeout(t,e))}s(P,"wait");function g(e){return new Promise(t=>{const i=`/v1${e.path}`,n=l.startsWith("http")?new URL(l.replace(/\/$/,"")+i):null,u=e.data===void 0?void 0:JSON.stringify(e.data);let _=!1;const f=s(o=>{_||(_=!0,t(o))},"finish"),T=s(o=>{const D=[];o.on("data",h=>D.push(h)),o.on("aborted",()=>f({error:"conversation store response ended before completion"})),o.on("error",h=>f({error:h.message})),o.on("end",()=>f({status:o.statusCode,body:Buffer.concat(D).toString("utf8"),path:o.headers["x-conversation-path"],tail:o.headers["x-conversation-tail"]}))},"onResponse"),a=n?(n.protocol==="https:"?$:v)(n,{method:e.method},T):v({socketPath:l,path:i,method:e.method,agent:!1},T);a.on("error",o=>f({error:o.message})),a.setTimeout(O(),()=>{f({error:"conversation store request timed out"}),a.destroy()}),e.reply?.on("message",o=>{o==="cancel"&&a.destroy()}),b&&a.setHeader("authorization",`Bearer ${b}`),u!==void 0?(a.setHeader("content-type","application/json"),a.end(u)):a.end()})}s(g,"send");function p(e,t){e.reply?.postMessage(t),e.signal&&(Atomics.store(new Int32Array(e.signal),0,1),Atomics.notify(new Int32Array(e.signal),0)),e.reply?.close()}s(p,"answer");function q(e){y=e;for(const t of r.splice(0))t.kind!=="append"&&p(t,{error:`conversation_write_failed: ${e}`});d=0,c=500}s(q,"giveUp");const A=s(e=>!!e.error||!e.status||e.status>=400,"failed");async function R(e){if(d||(d=Date.now()),Date.now()-d>=I||Date.now()>=k){q(e);return}await P(c),c=Math.min(c*2,3e4)}s(R,"backoff");async function S(){if(!w){w=!0;try{for(;r.length;){const e=r[0];if(e.kind==="append"){const t=[];for(;r[t.length]?.kind==="append"&&r[t.length]?.path===e.path;)t.push(r[t.length]);const i=t.flatMap(u=>u.data.entries),n=await g({method:"POST",path:e.path,data:{entries:i}});if(A(n)){await R(n.error??n.body??`HTTP ${n.status}`);continue}d=0,c=500,m.add(e.path.replace(/\/entries$/,"")),r.splice(0,t.length);continue}if(e.kind==="flush"){if(y){p(e,{error:`conversation_write_failed: ${y}`}),r.shift();continue}let t;for(const i of m){const n=await g({method:"POST",path:`${i}/commit`});if(A(n)){t=n.error??n.body??`HTTP ${n.status}`;break}m.delete(i)}if(t){await R(t);continue}d=0,c=500,p(e,{status:200}),r.shift();continue}p(e,await g(e)),r.shift()}}finally{w=!1}}}s(S,"drain"),M?.on("message",e=>{r.push(e),S()});
@@ -180,7 +180,9 @@ export interface TeamRecord {
180
180
  team: string;
181
181
  members: string[];
182
182
  }
183
- /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. */
183
+ /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. Team
184
+ * membership is advisory next to the grants the same answer carries, so an entry that is not a directory team
185
+ * (`team:<id>`, e.g. a canvas group row echoed back) is dropped rather than failing the sync. */
184
186
  export declare function teamsOf(value: unknown): TeamRecord[];
185
187
  /** Replace the mirror with `grants` and the `written_by = 'directory'` team `member` facts with `teams`, in one transaction. The
186
188
  * ledger's `grant:<id>` limit rows follow from the `grants` trigger `crtr_grant_limit` (schema delta 002). */
@@ -1,11 +1,11 @@
1
- var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],F=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(v,"runtimeScope");async function i(e,r,n=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function k(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(k,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!k(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:a}=e;return typeof r!="string"||!$.includes(r)||n!==void 0&&typeof n!="string"||a!==void 0&&typeof a!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...a===void 0?{}:{step:a}}}t(U,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const a=U(s);a&&(r[n]=a)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const a of F){const o=n[a];typeof o=="string"&&o&&(s[a]=o)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const a=H.exec(s);a&&a[1]!=="crtr"&&r.add(a[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
1
+ var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],F=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(v,"runtimeScope");async function i(e,r,n=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function k(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(k,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!k(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:o}=e;return typeof r!="string"||!$.includes(r)||n!==void 0&&typeof n!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...o===void 0?{}:{step:o}}}t(U,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const o=U(s);o&&(r[n]=o)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const o of F){const a=n[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const o=H.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
2
2
  SELECT DISTINCT e->>'scope' AS scope FROM (
3
3
  SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${x()}${e.sql}) d OFFSET 0) p
4
4
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
5
5
  CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
6
6
  WHERE m[1] <> 'crtr'`).all(...e.args)).map(n=>n.id).sort()}t(se,"activeProviderIds");async function ae(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}t(ae,"anyActiveGrant");async function oe(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
7
7
  SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
8
- WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function Ee(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(Ee,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function ve(e){return(await i("id",e)).map(r=>r.id)}t(ve,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Te(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Te,"runNoticeTarget");async function Ne(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Ne,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function we(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(we,"backfillComputedRev");function be(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");return e.map(r=>{const{team:n,members:s}=r??{};if(typeof n!="string"||!/^team:\S+$/.test(n)||!Array.isArray(s)||s.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");return{team:n,members:s}})}t(be,"teamsOf");async function Re(e,r,n,s=[]){const a=new Set;for(const o of e){if(a.has(o.id)||!o.id||!o.runtime||!o.sub||!o.grantee||!Number.isInteger(o.rev)||!["active","revoked","removed"].includes(o.status))throw new TypeError("invalid grant sync response");a.add(o.id),l(o.scopes),l(o.resolved_scopes)}await T(async o=>{let E=0;const g=[...a];E+=Number((await(g.length?o.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):o.prepareUncached("DELETE FROM grants").run())).changes);const w=o.prepare(`INSERT INTO grants
8
+ WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function Ee(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(Ee,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function ve(e){return(await i("id",e)).map(r=>r.id)}t(ve,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Te(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Te,"runNoticeTarget");async function Ne(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Ne,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function we(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(we,"backfillComputedRev");function be(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const n of e){const{team:s,members:o}=n??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}t(be,"teamsOf");async function he(e,r,n,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let E=0;const g=[...o];E+=Number((await(g.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):a.prepareUncached("DELETE FROM grants").run())).changes);const w=a.prepare(`INSERT INTO grants
9
9
  (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
10
10
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
11
11
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -19,4 +19,4 @@ var h=Object.defineProperty;var t=(e,r)=>h(e,"name",{value:r,configurable:!0});i
19
19
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
20
20
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
21
21
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
22
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(o,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(R=>({resourceId:c,subject:C(R)})))),await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),E>0&&await o.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(Re,"replaceGrants");async function he(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(he,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,we as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,ve as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,Ee as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,he as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,Re as replaceGrants,Te as runNoticeTarget,v as runtimeScope,be as teamsOf,Ne as terminalGrant};
22
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(a,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(h=>({resourceId:c,subject:C(h)})))),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(he,"replaceGrants");async function Re(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(Re,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,we as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,ve as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,Ee as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,Re as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,he as replaceGrants,Te as runNoticeTarget,v as runtimeScope,be as teamsOf,Ne as terminalGrant};
@@ -47,10 +47,13 @@ export declare function cronWakeOrigin(c: Cron, kind: WakeOrigin['kind']): Promi
47
47
  * carry the signal, and a raw ISO instant is noise an agent cannot cheaply turn
48
48
  * into an elapsed delta. */
49
49
  export declare function buildWakeBearings(origin: WakeOrigin): string;
50
+ /** The `<project_context>` snapshot of the node's cwd: it spawns git and tmux and reads this host's disk, so a caller builds it BEFORE
51
+ * opening the delivery transaction and passes it in as `projectContext`; '' when the node's engine does not run on this host. */
52
+ export declare function projectContextForNode(nodeId: string): Promise<string>;
50
53
  /** The bearings on the row-backed delivery engine: the knowledge catalog and
51
54
  * the workspace-open documents render against `ctx`'s ledger; `delivered`
52
55
  * lists what they delivered, for the caller to record. */
53
- export declare function buildContextBearings(nodeId: string, ctx: RenderContext): Promise<{
56
+ export declare function buildContextBearings(nodeId: string, ctx: RenderContext, projectContext: string): Promise<{
54
57
  content: string;
55
58
  delivered: DeliveredDoc[];
56
59
  }>;
@@ -1,7 +1,7 @@
1
- var g=Object.defineProperty;var i=(e,r)=>g(e,"name",{value:r,configurable:!0});import{getNode as s,latestExecutionForNode as N,fullName as w,isSafeNodeId as v,subscriptionsOf as x}from"../canvas/index.js";import{cadenceDisplay as _}from"../wake.js";import{renderKnowledge as Y,renderWorkspaceOpen as $}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as f}from"../canvas/node-order.js";import{buildProjectContextBlock as p,contextDirNote as h,orchestratorContextNote as m,whereYouRunNote as S,profileNote as E,renderGraphMap as O,buildIdentityAssertion as R,worktreeNote as A}from"./bearings-render.js";import{mapAsync as j}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as re}from"../../shared/generated-context.js";async function B(e,r){const n=r!==void 0?r:await s(e);return n===null?"":E(n.cwd,n.profile_id)}i(B,"profileNote");async function T(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const a=await s(o);if(a===null)break;n.unshift(a),o=a.parent??null}return n}i(T,"ancestorTrunk");const J=5;async function W(e){return(await j(await x(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>f(r.status)-f(n.status))}i(W,"childNodes");async function D(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await T(e,n),o=await W(e);return O(e,n.kind,n.mode,t,o)}i(D,"buildGraphMap");async function H(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&v(n)?await s(n):null,o=t!==null?`${n} ("${w(t)}")`:n??"";return R(e,r?.kind??"general",r?.mode??"base",n,o)}i(H,"buildIdentityAssertion");function L(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}i(L,"armerPhrase");async function Q(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:w(n)}:{},armedAt:e.created,recur:e.recur}}i(Q,"cronWakeOrigin");function V(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?_(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
- ${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
- </crtr-wake>`;const t=L(e);return`<crtr-wake>
4
- ${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}i(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}i(M,"managedWorktreeNote");async function P(e,r,n){const t=await s(e),o=await N(e),a=["<crtr-bearings>",await H(e,t)],u=S(o?.runner);u!==""&&a.push("","## Where you run",u);const c=await D(e,t);c!==""&&a.push("","## Your place in the canvas",c),a.push("","## Your documents and context directory",h(e,t?.grantee));const d=await B(e,t);d!==""&&a.push("",d);const l=M(t);l!==""&&a.push("","## Your managed worktree",l),t?.mode==="orchestrator"&&a.push("",m()),a.push("</crtr-bearings>");const y=await C(e)??"",b=t?.cwd!==void 0&&o?.runner==="process"?p(t.cwd):"";return[a.join(`
6
- `),r,n,y,b].filter(k=>k!=="").join(`
7
- `)}i(P,"bearingsShell");async function Z(e,r){const n=await Y(r),t=await $(r);return{content:await P(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}i(Z,"buildContextBearings");export{re as CONTEXT_INTRO_CUSTOM_TYPE,Z as buildContextBearings,D as buildGraphMap,p as buildProjectContextBlock,V as buildWakeBearings,h as contextDirNote,Q as cronWakeOrigin,m as orchestratorContextNote,B as profileNote};
1
+ var g=Object.defineProperty;var a=(e,n)=>g(e,"name",{value:n,configurable:!0});import{getNode as s,latestExecutionForNode as f,fullName as p,isSafeNodeId as v,subscriptionsOf as x}from"../canvas/index.js";import{cadenceDisplay as _}from"../wake.js";import{renderKnowledge as Y,renderWorkspaceOpen as $}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as C}from"./situational-context.js";import{statusRank as h}from"../canvas/node-order.js";import{buildProjectContextBlock as m,contextDirNote as y,orchestratorContextNote as b,whereYouRunNote as S,profileNote as E,renderGraphMap as O,buildIdentityAssertion as R,worktreeNote as A}from"./bearings-render.js";import{mapAsync as j}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as te}from"../../shared/generated-context.js";async function B(e,n){const r=n!==void 0?n:await s(e);return r===null?"":E(r.cwd,r.profile_id)}a(B,"profileNote");async function T(e,n){const r=[],o=new Set([e]);let t=n.parent??null;for(;t!==null&&t!==""&&!o.has(t);){o.add(t);const u=await s(t);if(u===null)break;r.unshift(u),t=u.parent??null}return r}a(T,"ancestorTrunk");const J=5;async function W(e){return(await j(await x(e),async n=>await s(n.node_id))).filter(n=>n!==null&&n.kind!=="human").sort((n,r)=>h(n.status)-h(r.status))}a(W,"childNodes");async function D(e,n){const r=n!==void 0?n:await s(e);if(r===null)return"";const o=await T(e,r),t=await W(e);return O(e,r.kind,r.mode,o,t)}a(D,"buildGraphMap");async function H(e,n){const r=n?.fork_from,o=r!=null&&r!==""&&v(r)?await s(r):null,t=o!==null?`${r} ("${p(o)}")`:r??"";return R(e,n?.kind??"general",n?.mode??"base",r,t)}a(H,"buildIdentityAssertion");function L(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(L,"armerPhrase");async function Q(e,n){const r=e.created_by!=null?await s(e.created_by):null;return{kind:n,ownerId:e.created_by,...r!==null?{ownerName:p(r)}:{},armedAt:e.created,recur:e.recur}}a(Q,"cronWakeOrigin");function V(e){const n=e.recur!==null&&e.recur!==void 0&&e.recur!=="",r=n?_(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
+ ${n?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${r} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
+ </crtr-wake>`;const o=L(e);return`<crtr-wake>
4
+ ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${o}, firing ${r}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${o} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
+ </crtr-wake>`}a(V,"buildWakeBearings");function M(e){return A(e?.managed_worktree)}a(M,"managedWorktreeNote");async function F(e,n,r,o){const t=await s(e),u=await f(e),i=["<crtr-bearings>",await H(e,t)],c=S(u?.runner);c!==""&&i.push("","## Where you run",c);const d=await D(e,t);d!==""&&i.push("","## Your place in the canvas",d),i.push("","## Your documents and context directory",y(e,t?.grantee));const l=await B(e,t);l!==""&&i.push("",l);const w=M(t);w!==""&&i.push("","## Your managed worktree",w),t?.mode==="orchestrator"&&i.push("",b()),i.push("</crtr-bearings>");const k=await C(e)??"";return[i.join(`
6
+ `),n,r,k,o].filter(N=>N!=="").join(`
7
+ `)}a(F,"bearingsShell");async function Z(e){const n=await s(e),r=await f(e);return n?.cwd!==void 0&&r?.runner==="process"?m(n.cwd):""}a(Z,"projectContextForNode");async function ee(e,n,r){const o=await Y(n),t=await $(n);return{content:await F(e,o.content,t.content,r),delivered:[...o.delivered,...t.delivered]}}a(ee,"buildContextBearings");export{te as CONTEXT_INTRO_CUSTOM_TYPE,ee as buildContextBearings,D as buildGraphMap,m as buildProjectContextBlock,V as buildWakeBearings,y as contextDirNote,Q as cronWakeOrigin,b as orchestratorContextNote,B as profileNote,Z as projectContextForNode};
@@ -1 +1 @@
1
- var b=Object.defineProperty;var p=(c,f)=>b(c,"name",{value:f,configurable:!0});import{createServer as _,request as y}from"node:http";import{request as k}from"node:https";import{chmodSync as v,existsSync as R,rmSync as A,unlinkSync as E}from"node:fs";import{join as u}from"node:path";import{apiSocketPath as B,BROKER_RELEASED_MARKER as C,BROKER_RELAY_GENERATION as O,nodeRunDir as S}from"../../canvas/paths.js";import{writeFileBeneath as N}from"../../spaces/open-beneath.js";import{currentCausedBy as U}from"./turn-cause.js";import{brokerApiUrl as q}from"./daemon-ops.js";import{northlightUnreachable as x}from"../../directory/reach.js";async function F(c,f){const o=u(S(c),"cli.sock"),d=q(),w=p((r,e,t,i)=>{if(d===void 0)return y({socketPath:B(),path:r,method:e,headers:t},i);const s=new URL(r??"/",d);return delete t.host,(s.protocol==="https:"?k:y)(s,{method:e,headers:t},i)},"forward"),a=_((r,e)=>{const t={...r.headers,authorization:`Bearer ${f}`},i=U();i!==void 0&&t["crtr-caused-by"]===void 0&&(t["crtr-caused-by"]=i),delete t.connection;const s=w(r.url,r.method,t,n=>{e.writeHead(n.statusCode??502,n.headers),n.pipe(e)});s.on("error",n=>{if(e.headersSent||e.writeHead(503,{"content-type":"application/json"}),d===void 0)return void e.end(JSON.stringify({error:{code:"daemon_unavailable",message:n.message}}));const m=x(n,d);e.end(JSON.stringify({error:{code:m.code,message:m.message,retryable:!0,details:m.details}}))}),r.pipe(s),e.on("close",()=>s.destroy())});R(o)&&E(o),await new Promise((r,e)=>{a.once("error",e),a.listen(o,()=>{a.off("error",e),r()})}),v(o,384);const l=S(c),h=process.env.CRTR_EXECUTION_ID;if(!h)throw new Error("broker relay has no execution id");return N(l,u(l,O),h,{atomic:!0}),A(u(l,C),{force:!0}),{path:o,close(){a.closeAllConnections(),a.close(),R(o)&&E(o)}}}p(F,"serveCliRelay");export{F as serveCliRelay};
1
+ var b=Object.defineProperty;var p=(c,f)=>b(c,"name",{value:f,configurable:!0});import{createServer as _,request as y}from"node:http";import{request as k}from"node:https";import{chmodSync as v,existsSync as R,rmSync as A,unlinkSync as E}from"node:fs";import{join as u}from"node:path";import{apiSocketPath as B,BROKER_RELEASED_MARKER as C,BROKER_RELAY_GENERATION as O,nodeRunDir as S}from"../../canvas/paths.js";import{writeFileBeneath as N}from"../../spaces/open-beneath.js";import{currentCausedBy as U}from"./turn-cause.js";import{brokerApiUrl as q}from"./daemon-ops.js";import{northlightUnreachable as x}from"../../directory/reach.js";async function F(c,f){const o=u(S(c),"cli.sock"),d=q(),w=p((r,e,t,i)=>{if(d===void 0)return y({socketPath:B(),path:r,method:e,headers:t,agent:!1},i);const s=new URL(r??"/",d);return delete t.host,(s.protocol==="https:"?k:y)(s,{method:e,headers:t},i)},"forward"),a=_((r,e)=>{const t={...r.headers,authorization:`Bearer ${f}`},i=U();i!==void 0&&t["crtr-caused-by"]===void 0&&(t["crtr-caused-by"]=i),delete t.connection;const s=w(r.url,r.method,t,n=>{e.writeHead(n.statusCode??502,n.headers),n.pipe(e)});s.on("error",n=>{if(e.headersSent||e.writeHead(503,{"content-type":"application/json"}),d===void 0)return void e.end(JSON.stringify({error:{code:"daemon_unavailable",message:n.message}}));const m=x(n,d);e.end(JSON.stringify({error:{code:m.code,message:m.message,retryable:!0,details:m.details}}))}),r.pipe(s),e.on("close",()=>s.destroy())});R(o)&&E(o),await new Promise((r,e)=>{a.once("error",e),a.listen(o,()=>{a.off("error",e),r()})}),v(o,384);const l=S(c),h=process.env.CRTR_EXECUTION_ID;if(!h)throw new Error("broker relay has no execution id");return N(l,u(l,O),h,{atomic:!0}),A(u(l,C),{force:!0}),{path:o,close(){a.closeAllConnections(),a.close(),R(o)&&E(o)}}}p(F,"serveCliRelay");export{F as serveCliRelay};
@@ -1 +1 @@
1
- var m=Object.defineProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});import{getNode as s}from"../canvas/index.js";import{openDb as c,withCanvasWrite as l}from"../canvas/db.js";import{readerForNode as u,warmNodeRepos as f}from"../graph/reader.js";import{checkoutsForCwd as p}from"../graph/repo-sync/repos.js";import{deliver as v}from"../substrate/delivery/deliver.js";import{oneShotControllerRequest as w}from"./broker-request.js";import{isBrokerLive as d}from"./model-swap.js";import{CONTEXT_INTRO_CUSTOM_TYPE as y}from"./bearings.js";import{formatCard as T}from"../../shared/generated-context.js";async function C(e,t){const r=await s(e);if(r===null)throw new Error(`deliverCustomMessageLive: unknown node ${e}`);d(r)&&await w({nodeId:e,what:`the ${t.customType} delivery`,ackFor:"deliver_custom_message",frame:o(()=>({type:"deliver_custom_message",customType:t.customType,content:t.content,...t.deliverAs!==void 0?{deliverAs:t.deliverAs}:{},...t.details!==void 0?{details:t.details}:{}}),"frame"),result:o(()=>{},"result")})}o(C,"deliverCustomMessageLive");async function R(e){await f(await c(),e);const{content:t}=await l(async r=>await v(r,await u(r,e,async(i,a,n)=>await p(r,i,a,n)),{activity:"boot"}));await C(e,{customType:y,content:T("bearings",{},t),details:{nodeId:e}})}o(R,"deliverBearingsLive");export{R as deliverBearingsLive,C as deliverCustomMessageLive};
1
+ var m=Object.defineProperty;var r=(t,e)=>m(t,"name",{value:e,configurable:!0});import{getNode as c}from"../canvas/index.js";import{openDb as u,withCanvasWrite as l}from"../canvas/db.js";import{readerForNode as f,warmNodeRepos as p}from"../graph/reader.js";import{checkoutsForCwd as w}from"../graph/repo-sync/repos.js";import{deliver as v,withProjectContext as d}from"../substrate/delivery/deliver.js";import{oneShotControllerRequest as y}from"./broker-request.js";import{isBrokerLive as C}from"./model-swap.js";import{CONTEXT_INTRO_CUSTOM_TYPE as T}from"./bearings.js";import{formatCard as h}from"../../shared/generated-context.js";async function _(t,e){const o=await c(t);if(o===null)throw new Error(`deliverCustomMessageLive: unknown node ${t}`);C(o)&&await y({nodeId:t,what:`the ${e.customType} delivery`,ackFor:"deliver_custom_message",frame:r(()=>({type:"deliver_custom_message",customType:e.customType,content:e.content,...e.deliverAs!==void 0?{deliverAs:e.deliverAs}:{},...e.details!==void 0?{details:e.details}:{}}),"frame"),result:r(()=>{},"result")})}r(_,"deliverCustomMessageLive");async function q(t){await p(await u(),t);const e=await d(t,{activity:"boot"}),{content:o}=await l(async i=>await v(i,await f(i,t,async(a,n,s)=>await w(i,a,n,s)),e));await _(t,{customType:T,content:h("bearings",{},o),details:{nodeId:t}})}r(q,"deliverBearingsLive");export{q as deliverBearingsLive,_ as deliverCustomMessageLive};
@@ -10,7 +10,12 @@ export interface DeliveryRequestInput {
10
10
  activity: DeliveryActivity;
11
11
  subject?: string;
12
12
  inherited?: boolean;
13
+ /** The live node's `<project_context>` snapshot, built outside the transaction by `withProjectContext`; a node `boot` needs it. */
14
+ projectContext?: string;
13
15
  }
16
+ /** `req` with what a `boot` of node `nodeId` reads from this host's disk and processes (git, tmux, a directory listing), computed now so the
17
+ * delivery transaction that follows holds its pooled connection for db statements only. Call before `withCanvasWrite`. */
18
+ export declare function withProjectContext(nodeId: string, req: DeliveryRequestInput): Promise<DeliveryRequestInput>;
14
19
  export interface DeliveryResult {
15
20
  content: string;
16
21
  inherited?: boolean;
@@ -1,6 +1,6 @@
1
- var $=Object.defineProperty;var l=(t,e)=>$(t,"name",{value:e,configurable:!0});import{dirname as P}from"node:path";import{isCloudRole as T}from"../../canvas/person-state.js";import{machineEnvironmentOfProfile as H}from"../../runtime/runner/machine/environment.js";import{clearLedger as W,demoteTranscript as x,freezePreferences as O,loadLedger as Y,saveLedger as B}from"../../graph/exposures.js";import{recordWatches as U}from"../../graph/watches.js";import{publishMany as J}from"../../graph/events.js";import{checkoutsForCwd as h}from"../../graph/repo-sync/repos.js";import{liveLookups as K,profileObject as V,viewRepos as G}from"../../graph/reader.js";import{ownerForGrantee as X}from"../../graph/objects.js";import{resolveName as z}from"../../graph/names.js";import{SCOPE_VOCABULARY as Q}from"../../scopes.js";import{getNode as Z}from"../../canvas/index.js";import{recordMemoryReadsIn as q}from"../../canvas/memory-reads.js";import{lookupProfile as ee}from"../../profiles/manifest.js";import{getDefaultProfileId as te}from"../../profiles/default-binding.js";import{effectiveScopes as ne,profileNameFor as oe,scopeForCwd as re}from"../subject-fields.js";import{spineDepth as ae}from"../subject.js";import{appForNode as ie}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as se}from"../../canvas/paths.js";import{readableProjectForScopes as k}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as ce}from"../../runtime/bearings.js";import{deliveryDocOf as N,listingCorpora as de,loadCorpus as w,nodeSubject as R,primeBodies as le,profileIdOfObject as pe,viewOwners as ue}from"./corpus.js";import{listingPrefixes as me}from"./listings.js";import{planDelivery as fe}from"./plan.js";import{renderEvent as _,renderExplicitRead as S}from"./render-event.js";import{renderConfigDelta as we,renderKnowledge as ye,renderPreferences as E,renderWorkspaceOpen as D}from"./render-boot.js";import{mapAsync as I}from"../../async-array.js";function f(t){if(t.class!=="node")throw new Error(`delivery needs a node reader, got ${t.class}`);return t}l(f,"nodeOf");const C="hypothetical";function v(t){return t.node.id===C}l(v,"isHypothetical");async function g(t,e){if(!v(e))return await ie(e.node.id);const n=await t.prepare("SELECT external_id FROM identities WHERE object = ?").get(e.app.id);if(!n)throw new Error(`app object ${e.app.id} has no identity`);return n.external_id}l(g,"granteeOf");async function he(t,e,n,o=async(r,c)=>await h(t,r,c)){const r=f(e).node,c=new Set,a=new Date().toISOString(),s=[],i=[];for(const{doc:d,level:p}of n)p!=="content"||c.has(d.object.id)||(c.add(d.object.id),i.push({watcher:r,object:d.object,start:"deliver",opts:{readHeadsKey:d.headsKey}}),s.push({name:d.name,scope:d.ownerHandle,at:a,type:"loaded"}));await U(t,i),await J(t,i.map(d=>({event:"read",object:d.object,actor:r,attrs:{}})),o),v(f(e))||await q(t,r.id,s)}l(he,"recordContentDelivery");async function A(t,e,n){if(await b(t,e,n))return e;const o=(await h(t,P(n))).filter(r=>!e.repos.some(c=>c.id===r.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(r=>r.repo)],checkouts:[...e.checkouts,...o]}}l(A,"fileReadReader");async function b(t,e,n){const o=await g(t,e);if(o!=="app:terminal"||!T()||e.profile==null)return!1;const r=await pe(t,e.profile.id);return r!==null&&await H(r)!==null&&!k(n,o,e.scopes??[],null)}l(b,"isMacEnforcedRead");async function F(t,e,n){if(!await b(t,e,n))return{absoluteFile:n};const o=new Map;for(const{root:r,repo:c}of e.checkouts)n.startsWith(r.endsWith("/")?r:`${r}/`)&&!o.has(c.id)&&o.set(c.id,r);return{absoluteFile:n,readFrontmatter:{},repoRoots:o,remotePath:!0}}l(F,"fileReadPayload");async function ve(t,e,n){const o=await g(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||await b(t,e,n)||k(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(ve,"assertReadableFile");async function ge(t){const e=f(t.reader),n=e.node,o=await g(t.db,e),r=await w(t.db,t.reader,["slash-command"]);await le(t.db,r);const c=await I(r,async a=>{const s=await a.body();return{name:a.displayName,command_name:a.displayName,description:a.preview,canonical_body:s,execution_body:se(s,n.id,o)}});return{docs:r,commands:c}}l(ge,"slashCommands");function be(t){if(t.shipped)return"builtin";switch(t.owner.type){case"node":return"node";case"repo":return"project";case"profile":return"profile";default:return"user"}}l(be,"scopeOf");async function je(t,e){const n=[],o=new Set,r=await ue(t,e),c=await de(t,e,r);for(const a of r){const s=c.get(a.id);for(const i of s){n.push({name:i.displayName,kind:i.kind,scope:be(i),shortForm:i.preview,gatewayVisible:!i.shipped}),o.add(i.displayName);const d=i.displayName===i.name?"":`${i.ownerHandle}/`;for(const p of me(s,i.name))o.add(`${d}${p}`)}}return{refs:n,names:[...o]}}l(je,"composerNames");async function L(t,e){const n=f(t.reader),{db:o,ledger:r}=t,c=l(()=>{if(typeof e.subject!="string"||e.subject==="")throw new m(400,"usage",`delivery activity ${e.activity} requires a subject`);return e.subject},"requireSubject");switch(e.activity){case"boot":{if(e.inherited===!0){for(const[i,d]of r.objects)if(d.transcript===void 0)r.objects.delete(i);else{const{system:p,...u}=d;r.objects.set(i,u)}for(const[i,d]of r.listed)d.transcript===void 0?r.listed.delete(i):r.listed.set(i,{transcript:d.transcript});return r.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const a=v(n)?await Oe(t):await ce(n.node.id,t),s=await E({...t,channel:"system"});return O(r,s.content),{result:{content:a.content},delivered:[...a.delivered,...s.delivered]}}case"system-prompt":{if(r.preferenceSnapshot!==null)return{result:{content:r.preferenceSnapshot},delivered:[]};const a=await E({...t,channel:"system"});return{result:{content:O(r,a.content)},delivered:a.delivered}}case"compact":{for(const a of await w(o,n,["pre-command"]))x(r,a.object.id);return{result:{content:""},delivered:[]}}case"persona":{const a=await we(t);return{result:{content:a.content},delivered:a.delivered}}case"file-read":{const a=c();await ve(o,n,a);const s=await A(o,n,a),i={...t,reader:s},d=await _(i,"file-read",await F(o,n,a),await w(o,s,["file-read"]));return{result:{content:d.content},delivered:d.delivered}}case"command":case"pre-command":{const a=await _(t,e.activity,{command:c()});return{result:{content:a.content},delivered:a.delivered}}case"slash-command":{const{docs:a,commands:s}=await ge(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const i=a.findIndex(u=>u.displayName===e.subject||u.name===e.subject);if(i<0)throw new m(404,"not_found",`no slash command named ${e.subject}`);const d=a[i],p=await S(t,d,!0);return{result:{content:"",execution_body:s[i].execution_body,blocks:p.attachments===""?[]:[p.attachments]},delivered:[{doc:d,level:"content"},...p.delivered]}}case"workspace-open":{const a=await D(t);return{result:{content:a.content},delivered:a.delivered}}case"document-read":{const a=await M(o,n,c()),s=await S(t,await N(o,n,a),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await je(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(L,"render");async function Oe(t){const e=await ye(t),n=await D(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
2
- `),delivered:[...e.delivered,...n.delivered]}}l(Oe,"hypotheticalBearings");async function M(t,e,n){const o=await z(t,e,n);if("object"in o&&o.object.type==="document")return o.object;throw"ambiguous"in o?new m(409,"ambiguous",`${n} names ${o.ambiguous.length} documents; name one as <type>:<owner>/<name>`):new m(404,"not_found",`no document ${n} the reader can read`)}l(M,"readDocument");const ke=["workspace-open","document-read"];async function tt(t,e,n,o){if(ke.includes(n.activity))throw new m(400,"usage",`delivery activity ${n.activity} is available to a dry run only`);const r=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await W(t,r.id);const c=await Y(t,r.id),a={db:t,reader:e,subject:o??await R(t,e),ledger:c,channel:"transcript"},{result:s,delivered:i}=await L(a,n);return await he(t,e,i),await B(t,c),s}l(tt,"deliver");const Ne={boot:"boot","workspace-open":"workspace-open","file-read":"file-read","document-read":"document-read",command:"command","pre-command":"pre-command","slash-command":"slash-command"};async function nt(t,e){const n=await Z(t);if(n===null)throw new m(404,"not_found",`no node ${t}`);return{cwd:e.cwd??n.cwd,profile:e.profile!==void 0?e.profile:n.profile_id,grantee:e.grantee??n.grantee,kind:e.kind??n.kind,mode:e.mode??n.mode,lifecycle:e.lifecycle??n.lifecycle,hasManager:e.hasManager??(n.parent??null)!==null,depth:e.depth??await ae(t)}}l(nt,"hypotheticalFrom");function Re(t,e){if(t===null)return null;if(t===void 0||t==="")return te(e);const n=ee(t);if(n.kind!=="resolved"){const o=`no profile ${t}`;throw new m(404,"not_found",o,{error:"not_found",message:o,next:"List profile ids and names with `crtr profile list`."})}return n.entry.profileId}l(Re,"resolveProfileId");async function ot(t,e){const n=await X(t,e.grantee??"app:terminal"),o=Re(e.profile,e.cwd),r=await G(t,e.cwd,o,async(p,u,y)=>await h(t,p,u,y),K(t)),{repos:c}=r,a=e.mode??"base",i={class:"node",node:{id:C,seq:0,type:"node",kind:e.kind??"general",owner:n.id,privacy:"private",name:"hypothetical",preview:"",created_at:new Date(0).toISOString(),deleted_at:null},app:n,scopes:[...Q],cwd:e.cwd,...r,profile:o===null?null:await V(t,o,n)},d={kind:e.kind??"general",mode:a,lifecycle:e.lifecycle??(a==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:re(e.cwd),orchestration:{depth:e.depth??0},profile:oe(o),app:e.grantee??"app:terminal",scopes:ne(null),repo:[...c,...r.projectRepos].map(p=>p.name)};return{reader:i,subject:d}}l(ot,"hypotheticalReader");async function rt(t,e,n,o,r){const a={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...r??await R(t,e),...o},i={db:t,reader:e,subject:s,ledger:a,channel:"transcript"},{result:d}=await L(i,n),p=Ne[n.activity];let u=null;if(p!==void 0){const y=n.activity==="file-read"?await F(t,f(e),n.subject):n.activity==="command"||n.activity==="pre-command"?{command:n.subject}:n.activity==="document-read"&&n.subject!==void 0?{doc:await N(t,e,await M(t,e,n.subject))}:{},j=n.activity==="file-read"&&n.subject!==void 0?await A(t,f(e),n.subject):e;u=await fe(t,s,j,await w(t,j,[p]),p,y)}return{result:d,plan:u}}l(rt,"inspect");async function at(t,e,n){const o=await t.prepare(`SELECT o.*, MAX(r.number) AS to_seq, string_agg(DISTINCT a.id, ',') AS authors
1
+ var L=Object.defineProperty;var l=(t,e)=>L(t,"name",{value:e,configurable:!0});import{dirname as M}from"node:path";import{isCloudRole as $}from"../../canvas/person-state.js";import{machineEnvironmentOfProfile as T}from"../../runtime/runner/machine/environment.js";import{clearLedger as H,demoteTranscript as W,freezePreferences as N,loadLedger as Y,saveLedger as B}from"../../graph/exposures.js";import{recordWatches as U}from"../../graph/watches.js";import{publishMany as J}from"../../graph/events.js";import{checkoutsForCwd as h}from"../../graph/repo-sync/repos.js";import{liveLookups as K,profileObject as V,viewRepos as G}from"../../graph/reader.js";import{ownerForGrantee as X}from"../../graph/objects.js";import{resolveName as z}from"../../graph/names.js";import{SCOPE_VOCABULARY as Q}from"../../scopes.js";import{getNode as Z}from"../../canvas/index.js";import{recordMemoryReadsIn as q}from"../../canvas/memory-reads.js";import{lookupProfile as ee}from"../../profiles/manifest.js";import{getDefaultProfileId as te}from"../../profiles/default-binding.js";import{effectiveScopes as ne,profileNameFor as oe,scopeForCwd as re}from"../subject-fields.js";import{spineDepth as ie}from"../subject.js";import{appForNode as ae}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as se}from"../../canvas/paths.js";import{readableProjectForScopes as O}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as ce,projectContextForNode as de}from"../../runtime/bearings.js";import{deliveryDocOf as k,listingCorpora as le,loadCorpus as w,nodeSubject as R,primeBodies as pe,profileIdOfObject as ue,viewOwners as me}from"./corpus.js";import{listingPrefixes as fe}from"./listings.js";import{planDelivery as we}from"./plan.js";import{renderEvent as _,renderExplicitRead as C}from"./render-event.js";import{renderConfigDelta as ye,renderKnowledge as he,renderPreferences as S,renderWorkspaceOpen as E}from"./render-boot.js";import{mapAsync as D}from"../../async-array.js";async function ot(t,e){return e.activity==="boot"&&e.inherited!==!0?{...e,projectContext:await de(t)}:e}l(ot,"withProjectContext");function f(t){if(t.class!=="node")throw new Error(`delivery needs a node reader, got ${t.class}`);return t}l(f,"nodeOf");const I="hypothetical";function v(t){return t.node.id===I}l(v,"isHypothetical");async function g(t,e){if(!v(e))return await ae(e.node.id);const n=await t.prepare("SELECT external_id FROM identities WHERE object = ?").get(e.app.id);if(!n)throw new Error(`app object ${e.app.id} has no identity`);return n.external_id}l(g,"granteeOf");async function ve(t,e,n,o=async(r,c)=>await h(t,r,c)){const r=f(e).node,c=new Set,i=new Date().toISOString(),s=[],a=[];for(const{doc:d,level:p}of n)p!=="content"||c.has(d.object.id)||(c.add(d.object.id),a.push({watcher:r,object:d.object,start:"deliver",opts:{readHeadsKey:d.headsKey}}),s.push({name:d.name,scope:d.ownerHandle,at:i,type:"loaded"}));await U(t,a),await J(t,a.map(d=>({event:"read",object:d.object,actor:r,attrs:{}})),o),v(f(e))||await q(t,r.id,s)}l(ve,"recordContentDelivery");async function F(t,e,n){if(await b(t,e,n))return e;const o=(await h(t,M(n))).filter(r=>!e.repos.some(c=>c.id===r.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(r=>r.repo)],checkouts:[...e.checkouts,...o]}}l(F,"fileReadReader");async function b(t,e,n){const o=await g(t,e);if(o!=="app:terminal"||!$()||e.profile==null)return!1;const r=await ue(t,e.profile.id);return r!==null&&await T(r)!==null&&!O(n,o,e.scopes??[],null)}l(b,"isMacEnforcedRead");async function P(t,e,n){if(!await b(t,e,n))return{absoluteFile:n};const o=new Map;for(const{root:r,repo:c}of e.checkouts)n.startsWith(r.endsWith("/")?r:`${r}/`)&&!o.has(c.id)&&o.set(c.id,r);return{absoluteFile:n,readFrontmatter:{},repoRoots:o,remotePath:!0}}l(P,"fileReadPayload");async function ge(t,e,n){const o=await g(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||await b(t,e,n)||O(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(ge,"assertReadableFile");async function be(t){const e=f(t.reader),n=e.node,o=await g(t.db,e),r=await w(t.db,t.reader,["slash-command"]);await pe(t.db,r);const c=await D(r,async i=>{const s=await i.body();return{name:i.displayName,command_name:i.displayName,description:i.preview,canonical_body:s,execution_body:se(s,n.id,o)}});return{docs:r,commands:c}}l(be,"slashCommands");function je(t){if(t.shipped)return"builtin";switch(t.owner.type){case"node":return"node";case"repo":return"project";case"profile":return"profile";default:return"user"}}l(je,"scopeOf");async function Ne(t,e){const n=[],o=new Set,r=await me(t,e),c=await le(t,e,r);for(const i of r){const s=c.get(i.id);for(const a of s){n.push({name:a.displayName,kind:a.kind,scope:je(a),shortForm:a.preview,gatewayVisible:!a.shipped}),o.add(a.displayName);const d=a.displayName===a.name?"":`${a.ownerHandle}/`;for(const p of fe(s,a.name))o.add(`${d}${p}`)}}return{refs:n,names:[...o]}}l(Ne,"composerNames");async function x(t,e){const n=f(t.reader),{db:o,ledger:r}=t,c=l(()=>{if(typeof e.subject!="string"||e.subject==="")throw new m(400,"usage",`delivery activity ${e.activity} requires a subject`);return e.subject},"requireSubject");switch(e.activity){case"boot":{if(e.inherited===!0){for(const[a,d]of r.objects)if(d.transcript===void 0)r.objects.delete(a);else{const{system:p,...u}=d;r.objects.set(a,u)}for(const[a,d]of r.listed)d.transcript===void 0?r.listed.delete(a):r.listed.set(a,{transcript:d.transcript});return r.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const i=v(n)?await ke(t):await ce(n.node.id,t,Oe(e)),s=await S({...t,channel:"system"});return N(r,s.content),{result:{content:i.content},delivered:[...i.delivered,...s.delivered]}}case"system-prompt":{if(r.preferenceSnapshot!==null)return{result:{content:r.preferenceSnapshot},delivered:[]};const i=await S({...t,channel:"system"});return{result:{content:N(r,i.content)},delivered:i.delivered}}case"compact":{for(const i of await w(o,n,["pre-command"]))W(r,i.object.id);return{result:{content:""},delivered:[]}}case"persona":{const i=await ye(t);return{result:{content:i.content},delivered:i.delivered}}case"file-read":{const i=c();await ge(o,n,i);const s=await F(o,n,i),a={...t,reader:s},d=await _(a,"file-read",await P(o,n,i),await w(o,s,["file-read"]));return{result:{content:d.content},delivered:d.delivered}}case"command":case"pre-command":{const i=await _(t,e.activity,{command:c()});return{result:{content:i.content},delivered:i.delivered}}case"slash-command":{const{docs:i,commands:s}=await be(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const a=i.findIndex(u=>u.displayName===e.subject||u.name===e.subject);if(a<0)throw new m(404,"not_found",`no slash command named ${e.subject}`);const d=i[a],p=await C(t,d,!0);return{result:{content:"",execution_body:s[a].execution_body,blocks:p.attachments===""?[]:[p.attachments]},delivered:[{doc:d,level:"content"},...p.delivered]}}case"workspace-open":{const i=await E(t);return{result:{content:i.content},delivered:i.delivered}}case"document-read":{const i=await A(o,n,c()),s=await C(t,await k(o,n,i),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await Ne(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(x,"render");function Oe(t){if(t.projectContext===void 0)throw new Error("a node boot delivery needs its project context built before the transaction: pass the request through withProjectContext");return t.projectContext}l(Oe,"requireProjectContext");async function ke(t){const e=await he(t),n=await E(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
2
+ `),delivered:[...e.delivered,...n.delivered]}}l(ke,"hypotheticalBearings");async function A(t,e,n){const o=await z(t,e,n);if("object"in o&&o.object.type==="document")return o.object;throw"ambiguous"in o?new m(409,"ambiguous",`${n} names ${o.ambiguous.length} documents; name one as <type>:<owner>/<name>`):new m(404,"not_found",`no document ${n} the reader can read`)}l(A,"readDocument");const Re=["workspace-open","document-read"];async function rt(t,e,n,o){if(Re.includes(n.activity))throw new m(400,"usage",`delivery activity ${n.activity} is available to a dry run only`);const r=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await H(t,r.id);const c=await Y(t,r.id),i={db:t,reader:e,subject:o??await R(t,e),ledger:c,channel:"transcript"},{result:s,delivered:a}=await x(i,n);return await ve(t,e,a),await B(t,c),s}l(rt,"deliver");const _e={boot:"boot","workspace-open":"workspace-open","file-read":"file-read","document-read":"document-read",command:"command","pre-command":"pre-command","slash-command":"slash-command"};async function it(t,e){const n=await Z(t);if(n===null)throw new m(404,"not_found",`no node ${t}`);return{cwd:e.cwd??n.cwd,profile:e.profile!==void 0?e.profile:n.profile_id,grantee:e.grantee??n.grantee,kind:e.kind??n.kind,mode:e.mode??n.mode,lifecycle:e.lifecycle??n.lifecycle,hasManager:e.hasManager??(n.parent??null)!==null,depth:e.depth??await ie(t)}}l(it,"hypotheticalFrom");function Ce(t,e){if(t===null)return null;if(t===void 0||t==="")return te(e);const n=ee(t);if(n.kind!=="resolved"){const o=`no profile ${t}`;throw new m(404,"not_found",o,{error:"not_found",message:o,next:"List profile ids and names with `crtr profile list`."})}return n.entry.profileId}l(Ce,"resolveProfileId");async function at(t,e){const n=await X(t,e.grantee??"app:terminal"),o=Ce(e.profile,e.cwd),r=await G(t,e.cwd,o,async(p,u,y)=>await h(t,p,u,y),K(t)),{repos:c}=r,i=e.mode??"base",a={class:"node",node:{id:I,seq:0,type:"node",kind:e.kind??"general",owner:n.id,privacy:"private",name:"hypothetical",preview:"",created_at:new Date(0).toISOString(),deleted_at:null},app:n,scopes:[...Q],cwd:e.cwd,...r,profile:o===null?null:await V(t,o,n)},d={kind:e.kind??"general",mode:i,lifecycle:e.lifecycle??(i==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:re(e.cwd),orchestration:{depth:e.depth??0},profile:oe(o),app:e.grantee??"app:terminal",scopes:ne(null),repo:[...c,...r.projectRepos].map(p=>p.name)};return{reader:a,subject:d}}l(at,"hypotheticalReader");async function st(t,e,n,o,r){const i={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...r??await R(t,e),...o},a={db:t,reader:e,subject:s,ledger:i,channel:"transcript"},{result:d}=await x(a,n),p=_e[n.activity];let u=null;if(p!==void 0){const y=n.activity==="file-read"?await P(t,f(e),n.subject):n.activity==="command"||n.activity==="pre-command"?{command:n.subject}:n.activity==="document-read"&&n.subject!==void 0?{doc:await k(t,e,await A(t,e,n.subject))}:{},j=n.activity==="file-read"&&n.subject!==void 0?await F(t,f(e),n.subject):e;u=await we(t,s,j,await w(t,j,[p]),p,y)}return{result:d,plan:u}}l(st,"inspect");async function ct(t,e,n){const o=await t.prepare(`SELECT o.*, MAX(r.number) AS to_seq, string_agg(DISTINCT a.id, ',') AS authors
3
3
  FROM watches w JOIN objects o ON o.id = w.object AND o.type = 'document' AND o.deleted_at IS NULL
4
4
  JOIN revisions r ON r.document = o.id LEFT JOIN objects a ON a.id = r.author
5
5
  WHERE w.watcher = ? AND r.created_at > ? AND (r.author IS NULL OR r.author != ?)
6
- GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await I(o,async({to_seq:r,authors:c,...a})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(a.id,n);return{doc:a,from:s.seq,to:r,authors:c===null?[]:c.split(",")}})}l(at,"changedWhileDone");export{ke as DRY_RUN_ONLY,at as changedWhileDone,tt as deliver,nt as hypotheticalFrom,ot as hypotheticalReader,rt as inspect,he as recordContentDelivery};
6
+ GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await D(o,async({to_seq:r,authors:c,...i})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(i.id,n);return{doc:i,from:s.seq,to:r,authors:c===null?[]:c.split(",")}})}l(ct,"changedWhileDone");export{Re as DRY_RUN_ONLY,ct as changedWhileDone,rt as deliver,it as hypotheticalFrom,at as hypotheticalReader,st as inspect,ve as recordContentDelivery,ot as withProjectContext};
@@ -1 +1 @@
1
- var K=Object.defineProperty;var s=(t,e)=>K(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as z,findNodeBySessionFile as Q,getNode as v,getNodes as X,isWarmSpare as Z,recordLaunch as I,recordRespawnAttempt as q,recordSettledTurn as ee,setPresence as g,subscriptionsOf as te,updateNode as S,updateNodeTelemetry as ne}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as x,recordExecutionIdle as ie,recordExecutionPid as re}from"../../../core/canvas/executions.js";import{bindSession as oe,readLiveSession as ae,transferSession as se}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ce}from"../../../core/canvas/paths.js";import{isPidAlive as de}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as le}from"../../../core/substrate/subject.js";import{shareCorpusReads as ue}from"../../../core/substrate/delivery/corpus.js";import{openDb as R,withCanvasWrite as w}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as E,usage as d}from"../../../core/errors.js";import{hasUnseenWakeMail as T,releaseExecutionMail as fe}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as me}from"../../../core/runtime/kickoff.js";import{readRoadmap as we}from"../../../core/runtime/roadmap.js";import{forkSourceNode as ye}from"../../../core/runtime/nodes.js";import{transition as b}from"../../../core/runtime/lifecycle.js";import{confirmViewer as C,probeViewer as F,tearDownNode as N}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as he}from"../viewer-presence.js";import{evaluateStop as be}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as B}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as _e,recordFault as ke}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ve}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as ge}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as Se,recordPendingParkActivity as xe}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Ee}from"../../../core/runtime/situational-context.js";import{recoveryState as Oe,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Ce}from"../../../core/graph/reader.js";import{checkoutsForCwd as Fe}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Ne}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as Be}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Le,writeNodeTelemetryRecord as De}from"./telemetry-record.js";import{mapAsync as Me}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Ue}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ve}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as $e,cycleCompatible as We}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as je,drainBearings as He}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Je}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ge}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Ye}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Ke}from"../../../core/runtime/stamp/protocol.js";import{ApiError as ze}from"../../../api/errors.js";function m(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} requires a JSON body`);return t}s(m,"objectBody");function M(t){const e=m(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw d("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw d("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw d("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw d("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw d("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw d("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function Qe(t){const e=m(t,"broker settle");if(typeof e.stopReason!="string")throw d("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw d(`${n} must be a boolean`);return e}s(Qe,"parseSettleBody");function Xe(t){const e=m(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw d("brokerVersion must be a non-empty string");return e}s(Xe,"parseCycleBody");function Ze(t){const e=m(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw d("outcome must be completed or failed");return e}s(Ze,"parseParkCompleteBody");function Ie(t){const e=m(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw d("expected_execution_id must be a non-empty string");const n=Le(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(Ie,"parseTelemetryBody");function qe(t){const e=m(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw d("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw d("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw d("userSelected must be a boolean");return e}s(qe,"parseModelCommitBody");async function y(t){const e=await v(t);if(e===null)throw E(`unknown node: ${t}`,{received:t});return e}s(y,"requireNode");async function _(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(_,"extensionNode");async function U(t,e){const n=await y(t),r=[],i=new Set([t]);let a=n.parent??null;for(;a!==null&&a!==""&&!i.has(a);){i.add(a);const u=await v(a);if(u===null)break;r.unshift(await _(u)),a=u.parent??null}const o=await Me((await X((await te(t)).map(u=>u.node_id))).filter(u=>u.kind!=="human").sort((u,p)=>u.status===p.status?0:u.status==="active"?-1:p.status==="active"?1:0),_),c=typeof n.fork_source_file=="string"?await ye(n.fork_source_file):null,l=e??await le(t);if(l===null)throw E(`unknown node: ${t}`,{received:t});return{node:await _(n),warm_spare:await Z(t),situational_card:await Ee(t),ancestors:r,children:o,fork_source:c===null?null:await _(c),subject:l,roadmap:await we(t)}}s(U,"extensionState");function A(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(A,"samePersona");function et(t){const e=m(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw d("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw d("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw d("recap expected must contain name, description, title, icon, and kind strings");return e}s(et,"parseGeneratedNameBody");function tt(t){const e=m(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw d(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(tt,"parsePersonaAckBody");async function V(t,e){const n=e.sessionFile===null?null:z(e.sessionFile);return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t);if(await re(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await Q(n);if(o!==null&&o.node_id!==t){if(de(o.pi_pid))return await ke(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await ae(o.node_id);if(c===null||await se({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await oe(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await me(t),i.intent==="refresh"&&await b(t,"revive")),{action:"none"}})}s(V,"commitSessionBound");async function nt(t){return{status:200,body:await V(t.params.id,M(t.body))}}s(nt,"handleSessionBound");function it(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw d("bearings must be fresh, inherited or present");return e}s(it,"parseCycleStartBody");async function rt(t,e,n,r,i,a){const o=r.warm_spare||a,c=!o&&i!=="present",l=await O(t,e,{activity:"names"},n),u=c?await O(t,e,{activity:"boot",...i==="inherited"?{inherited:!0}:{}},n):void 0,p=o?void 0:await O(t,e,{activity:"system-prompt"},n);return{names:{refs:l.refs,names:l.names},...u===void 0?{}:{boot:{content:u.content,...u.inherited===!0?{inherited:!0}:{}}},...p===void 0?{}:{system_prompt:p.content}}}s(rt,"startupDelivery");async function $(t,e,n,r=!1){r||await Ce(await R(),t);const{state:i,delivery:a}=await w(async o=>{const c=await Te(o,t,async(p,k,Y)=>await Fe(o,p,k,Y));ue(c);const l=await Ne(o,c),u=await U(t,l);return{state:u,delivery:await rt(o,c,l,u,e,n)}});if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,l=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};A(l,o)||await G(t,l,o)}return{state:i,delivery:a}}s($,"renderStartData");async function fn(t){const{state:e,delivery:n}=await $(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(fn,"renderCarriedStart");async function ot(t){const e=t.params.id,n=it(t.body),r=await y(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.pi_session_id==null;if(o)await f(e,n.executionId);else{const{action:p}=await V(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:l}=await $(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...l,recovery:await Oe(e),attachments:(await Ae(e)).map(({path:p,sha256:k})=>({path:p,sha256:k})),structured_request:await B(e)}}}s(ot,"handleCycleStart");async function W(t,e){return e.live!==null||await he(t)||await T(t)}s(W,"isHeldAwake");async function j(t,e){return(await x(t))?.runner==="blaxel"&&!await W(t,e)&&(await pe(await R(),t)).length===0}s(j,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function at(t,e,n){const r=await v(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw E(`unknown node: ${t}`,{received:t})}if(await ee(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await q(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await b(t,"finish"),await h(t),await g(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await _e(t))?.retry.disposition==="fatal"&&await B(t)===null&&await j(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await g(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:H(e),closePane:!1};const a=await be(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await T(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await W(t,n);return(await x(t))?.runner==="blaxel"?{directive:await j(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await b(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(at,"settleBroker");async function st(t){const e=t.params.id,n=Xe(t.body);await f(e,n.expected_execution_id);const r=await y(e);if(r.intent!=="refresh")throw new ze(409,"not_yielding",`${e} has no pending yield`);const i=await x(e),a=Ue(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&We(i.launchJson,await Ve(e,a,r.cwd))?{status:200,body:await ct(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(st,"handleCycle");async function ct(t,e,n,r){e.cycles=(e.cycles??0)+1,await fe(t,n);const i=await He(e,n),a=await je(e,i);await Je(t),await Ge(t,e,!1),await Ye(t),await h(t,{preserveEpisode:!0}),await I(t,new Date().toISOString()),await(await R()).prepare("UPDATE nodes SET cycles = ?, cycle_pending = 1, intent = NULL WHERE node_id = ?").run(e.cycles,t);const o={};for(const c of $e)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Ke({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(ct,"startCycleRecord");async function dt(t){const e=t.params.id,n=m(t.body,"broker idle");return await f(e,n.expected_execution_id),await ie(n.expected_execution_id),{status:204}}s(dt,"handleIdle");async function lt(t){const e=t.params.id,n=Qe(t.body);await f(e,n.expected_execution_id);const r=await F(e),{directive:i,closePane:a}=await w(async()=>await at(e,n,await C(r)));return a&&await N(e),i.action!=="reprompt"&&ge(e).catch(o=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(lt,"handleSettle");async function ut(t){const e=t.params.id,n=Ze(t.body);await f(e,n.expected_execution_id);const r=await F(e),i=await w(async()=>{const a=await Se(e);if(a===void 0)return{action:"stay_dormant"};const o=await y(e);return await Pe(e,o,a,await C(r))?(await h(e),await b(e,"park"),await g(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ce(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await N(e),{status:200,body:i}}s(ut,"handleParkComplete");async function pt(t){const e=t.params.id;return await f(e,m(t.body,"broker park-activity").expected_execution_id),{status:200,body:await w(async()=>({activity:await xe(e)?"recorded":"none"}))}}s(pt,"handleParkActivity");async function ft(t){const e=t.params.id,n=Ie(t.body);return await f(e,n.expected_execution_id),await w(async()=>{await ne(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),De(e,n)}),{status:204}}s(ft,"handleTelemetry");async function mt(t){const e=t.params.id,n=qe(t.body);return await f(e,n.expected_execution_id),{status:200,body:{modelOverride:(await w(async()=>await ve(await y(e),n.spec,n.intent,n.userSelected))).model_override}}}s(mt,"handleModelCommit");let J=!0;function mn(t){J=t}s(mn,"setRequestsStartRunObservers");async function wt(t){const e=t.params.id,n=await y(e);return n.run_id&&J&&await Be(e,n.run_id),{status:200,body:await U(e)}}s(wt,"handleExtensionState");async function yt(t){const e=t.params.id,n=et(t.body);return await f(e,n.expected_execution_id),{status:200,body:await w(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await y(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const l=await S(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(l),description:l.description??"",title:l.title??"",icon:l.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await S(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(yt,"handleGeneratedName");async function ht(t){const e=t.params.id,n=tt(t.body);return await f(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(ht,"handlePersonaAck");async function G(t,e,n){return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!A(a,n)||!A(c,e)?!1:(await S(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const wn=Re([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:nt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:ot},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:lt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:mt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:yt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:ht}]);export{wn as brokerOperationRoutes,_ as extensionNode,fn as renderCarriedStart,$ as renderStartData,mn as setRequestsStartRunObservers};
1
+ var z=Object.defineProperty;var s=(t,e)=>z(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as Q,findNodeBySessionFile as X,getNode as v,getNodes as Z,isWarmSpare as q,recordLaunch as I,recordRespawnAttempt as ee,recordSettledTurn as te,setPresence as g,subscriptionsOf as ne,updateNode as x,updateNodeTelemetry as ie}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as re,recordExecutionPid as oe}from"../../../core/canvas/executions.js";import{bindSession as ae,readLiveSession as se,transferSession as ce}from"../../../core/canvas/sessions.js";import{isSafeNodeId as de}from"../../../core/canvas/paths.js";import{isPidAlive as le}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as ue}from"../../../core/substrate/subject.js";import{shareCorpusReads as pe}from"../../../core/substrate/delivery/corpus.js";import{openDb as R,withCanvasWrite as y}from"../../../core/canvas/db.js";import{runningJobs as fe}from"../../../core/graph/jobs.js";import{notFound as E,usage as u}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as me}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as we}from"../../../core/runtime/kickoff.js";import{readRoadmap as ye}from"../../../core/runtime/roadmap.js";import{forkSourceNode as he}from"../../../core/runtime/nodes.js";import{transition as _}from"../../../core/runtime/lifecycle.js";import{confirmViewer as T,probeViewer as F,tearDownNode as N}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as be}from"../viewer-presence.js";import{evaluateStop as _e}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as B}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as ke,recordFault as ve}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ge}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as xe}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as Se,recordPendingParkActivity as Pe}from"../../park-pending.js";import{shouldParkAfterSummary as Re}from"../../park-activity.js";import{ownerOnly as Ee}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ae,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ce}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Ne}from"../../../core/graph/repo-sync/repos.js";import{deliver as O,withProjectContext as Be}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Le}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as De}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Me,writeNodeTelemetryRecord as je}from"./telemetry-record.js";import{mapAsync as Ue}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Ve}from"../../../core/runtime/launch.js";import{brokerLaunchJson as $e}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as We,cycleCompatible as He}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Je,drainBearings as Ge}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Ye}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ke}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as ze}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Qe}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Xe}from"../../../api/errors.js";function m(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw u(`${e} requires a JSON body`);return t}s(m,"objectBody");function M(t){const e=m(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw u("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw u("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw u("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw u("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw u("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw u("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function Ze(t){const e=m(t,"broker settle");if(typeof e.stopReason!="string")throw u("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw u(`${n} must be a boolean`);return e}s(Ze,"parseSettleBody");function qe(t){const e=m(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw u("brokerVersion must be a non-empty string");return e}s(qe,"parseCycleBody");function Ie(t){const e=m(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw u("outcome must be completed or failed");return e}s(Ie,"parseParkCompleteBody");function et(t){const e=m(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw u("expected_execution_id must be a non-empty string");const n=Me(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(et,"parseTelemetryBody");function tt(t){const e=m(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw u("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const o=n!==null&&typeof n=="object"?n:void 0;if(o===void 0||typeof o.family!="string"||o.family===""||!["ultra","strong","medium","light"].includes(o.strength))throw u("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw u("userSelected must be a boolean");return e}s(tt,"parseModelCommitBody");async function w(t){const e=await v(t);if(e===null)throw E(`unknown node: ${t}`,{received:t});return e}s(w,"requireNode");async function k(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(k,"extensionNode");async function j(t,e){const n=await w(t),o=[],i=new Set([t]);let r=n.parent??null;for(;r!==null&&r!==""&&!i.has(r);){i.add(r);const l=await v(r);if(l===null)break;o.unshift(await k(l)),r=l.parent??null}const a=await Ue((await Z((await ne(t)).map(l=>l.node_id))).filter(l=>l.kind!=="human").sort((l,p)=>l.status===p.status?0:l.status==="active"?-1:p.status==="active"?1:0),k),c=typeof n.fork_source_file=="string"?await he(n.fork_source_file):null,d=e??await ue(t);if(d===null)throw E(`unknown node: ${t}`,{received:t});return{node:await k(n),warm_spare:await q(t),situational_card:await Oe(t),ancestors:o,children:a,fork_source:c===null?null:await k(c),subject:d,roadmap:await ye(t)}}s(j,"extensionState");function A(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(A,"samePersona");function nt(t){const e=m(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw u("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw u("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(o=>typeof n[o]!="string"))throw u("recap expected must contain name, description, title, icon, and kind strings");return e}s(nt,"parseGeneratedNameBody");function it(t){const e=m(t,"broker persona-ack"),n=s(o=>{const i=e[o];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw u(`${o} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(it,"parsePersonaAckBody");async function U(t,e){const n=e.sessionFile===null?null:Q(e.sessionFile);return await y(async o=>{await o.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await w(t);if(await oe(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const r=i.review_binding?.review_id;if(r!==void 0&&!e.reviewBoundaryIds.includes(r))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const a=n===null?null:await X(n);if(a!==null&&a.node_id!==t){if(le(a.pi_pid))return await ve(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${a.node_id}`}),{action:"shutdown"};const c=await se(a.node_id);if(c===null||await ce({fromNodeId:a.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await ae(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await we(t),i.intent==="refresh"&&await _(t,"revive")),{action:"none"}})}s(U,"commitSessionBound");async function rt(t){return{status:200,body:await U(t.params.id,M(t.body))}}s(rt,"handleSessionBound");function ot(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw u("bearings must be fresh, inherited or present");return e}s(ot,"parseCycleStartBody");async function at(t,e,n,o,i,r,a){const c=o.warm_spare||r,d=!c&&i!=="present",l=await O(t,e,{activity:"names"},n),p=d?await O(t,e,{activity:"boot",...i==="inherited"?{inherited:!0}:{},...a===void 0?{}:{projectContext:a}},n):void 0,b=c?void 0:await O(t,e,{activity:"system-prompt"},n);return{names:{refs:l.refs,names:l.names},...p===void 0?{}:{boot:{content:p.content,...p.inherited===!0?{inherited:!0}:{}}},...b===void 0?{}:{system_prompt:b.content}}}s(at,"startupDelivery");async function V(t,e,n,o=!1){o||await Fe(await R(),t);const i=!n&&e==="fresh"?(await Be(t,{activity:"boot"})).projectContext:void 0,{state:r,delivery:a}=await y(async c=>{const d=await Te(c,t,async(b,Y,K)=>await Ne(c,b,Y,K));pe(d);const l=await Le(c,d),p=await j(t,l);return{state:p,delivery:await at(c,d,l,p,e,n,i)}});if(a.boot!==void 0){const c={kind:r.node.kind,mode:r.node.mode,lifecycle:r.node.lifecycle},d=r.node.persona_ack,l=d===void 0?c:{kind:d.kind??r.node.kind,mode:d.mode,lifecycle:d.lifecycle};A(l,c)||await G(t,l,c)}return{state:r,delivery:a}}s(V,"renderStartData");async function wn(t){const{state:e,delivery:n}=await V(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(wn,"renderCarriedStart");async function st(t){const e=t.params.id,n=ot(t.body),o=await w(e),i=o.review_binding?.review_id,r=i!==void 0&&!n.reviewBoundaryIds.includes(i),a=r||o.cycle_pending===!0||o.pi_session_id==null;if(a)await f(e,n.executionId);else{const{action:p}=await U(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:d}=await V(e,n.bearings,r);return{status:200,body:{action:"none",...a?{bind_pending:!0}:{},state:c,...d,recovery:await Ae(e),attachments:(await Ce(e)).map(({path:p,sha256:b})=>({path:p,sha256:b})),structured_request:await B(e)}}}s(st,"handleCycleStart");async function $(t,e){return e.live!==null||await be(t)||await C(t)}s($,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await $(t,e)&&(await fe(await R(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function ct(t,e,n){const o=await v(t);if(o===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw E(`unknown node: ${t}`,{received:t})}if(await te(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await ee(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(o.status==="active"||o.status==="idle")&&o.intent===null&&(await _(t,"finish"),await h(t),await g(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),o.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await ke(t))?.retry.disposition==="fatal"&&await B(t)===null&&await W(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||o.status==="done")return await h(t),await g(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(o.intent==="refresh")return await h(t),{directive:H(e),closePane:!1};const r=await _e(t,i);if(await h(t),r.action==="reprompt")return{directive:{action:"reprompt",prompt:r.message},closePane:!1};if(r.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const a=await $(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:r.reason!=="awaiting"&&r.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:a?{directive:{action:"stay_dormant"},closePane:!1}:(await _(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ct,"settleBroker");async function dt(t){const e=t.params.id,n=qe(t.body);await f(e,n.expected_execution_id);const o=await w(e);if(o.intent!=="refresh")throw new Xe(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),r=Ve(o);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&He(i.launchJson,await $e(e,r,o.cwd))?{status:200,body:await lt(e,o,i.executionId,r.env)}:{status:200,body:{action:"restart"}}}s(dt,"handleCycle");async function lt(t,e,n,o){e.cycles=(e.cycles??0)+1,await me(t,n);const i=await Ge(e,n),r=await Je(e,i);await Ye(t),await Ke(t,e,!1),await ze(t),await h(t,{preserveEpisode:!0}),await I(t,new Date().toISOString()),await(await R()).prepare("UPDATE nodes SET cycles = ?, cycle_pending = 1, intent = NULL WHERE node_id = ?").run(e.cycles,t);const a={};for(const c of We)o[c]!==void 0&&(a[c]=o[c]);return a.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:r,origin:Qe({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:a,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(lt,"startCycleRecord");async function ut(t){const e=t.params.id,n=m(t.body,"broker idle");return await f(e,n.expected_execution_id),await re(n.expected_execution_id),{status:204}}s(ut,"handleIdle");async function pt(t){const e=t.params.id,n=Ze(t.body);await f(e,n.expected_execution_id);const o=await F(e),{directive:i,closePane:r}=await y(async()=>await ct(e,n,await T(o)));return r&&await N(e),i.action!=="reprompt"&&xe(e).catch(a=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:a})),{status:200,body:i}}s(pt,"handleSettle");async function ft(t){const e=t.params.id,n=Ie(t.body);await f(e,n.expected_execution_id);const o=await F(e),i=await y(async()=>{const r=await Se(e);if(r===void 0)return{action:"stay_dormant"};const a=await w(e);return await Re(e,a,r,await T(o))?(await h(e),await _(e,"park"),await g(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...de(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await N(e),{status:200,body:i}}s(ft,"handleParkComplete");async function mt(t){const e=t.params.id;return await f(e,m(t.body,"broker park-activity").expected_execution_id),{status:200,body:await y(async()=>({activity:await Pe(e)?"recorded":"none"}))}}s(mt,"handleParkActivity");async function wt(t){const e=t.params.id,n=et(t.body);return await f(e,n.expected_execution_id),await ie(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),je(e,n),{status:204}}s(wt,"handleTelemetry");async function yt(t){const e=t.params.id,n=tt(t.body);return await f(e,n.expected_execution_id),{status:200,body:{modelOverride:(await y(async()=>await ge(await w(e),n.spec,n.intent,n.userSelected))).model_override}}}s(yt,"handleModelCommit");let J=!0;function yn(t){J=t}s(yn,"setRequestsStartRunObservers");async function ht(t){const e=t.params.id,n=await w(e);return n.run_id&&J&&await De(e,n.run_id),{status:200,body:await j(e)}}s(ht,"handleExtensionState");async function bt(t){const e=t.params.id,n=nt(t.body);return await f(e,n.expected_execution_id),{status:200,body:await y(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const r=await w(e);if(n.kind==="initial"){if((r.description??"").trim()!=="")return{applied:!1};const d=await x(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(d),description:d.description??"",title:d.title??"",icon:d.icon??""}}const a=n.expected;if(r.name!==a.name||(r.description??"")!==a.description||(r.title??"")!==a.title||(r.icon??"")!==a.icon||r.kind!==a.kind)return{applied:!1};const c=await x(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(bt,"handleGeneratedName");async function _t(t){const e=t.params.id,n=it(t.body);return await f(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(_t,"handlePersonaAck");async function G(t,e,n){return await y(async o=>{await o.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await w(t),r={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},a=i.persona_ack,c=a===void 0?r:{kind:a.kind??i.kind,mode:a.mode,lifecycle:a.lifecycle};return!A(r,n)||!A(c,e)?!1:(await x(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const hn=Ee([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:mt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:bt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:_t}]);export{hn as brokerOperationRoutes,k as extensionNode,wn as renderCarriedStart,V as renderStartData,yn as setRequestsStartRunObservers};
@@ -1 +1 @@
1
- var k=Object.defineProperty;var d=(e,n)=>k(e,"name",{value:n,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{dirname as N}from"node:path";import{openDb as q,withCanvasWrite as h}from"../../../core/canvas/db.js";import{readerForNode as p,warmNodeDirs as b,warmNodeRepos as A}from"../../../core/graph/reader.js";import{checkoutsForCwd as y}from"../../../core/graph/repo-sync/repos.js";import{DRY_RUN_ONLY as D,deliver as R,hypotheticalFrom as C,hypotheticalReader as O,inspect as w}from"../../../core/substrate/delivery/deliver.js";import{actsAsPerson as S,mayOnNode as P}from"../router.js";import{requireCurrentExecution as T}from"./broker-recovery.js";const E=["boot","system-prompt","compact","persona","file-read","command","pre-command","slash-command","names",...D];function g(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","delivery requires a JSON body");const n=e;if(!E.includes(n.activity))throw new r(400,"usage",`invalid delivery activity: ${String(n.activity)}`);if(n.subject!==void 0&&typeof n.subject!="string")throw new r(400,"usage","delivery subject must be a string");return n}d(g,"parse");async function v(e,n,i){const t=e.principal;if(t.class==="person"&&t.sub!==void 0){if(i!==void 0)throw new r(403,"permission_error","a hypothetical delivery dry run is not available to a person bearer; name a node you can read");if(n===void 0||!await P(t,"read",n))throw new r(404,"not_found","node not found");return}F(e)}d(v,"requireDryRunCaller");function F(e){if(!S(e.principal)&&e.principal.class!=="broker")throw new r(403,"permission_error","a delivery dry run is available to a person or a node only")}d(F,"requirePerson");function W(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","hypothetical must be an object");const n=d((o,s)=>{if(o!==void 0){if(typeof o!="string"||o==="")throw new r(400,"usage",`hypothetical.${s} must be a non-empty string`);return o}},"str"),i=n(e.cwd,"cwd");if(i!==void 0&&!i.startsWith("/"))throw new r(400,"usage","hypothetical.cwd must be an absolute path");if(e.mode!==void 0&&e.mode!=="base"&&e.mode!=="orchestrator")throw new r(400,"usage","hypothetical.mode must be base or orchestrator");if(e.lifecycle!==void 0&&e.lifecycle!=="terminal"&&e.lifecycle!=="resident")throw new r(400,"usage","hypothetical.lifecycle must be terminal or resident");if(e.has_manager!==void 0&&typeof e.has_manager!="boolean")throw new r(400,"usage","hypothetical.has_manager must be a boolean");if(e.depth!==void 0&&(!Number.isInteger(e.depth)||e.depth<0))throw new r(400,"usage","hypothetical.depth must be a non-negative integer");const t={};i!==void 0&&(t.cwd=i),e.profile!==void 0&&(t.profile=e.profile===null?null:n(e.profile,"profile"));const u=n(e.grantee,"grantee");u!==void 0&&(t.grantee=u);const a=n(e.kind,"kind");return a!==void 0&&(t.kind=a),e.mode!==void 0&&(t.mode=e.mode),e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),e.has_manager!==void 0&&(t.hasManager=e.has_manager),e.depth!==void 0&&(t.depth=e.depth),t}d(W,"hypotheticalOf");async function m(e,n,i){const t=await q();e!==void 0&&await A(t,e),n&&await b(t,e,[n]),i!==void 0&&i.startsWith("/")&&await b(t,e,[N(i)])}d(m,"warmDeliveryCwds");async function I(e){const n=g(e.body);if(n.node!==void 0&&typeof n.node!="string")throw new r(400,"usage","node must be a node id");await v(e,n.node,n.hypothetical);const i={activity:n.activity,...n.subject!==void 0?{subject:n.subject}:{}};await m(n.node,n.hypothetical?.cwd,n.activity==="file-read"?n.subject:void 0);const{result:t,plan:u}=await h(async a=>{if(n.hypothetical===void 0){if(n.node===void 0)throw new r(400,"usage","a delivery dry run names a node, a hypothetical node, or both");return await w(a,await p(a,n.node,async(l,j,_)=>await y(a,l,j,_)),i,n.subject_override)}const o=W(n.hypothetical),s=n.node!==void 0?await C(n.node,o):{...o,cwd:o.cwd??""};if(s.cwd==="")throw new r(400,"usage","a hypothetical node needs a cwd");const{reader:c,subject:f}=await O(a,s);return await w(a,c,i,n.subject_override,f)},{rollback:!0});return{status:200,body:{...t,plan:u}}}d(I,"handleDryRun");async function Y(e){const n=e.params.id,i=g(e.body),t={activity:i.activity,...i.subject!==void 0?{subject:i.subject}:{},...i.inherited===!0?{inherited:!0}:{}};if(i.dry_run===!0){await v(e,n,void 0),await m(n,void 0,i.activity==="file-read"?i.subject:void 0);const{result:a,plan:o}=await h(async s=>await w(s,await p(s,n,async(c,f,l)=>await y(s,c,f,l)),t,i.subject_override),{rollback:!0});return{status:200,body:{...a,plan:o}}}if(e.principal.class==="broker"&&e.principal.node!==n)throw new r(403,"permission_error","delivery is performed by the node's own broker");return await T(n,i.expected_execution_id),await m(n,void 0,i.activity==="file-read"?i.subject:void 0),{status:200,body:await h(async a=>await R(a,await p(a,n,async(o,s,c)=>await y(a,o,s,c)),t))}}d(Y,"handleDelivery");const H=[{method:"POST",pattern:"/v1/nodes/:id/delivery",handler:Y},{method:"POST",pattern:"/v1/delivery/dry-run",handler:I}];export{H as deliveryRoutes};
1
+ var q=Object.defineProperty;var s=(e,n)=>q(e,"name",{value:n,configurable:!0});import{ApiError as a}from"../../../api/errors.js";import{dirname as A}from"node:path";import{openDb as C,withCanvasWrite as y}from"../../../core/canvas/db.js";import{readerForNode as w,warmNodeDirs as j,warmNodeRepos as D}from"../../../core/graph/reader.js";import{checkoutsForCwd as m}from"../../../core/graph/repo-sync/repos.js";import{DRY_RUN_ONLY as R,deliver as O,hypotheticalFrom as P,hypotheticalReader as S,inspect as b,withProjectContext as g}from"../../../core/substrate/delivery/deliver.js";import{actsAsPerson as T,mayOnNode as E}from"../router.js";import{requireCurrentExecution as F}from"./broker-recovery.js";const W=["boot","system-prompt","compact","persona","file-read","command","pre-command","slash-command","names",...R];function _(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new a(400,"usage","delivery requires a JSON body");const n=e;if(!W.includes(n.activity))throw new a(400,"usage",`invalid delivery activity: ${String(n.activity)}`);if(n.subject!==void 0&&typeof n.subject!="string")throw new a(400,"usage","delivery subject must be a string");return n}s(_,"parse");async function k(e,n,i){const t=e.principal;if(t.class==="person"&&t.sub!==void 0){if(i!==void 0)throw new a(403,"permission_error","a hypothetical delivery dry run is not available to a person bearer; name a node you can read");if(n===void 0||!await E(t,"read",n))throw new a(404,"not_found","node not found");return}I(e)}s(k,"requireDryRunCaller");function I(e){if(!T(e.principal)&&e.principal.class!=="broker")throw new a(403,"permission_error","a delivery dry run is available to a person or a node only")}s(I,"requirePerson");function Y(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new a(400,"usage","hypothetical must be an object");const n=s((r,o)=>{if(r!==void 0){if(typeof r!="string"||r==="")throw new a(400,"usage",`hypothetical.${o} must be a non-empty string`);return r}},"str"),i=n(e.cwd,"cwd");if(i!==void 0&&!i.startsWith("/"))throw new a(400,"usage","hypothetical.cwd must be an absolute path");if(e.mode!==void 0&&e.mode!=="base"&&e.mode!=="orchestrator")throw new a(400,"usage","hypothetical.mode must be base or orchestrator");if(e.lifecycle!==void 0&&e.lifecycle!=="terminal"&&e.lifecycle!=="resident")throw new a(400,"usage","hypothetical.lifecycle must be terminal or resident");if(e.has_manager!==void 0&&typeof e.has_manager!="boolean")throw new a(400,"usage","hypothetical.has_manager must be a boolean");if(e.depth!==void 0&&(!Number.isInteger(e.depth)||e.depth<0))throw new a(400,"usage","hypothetical.depth must be a non-negative integer");const t={};i!==void 0&&(t.cwd=i),e.profile!==void 0&&(t.profile=e.profile===null?null:n(e.profile,"profile"));const u=n(e.grantee,"grantee");u!==void 0&&(t.grantee=u);const f=n(e.kind,"kind");return f!==void 0&&(t.kind=f),e.mode!==void 0&&(t.mode=e.mode),e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),e.has_manager!==void 0&&(t.hasManager=e.has_manager),e.depth!==void 0&&(t.depth=e.depth),t}s(Y,"hypotheticalOf");async function v(e,n,i){const t=await C();e!==void 0&&await D(t,e),n&&await j(t,e,[n]),i!==void 0&&i.startsWith("/")&&await j(t,e,[A(i)])}s(v,"warmDeliveryCwds");async function $(e){const n=_(e.body);if(n.node!==void 0&&typeof n.node!="string")throw new a(400,"usage","node must be a node id");await k(e,n.node,n.hypothetical);const i={activity:n.activity,...n.subject!==void 0?{subject:n.subject}:{}};await v(n.node,n.hypothetical?.cwd,n.activity==="file-read"?n.subject:void 0);const t=n.hypothetical===void 0&&n.node!==void 0?await g(n.node,i):i,{result:u,plan:f}=await y(async r=>{if(n.hypothetical===void 0){if(n.node===void 0)throw new a(400,"usage","a delivery dry run names a node, a hypothetical node, or both");return await b(r,await w(r,n.node,async(h,p,N)=>await m(r,h,p,N)),t,n.subject_override)}const o=Y(n.hypothetical),c=n.node!==void 0?await P(n.node,o):{...o,cwd:o.cwd??""};if(c.cwd==="")throw new a(400,"usage","a hypothetical node needs a cwd");const{reader:d,subject:l}=await S(r,c);return await b(r,d,t,n.subject_override,l)},{rollback:!0});return{status:200,body:{...u,plan:f}}}s($,"handleDryRun");async function J(e){const n=e.params.id,i=_(e.body),t={activity:i.activity,...i.subject!==void 0?{subject:i.subject}:{},...i.inherited===!0?{inherited:!0}:{}};if(i.dry_run===!0){await k(e,n,void 0),await v(n,void 0,i.activity==="file-read"?i.subject:void 0);const r=await g(n,t),{result:o,plan:c}=await y(async d=>await b(d,await w(d,n,async(l,h,p)=>await m(d,l,h,p)),r,i.subject_override),{rollback:!0});return{status:200,body:{...o,plan:c}}}if(e.principal.class==="broker"&&e.principal.node!==n)throw new a(403,"permission_error","delivery is performed by the node's own broker");await F(n,i.expected_execution_id),await v(n,void 0,i.activity==="file-read"?i.subject:void 0);const u=await g(n,t);return{status:200,body:await y(async r=>await O(r,await w(r,n,async(o,c,d)=>await m(r,o,c,d)),u))}}s(J,"handleDelivery");const Q=[{method:"POST",pattern:"/v1/nodes/:id/delivery",handler:J},{method:"POST",pattern:"/v1/delivery/dry-run",handler:$}];export{Q as deliveryRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.717",
3
+ "version": "0.3.718",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.717",
162
- "@north-light/plugin": "0.3.717",
161
+ "@north-light/identity": "0.3.718",
162
+ "@north-light/plugin": "0.3.718",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -50,7 +50,11 @@ export function socketFetch(socketPath) {
50
50
  if (payload !== undefined)
51
51
  headers['content-length'] = String(Buffer.byteLength(payload));
52
52
  return new Promise((resolvePromise, reject) => {
53
- const req = httpRequest({ socketPath, path: url.pathname + url.search, method, headers }, (res) => {
53
+ // `agent: false` = a private connection per request. The global agent pools sockets, and crtrd closes an idle one at its
54
+ // `keepAliveTimeout` without reading what is already written to it, so a POST landing on a socket the daemon is closing
55
+ // resets (ECONNRESET) and, being a mutation, is never replayed: `daemon_request_interrupted`. A fresh unix-socket connect
56
+ // costs microseconds; no pooled socket means no window. Every client of api.sock must do the same.
57
+ const req = httpRequest({ socketPath, path: url.pathname + url.search, method, headers, agent: false }, (res) => {
54
58
  const body = new ReadableStream({
55
59
  start(controller) {
56
60
  res.on('data', (chunk) => controller.enqueue(new Uint8Array(chunk)));
@@ -398,19 +398,24 @@ export async function dropLocalGrantMirror(db) {
398
398
  export async function backfillComputedRev() {
399
399
  return await withCanvasWrite(async (db) => Number((await db.prepare('UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL').run()).changes));
400
400
  }
401
- /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. */
401
+ /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. Team
402
+ * membership is advisory next to the grants the same answer carries, so an entry that is not a directory team
403
+ * (`team:<id>`, e.g. a canvas group row echoed back) is dropped rather than failing the sync. */
402
404
  export function teamsOf(value) {
403
405
  if (value === undefined)
404
406
  return [];
405
407
  if (!Array.isArray(value))
406
408
  throw new TypeError('invalid grant sync response');
407
- return value.map((entry) => {
409
+ const teams = [];
410
+ for (const entry of value) {
408
411
  const { team, members } = (entry ?? {});
409
- if (typeof team !== 'string' || !/^team:\S+$/.test(team) || !Array.isArray(members) ||
410
- members.some((member) => typeof member !== 'string' || !/^user:[^\s*]+$/.test(member)))
412
+ if (typeof team !== 'string' || !/^team:\S+$/.test(team))
413
+ continue;
414
+ if (!Array.isArray(members) || members.some((member) => typeof member !== 'string' || !/^user:[^\s*]+$/.test(member)))
411
415
  throw new TypeError('invalid grant sync response');
412
- return { team, members };
413
- });
416
+ teams.push({ team, members });
417
+ }
418
+ return teams;
414
419
  }
415
420
  /** Replace the mirror with `grants` and the `written_by = 'directory'` team `member` facts with `teams`, in one transaction. The
416
421
  * ledger's `grant:<id>` limit rows follow from the `grants` trigger `crtr_grant_limit` (schema delta 002). */
@@ -160,7 +160,7 @@ function managedWorktreeNote(node) {
160
160
  * AGENTS.md/CLAUDE.md injection stays suppressed (`noContextFiles` in
161
161
  * broker.ts); `crtr sys sync project-guidance` imports that guidance into
162
162
  * documents owned by the directory's repo (its `<repo>/index` is the workspace front door). */
163
- async function bearingsShell(nodeId, knowledge, workspaceContext) {
163
+ async function bearingsShell(nodeId, knowledge, workspaceContext, projectCtx) {
164
164
  const node = await getNode(nodeId);
165
165
  const execution = await latestExecutionForNode(nodeId);
166
166
  const bearings = ['<crtr-bearings>', await buildIdentityAssertion(nodeId, node)];
@@ -187,16 +187,22 @@ async function bearingsShell(nodeId, knowledge, workspaceContext) {
187
187
  // nested card inside the outer envelope. Never routed through the visible
188
188
  // chat/digest path. '' when nothing was ever set.
189
189
  const situational = await situationalContextEnvelope(nodeId) ?? '';
190
- const projectCtx = node?.cwd !== undefined && execution?.runner === 'process' ? buildProjectContextBlock(node.cwd) : ''; // reads this host
191
190
  return [bearings.join('\n'), knowledge, workspaceContext, situational, projectCtx]
192
191
  .filter((s) => s !== '')
193
192
  .join('\n');
194
193
  }
194
+ /** The `<project_context>` snapshot of the node's cwd: it spawns git and tmux and reads this host's disk, so a caller builds it BEFORE
195
+ * opening the delivery transaction and passes it in as `projectContext`; '' when the node's engine does not run on this host. */
196
+ export async function projectContextForNode(nodeId) {
197
+ const node = await getNode(nodeId);
198
+ const execution = await latestExecutionForNode(nodeId);
199
+ return node?.cwd !== undefined && execution?.runner === 'process' ? buildProjectContextBlock(node.cwd) : '';
200
+ }
195
201
  /** The bearings on the row-backed delivery engine: the knowledge catalog and
196
202
  * the workspace-open documents render against `ctx`'s ledger; `delivered`
197
203
  * lists what they delivered, for the caller to record. */
198
- export async function buildContextBearings(nodeId, ctx) {
204
+ export async function buildContextBearings(nodeId, ctx, projectContext) {
199
205
  const knowledge = await renderKnowledge(ctx);
200
206
  const workspace = await renderWorkspaceOpen(ctx);
201
- return { content: await bearingsShell(nodeId, knowledge.content, workspace.content), delivered: [...knowledge.delivered, ...workspace.delivered] };
207
+ return { content: await bearingsShell(nodeId, knowledge.content, workspace.content, projectContext), delivered: [...knowledge.delivered, ...workspace.delivered] };
202
208
  }
@@ -21,7 +21,7 @@ import { getNode } from '../canvas/index.js';
21
21
  import { openDb, withCanvasWrite } from '../canvas/db.js';
22
22
  import { readerForNode, warmNodeRepos } from '../graph/reader.js';
23
23
  import { checkoutsForCwd } from '../graph/repo-sync/repos.js';
24
- import { deliver } from '../substrate/delivery/deliver.js';
24
+ import { deliver, withProjectContext } from '../substrate/delivery/deliver.js';
25
25
  import { oneShotControllerRequest } from './broker-request.js';
26
26
  import { isBrokerLive } from './model-swap.js';
27
27
  import { CONTEXT_INTRO_CUSTOM_TYPE } from './bearings.js';
@@ -75,7 +75,8 @@ export async function deliverBearingsLive(nodeId) {
75
75
  // The boot delivery clears and rewrites the ledger and freezes preferences in
76
76
  // one transaction before Pi receives the bearings.
77
77
  await warmNodeRepos(await openDb(), nodeId);
78
- const { content } = await withCanvasWrite(async (db) => await deliver(db, await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access)), { activity: 'boot' }));
78
+ const request = await withProjectContext(nodeId, { activity: 'boot' });
79
+ const { content } = await withCanvasWrite(async (db) => await deliver(db, await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access)), request));
79
80
  await deliverCustomMessageLive(nodeId, {
80
81
  customType: CONTEXT_INTRO_CUSTOM_TYPE,
81
82
  content: formatCard('bearings', {}, content),
@@ -24,13 +24,18 @@ import { appForNode } from '../../canvas/node-agent-paths.js';
24
24
  import { interpolateNodePaths } from '../../canvas/paths.js';
25
25
  import { readableProjectForScopes } from '../../spaces/permissions.js';
26
26
  import { ApiError } from '../../../api/errors.js';
27
- import { buildContextBearings } from '../../runtime/bearings.js';
27
+ import { buildContextBearings, projectContextForNode } from '../../runtime/bearings.js';
28
28
  import { deliveryDocOf, listingCorpora, loadCorpus, nodeSubject, primeBodies, profileIdOfObject, viewOwners } from './corpus.js';
29
29
  import { listingPrefixes } from './listings.js';
30
30
  import { planDelivery } from './plan.js';
31
31
  import { renderEvent, renderExplicitRead } from './render-event.js';
32
32
  import { renderConfigDelta, renderKnowledge, renderPreferences, renderWorkspaceOpen } from './render-boot.js';
33
33
  import { mapAsync } from '../../async-array.js';
34
+ /** `req` with what a `boot` of node `nodeId` reads from this host's disk and processes (git, tmux, a directory listing), computed now so the
35
+ * delivery transaction that follows holds its pooled connection for db statements only. Call before `withCanvasWrite`. */
36
+ export async function withProjectContext(nodeId, req) {
37
+ return req.activity === 'boot' && req.inherited !== true ? { ...req, projectContext: await projectContextForNode(nodeId) } : req;
38
+ }
34
39
  function nodeOf(reader) {
35
40
  if (reader.class !== 'node')
36
41
  throw new Error(`delivery needs a node reader, got ${reader.class}`);
@@ -173,7 +178,7 @@ async function render(ctx, req) {
173
178
  ledger.preferenceSnapshot = null;
174
179
  return { result: { content: '', inherited: true }, delivered: [] };
175
180
  }
176
- const bearings = isHypothetical(reader) ? await hypotheticalBearings(ctx) : await buildContextBearings(reader.node.id, ctx);
181
+ const bearings = isHypothetical(reader) ? await hypotheticalBearings(ctx) : await buildContextBearings(reader.node.id, ctx, requireProjectContext(req));
177
182
  const prefs = await renderPreferences({ ...ctx, channel: 'system' });
178
183
  freezePreferences(ledger, prefs.content);
179
184
  return { result: { content: bearings.content }, delivered: [...bearings.delivered, ...prefs.delivered] };
@@ -235,6 +240,11 @@ async function render(ctx, req) {
235
240
  throw new ApiError(400, 'usage', `unknown delivery activity ${String(req.activity)}`);
236
241
  }
237
242
  }
243
+ function requireProjectContext(req) {
244
+ if (req.projectContext === undefined)
245
+ throw new Error('a node boot delivery needs its project context built before the transaction: pass the request through withProjectContext');
246
+ return req.projectContext;
247
+ }
238
248
  /** A hypothetical node has no bearings of its own: its boot content is the
239
249
  * knowledge catalog and the workspace-open documents. */
240
250
  async function hypotheticalBearings(ctx) {
@@ -33,7 +33,7 @@ import { recoveryState, requireCurrentExecution } from './broker-recovery.js';
33
33
  import { runAttachments } from './node-records.js';
34
34
  import { readerForNode, warmNodeRepos } from '../../../core/graph/reader.js';
35
35
  import { checkoutsForCwd } from '../../../core/graph/repo-sync/repos.js';
36
- import { deliver } from '../../../core/substrate/delivery/deliver.js';
36
+ import { deliver, withProjectContext } from '../../../core/substrate/delivery/deliver.js';
37
37
  import { nodeSubject } from '../../../core/substrate/delivery/corpus.js';
38
38
  import { ensureRunObserver } from '../../runs/observer.js';
39
39
  import { parseNodeTelemetryRecord, writeNodeTelemetryRecord } from './telemetry-record.js';
@@ -296,11 +296,11 @@ function parseCycleStartBody(body) {
296
296
  /** The names, bearings and first system-prompt block a cycle opens with, delivered in one write the way the
297
297
  * delivery route would deliver each. A warm spare is owed no bearings and no system prompt: its claim delivers them.
298
298
  * `namesOnly` gives a node the same treatment while its bind is undecided. */
299
- async function startupDelivery(db, reader, subject, state, bearings, namesOnly) {
299
+ async function startupDelivery(db, reader, subject, state, bearings, namesOnly, projectContext) {
300
300
  const warm = state.warm_spare || namesOnly;
301
301
  const bootOwed = !warm && bearings !== 'present';
302
302
  const names = await deliver(db, reader, { activity: 'names' }, subject);
303
- const boot = bootOwed ? await deliver(db, reader, { activity: 'boot', ...(bearings === 'inherited' ? { inherited: true } : {}) }, subject) : undefined;
303
+ const boot = bootOwed ? await deliver(db, reader, { activity: 'boot', ...(bearings === 'inherited' ? { inherited: true } : {}), ...(projectContext === undefined ? {} : { projectContext }) }, subject) : undefined;
304
304
  const system = warm ? undefined : await deliver(db, reader, { activity: 'system-prompt' }, subject);
305
305
  return {
306
306
  names: { refs: names.refs, names: names.names },
@@ -314,12 +314,14 @@ async function startupDelivery(db, reader, subject, state, bearings, namesOnly)
314
314
  export async function renderStartData(nodeId, bearings, namesOnly, warmed = false) {
315
315
  if (!warmed)
316
316
  await warmNodeRepos(await openDb(), nodeId);
317
+ // A fresh boot's project-context snapshot (git, tmux, a directory listing) is built before the transaction, so it holds its connection for db statements only.
318
+ const projectContext = !namesOnly && bearings === 'fresh' ? (await withProjectContext(nodeId, { activity: 'boot' })).projectContext : undefined;
317
319
  const { state, delivery } = await withCanvasWrite(async (db) => {
318
320
  const reader = await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access));
319
321
  shareCorpusReads(reader);
320
322
  const subject = await nodeSubject(db, reader);
321
323
  const state = await extensionState(nodeId, subject);
322
- return { state, delivery: await startupDelivery(db, reader, subject, state, bearings, namesOnly) };
324
+ return { state, delivery: await startupDelivery(db, reader, subject, state, bearings, namesOnly, projectContext) };
323
325
  });
324
326
  // The bearings just rendered are the persona baseline; the broker does not acknowledge it separately.
325
327
  if (delivery.boot !== undefined) {
@@ -589,15 +591,14 @@ async function handleTelemetry(ctx) {
589
591
  const nodeId = ctx.params['id'];
590
592
  const request = parseTelemetryBody(ctx.body);
591
593
  await requireCurrentExecution(nodeId, request.expected_execution_id);
592
- await withCanvasWrite(async () => {
593
- await updateNodeTelemetry(nodeId, {
594
- tokensIn: request.tokens_in,
595
- contextTokens: request.context_tokens,
596
- lastActivity: request.last_activity,
597
- updatedAt: request.updated_at,
598
- });
599
- writeNodeTelemetryRecord(nodeId, request);
594
+ // One statement, atomic on its own; the node-local file is filesystem work and must not hold a pooled connection.
595
+ await updateNodeTelemetry(nodeId, {
596
+ tokensIn: request.tokens_in,
597
+ contextTokens: request.context_tokens,
598
+ lastActivity: request.last_activity,
599
+ updatedAt: request.updated_at,
600
600
  });
601
+ writeNodeTelemetryRecord(nodeId, request);
601
602
  return { status: 204 };
602
603
  }
603
604
  async function handleModelCommit(ctx) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.717",
3
+ "version": "0.3.718",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.717",
3
+ "version": "0.3.718",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.717",
3
+ "version": "0.3.718",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.717",
31
- "@north-light/identity": "0.3.717"
30
+ "@north-light/api": "0.3.718",
31
+ "@north-light/identity": "0.3.718"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.717",
3
+ "version": "0.3.718",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.717",
9
+ "version": "0.3.718",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.717",
32
- "@north-light/plugin": "0.3.717",
31
+ "@north-light/identity": "0.3.718",
32
+ "@north-light/plugin": "0.3.718",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.717",
11905
+ "version": "0.3.718",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.717",
11910
+ "version": "0.3.718",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.717",
11915
+ "version": "0.3.718",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.717",
11923
+ "version": "0.3.718",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.717",
11927
- "@north-light/identity": "0.3.717"
11926
+ "@north-light/api": "0.3.718",
11927
+ "@north-light/identity": "0.3.718"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.717",
11932
+ "version": "0.3.718",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.717",
11936
- "@north-light/identity": "0.3.717",
11937
- "@north-light/plugin": "0.3.717",
11935
+ "@north-light/api": "0.3.718",
11936
+ "@north-light/identity": "0.3.718",
11937
+ "@north-light/plugin": "0.3.718",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {