@north-light/cli 0.3.659 → 0.3.660

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/api/client.d.ts +3 -0
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/files.d.ts +20 -0
  6. package/dist/api/dto/run-events.d.ts +9 -1
  7. package/dist/api/routes.d.ts +2 -0
  8. package/dist/api/routes.js +1 -1
  9. package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +12 -6
  10. package/dist/clients/attach/viewer.js +1 -1
  11. package/dist/commands/push.js +6 -4
  12. package/dist/core/canvas/export-sqlite.js +1 -1
  13. package/dist/core/canvas/migrations.js +1 -1
  14. package/dist/core/canvas/person.js +3 -3
  15. package/dist/core/canvas/schema-pg/019-outbound-files.sql +26 -0
  16. package/dist/core/canvas/schema-version.d.ts +1 -1
  17. package/dist/core/canvas/schema-version.js +1 -1
  18. package/dist/core/grants/remove.js +1 -1
  19. package/dist/core/import/bundle/layout.d.ts +1 -1
  20. package/dist/core/import/bundle/layout.js +3 -3
  21. package/dist/core/import/load/bind.js +8 -8
  22. package/dist/core/providers/files.js +1 -1
  23. package/dist/core/runs/operations.js +4 -4
  24. package/dist/core/storage/download.d.ts +0 -1
  25. package/dist/core/storage/download.js +1 -1
  26. package/dist/core/storage/media-types.d.ts +1 -0
  27. package/dist/core/storage/media-types.js +1 -0
  28. package/dist/core/storage/shares.d.ts +15 -6
  29. package/dist/core/storage/shares.js +1 -1
  30. package/dist/core/storage/tables.d.ts +31 -1
  31. package/dist/core/storage/tables.js +4 -3
  32. package/dist/daemon/api/handlers/node-files.d.ts +2 -0
  33. package/dist/daemon/api/handlers/node-files.js +1 -0
  34. package/dist/daemon/api/handlers/transfer.d.ts +2 -2
  35. package/dist/daemon/api/handlers/transfer.js +1 -1
  36. package/dist/daemon/api/operations.js +1 -1
  37. package/dist/daemon/api/server.js +1 -1
  38. package/dist/daemon/reconcilers/ledger-storage.js +3 -3
  39. package/docs/apps/guides/files-and-documents.md +11 -6
  40. package/package.json +2 -2
  41. package/packages/crouter-identity/package.json +1 -1
  42. package/runtime.lock.json +13 -13
@@ -85,7 +85,7 @@ ${i}`);return e.join(`
85
85
  `)||e.includes("\r")||Buffer.byteLength(e,"utf8")+1>pZe?!1:hZe(t,[e])}function mZe(t,e){if(e.includes(`
86
86
  `)||e.includes("\r"))return!1;let n=Buffer.byteLength(e,"utf8")+1;return n>pZe?!1:(Kd!==void 0&&Kd.path!==t&&C6(),Kd===void 0&&(Kd={path:t,records:[],bytes:0},dZe||(process.on("exit",C6),dZe=!0)),Kd.path=t,Kd.records.push(e),Kd.bytes+=n,Kd.bytes>=FSn?C6():Kd.timer===void 0&&(Kd.timer=setTimeout(C6,USn),Kd.timer.unref()),!0)}function C6(){let t=Kd;if(!(t===void 0||t.records.length===0)&&(t.timer!==void 0&&clearTimeout(t.timer),Kd=void 0,!hZe(t.path,t.records,OSn)))for(let e of t.records)process.stderr.write(`[crtrd] event log append failed: ${e}
87
87
  `)}var pZe,QSn,OSn,FSn,USn,Kd,dZe,oge=y(()=>{"use strict";pZe=65536,QSn=5*1024*1024,OSn=16*1024*1024,FSn=128*1024,USn=200;dZe=!1});var sge,fZe=y(()=>{"use strict";sge=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"]});function $Sn(t){return typeof t=="object"&&t!==null?t:void 0}function gZe(t){return typeof t=="string"?t:""}function AZe(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=$Sn(t);return{type:gZe(e?.name)||"Error",message:gZe(e?.message)||String(t)}}var yZe=y(()=>{"use strict";fZe()});import{AsyncLocalStorage as WSn}from"node:async_hooks";import{randomBytes as HSn}from"node:crypto";function v6(t){if(typeof t!="string"||!GSn.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function cge(){let t;do t=HSn(16).toString("hex");while(t==="00000000000000000000000000000000");return v6(t)}var GSn,age,wZe,EZe=y(()=>{"use strict";GSn=/^(?!0{32}$)[0-9a-f]{32}$/,age=new WSn;wZe={current:()=>age.getStore(),run:(t,e)=>age.run(v6(t),e),fresh:t=>{let e=cge();return age.run(e,()=>t(e))}}});function JSn(t){return Buffer.byteLength(t,"utf8")}function S6(t,e,n=128){if(typeof t!="string"||t===""||JSn(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function XSn(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 ZSn(t){if(!YSn.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=S6(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!KSn.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function xZe(t){if(!jSn.has(t.level))throw new TypeError("level is invalid");if(!zSn.has(t.component))throw new TypeError("component is invalid");let e=S6(t.event,"event");if(!qSn.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?wZe.current()??cge():v6(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():XSn(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=S6(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=S6(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(!VSn.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=ZSn(t.error_class)),t.error!==void 0&&(r.error=AZe(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}var qSn,jSn,zSn,VSn,KSn,YSn,bZe=y(()=>{"use strict";yZe();EZe();qSn=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,jSn=new Set(["error","warn","info","debug"]),zSn=new Set(["daemon","broker","control-plane","front","sentinel"]),VSn=new Set(["succeeded","failed","skipped"]),KSn=new Set(["auto","manual","fatal"]),YSn=new Set(sge)});function qI(t){return Buffer.byteLength(t,"utf8")}function GI(t,e){if(qI(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-qI(n),i=0,o="";for(let s of t){let a=qI(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function e_n(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 uge(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=GI(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:e_n(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=uge(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=GI(l,128),p;try{p=uge(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 t_n(t){let e=GI(String(t.type),128),n=GI(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=GI(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=GI(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function _6(t){return JSON.stringify(t)}function vF(t){return qI(_6(t))+1}function CZe(t){let e=t.fields===void 0?void 0:uge(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:t_n(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=vF(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});vF(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=qI(_6(u[p]))-qI(_6(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;vF(r)>65536&&a?.stack!==void 0&&delete a.stack,vF(r)>65536&&a?.cause!==void 0&&delete a.cause,vF(r)>65536&&a!==void 0&&(a.message=GI(a.message,64).value);let c=_6(r);if(qI(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}var IZe=y(()=>{"use strict"});import{AsyncLocalStorage as n_n}from"node:async_hooks";function SZe(t){lge=t}function k6(){return vZe}function dge(){let t=r_n.getStore();if(t!==void 0)return t;if(vZe)throw new _F;if(lge===void 0)throw new SF;return lge}var SF,_F,lge,vZe,r_n,XR=y(()=>{"use strict";SF=class extends Error{code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}},_F=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"}},vZe=!1,r_n=new n_n});import{existsSync as T6,lstatSync as kEi,mkdirSync as i_n,readdirSync as o_n,readFileSync as kZe,rmSync as s_n,statSync as a_n,symlinkSync as TEi,writeFileSync as c_n,cpSync as REi,readlinkSync as BEi,renameSync as u_n,chmodSync as l_n,realpathSync as d_n,closeSync as TZe,fsyncSync as RZe,openSync as BZe,linkSync as DEi,unlinkSync as MEi,writeSync as PEi}from"node:fs";import{dirname as _Ze,join as p_n,relative as LEi,sep as QEi}from"node:path";import{homedir as h_n,platform as m_n}from"node:os";function Ym(t){try{return d_n(t)}catch{return t}}function DZe(t,e=h_n()){return t==="~"?e:t.startsWith("~/")||m_n()==="win32"&&t.startsWith("~\\")?p_n(e,t.slice(2)):t}function R6(t){i_n(t,{recursive:!0})}function ZR(t,e,n){pge(t,JSON.stringify(e,null,2)+`
88
- `,n)}function f_n(t){let e=BZe(t,"r");try{RZe(e)}finally{TZe(e)}}function MZe(t){let e=BZe(t,"r");try{RZe(e)}finally{TZe(e)}}function pge(t,e,n){n?.createParent!==!1&&R6(_Ze(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(T6(t)?a_n(t).mode&511:384);try{c_n(r,e,{mode:i}),l_n(r,i),n?.durable===!0&&f_n(r),u_n(r,t),n?.durable===!0&&MZe(_Ze(t))}finally{T6(r)&&s_n(r,{force:!0})}}function g_n(t){return JSON.parse(kZe(t,"utf8"))}function jI(t){try{return g_n(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function zI(t){try{return JSON.parse(kZe(t,"utf8"))}catch{return null}}function hge(t){return T6(t)}function mge(t){return T6(t)?o_n(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var $l=y(()=>{"use strict"});import{homedir as A_n,userInfo as y_n}from"node:os";import{basename as w_n,dirname as HEi,isAbsolute as GEi,join as Yd,resolve as PZe}from"node:path";function D6(){let t=PZe(Q0()||(process.platform==="linux"?"/":Yd(A_n(),".crouter")));if(E_n()&&t===x_n())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 E_n(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function x_n(){if(B6===void 0)try{B6=PZe(y_n().homedir,".crouter")}catch{B6=null}return B6}function vg(){return Yd(D6(),"runtime")}function fge(){return Yd(D6(),"apps")}function $0(){return Yd(vg(),"secrets")}function NZe(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=kF(t);return{dir:Yd(n.profiles,e),env:Yd($0(),"env",w_n(n.root),e),home:n.home}}function gge(){return process.platform==="linux"?"/run/crtr":vg()}function kF(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=Yd(fge(),e);return{root:n,profiles:Yd(n,"profiles"),conversations:Yd(n,"conversations"),nodes:Yd(n,"nodes"),files:Yd(n,"files"),home:Yd(n,"home"),cache:Yd(n,"cache")}}var B6,W0=y(()=>{"use strict";du();Jd();XR();$l()});import{chmodSync as JEi,chownSync as XEi,closeSync as cE,constants as M6,fchmodSync as ZEi,fchownSync as exi,fstatSync as FZe,fsyncSync as txi,linkSync as nxi,lstatSync as rxi,mkdirSync as ixi,openSync as LZe,readdirSync as oxi,readFileSync as b_n,readlinkSync as sxi,readSync as axi,realpathSync as cxi,renameSync as uxi,rmdirSync as lxi,rmSync as dxi,statSync as pxi,symlinkSync as hxi,unlinkSync as mxi,writeSync as fxi}from"node:fs";import{basename as Axi,dirname as yxi,join as wxi,relative as UZe,resolve as wge,sep as QZe}from"node:path";import{loadLinuxNative as C_n,O_CLOEXEC as Ege,O_PATH as xge,RESOLVE_BENEATH as I_n,RESOLVE_NO_SYMLINKS as v_n}from"../../native/linux.js";function $Ze(){return Age===null&&(Age=C_n()),Age}function __n(t){return t.code}function k_n(t,e){switch(__n(t)){case"ELOOP":case"EXDEV":return new VI(`path meets a symlink: ${e}`);case"ENXIO":return new VI(`path is not a regular file: ${e}`);case"EAGAIN":return new VI(`path is held by a lease: ${e}`);default:return t}}function yge(t,e,n,r,i){try{return t.openat2(e,n,r,S_n)}catch(o){throw k_n(o,i)}}function T_n(t,e,n){let r;try{r=FZe(t)}catch(i){throw cE(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw cE(t),new VI(`path is not a regular file: ${e}`)}function R_n(t,e){let n=UZe(wge(t),wge(e));if(n===".."||n.startsWith(`..${QZe}`)||n.startsWith(QZe))throw new Error(`${e} is outside ${t}`);return n}function WZe(t,e,n){if(n&M6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=R_n(t,e),i=$Ze();if(!i)return LZe(e,n);let o=LZe("/",OZe),s;try{s=yge(i,o,UZe("/",wge(t))||".",OZe,t)}finally{cE(o)}try{return n&xge?yge(i,s,r||".",n|Ege,e):T_n(yge(i,s,r||".",n|Ege|M6.O_NONBLOCK,e),e,!0)}finally{cE(s)}}function bge(t,e){let n=WZe(t,e,M6.O_RDONLY);try{return b_n(n)}finally{cE(n)}}function HZe(t,e){if(!$Ze())return{path:e,release:()=>{}};let n=WZe(t,e,xge),r;try{r=FZe(n)}catch(o){throw cE(n),o}if(!r.isSocket())throw cE(n),new VI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,cE(n))}}}var S_n,OZe,Age,VI,TF=y(()=>{"use strict";S_n=I_n|v_n,OZe=xge|M6.O_DIRECTORY|Ege,Age=null;VI=class extends Error{}});import{join as Sg}from"node:path";function oc(){return vg()}function GZe(){return Sg(oc(),"on-disk-migration.lock")}function eB(t){return Sg(tB(t),"view.sock")}function B_n(){return Sg(oc(),"nodes")}function qZe(){return Sg(gge(),"api.sock")}function jZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=D_n}function Cge(t){if(!jZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function M_n(t){return Cge(t),Sg(B_n(),t)}function P_n(t,e){Cge(t);let n=e??(xfe()===t?vJe():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return Sg(kF(n).nodes,t)}function tB(t){return Cge(t),process.platform==="linux"?Sg(gge(),"nodes",t):Sg(M_n(t),"run")}function KZe(t,e){return Sg(P_n(t,e),"context")}function YZe(t){return Sg(tB(t),"job")}var D_n,zZe,VZe,Hl=y(()=>{"use strict";W0();du();TF();D_n=128;zZe="broker-released",VZe="cli-relay-generation"});import{join as N_n}from"node:path";function L_n(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function Q_n(t){if(P6===void 0){P6=t;return}if(!L_n(P6,t))throw new Error("event source is already bound for this process")}function JZe(){Q_n({component:"daemon",path:N_n(oc(),"crtrd.log")})}function N6(){return P6}var P6,Ige=y(()=>{"use strict";Hl()});function XZe(t){return t instanceof Xt?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||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 vge(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 Xt,_g=y(()=>{"use strict";Xt=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,Sge=y(()=>{"use strict";se={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonDrain:()=>"/v1/daemon/drain",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,executionStart:t=>`/v1/executions/${t}/start`,executionImportUnpacked:t=>`/v1/executions/${t}/import-unpacked`,environmentGitCredential:t=>`/v1/environments/${t}/git-credential`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,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`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,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",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`,humanReviewCommentRanges:t=>`/v1/human/reviews/${t}/comment-ranges`,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}`,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 L6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var _ge=y(()=>{"use strict"});function ZZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var kge=y(()=>{"use strict"});function eet(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Tge=y(()=>{"use strict"});async function O6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=$_n,retry:i=()=>!0,now:o=Date.now,sleep:s=oet}){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 nB(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 Xt(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 KI(t,e){let n=t.status>=200&&t.status<300,r=(await iet(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new Xt(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw vge(i)?new Xt(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new Xt(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function H_n(t){return t==="GET"||t==="HEAD"}async function G_n(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await iet(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 q_n(t){return t===429||t>=500}async function Rge(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 iet(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(()=>{}),nB(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(nB(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function tet(t){return Math.min(2e3,250*2**(t-1))}function Bge(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 net(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function uE(t,e){if(e?.aborted)return new Xt(0,"request_aborted","request aborted by caller signal");if(t instanceof Xt)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new Xt(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new Xt(0,"request_aborted","request aborted by caller signal");let n=Bge(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new Xt(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new Xt(504,"request_timeout",`crtrd request timed out: ${r}`):new Xt(503,"transport_error",r)}function j_n(t,e){return t==="GET"||t==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new Xt(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 ret(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function Q6(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new Xt(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=nB(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 oet(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new Xt(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function z_n(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function oet(t){return new Promise(e=>setTimeout(e,t))}function V_n(t){if(t!==void 0)try{return t()}catch{return}}var O_n,F_n,U_n,$_n,BF,RF,kg,W_n,F6=y(()=>{"use strict";_g();Sge();_ge();kge();Tge();O_n=3e4,F_n=Symbol.for("@north-light/api/local-socket-fetch"),U_n=1e4,$_n=200;BF=2147483647;RF=t=>nB(t??Date.now()),kg=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??O_n,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[F_n]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??U_n}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 KI(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 KI(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 KI(r),new Uint8Array(await r.arrayBuffer())}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)}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 KI(i);return}if(i.body===null)throw new Xt(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(`
88
+ `,n)}function f_n(t){let e=BZe(t,"r");try{RZe(e)}finally{TZe(e)}}function MZe(t){let e=BZe(t,"r");try{RZe(e)}finally{TZe(e)}}function pge(t,e,n){n?.createParent!==!1&&R6(_Ze(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(T6(t)?a_n(t).mode&511:384);try{c_n(r,e,{mode:i}),l_n(r,i),n?.durable===!0&&f_n(r),u_n(r,t),n?.durable===!0&&MZe(_Ze(t))}finally{T6(r)&&s_n(r,{force:!0})}}function g_n(t){return JSON.parse(kZe(t,"utf8"))}function jI(t){try{return g_n(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function zI(t){try{return JSON.parse(kZe(t,"utf8"))}catch{return null}}function hge(t){return T6(t)}function mge(t){return T6(t)?o_n(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var $l=y(()=>{"use strict"});import{homedir as A_n,userInfo as y_n}from"node:os";import{basename as w_n,dirname as HEi,isAbsolute as GEi,join as Yd,resolve as PZe}from"node:path";function D6(){let t=PZe(Q0()||(process.platform==="linux"?"/":Yd(A_n(),".crouter")));if(E_n()&&t===x_n())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 E_n(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function x_n(){if(B6===void 0)try{B6=PZe(y_n().homedir,".crouter")}catch{B6=null}return B6}function vg(){return Yd(D6(),"runtime")}function fge(){return Yd(D6(),"apps")}function $0(){return Yd(vg(),"secrets")}function NZe(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=kF(t);return{dir:Yd(n.profiles,e),env:Yd($0(),"env",w_n(n.root),e),home:n.home}}function gge(){return process.platform==="linux"?"/run/crtr":vg()}function kF(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=Yd(fge(),e);return{root:n,profiles:Yd(n,"profiles"),conversations:Yd(n,"conversations"),nodes:Yd(n,"nodes"),files:Yd(n,"files"),home:Yd(n,"home"),cache:Yd(n,"cache")}}var B6,W0=y(()=>{"use strict";du();Jd();XR();$l()});import{chmodSync as JEi,chownSync as XEi,closeSync as cE,constants as M6,fchmodSync as ZEi,fchownSync as exi,fstatSync as FZe,fsyncSync as txi,linkSync as nxi,lstatSync as rxi,mkdirSync as ixi,openSync as LZe,readdirSync as oxi,readFileSync as b_n,readlinkSync as sxi,readSync as axi,realpathSync as cxi,renameSync as uxi,rmdirSync as lxi,rmSync as dxi,statSync as pxi,symlinkSync as hxi,unlinkSync as mxi,writeSync as fxi}from"node:fs";import{basename as Axi,dirname as yxi,join as wxi,relative as UZe,resolve as wge,sep as QZe}from"node:path";import{loadLinuxNative as C_n,O_CLOEXEC as Ege,O_PATH as xge,RESOLVE_BENEATH as I_n,RESOLVE_NO_SYMLINKS as v_n}from"../../native/linux.js";function $Ze(){return Age===null&&(Age=C_n()),Age}function __n(t){return t.code}function k_n(t,e){switch(__n(t)){case"ELOOP":case"EXDEV":return new VI(`path meets a symlink: ${e}`);case"ENXIO":return new VI(`path is not a regular file: ${e}`);case"EAGAIN":return new VI(`path is held by a lease: ${e}`);default:return t}}function yge(t,e,n,r,i){try{return t.openat2(e,n,r,S_n)}catch(o){throw k_n(o,i)}}function T_n(t,e,n){let r;try{r=FZe(t)}catch(i){throw cE(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw cE(t),new VI(`path is not a regular file: ${e}`)}function R_n(t,e){let n=UZe(wge(t),wge(e));if(n===".."||n.startsWith(`..${QZe}`)||n.startsWith(QZe))throw new Error(`${e} is outside ${t}`);return n}function WZe(t,e,n){if(n&M6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=R_n(t,e),i=$Ze();if(!i)return LZe(e,n);let o=LZe("/",OZe),s;try{s=yge(i,o,UZe("/",wge(t))||".",OZe,t)}finally{cE(o)}try{return n&xge?yge(i,s,r||".",n|Ege,e):T_n(yge(i,s,r||".",n|Ege|M6.O_NONBLOCK,e),e,!0)}finally{cE(s)}}function bge(t,e){let n=WZe(t,e,M6.O_RDONLY);try{return b_n(n)}finally{cE(n)}}function HZe(t,e){if(!$Ze())return{path:e,release:()=>{}};let n=WZe(t,e,xge),r;try{r=FZe(n)}catch(o){throw cE(n),o}if(!r.isSocket())throw cE(n),new VI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,cE(n))}}}var S_n,OZe,Age,VI,TF=y(()=>{"use strict";S_n=I_n|v_n,OZe=xge|M6.O_DIRECTORY|Ege,Age=null;VI=class extends Error{}});import{join as Sg}from"node:path";function oc(){return vg()}function GZe(){return Sg(oc(),"on-disk-migration.lock")}function eB(t){return Sg(tB(t),"view.sock")}function B_n(){return Sg(oc(),"nodes")}function qZe(){return Sg(gge(),"api.sock")}function jZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=D_n}function Cge(t){if(!jZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function M_n(t){return Cge(t),Sg(B_n(),t)}function P_n(t,e){Cge(t);let n=e??(xfe()===t?vJe():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return Sg(kF(n).nodes,t)}function tB(t){return Cge(t),process.platform==="linux"?Sg(gge(),"nodes",t):Sg(M_n(t),"run")}function KZe(t,e){return Sg(P_n(t,e),"context")}function YZe(t){return Sg(tB(t),"job")}var D_n,zZe,VZe,Hl=y(()=>{"use strict";W0();du();TF();D_n=128;zZe="broker-released",VZe="cli-relay-generation"});import{join as N_n}from"node:path";function L_n(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function Q_n(t){if(P6===void 0){P6=t;return}if(!L_n(P6,t))throw new Error("event source is already bound for this process")}function JZe(){Q_n({component:"daemon",path:N_n(oc(),"crtrd.log")})}function N6(){return P6}var P6,Ige=y(()=>{"use strict";Hl()});function XZe(t){return t instanceof Xt?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||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 vge(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 Xt,_g=y(()=>{"use strict";Xt=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,Sge=y(()=>{"use strict";se={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonDrain:()=>"/v1/daemon/drain",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,executionStart:t=>`/v1/executions/${t}/start`,executionImportUnpacked:t=>`/v1/executions/${t}/import-unpacked`,environmentGitCredential:t=>`/v1/environments/${t}/git-credential`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeFiles:t=>`/v1/nodes/${t}/files`,nodeFileComplete:(t,e)=>`/v1/nodes/${t}/files/${encodeURIComponent(e)}/complete`,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`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,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",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`,humanReviewCommentRanges:t=>`/v1/human/reviews/${t}/comment-ranges`,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}`,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 L6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var _ge=y(()=>{"use strict"});function ZZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var kge=y(()=>{"use strict"});function eet(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Tge=y(()=>{"use strict"});async function O6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=$_n,retry:i=()=>!0,now:o=Date.now,sleep:s=oet}){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 nB(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 Xt(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 KI(t,e){let n=t.status>=200&&t.status<300,r=(await iet(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new Xt(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw vge(i)?new Xt(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new Xt(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function H_n(t){return t==="GET"||t==="HEAD"}async function G_n(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await iet(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 q_n(t){return t===429||t>=500}async function Rge(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 iet(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(()=>{}),nB(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(nB(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function tet(t){return Math.min(2e3,250*2**(t-1))}function Bge(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 net(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function uE(t,e){if(e?.aborted)return new Xt(0,"request_aborted","request aborted by caller signal");if(t instanceof Xt)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new Xt(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new Xt(0,"request_aborted","request aborted by caller signal");let n=Bge(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new Xt(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new Xt(504,"request_timeout",`crtrd request timed out: ${r}`):new Xt(503,"transport_error",r)}function j_n(t,e){return t==="GET"||t==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new Xt(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 ret(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function Q6(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new Xt(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=nB(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 oet(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new Xt(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function z_n(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function oet(t){return new Promise(e=>setTimeout(e,t))}function V_n(t){if(t!==void 0)try{return t()}catch{return}}var O_n,F_n,U_n,$_n,BF,RF,kg,W_n,F6=y(()=>{"use strict";_g();Sge();_ge();kge();Tge();O_n=3e4,F_n=Symbol.for("@north-light/api/local-socket-fetch"),U_n=1e4,$_n=200;BF=2147483647;RF=t=>nB(t??Date.now()),kg=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??O_n,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[F_n]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??U_n}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 KI(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 KI(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 KI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",se.nodeFiles(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)}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 KI(i);return}if(i.body===null)throw new Xt(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 Xt(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)),{})}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)}settleBroker(e,n){return this.request("POST",se.nodeBrokerSettle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",se.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",se.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",se.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",se.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",se.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",se.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",se.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",se.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",se.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${se.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",se.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${se.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",se.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",se.executionStart(e))}executionImportUnpacked(e){return this.request("POST",se.executionImportUnpacked(e),{})}gitCredential(e,n){return this.request("POST",se.environmentGitCredential(e),n)}brokerExtensionState(e){return this.request("GET",se.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",se.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",se.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",se.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",se.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",se.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",se.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",se.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",se.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",se.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",se.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",se.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",se.kinds())}patchConfig(e,n){return this.request("PATCH",se.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",se.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",se.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",se.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",se.quarantinedWorktrees())}showLimits(){return this.request("GET",se.limits())}setAppLimits(e,n){return this.request("PUT",se.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(se.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(se.charges(),e))}listSpendLimits(){return this.request("GET",se.spendLimits())}setSpendLimit(e,n){return this.request("PUT",se.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",se.spendLimit(e))}listSpaces(){return this.request("GET",se.spaces())}subscribe(e,n){return this.request("POST",se.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",se.focuses())}focusOf(e){return this.request("GET",kr(se.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(se.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",se.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",se.focus(e),n)}async closeFocus(e){await this.request("DELETE",se.focus(e))}async unsubscribe(e,n){await this.request("DELETE",se.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",se.crons(),e)}listCrons(e){return this.request("GET",kr(se.crons(),e))}showCron(e,n){return this.request("GET",kr(se.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(se.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(se.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(se.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(se.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",se.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",se.nodeAttach(this.nodePath(e)),n??{})}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))}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))}updateReviewCommentRanges(e,n){return this.request("POST",se.humanReviewCommentRanges(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))}canvasRoster(){return this.request("GET",se.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",se.canvasBrowse());return e.ok||await KI(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 KI(s,o?.deadlineAt)}catch(o){throw j_n(e,uE(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw uE(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()+W_n);for(let u=0;;u++){let l;try{l=await this.transport(e,n,r,o)}catch(d){if(this.isColdSocketError(d)||this.isInterruptedSocketError(d)){let p=this.availabilityFailure?.();if(p!==void 0)throw p}if(this.isColdSocketError(d))try{await this.handleColdSocket(d,o.deadlineAt),l=await this.transport(e,n,r,o)}catch(p){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!net(p,o.signal)?nB(o.deadlineAt):uE(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&&!net(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await Q6(tet(u+1),o);continue}else throw uE(d,o.signal)}}if(H_n(e)&&a>0&&l.status===503&&await G_n(l,o.deadlineAt)){let d=Math.max(250,(ret(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await Rge(l,o.deadlineAt),await Q6(d,{signal:o.signal});continue}if(s&&u<a&&q_n(l.status)){await Rge(l,o.deadlineAt),await Q6(tet(u+1),o,ret(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>BF))throw new RangeError(`budgetMs must be a positive finite number of at most ${BF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>BF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${BF} 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 RF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(RF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await KI(await this.transport(e,n,r,o))}catch(s){throw uE(s,o.signal)}}nodePath(e){if(!L6(e))throw new Xt(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!ZZe(e))throw new Xt(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!eet(e))throw new Xt(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!L6(e))throw new Xt(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(!L6(e))throw new Xt(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new Xt(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(RF(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?RF(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 z_n(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>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=Bge(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=Bge(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw uE(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new Xt(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 uE(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw RF(n);let i,o;try{await O6({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 Xt(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 Rge(u);return}let l=await u.text();try{if(typeof JSON.parse(l).startup_blocked=="string")return}catch{}throw new Xt(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=V_n(this.coldStartDiagnostic);if(o!==void 0){let s=uE(i);throw new Xt(s.status,s.code,`${s.message}
90
90
  ${o}`)}}throw i}}};W_n=6e4});function set(){return K_n??void 0}var K_n,aet=y(()=>{"use strict";K_n=null});import{request as Y_n}from"node:http";import{homedir as J_n}from"node:os";import{join as Dge}from"node:path";function tkn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:Dge(J_n(),X_n);return Dge(process.platform==="linux"?"/run/crtr":Dge(n,"runtime"),Z_n)}function nkn(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=Y_n({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[ekn]=!0,e}function lE(t={}){let{socketPath:e,...n}=t;return new kg({baseUrl:"http://localhost",fetch:nkn(e??tkn()),autostart:!0,...n})}var X_n,Z_n,ekn,U6=y(()=>{"use strict";F6();X_n=".crouter",Z_n="api.sock",ekn=Symbol.for("@north-light/api/local-socket-fetch")});var cet=y(()=>{"use strict";MF();_g()});var Pge=Q(uet=>{"use strict";uet.parse=function(t,e){return new Mge(t,e).parse()};var Mge=class t{constructor(e,n){this.source=e,this.transform=n||rkn,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 rkn(t){return t}});var Nge=Q((Zxi,det)=>{var ikn=Pge();det.exports={create:function(t,e){return{parse:function(){return ikn.parse(t,e)}}}}});var met=Q((ebi,het)=>{"use strict";var okn=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,skn=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,akn=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,ckn=/^-?infinity$/;het.exports=function(e){if(ckn.test(e))return Number(e.replace("i","I"));var n=okn.exec(e);if(!n)return ukn(e)||null;var r=!!n[8],i=parseInt(n[1],10);r&&(i=pet(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=lkn(e);return p!=null?(d=new Date(Date.UTC(i,o,s,a,c,u,l)),Lge(i)&&d.setUTCFullYear(i),p!==0&&d.setTime(d.getTime()-p)):(d=new Date(i,o,s,a,c,u,l),Lge(i)&&d.setFullYear(i)),d};function ukn(t){var e=skn.exec(t);if(e){var n=parseInt(e[1],10),r=!!e[4];r&&(n=pet(n));var i=parseInt(e[2],10)-1,o=e[3],s=new Date(n,i,o);return Lge(n)&&s.setFullYear(n),s}}function lkn(t){if(t.endsWith("+00"))return 0;var e=akn.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 pet(t){return-(t-1)}function Lge(t){return t>=0&&t<100}});var get=Q((tbi,fet)=>{fet.exports=pkn;var dkn=Object.prototype.hasOwnProperty;function pkn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)dkn.call(n,r)&&(t[r]=n[r])}return t}});var wet=Q((nbi,yet)=>{"use strict";var hkn=get();yet.exports=rB;function rB(t){if(!(this instanceof rB))return new rB(t);hkn(this,vkn(t))}var mkn=["seconds","minutes","hours","days","months","years"];rB.prototype.toPostgres=function(){var t=mkn.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 fkn={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},gkn=["years","months","days"],Akn=["hours","minutes","seconds"];rB.prototype.toISOString=rB.prototype.toISO=function(){var t=gkn.map(n,this).join(""),e=Akn.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+fkn[r]}};var Qge="([+-]?\\d+)",ykn=Qge+"\\s+years?",wkn=Qge+"\\s+mons?",Ekn=Qge+"\\s+days?",xkn="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",bkn=new RegExp([ykn,wkn,Ekn,xkn].map(function(t){return"("+t+")?"}).join("\\s*")),Aet={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},Ckn=["hours","minutes","seconds","milliseconds"];function Ikn(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}function vkn(t){if(!t)return{};var e=bkn.exec(t),n=e[8]==="-";return Object.keys(Aet).reduce(function(r,i){var o=Aet[i],s=e[o];return!s||(s=i==="milliseconds"?Ikn(s):parseInt(s,10),!s)||(n&&~Ckn.indexOf(i)&&(s*=-1),r[i]=s),r},{})}});var bet=Q((rbi,xet)=>{"use strict";var Eet=Buffer.from||Buffer;xet.exports=function(e){if(/^\\x/.test(e))return Eet(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 Eet(n,"binary")}});var Ret=Q((ibi,Tet)=>{var PF=Pge(),NF=Nge(),$6=met(),Iet=wet(),vet=bet();function W6(t){return function(n){return n===null?n:t(n)}}function _et(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}function Skn(t){return t?PF.parse(t,_et):null}function _kn(t){return parseInt(t,10)}function Oge(t){return t?PF.parse(t,W6(_kn)):null}function kkn(t){return t?PF.parse(t,W6(function(e){return ket(e).trim()})):null}var Tkn=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=Wge(n)),n});return e.parse()},Fge=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=parseFloat(n)),n});return e.parse()},lh=function(t){if(!t)return null;var e=NF.create(t);return e.parse()},Uge=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=$6(n)),n});return e.parse()},Rkn=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=Iet(n)),n});return e.parse()},Bkn=function(t){return t?PF.parse(t,W6(vet)):null},$ge=function(t){return parseInt(t,10)},ket=function(t){var e=String(t);return/^\d+$/.test(e)?e:t},Cet=function(t){return t?PF.parse(t,W6(JSON.parse)):null},Wge=function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},Dkn=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=Wge(e);return o.radius=parseFloat(n),o},Mkn=function(t){t(20,ket),t(21,$ge),t(23,$ge),t(26,$ge),t(700,parseFloat),t(701,parseFloat),t(16,_et),t(1082,$6),t(1114,$6),t(1184,$6),t(600,Wge),t(651,lh),t(718,Dkn),t(1e3,Skn),t(1001,Bkn),t(1005,Oge),t(1007,Oge),t(1028,Oge),t(1016,kkn),t(1017,Tkn),t(1021,Fge),t(1022,Fge),t(1231,Fge),t(1014,lh),t(1015,lh),t(1008,lh),t(1009,lh),t(1040,lh),t(1041,lh),t(1115,Uge),t(1182,Uge),t(1185,Uge),t(1186,Iet),t(1187,Rkn),t(17,vet),t(114,JSON.parse.bind(JSON)),t(3802,JSON.parse.bind(JSON)),t(199,Cet),t(3807,Cet),t(3907,lh),t(2951,lh),t(791,lh),t(1183,lh),t(1270,lh)};Tet.exports={init:Mkn}});var Det=Q((obi,Bet)=>{"use strict";var Gl=1e6;function Pkn(t){var e=t.readInt32BE(0),n=t.readUInt32BE(4),r="";e<0&&(e=~e+(n===0),n=~n+1>>>0,r="-");var i="",o,s,a,c,u,l;{if(o=e%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}return o=e%Gl,s=4294967296*o+n,a=""+s%Gl,r+a+i}Bet.exports=Pkn});var Qet=Q((sbi,Let)=>{var Nkn=Det(),as=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},Net=function(t,e,n){var r=Math.pow(2,n-1)-1,i=as(t,1),o=as(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=as(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},Lkn=function(t){return as(t,1)==1?-1*(as(t,15,1,!0)+1):as(t,15,1)},Met=function(t){return as(t,1)==1?-1*(as(t,31,1,!0)+1):as(t,31,1)},Qkn=function(t){return Net(t,23,8)},Okn=function(t){return Net(t,52,11)},Fkn=function(t){var e=as(t,16,32);if(e==49152)return NaN;for(var n=Math.pow(1e4,as(t,16,16)),r=0,i=[],o=as(t,16),s=0;s<o;s++)r+=as(t,16,64+16*s)*n,n/=1e4;var a=Math.pow(10,as(t,16,48));return(e===0?1:-1)*Math.round(r*a)/a},Pet=function(t,e){var n=as(e,1),r=as(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},LF=function(t){for(var e=as(t,32),n=as(t,32,32),r=as(t,32,64),i=96,o=[],s=0;s<e;s++)o[s]=as(t,32,i),i+=32,i+=32;var a=function(u){var l=as(t,32,i);if(i+=32,l==4294967295)return null;var d;if(u==23||u==20)return d=as(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)},Ukn=function(t){return t.toString("utf8")},$kn=function(t){return t===null?null:as(t,8)>0},Wkn=function(t){t(20,Nkn),t(21,Lkn),t(23,Met),t(26,Met),t(1700,Fkn),t(700,Qkn),t(701,Okn),t(16,$kn),t(1114,Pet.bind(null,!1)),t(1184,Pet.bind(null,!0)),t(1e3,LF),t(1007,LF),t(1016,LF),t(1008,LF),t(1009,LF),t(25,Ukn)};Let.exports={init:Wkn}});var Fet=Q((abi,Oet)=>{Oet.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 FF=Q(OF=>{var Hkn=Ret(),Gkn=Qet(),qkn=Nge(),jkn=Fet();OF.getTypeParser=zkn;OF.setTypeParser=Vkn;OF.arrayParser=qkn;OF.builtins=jkn;var QF={text:{},binary:{}};function Uet(t){return String(t)}function zkn(t,e){return e=e||"text",QF[e]&&QF[e][t]||Uet}function Vkn(t,e,n){typeof e=="function"&&(n=e,e="text"),QF[e][t]=n}Hkn.init(function(t,e){QF.text[t]=e});Gkn.init(function(t,e){QF.binary[t]=e})});var UF=Q((ubi,Hge)=>{"use strict";var $et;try{$et=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}Hge.exports={host:"localhost",user:$et,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 iB=FF(),Kkn=iB.getTypeParser(20,"text"),Ykn=iB.getTypeParser(1016,"text");Hge.exports.__defineSetter__("parseInt8",function(t){iB.setTypeParser(20,"text",t?iB.getTypeParser(23,"text"):Kkn),iB.setTypeParser(1016,"text",t?iB.getTypeParser(1007,"text"):Ykn)})});var YI=Q((lbi,Het)=>{"use strict";var Jkn=UF(),Xkn=J("util"),{isDate:Zkn}=J("util/types"),eTn=Xkn.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 tTn(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function Wet(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+=Wet(r):ArrayBuffer.isView(r)?(r instanceof Buffer||(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),e+="\\\\x"+r.toString("hex")):e+=tTn(H6(r))}return e+="}",e}var H6=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):Zkn(t)?(isNaN(t.getTime())&&eTn(),Jkn.parseInputDatesAsUTC?iTn(t):rTn(t)):Array.isArray(t)?Wet(t):nTn(t,e):t.toString()};function nTn(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),H6(t.toPostgres(H6),e)}return JSON.stringify(t)}function rTn(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 iTn(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 oTn(t,e,n){return t=typeof t=="string"?{text:t}:sTn(t),e&&(typeof e=="function"?t.callback=e:t.values=e),n&&(t.callback=n),t}function sTn(t){return t==null?t:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),Object.getOwnPropertyDescriptors(t))}var aTn=function(t){return'"'+t.replace(/"/g,'""')+'"'},cTn=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};Het.exports={prepareValue:function(e){return H6(e)},normalizeQueryConfig:oTn,escapeIdentifier:aTn,escapeLiteral:cTn}});var jge=Q((dbi,jet)=>{var Get=J("crypto");jet.exports={postgresMd5PasswordHash:lTn,randomBytes:uTn,deriveKey:mTn,sha256:dTn,hashByName:pTn,hmacSha256:hTn,md5:Gge};var qet=Get.webcrypto||globalThis.crypto,JI=qet.subtle,qge=new TextEncoder;function uTn(t){return qet.getRandomValues(Buffer.alloc(t))}async function Gge(t){try{return Get.createHash("md5").update(t,"utf-8").digest("hex")}catch{let n=typeof t=="string"?qge.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 lTn(t,e,n){let r=await Gge(e+t);return"md5"+await Gge(Buffer.concat([Buffer.from(r),n]))}async function dTn(t){return await JI.digest("SHA-256",t)}async function pTn(t,e){return await JI.digest(t,e)}async function hTn(t,e){let n=await JI.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await JI.sign("HMAC",n,qge.encode(e))}async function mTn(t,e,n){let r=await JI.importKey("raw",qge.encode(t),"PBKDF2",!1,["deriveBits"]),i={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:n};return await JI.deriveBits(i,r,256,["deriveBits"])}});var Ket=Q((pbi,Vet)=>{function XI(t,e){return new Error("SASL channel binding: "+t+" when parsing public certificate "+e.toString("base64"))}function zge(t,e){let n=t[e++];if(n<128)return{length:n,index:e};let r=n&127;if(r>4)throw XI("bad length",t);n=0;for(let i=0;i<r;i++)n=n<<8|t[e++];return{length:n,index:e}}function zet(t,e){if(t[e++]!==6)throw XI("non-OID data",t);let{length:n,index:r}=zge(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 $F(t,e){if(t[e++]!==48)throw XI("non-sequence data",t);return zge(t,e)}function fTn(t,e){e===void 0&&(e=0),e=$F(t,e).index;let{length:n,index:r}=$F(t,e);e=r+n,e=$F(t,e).index;let{oid:i,index:o}=zet(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=$F(t,e).index,t[e++]!==160)throw XI("non-tag data",t);e=zge(t,e).index,e=$F(t,e).index;let{oid:s}=zet(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 XI("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 XI("Ed448 certificate channel binding is not currently supported by Postgres")}throw XI("unknown OID "+i,t)}Vet.exports={signatureAlgorithmHashFromCertificate:fTn}});var Zet=Q((hbi,Xet)=>{"use strict";var dE=jge(),{signatureAlgorithmHashFromCertificate:gTn}=Ket();function ATn(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 Vge=1e5;function yTn(t,e,n=Vge){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=dE.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 wTn(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=bTn(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:Vge;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=gTn(b);(v==="MD5"||v==="SHA-1")&&(v="SHA-256");let S=await dE.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 dE.deriveKey(ATn(e),d,i.iteration),h=await dE.hmacSha256(p,"Client Key"),m=await dE.sha256(h),f=await dE.hmacSha256(m,l),g=ITn(Buffer.from(h),Buffer.from(f)).toString("base64"),A=await dE.hmacSha256(p,"Server Key"),x=await dE.hmacSha256(A,l);t.message="SASLResponse",t.serverSignature=Buffer.from(x).toString("base64"),t.response=u+",p="+g}function ETn(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}=CTn(e);if(n!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function xTn(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 Yet(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}function Jet(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 bTn(t){let e=Jet(t),n=e.get("r");if(n){if(!xTn(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(!Yet(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 CTn(t){let e=Jet(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(!Yet(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 ITn(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]))}Xet.exports={startSession:yTn,continueSession:wTn,finalizeSession:ETn,DEFAULT_MAX_SCRAM_ITERATIONS:Vge}});var q6=Q((mbi,ett)=>{"use strict";var vTn=FF();function G6(t){this._types=t||vTn,this.text={},this.binary={}}G6.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};G6.prototype.setTypeParser=function(t,e,n){typeof e=="function"&&(n=e,e="text"),this.getOverrides(e)[t]=n};G6.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};ett.exports=G6});var rtt=Q((fbi,ntt)=>{"use strict";function oB(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?J("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"&&Kge(n.sslmode);break}case"no-verify":{n.ssl.rejectUnauthorized=!1;break}}return n}function STn(t){return Object.entries(t).reduce((n,[r,i])=>(i!=null&&(n[r]=i),n),Object.create(null))}function ttt(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]=STn(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 _Tn(t){return ttt(oB(t))}function Kge(t){!Kge.warned&&typeof process<"u"&&process.emitWarning&&(Kge.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.
@@ -1,8 +1,10 @@
1
- var y=Object.defineProperty;var i=(e,r)=>y(e,"name",{value:r,configurable:!0});import{envNodeId as b}from"../shared/env.js";import{defineBranch as k,defineLeaf as c}from"../core/command.js";import{InputError as d,readStdinRaw as h}from"../core/io.js";import{ApiError as q}from"../api/index.js";import{cliClient as p,rethrowAsCliError as u}from"./api-client.js";function f(){const e=b();if(e===void 0||e.trim()==="")throw new d({error:"no_node_context",message:"CRTR_NODE_ID is not set \u2014 push runs inside a canvas node.",next:"Run push from a node process spawned by the runtime."});return e.trim()}i(f,"requireCallerNode");const m={update:"report progress to subscribers",final:"finish: write the canonical result, mark the node done, close its window"},_={update:"you have progress worth surfacing to your managers while work remains in flight. Use normal delivery unless it can wait for their next real wake (--tier deferred) or needs immediate attention (--tier urgent); use push final only when the work is actually done.",final:"the work this node was spawned to do is complete and you are ready to hand back the canonical result \u2014 this writes that result, marks the node done, and closes its window, so it is the LAST thing you do here, not a progress note. Use push update while work is still in flight, and do not reach for final on a node working directly with the user: it has no manager to report up to and would close mid-conversation (the guard blocks it unless you pass --force after the user confirms)."};function v(){return c({name:"result",description:"answer a pending structured-output request with the required JSON result, or decline it",whenToUse:'your system prompt names a pending structured-output request you must answer. The value is validated against the required schema server-side; a mismatch rejects with field errors and records nothing, so fix and rerun. When the schema cannot be honestly satisfied (blocked, unavailable, bad input), pass `--decline "<reason>" --code <token>` (plus `--retryable` when the same request could succeed later) instead of inventing a value; your requester names the code tokens it accepts. For a terminal request either path IS how the node finishes \u2014 never call `crtr push final` alongside it.',help:{name:"push result",summary:"answer a pending structured-output request",params:[{kind:"stdin",name:"value",required:!1,constraint:"The JSON result. Pipe it from a single-quoted heredoc (`<<'EOF'`) to preserve literal bytes. Required unless `--decline` is passed."},{kind:"flag",name:"request",type:"string",required:!0,constraint:"The request id from the structured-output instruction. It binds this result to that exact request; crouter never selects a pending request implicitly."},{kind:"flag",name:"decline",type:"string",required:!1,constraint:"Decline instead of answering: one plain sentence on why the schema cannot be honestly satisfied (blocked, unavailable, bad input). Requires `--code`. Records a failure outcome with reason `declined` carrying the reason, code, and retryable flag, and clears the request; for a terminal request this finishes the node."},{kind:"flag",name:"code",type:"string",required:!1,constraint:"With `--decline`: one whitespace-free token (\u2264 64 chars) naming the decline class. crouter carries it verbatim; the requester validates it against the tokens it documented for you."},{kind:"flag",name:"retryable",type:"bool",required:!1,default:!1,constraint:"With `--decline`: the same request could succeed if issued again later (a transient block). Omit when the decline is final for this input."}],output:[{name:"mode",type:"string",required:!0,constraint:"Which request this answered: `terminal` finished the node; `oneoff` left it working."},{name:"declined",type:"object",required:!1,constraint:"Present only when the request was declined: { reason, code, retryable } as recorded."},{name:"report",type:"string",required:!0,constraint:"Name of the report document pushed alongside the result, `<node-id>/reports/<name>`."},{name:"notified",type:"string[]",required:!0,constraint:"Subscriber node ids that received an inbox pointer."},{name:"transitioned",type:"object",required:!1,constraint:"Present only for a terminal request that flipped the node \u2014 { from, to } lifecycle-status transition applied server-side."}],outputKind:"object",effects:["Validates the value against the pending schema server-side; a mismatch records nothing and the request stays pending.","Records the accepted result (or the decline) on the pending request and clears it.","A terminal decline records a `failure` outcome with reason `declined` whose `declined` field carries { reason, code, retryable }; the requester sees no value.","Pushes the mode-matched report: final for a terminal request (the node finishes \u2014 same effects as `push final`), update for a one-off request (the node keeps working)."]},run:i(async e=>{const r=f(),s=typeof e.request=="string"?e.request.trim():"";if(s==="")throw new d({error:"request_id_required",message:"a structured result needs its request id",field:"request",next:"Copy the request id named in the structured-output instruction and rerun with `--request <request-id>`."});const o=typeof e.decline=="string"?e.decline.trim():"",a=typeof e.code=="string"?e.code.trim():"";let n;if(o!==""){if(a==="")throw new d({error:"missing_decline_code",message:"a decline needs a code",field:"code",next:"Pass `--code <token>` \u2014 the whitespace-free token your requester documented for this decline class."});n={request_id:s,decline:o,code:a,retryable:e.retryable===!0}}else{if(a!==""||e.retryable===!0)throw new d({error:"decline_flags_without_decline",message:"--code and --retryable only apply with --decline",next:'Pass `--decline "<reason>"` alongside them, or drop them and submit the JSON result.'});let t=typeof e.value=="string"?e.value.trim():"";if(t===""&&(t=(await h()).trim()),t==="")throw new d({error:"missing_value",message:"no result value",field:"value",next:'Pass the JSON result as an argument or on stdin, or `--decline "<reason>" --code <token>` when the schema cannot be honestly satisfied.'});let l;try{l=JSON.parse(t)}catch(g){throw new d({error:"bad_result_json",message:`the result is not valid JSON: ${g.message}`,field:"value",next:"Pass one valid JSON value matching the requested schema."})}n={request_id:s,value:l}}try{const t=await p().submitResult(r,n);return{mode:t.mode,report:t.report,notified:t.notified,...t.declined===void 0?{}:{declined:t.declined},...t.transitioned!==void 0?{transitioned:t.transitioned}:{},...t.worktree_auto_dropped===!0?{worktree_auto_dropped:!0,worktree_auto_dropped_path:t.worktree_auto_dropped_path}:{}}}catch(t){u(t)}},"run"),render:i(e=>{const r=e.declined,s=e.mode==="terminal"?`${r?"Decline recorded":"Result recorded"} \u2014 node finished; its engine shuts down on next stop. Nothing more to do here: STOP your turn immediately. Reply with just "Done." and nothing else.`:`${r?"One-off request declined":"One-off result recorded"} and pushed \u2014 the structured-output gate is cleared; continue working normally.`,o=r===void 0?"":`
2
- - code: ${r.code} (${r.retryable?"retryable":"not retryable"})`;return`${s}
1
+ var P=Object.defineProperty;var d=(e,r)=>P(e,"name",{value:r,configurable:!0});import{createHash as O}from"node:crypto";import{closeSync as $,constants as _,createReadStream as k,fstatSync as N,openSync as R}from"node:fs";import{basename as T}from"node:path";import{Readable as A}from"node:stream";import{envNodeId as E}from"../shared/env.js";import{defineBranch as F,defineLeaf as g}from"../core/command.js";import{InputError as a,readStdinRaw as q}from"../core/io.js";import{ApiError as L}from"../api/index.js";import{cliClient as w,rethrowAsCliError as f}from"./api-client.js";import{contentTypeFor as U}from"../core/storage/media-types.js";const v=100*1024*1024;function y(){const e=E();if(e===void 0||e.trim()==="")throw new a({error:"no_node_context",message:"CRTR_NODE_ID is not set \u2014 push runs inside a canvas node.",next:"Run push from a node process spawned by the runtime."});return e.trim()}d(y,"requireCallerNode");const x={update:"report progress to subscribers",final:"finish: write the canonical result, mark the node done, close its window"},I={update:"you have progress worth surfacing to your managers while work remains in flight. Use normal delivery unless it can wait for their next real wake (--tier deferred) or needs immediate attention (--tier urgent); use push final only when the work is actually done.",final:"the work this node was spawned to do is complete and you are ready to hand back the canonical result \u2014 this writes that result, marks the node done, and closes its window, so it is the LAST thing you do here, not a progress note. Use push update while work is still in flight, and do not reach for final on a node working directly with the user: it has no manager to report up to and would close mid-conversation (the guard blocks it unless you pass --force after the user confirms)."};function j(){return g({name:"result",description:"answer a pending structured-output request with the required JSON result, or decline it",whenToUse:'your system prompt names a pending structured-output request you must answer. The value is validated against the required schema server-side; a mismatch rejects with field errors and records nothing, so fix and rerun. When the schema cannot be honestly satisfied (blocked, unavailable, bad input), pass `--decline "<reason>" --code <token>` (plus `--retryable` when the same request could succeed later) instead of inventing a value; your requester names the code tokens it accepts. For a terminal request either path IS how the node finishes \u2014 never call `crtr push final` alongside it.',help:{name:"push result",summary:"answer a pending structured-output request",params:[{kind:"stdin",name:"value",required:!1,constraint:"The JSON result. Pipe it from a single-quoted heredoc (`<<'EOF'`) to preserve literal bytes. Required unless `--decline` is passed."},{kind:"flag",name:"request",type:"string",required:!0,constraint:"The request id from the structured-output instruction. It binds this result to that exact request; crouter never selects a pending request implicitly."},{kind:"flag",name:"decline",type:"string",required:!1,constraint:"Decline instead of answering: one plain sentence on why the schema cannot be honestly satisfied (blocked, unavailable, bad input). Requires `--code`. Records a failure outcome with reason `declined` carrying the reason, code, and retryable flag, and clears the request; for a terminal request this finishes the node."},{kind:"flag",name:"code",type:"string",required:!1,constraint:"With `--decline`: one whitespace-free token (\u2264 64 chars) naming the decline class. crouter carries it verbatim; the requester validates it against the tokens it documented for you."},{kind:"flag",name:"retryable",type:"bool",required:!1,default:!1,constraint:"With `--decline`: the same request could succeed if issued again later (a transient block). Omit when the decline is final for this input."}],output:[{name:"mode",type:"string",required:!0,constraint:"Which request this answered: `terminal` finished the node; `oneoff` left it working."},{name:"declined",type:"object",required:!1,constraint:"Present only when the request was declined: { reason, code, retryable } as recorded."},{name:"report",type:"string",required:!0,constraint:"Name of the report document pushed alongside the result, `<node-id>/reports/<name>`."},{name:"notified",type:"string[]",required:!0,constraint:"Subscriber node ids that received an inbox pointer."},{name:"transitioned",type:"object",required:!1,constraint:"Present only for a terminal request that flipped the node \u2014 { from, to } lifecycle-status transition applied server-side."}],outputKind:"object",effects:["Validates the value against the pending schema server-side; a mismatch records nothing and the request stays pending.","Records the accepted result (or the decline) on the pending request and clears it.","A terminal decline records a `failure` outcome with reason `declined` whose `declined` field carries { reason, code, retryable }; the requester sees no value.","Pushes the mode-matched report: final for a terminal request (the node finishes \u2014 same effects as `push final`), update for a one-off request (the node keeps working)."]},run:d(async e=>{const r=y(),n=typeof e.request=="string"?e.request.trim():"";if(n==="")throw new a({error:"request_id_required",message:"a structured result needs its request id",field:"request",next:"Copy the request id named in the structured-output instruction and rerun with `--request <request-id>`."});const o=typeof e.decline=="string"?e.decline.trim():"",i=typeof e.code=="string"?e.code.trim():"";let s;if(o!==""){if(i==="")throw new a({error:"missing_decline_code",message:"a decline needs a code",field:"code",next:"Pass `--code <token>` \u2014 the whitespace-free token your requester documented for this decline class."});s={request_id:n,decline:o,code:i,retryable:e.retryable===!0}}else{if(i!==""||e.retryable===!0)throw new a({error:"decline_flags_without_decline",message:"--code and --retryable only apply with --decline",next:'Pass `--decline "<reason>"` alongside them, or drop them and submit the JSON result.'});let t=typeof e.value=="string"?e.value.trim():"";if(t===""&&(t=(await q()).trim()),t==="")throw new a({error:"missing_value",message:"no result value",field:"value",next:'Pass the JSON result as an argument or on stdin, or `--decline "<reason>" --code <token>` when the schema cannot be honestly satisfied.'});let h;try{h=JSON.parse(t)}catch(u){throw new a({error:"bad_result_json",message:`the result is not valid JSON: ${u.message}`,field:"value",next:"Pass one valid JSON value matching the requested schema."})}s={request_id:n,value:h}}try{const t=await w().submitResult(r,s);return{mode:t.mode,report:t.report,notified:t.notified,...t.declined===void 0?{}:{declined:t.declined},...t.transitioned!==void 0?{transitioned:t.transitioned}:{},...t.worktree_auto_dropped===!0?{worktree_auto_dropped:!0,worktree_auto_dropped_path:t.worktree_auto_dropped_path}:{}}}catch(t){f(t)}},"run"),render:d(e=>{const r=e.declined,n=e.mode==="terminal"?`${r?"Decline recorded":"Result recorded"} \u2014 node finished; its engine shuts down on next stop. Nothing more to do here: STOP your turn immediately. Reply with just "Done." and nothing else.`:`${r?"One-off request declined":"One-off result recorded"} and pushed \u2014 the structured-output gate is cleared; continue working normally.`,o=r===void 0?"":`
2
+ - code: ${r.code} (${r.retryable?"retryable":"not retryable"})`;return`${n}
3
3
 
4
- - report: ${e.report}${o}`},"render")})}i(v,"makeResultLeaf");function w(e){return c({name:e,description:m[e],whenToUse:_[e],help:{name:`push ${e}`,summary:m[e],params:[{kind:"stdin",name:"body",required:!0,constraint:"Report body (markdown). Pipe it from a single-quoted heredoc (`<<'EOF'`) to preserve literal bytes."},...e==="update"?[{kind:"flag",name:"tier",type:"enum",choices:["deferred","normal","urgent"],required:!1,default:"normal",constraint:"Delivery urgency: deferred holds for the receiver\u2019s next non-deferred wake; normal wakes normally; urgent steers a live receiver and wakes an idle receiver."}]:[{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Override the guard that blocks `push final` on a node the user is attending (a resident with no one to report up to). Only pass this after the user explicitly confirms they want this node finished."}]],output:[{name:"report",type:"string",required:!0,constraint:"Name of the written report document, `<node-id>/reports/<name>`."},{name:"notified",type:"string[]",required:!0,constraint:"Subscriber node ids that received an inbox pointer."},...e==="final"?[{name:"transitioned",type:"object",required:!1,constraint:"Present only for a final that flipped the node \u2014 { from, to } lifecycle-status transition applied server-side."},{name:"worktree_auto_dropped",type:"boolean",required:!1,constraint:"Present only when the server closed this node\u2019s managed-worktree record without requiring `node worktree close`; cleanup of an existing checkout remains pending (see worktree_auto_dropped_path)."},{name:"worktree_auto_dropped_path",type:"string",required:!1,constraint:"Present only alongside worktree_auto_dropped: the closed worktree path; an existing checkout remains until pending cleanup."}]:[]],outputKind:"object",effects:["Creates the report document `<node-id>/reports/<compact-ts>-<uuid8>-<kind>` (server-side).","Appends one inbox pointer per subscriber.",...e==="final"?["Marks the node done (status + intent) server-side; its engine shuts down on next stop.","When this node owns a clean managed worktree already contained in its local base, the server closes its record with cleanup pending instead of blocking on `node worktree close`. A clean worktree whose exact tip exists on any branch on origin may also finalize while retaining its branch and checkout; uncommitted changes or a tip absent from origin still block with open_managed_worktree."]:[]]},run:i(async r=>{const s=f();let o=typeof r.body=="string"?r.body.trim():"";if(o===""&&(o=(await h()).trim()),o==="")throw new d({error:"missing_body",message:"no report body",field:"body",next:"Pass the body as an argument or on stdin."});const a=p();if(e==="final"&&r.force!==!0){let n=null;try{n=await a.getNode(s)}catch(t){t instanceof q&&t.status===404||u(t)}if(n!==null&&n.lifecycle==="resident"&&n.edges.subscribers.length===0)throw new d({error:"no_final_recipient",message:"This node is working directly with the user \u2014 it has no manager to submit a final result to. `push final` would end the conversation mid-stream.",next:'You almost certainly do NOT need to finish here \u2014 just keep working with the user. If the user has explicitly asked you to finish and close this node, confirm with them first, then rerun with `crtr push final --force "<result>"`.'})}try{const n=r.tier,t=await a.pushReport(s,{tier:e,body:o,...n===void 0?{}:{delivery_tier:n}});return{report:t.report,notified:t.notified,...t.transitioned!==void 0?{transitioned:t.transitioned}:{},...t.worktree_auto_dropped===!0?{worktree_auto_dropped:!0,worktree_auto_dropped_path:t.worktree_auto_dropped_path}:{}}}catch(n){u(n)}},"run"),render:i(r=>{const s=Array.isArray(r.notified)?r.notified.length:0,o=e==="final"?'Result recorded \u2014 node finished; its engine shuts down on next stop. Nothing more to do here: STOP your turn immediately. Reply with just "Done." and nothing else.':`Progress report fanned to ${s} subscriber(s).`,a=r.worktree_auto_dropped===!0?`
4
+ - report: ${e.report}${o}`},"render")})}d(j,"makeResultLeaf");function z(){return g({name:"file",description:"hand a file from this node\u2019s machine to the person you work for",whenToUse:"you produced a file the person should have \u2014 a report, export, image, spreadsheet \u2014 and the person works through an app or chat, not in your shell. Writing a path into a message does not give them the file; this does. One file per call, up to 100 MiB. The file is copied when you run this, so later edits are not sent; run it again for a new version. The node must belong to an app run (a conversation someone started through an app); otherwise there is no one to give it to.",help:{name:"push file",summary:"hand a file to the person",params:[{kind:"positional",name:"path",required:!0,constraint:"Path of one regular file, at most 100 MiB. A symbolic link is refused. The file name shown to the person is its base name."}],output:[{name:"file_id",type:"string",required:!0,constraint:"Id of the stored file; the app downloads or shares it by this id."},{name:"name",type:"string",required:!0,constraint:"File name as the person sees it."},{name:"media_type",type:"string",required:!0,constraint:"Media type chosen from the file extension (`application/octet-stream` when unknown)."},{name:"size",type:"number",required:!0,constraint:"Size in bytes."}],outputKind:"object",effects:["Uploads a copy of the file to storage and records it against this node\u2019s app run.","Appends a `file.sent` event to the run, which the app sees.","Fails without recording anything when the stored bytes do not match the file as read, or the node belongs to no app run."]},run:d(async e=>{const r=y(),n=typeof e.path=="string"?e.path:"";if(n==="")throw new a({error:"missing_path",message:"no file path",field:"path",next:"Pass the path of the file to hand over."});let o;try{o=R(n,_.O_RDONLY|_.O_NOFOLLOW)}catch(i){throw new a({error:"file_unreadable",message:`cannot open ${n}: ${i.code==="ELOOP"?"it is a symbolic link":i.message}`,field:"path",next:"Pass the path of a regular file you can read, not a link."})}try{const i=N(o);if(!i.isFile())throw new a({error:"not_a_file",message:`${n} is not a regular file`,field:"path",next:"Pass one regular file; zip a directory first."});if(i.size>v)throw new a({error:"file_too_large",message:`${n} is ${i.size} bytes; the limit is ${v}`,field:"path",next:"Split or compress the file below 100 MiB."});const s=T(n),t=U(s),h=O("sha256");let u=0;for await(const l of k("",{fd:o,autoClose:!1,start:0}))h.update(l),u+=l.length;if(u!==i.size)throw new a({error:"file_changed",message:`${n} changed while it was read`,field:"path",next:"Rerun when nothing is writing to the file."});const b=w();try{const l=await b.createNodeFile(r,{name:s,media_type:t,size:u,sha256:h.digest("hex")});let c;try{c=await fetch(l.upload_link,{method:"PUT",signal:AbortSignal.timeout(11e4),headers:{"Content-Type":t,"Content-Length":String(u)},body:u===0?new Uint8Array(0):A.toWeb(k("",{fd:o,autoClose:!1,start:0,end:u-1})),duplex:"half"})}catch(m){throw new a({error:"upload_failed",message:`storage could not be reached: ${m instanceof Error?m.message:String(m)}`,next:"Rerun `crtr push file` to try again."})}if(await c.body?.cancel().catch(()=>{}),!c.ok)throw new a({error:"upload_failed",message:`storage answered ${c.status} to the upload`,next:"Rerun `crtr push file` to try again."});const p=await b.completeNodeFile(r,l.file_id);return{file_id:p.file_id,name:p.name,media_type:p.media_type,size:p.size}}catch(l){if(l instanceof a)throw l;f(l)}}finally{$(o)}},"run"),render:d(e=>`File handed over: ${String(e.name)} (${String(e.size)} bytes, ${String(e.media_type)}).
5
+
6
+ - file_id: ${String(e.file_id)}`,"render")})}d(z,"makeFileLeaf");function S(e){return g({name:e,description:x[e],whenToUse:I[e],help:{name:`push ${e}`,summary:x[e],params:[{kind:"stdin",name:"body",required:!0,constraint:"Report body (markdown). Pipe it from a single-quoted heredoc (`<<'EOF'`) to preserve literal bytes."},...e==="update"?[{kind:"flag",name:"tier",type:"enum",choices:["deferred","normal","urgent"],required:!1,default:"normal",constraint:"Delivery urgency: deferred holds for the receiver\u2019s next non-deferred wake; normal wakes normally; urgent steers a live receiver and wakes an idle receiver."}]:[{kind:"flag",name:"force",type:"bool",required:!1,default:!1,constraint:"Override the guard that blocks `push final` on a node the user is attending (a resident with no one to report up to). Only pass this after the user explicitly confirms they want this node finished."}]],output:[{name:"report",type:"string",required:!0,constraint:"Name of the written report document, `<node-id>/reports/<name>`."},{name:"notified",type:"string[]",required:!0,constraint:"Subscriber node ids that received an inbox pointer."},...e==="final"?[{name:"transitioned",type:"object",required:!1,constraint:"Present only for a final that flipped the node \u2014 { from, to } lifecycle-status transition applied server-side."},{name:"worktree_auto_dropped",type:"boolean",required:!1,constraint:"Present only when the server closed this node\u2019s managed-worktree record without requiring `node worktree close`; cleanup of an existing checkout remains pending (see worktree_auto_dropped_path)."},{name:"worktree_auto_dropped_path",type:"string",required:!1,constraint:"Present only alongside worktree_auto_dropped: the closed worktree path; an existing checkout remains until pending cleanup."}]:[]],outputKind:"object",effects:["Creates the report document `<node-id>/reports/<compact-ts>-<uuid8>-<kind>` (server-side).","Appends one inbox pointer per subscriber.",...e==="final"?["Marks the node done (status + intent) server-side; its engine shuts down on next stop.","When this node owns a clean managed worktree already contained in its local base, the server closes its record with cleanup pending instead of blocking on `node worktree close`. A clean worktree whose exact tip exists on any branch on origin may also finalize while retaining its branch and checkout; uncommitted changes or a tip absent from origin still block with open_managed_worktree."]:[]]},run:d(async r=>{const n=y();let o=typeof r.body=="string"?r.body.trim():"";if(o===""&&(o=(await q()).trim()),o==="")throw new a({error:"missing_body",message:"no report body",field:"body",next:"Pass the body as an argument or on stdin."});const i=w();if(e==="final"&&r.force!==!0){let s=null;try{s=await i.getNode(n)}catch(t){t instanceof L&&t.status===404||f(t)}if(s!==null&&s.lifecycle==="resident"&&s.edges.subscribers.length===0)throw new a({error:"no_final_recipient",message:"This node is working directly with the user \u2014 it has no manager to submit a final result to. `push final` would end the conversation mid-stream.",next:'You almost certainly do NOT need to finish here \u2014 just keep working with the user. If the user has explicitly asked you to finish and close this node, confirm with them first, then rerun with `crtr push final --force "<result>"`.'})}try{const s=r.tier,t=await i.pushReport(n,{tier:e,body:o,...s===void 0?{}:{delivery_tier:s}});return{report:t.report,notified:t.notified,...t.transitioned!==void 0?{transitioned:t.transitioned}:{},...t.worktree_auto_dropped===!0?{worktree_auto_dropped:!0,worktree_auto_dropped_path:t.worktree_auto_dropped_path}:{}}}catch(s){f(s)}},"run"),render:d(r=>{const n=Array.isArray(r.notified)?r.notified.length:0,o=e==="final"?'Result recorded \u2014 node finished; its engine shuts down on next stop. Nothing more to do here: STOP your turn immediately. Reply with just "Done." and nothing else.':`Progress report fanned to ${n} subscriber(s).`,i=r.worktree_auto_dropped===!0?`
5
7
 
6
8
  Closed a clean managed-worktree record at ${String(r.worktree_auto_dropped_path)} \u2014 nothing to land; cleanup remains pending if the checkout still exists.`:"";return`${o}
7
9
 
8
- - report: ${r.report}${a}`},"render")})}i(w,"makePushLeaf");function $(){return k({name:"push",rootEntry:{concept:"the one verb up the graph \u2014 a node reports to whoever subscribes to it",desc:"push an update or final report to your subscribers",useWhen:"sharing progress, raising an alert, or finishing your work"},help:{name:"push",summary:"push a report to your subscribers",model:"A push writes a report document the node owns and fans a lightweight pointer to every subscriber's inbox. Delivery inlines reports under 1,000 characters; a longer report is read with `crtr canvas read <name>`. Point at documents you wrote as `[[<node-id>/<name>]]`, never as a file path. Nothing is pushed automatically \u2014 the feed contains only what a node pushes explicitly, so push whenever you want a manager to see something. Pipe markdown via a single-quoted heredoc so it reaches the report literally. `push final` is how ANY node finishes: write the canonical result, mark done, close the window."},children:[w("update"),w("final"),v()]})}i($,"registerPush");export{$ as registerPush};
10
+ - report: ${r.report}${i}`},"render")})}d(S,"makePushLeaf");function G(){return F({name:"push",rootEntry:{concept:"the one verb up the graph \u2014 a node reports to whoever subscribes to it",desc:"push an update or final report to your subscribers",useWhen:"sharing progress, raising an alert, or finishing your work"},help:{name:"push",summary:"push a report to your subscribers",model:"A push writes a report document the node owns and fans a lightweight pointer to every subscriber's inbox. Delivery inlines reports under 1,000 characters; a longer report is read with `crtr canvas read <name>`. Point at documents you wrote as `[[<node-id>/<name>]]`, never as a file path. Nothing is pushed automatically \u2014 the feed contains only what a node pushes explicitly, so push whenever you want a manager to see something. Pipe markdown via a single-quoted heredoc so it reaches the report literally. `push final` is how ANY node finishes: write the canonical result, mark done, close the window."},children:[S("update"),S("final"),j(),z()]})}d(G,"registerPush");export{G as registerPush};
@@ -1,3 +1,3 @@
1
- var V=Object.defineProperty;var d=(i,a)=>V(i,"name",{value:a,configurable:!0});import{DatabaseSync as W}from"node:sqlite";import{existsSync as Y,mkdirSync as D,mkdtempSync as J,renameSync as X,rmSync as P}from"node:fs";import{tmpdir as Q}from"node:os";import{join as A}from"node:path";import j from"pg";import{migrate as z,MIGRATIONS as I}from"./migrations.js";import{canvasDbPath as Z}from"./paths.js";import{canvasSearchPathOptions as ee}from"./schema-version.js";import{EXPORT_MARK_KEY as F,IMPORT_MARK_KEY as te,OBJECT_COLUMNS as ne,pgColumns as se,quote as m,TABLE_ORDER as C}from"./import-sqlite.js";const oe=5e3,re=new Set(["environments","relations","schemas","charges","charge_totals","limits","viewer_attachments","reconciler_leases","environment_repos","conversation_entries","conversation_parts","charge_chunks","profiles","profile_projects","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","import_runs","import_key_map","import_manifest","import_id_map","machine_links","machine_calls","machine_credentials","import_node_files","bodies","package_publications","credential_activations","hosted_endpoints","usage","grantee_usage","provider_receipts"]),ae={exposures:"node, object, channel",rules:"object, position",edges:"type, src, dst",unresolved_links:"src, name",revision_parents:"child, parent",canvas_meta:"key",runtime_state:"key",message_causes:"message_id",peer_ingested:"key",peer_ingested_destinations:"key",message_sequence:"id",messages:"seq",review_comment_events:"seq",audit_rows:"id",peer_outbox:"id",app_users:"uid"},ie={objects:"id",revisions:"rev_id",watches:"watch_id"},H=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated",te,F]);function ce(i){const a=J(A(Q(),"crtr-export-")),s=process.env.CRTR_HOME;process.env.CRTR_HOME=a,D(A(a,"runtime","nodes"),{recursive:!0});try{const o=new W(i);return o.exec("PRAGMA journal_mode = DELETE;"),o.exec("PRAGMA foreign_keys = ON;"),z(o),o.exec("DELETE FROM canvas_meta; DELETE FROM message_sequence;"),o}finally{s===void 0?delete process.env.CRTR_HOME:process.env.CRTR_HOME=s,P(a,{recursive:!0,force:!0})}}d(ce,"createEmptyDatabase");async function Re(i,a=()=>{}){const s=Z();if(Y(s))throw new Error(`${s} already exists; refusing to overwrite it`);D(A(s,".."),{recursive:!0,mode:448});const o=`${s}.exporting-${process.pid}`,_=Date.now(),t=new j.Client({connectionString:i,application_name:`crtr-export-${process.pid}`,options:ee(),types:{getTypeParser:d(((f,r)=>f===20?w=>Number(w):j.types.getTypeParser(f,r)),"getTypeParser")}});await t.connect();let u;try{if((await t.query("SELECT value FROM canvas_meta WHERE key = 'schema_version'").catch(()=>({rows:[]}))).rows.length===0)throw new Error("the Postgres database has no canvas schema; nothing to export");u=ce(o);const r=u;r.exec("PRAGMA foreign_keys = OFF;");const w=await se(t),L=[...w.keys()].filter(e=>!re.has(e)&&!C.includes(e));if(L.length>0)throw new Error(`export: Postgres tables with no export rule: ${L.join(", ")}`);await t.query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ");const E={};for(const[e,S]of Object.entries(ie)){const h=new Map;for(const l of(await t.query(`SELECT ${S} AS id, seq FROM ${e}`)).rows)h.set(l.id,Number(l.seq));E[e]=h}const B=E.objects;let M=0;r.exec("BEGIN");for(const e of C){const S=Date.now(),h=new Set(r.prepare(`PRAGMA table_info(${m(e)})`).all().map(n=>n.name)),l=w.get(e);if(l===void 0)throw new Error(`export: Postgres has no table ${e}`);const G=l.some(n=>n.name==="seq"),O=l.filter(n=>h.has(n.name)),K=new Set(ne[e]??[]),g=e==="objects"||e==="revisions"||e==="watches"||e==="watch_subscriptions",$=O.map(n=>n.type==="jsonb"?`${m(n.name)}::text AS ${m(n.name)}`:m(n.name));e==="watches"&&$.push("watch_id AS _watch_id"),g&&$.push("seq AS _seq");const R=O.map(n=>m(n.name)),U=r.prepare(`INSERT INTO ${m(e)} (${g?["rowid",...R]:R}) VALUES (${(g?["?",...R]:R).map(()=>"?").join(", ")})`),k=G?"seq":ae[e],b=`export_${e}`;await t.query(`DECLARE ${b} NO SCROLL CURSOR FOR SELECT ${$.join(", ")} FROM ${m(e)}${e==="canvas_meta"?` WHERE key NOT IN (${[...H].map(n=>`'${n}'`).join(", ")})`:""}${k===void 0?"":` ORDER BY ${k}`}`);let T=0;for(;;){const n=await t.query(`FETCH ${oe} FROM ${b}`);if(n.rows.length===0)break;for(const q of n.rows){const N=g?[Number(q._seq)]:[];for(const c of O){let p=q[c.name];e==="revision_parents"&&(c.name==="child"||c.name==="parent")?p=x(E.revisions,"revision",e,c.name,p):e==="watch_subscriptions"&&c.name==="watch"?p=x(E.watches,"watch",e,c.name,p):K.has(c.name)?p=x(B,"object",e,c.name,p):e==="jobs"&&(c.name==="job_dir"||c.name==="log_path")&&(p=p??""),N.push(p??null)}U.run(...N)}T+=n.rows.length}await t.query(`CLOSE ${b}`),M+=T,a(`export ${e}: ${T} rows in ${Date.now()-S} ms`)}r.exec("COMMIT"),await t.query("COMMIT");const v=r.prepare("PRAGMA foreign_key_check").all();if(v.length>0)throw new Error(`export: ${v.length} foreign key violation(s) in the exported canvas.db, first: ${JSON.stringify(v[0])}`);await pe(t,r);const y=r.prepare("PRAGMA user_version").get().user_version;if(y!==I.length)throw new Error(`export: exported canvas.db is at user_version ${y}, expected ${I.length}`);return r.close(),u=void 0,await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",[F,JSON.stringify({at:new Date().toISOString(),path:s})]),X(o,s),{path:s,rows:M,ms:Date.now()-_,userVersion:y}}catch(f){await t.query("ROLLBACK").catch(()=>{});try{u?.close()}catch{}for(const r of["","-wal","-shm","-journal"])P(`${o}${r}`,{force:!0});throw f}finally{await t.end().catch(()=>{})}}d(Re,"exportPostgresToSqlite");function x(i,a,s,o,_){if(_==null)return null;const t=i.get(_);if(t===void 0)throw new Error(`export: ${s}.${o} references ${a} ${String(_)}, which was not exported (`);return t}d(x,"mapId");async function pe(i,a){const s=[];for(const o of C){const _=Number((await i.query(`SELECT count(*) AS n FROM ${m(o)}`)).rows[0].n);let t=Number(a.prepare(`SELECT count(*) AS n FROM ${m(o)}`).get().n),u=_;o==="canvas_meta"&&(u=Number((await i.query("SELECT count(*) AS n FROM canvas_meta WHERE key <> ALL($1)",[[...H]])).rows[0].n),t=Number(a.prepare("SELECT count(*) AS n FROM canvas_meta").get().n)),u!==t&&s.push(`${o}: Postgres ${u} rows, SQLite ${t}`)}if(s.length>0)throw new Error(`Postgres \u2192 SQLite export verification failed:
1
+ var V=Object.defineProperty;var d=(i,a)=>V(i,"name",{value:a,configurable:!0});import{DatabaseSync as W}from"node:sqlite";import{existsSync as Y,mkdirSync as D,mkdtempSync as J,renameSync as X,rmSync as P}from"node:fs";import{tmpdir as Q}from"node:os";import{join as A}from"node:path";import j from"pg";import{migrate as z,MIGRATIONS as I}from"./migrations.js";import{canvasDbPath as Z}from"./paths.js";import{canvasSearchPathOptions as ee}from"./schema-version.js";import{EXPORT_MARK_KEY as F,IMPORT_MARK_KEY as te,OBJECT_COLUMNS as ne,pgColumns as se,quote as m,TABLE_ORDER as C}from"./import-sqlite.js";const oe=5e3,re=new Set(["environments","relations","schemas","charges","charge_totals","limits","viewer_attachments","reconciler_leases","environment_repos","conversation_entries","conversation_parts","charge_chunks","profiles","profile_projects","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","import_runs","import_key_map","import_manifest","import_id_map","machine_links","machine_calls","machine_credentials","import_node_files","bodies","package_publications","credential_activations","hosted_endpoints","files","usage","grantee_usage","provider_receipts"]),ae={exposures:"node, object, channel",rules:"object, position",edges:"type, src, dst",unresolved_links:"src, name",revision_parents:"child, parent",canvas_meta:"key",runtime_state:"key",message_causes:"message_id",peer_ingested:"key",peer_ingested_destinations:"key",message_sequence:"id",messages:"seq",review_comment_events:"seq",audit_rows:"id",peer_outbox:"id",app_users:"uid"},ie={objects:"id",revisions:"rev_id",watches:"watch_id"},H=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated",te,F]);function ce(i){const a=J(A(Q(),"crtr-export-")),s=process.env.CRTR_HOME;process.env.CRTR_HOME=a,D(A(a,"runtime","nodes"),{recursive:!0});try{const o=new W(i);return o.exec("PRAGMA journal_mode = DELETE;"),o.exec("PRAGMA foreign_keys = ON;"),z(o),o.exec("DELETE FROM canvas_meta; DELETE FROM message_sequence;"),o}finally{s===void 0?delete process.env.CRTR_HOME:process.env.CRTR_HOME=s,P(a,{recursive:!0,force:!0})}}d(ce,"createEmptyDatabase");async function Re(i,a=()=>{}){const s=Z();if(Y(s))throw new Error(`${s} already exists; refusing to overwrite it`);D(A(s,".."),{recursive:!0,mode:448});const o=`${s}.exporting-${process.pid}`,_=Date.now(),t=new j.Client({connectionString:i,application_name:`crtr-export-${process.pid}`,options:ee(),types:{getTypeParser:d(((f,r)=>f===20?w=>Number(w):j.types.getTypeParser(f,r)),"getTypeParser")}});await t.connect();let u;try{if((await t.query("SELECT value FROM canvas_meta WHERE key = 'schema_version'").catch(()=>({rows:[]}))).rows.length===0)throw new Error("the Postgres database has no canvas schema; nothing to export");u=ce(o);const r=u;r.exec("PRAGMA foreign_keys = OFF;");const w=await se(t),L=[...w.keys()].filter(e=>!re.has(e)&&!C.includes(e));if(L.length>0)throw new Error(`export: Postgres tables with no export rule: ${L.join(", ")}`);await t.query("BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ");const E={};for(const[e,S]of Object.entries(ie)){const h=new Map;for(const l of(await t.query(`SELECT ${S} AS id, seq FROM ${e}`)).rows)h.set(l.id,Number(l.seq));E[e]=h}const B=E.objects;let M=0;r.exec("BEGIN");for(const e of C){const S=Date.now(),h=new Set(r.prepare(`PRAGMA table_info(${m(e)})`).all().map(n=>n.name)),l=w.get(e);if(l===void 0)throw new Error(`export: Postgres has no table ${e}`);const G=l.some(n=>n.name==="seq"),O=l.filter(n=>h.has(n.name)),K=new Set(ne[e]??[]),g=e==="objects"||e==="revisions"||e==="watches"||e==="watch_subscriptions",$=O.map(n=>n.type==="jsonb"?`${m(n.name)}::text AS ${m(n.name)}`:m(n.name));e==="watches"&&$.push("watch_id AS _watch_id"),g&&$.push("seq AS _seq");const R=O.map(n=>m(n.name)),U=r.prepare(`INSERT INTO ${m(e)} (${g?["rowid",...R]:R}) VALUES (${(g?["?",...R]:R).map(()=>"?").join(", ")})`),k=G?"seq":ae[e],b=`export_${e}`;await t.query(`DECLARE ${b} NO SCROLL CURSOR FOR SELECT ${$.join(", ")} FROM ${m(e)}${e==="canvas_meta"?` WHERE key NOT IN (${[...H].map(n=>`'${n}'`).join(", ")})`:""}${k===void 0?"":` ORDER BY ${k}`}`);let T=0;for(;;){const n=await t.query(`FETCH ${oe} FROM ${b}`);if(n.rows.length===0)break;for(const q of n.rows){const N=g?[Number(q._seq)]:[];for(const c of O){let p=q[c.name];e==="revision_parents"&&(c.name==="child"||c.name==="parent")?p=x(E.revisions,"revision",e,c.name,p):e==="watch_subscriptions"&&c.name==="watch"?p=x(E.watches,"watch",e,c.name,p):K.has(c.name)?p=x(B,"object",e,c.name,p):e==="jobs"&&(c.name==="job_dir"||c.name==="log_path")&&(p=p??""),N.push(p??null)}U.run(...N)}T+=n.rows.length}await t.query(`CLOSE ${b}`),M+=T,a(`export ${e}: ${T} rows in ${Date.now()-S} ms`)}r.exec("COMMIT"),await t.query("COMMIT");const v=r.prepare("PRAGMA foreign_key_check").all();if(v.length>0)throw new Error(`export: ${v.length} foreign key violation(s) in the exported canvas.db, first: ${JSON.stringify(v[0])}`);await pe(t,r);const y=r.prepare("PRAGMA user_version").get().user_version;if(y!==I.length)throw new Error(`export: exported canvas.db is at user_version ${y}, expected ${I.length}`);return r.close(),u=void 0,await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",[F,JSON.stringify({at:new Date().toISOString(),path:s})]),X(o,s),{path:s,rows:M,ms:Date.now()-_,userVersion:y}}catch(f){await t.query("ROLLBACK").catch(()=>{});try{u?.close()}catch{}for(const r of["","-wal","-shm","-journal"])P(`${o}${r}`,{force:!0});throw f}finally{await t.end().catch(()=>{})}}d(Re,"exportPostgresToSqlite");function x(i,a,s,o,_){if(_==null)return null;const t=i.get(_);if(t===void 0)throw new Error(`export: ${s}.${o} references ${a} ${String(_)}, which was not exported (`);return t}d(x,"mapId");async function pe(i,a){const s=[];for(const o of C){const _=Number((await i.query(`SELECT count(*) AS n FROM ${m(o)}`)).rows[0].n);let t=Number(a.prepare(`SELECT count(*) AS n FROM ${m(o)}`).get().n),u=_;o==="canvas_meta"&&(u=Number((await i.query("SELECT count(*) AS n FROM canvas_meta WHERE key <> ALL($1)",[[...H]])).rows[0].n),t=Number(a.prepare("SELECT count(*) AS n FROM canvas_meta").get().n)),u!==t&&s.push(`${o}: Postgres ${u} rows, SQLite ${t}`)}if(s.length>0)throw new Error(`Postgres \u2192 SQLite export verification failed:
2
2
  ${s.join(`
3
3
  `)}`)}d(pe,"verify");export{Re as exportPostgresToSqlite};
@@ -1052,7 +1052,7 @@ CREATE INDEX idx_structured_requests_effects ON structured_requests(effects_done
1052
1052
  name TEXT NOT NULL,
1053
1053
  PRIMARY KEY (src, name)
1054
1054
  ) WITHOUT ROWID;
1055
- `),ce,e=>e.exec("ALTER TABLE uploads ADD COLUMN sub TEXT")];function Wt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'waits'").get()===void 0&&e.exec("CREATE TABLE waits (wait_id TEXT PRIMARY KEY, node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE, kind TEXT, target_id TEXT, generation INTEGER, created_at INTEGER, satisfied_at INTEGER)");const t=e.prepare("SELECT COUNT(*) AS n FROM waits").get().n;e.exec(`
1055
+ `),ce,e=>e.exec("ALTER TABLE uploads ADD COLUMN sub TEXT"),e=>e.exec("ALTER TABLE shares ADD COLUMN sub TEXT")];function Wt(e){e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'waits'").get()===void 0&&e.exec("CREATE TABLE waits (wait_id TEXT PRIMARY KEY, node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE, kind TEXT, target_id TEXT, generation INTEGER, created_at INTEGER, satisfied_at INTEGER)");const t=e.prepare("SELECT COUNT(*) AS n FROM waits").get().n;e.exec(`
1056
1056
  CREATE TABLE waits_new (
1057
1057
  wait_id TEXT PRIMARY KEY,
1058
1058
  node_id TEXT NOT NULL REFERENCES nodes(node_id) ON DELETE CASCADE,
@@ -1,11 +1,11 @@
1
- var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as N,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new N;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await j(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["uploads","sub"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=s(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
1
+ var H=Object.defineProperty;var c=(n,e)=>H(n,"name",{value:e,configurable:!0});import{randomBytes as W}from"node:crypto";import{CrtrError as g}from"../errors.js";import{PersonUnresolvedError as f,PersonOutsideRequestError as A,setPersonId as y,markCloudRole as v,isCloudRole as D,runAsPerson as b,personId as $,bootPersonId as k,requestPersonId as C}from"./person-state.js";import{readConfig as S}from"../config.js";import{joinedIssuer as M,joinedOwner as h}from"../directory/join.js";import{installLocalTerminalGrant as F}from"../grants/local.js";import{dropLocalGrantMirror as x}from"../grants/mirror.js";import{ownerForGrantee as G,ensureOwner as J}from"../graph/objects.js";import{canvasDatabaseUrl as q,CanvasConstraintError as B,withCanvasWrite as j}from"./db.js";import{LEGACY_LOCAL_PERSON as E,LEGACY_LOCAL_TERMINAL_GRANT as Y}from"./legacy-person.js";import{rebuildTotalsFor as z}from"../ledger/totals.js";const l="person_id",O="local_person_retired",K=/^user:[A-Za-z0-9._-]+$/,I="abcdefghijklmnopqrstuvwxyz0123456789",L=new Map;async function me(){const n=C();if(n!==void 0)return n;if(D())throw new A;const e=k();if(e!==void 0)return e;const r=await q(),t=L.get(r);if(t!==void 0)return t;const a=await Z();if(a===null)throw new f;return L.set(r,a),a}c(me,"personIdAsync");function X(){const n=W(12);let e="user:";for(let r=0;r<12;r++)e+=I[n[r]%I.length];return e}c(X,"mintPersonId");async function m(n,e){return(await n.prepare("SELECT value FROM canvas_meta WHERE key = ?").get(e))?.value??null}c(m,"readMeta");async function _(n,e,r){await n.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e,r)}c(_,"writeMeta");async function V(){return await j(async n=>{const e=await m(n,l);if(e!==null)return{id:e,source:"stored"};const r=h();if(r!==null)return await _(n,l,r),{id:r,source:"joined"};if(S("user").runtime?.issuer){const a=await n.prepare("SELECT DISTINCT sub FROM grants").all();return a.length!==1?null:(await _(n,l,a[0].sub),{id:a[0].sub,source:"grants"})}const t=X();return await _(n,l,t),{id:t,source:"minted"}})}c(V,"resolvePerson");async function Z(){return(await V())?.id??null}c(Z,"resolvePersonId");const s=c(n=>Number(n.changes),"changes"),Q=[["nodes","sub"],["node_tokens","sub"],["grants","sub"],["crons","sub"],["audit_rows","sub"],["provider_approvals","sub"],["audit_rows","grantee"],["run_events","grantee"],["node_tokens","grantee"],["uploads","grantee"],["uploads","sub"],["files","sub"],["files","grantee"],["shares","sub"],["provider_approvals","grantee"]],ee=["profiles","profile_defaults","scope_settings","scope_bookkeeping","scope_marketplaces","scope_plugins","person_settings","model_accounts","model_account_cooldowns","model_api_keys","model_settings","model_sign_in_flows","env_vars","hosted_endpoints"],ne=[["charges","sub"],["charges","payer"],["charges","grantee"],["limits","payer"],["limits","sub"],["limits","grantee"]];function P(n,e){if(!K.test(e))throw new g("invalid_person",`${n} must be a user:<id> principal, got ${JSON.stringify(e)}`)}c(P,"assertPerson");async function re(n,e){return await n.prepare("SELECT 1 AS found FROM charge_totals WHERE payer = ? OR sub = ? OR grantee = ? UNION ALL SELECT 1 FROM charge_chunks WHERE payer = ? LIMIT 1").get(e,e,e,e)!==void 0}c(re,"namesPerson");async function U(n,e,r){if(P("from",e),P("to",r),e===r)throw new g("invalid_person","cannot substitute a person with itself");const t={};try{t.identities=s(await n.prepare("UPDATE identities SET scheme = 'user', external_id = ? WHERE scheme IN ('local-user', 'user') AND external_id = ?").run(r,e)),t["identities.person"]=s(await n.prepare("UPDATE identities SET person = ? WHERE person = ?").run(r,e))}catch(o){throw o instanceof B?new g("person_conflict",`another person object or repo identity already holds ${r}; merging two persons is not supported (${o.message})`,void 0,{from:e,to:r}):o}t["daemon_actions.principal_sub"]=s(await n.prepare(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,sub}', to_jsonb(?::text))::text
2
2
  WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
3
3
  AND adapter_json::jsonb #>> '{principal,sub}' = ?`).run(r,e));for(const[o,i]of Q)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));t["idempotency_keys.grantee"]=s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = ?)").run(e,r))+s(await n.prepare("UPDATE idempotency_keys SET grantee = ? WHERE grantee = ?").run(r,e));const a=e.replace(/^user:/,""),p=r.replace(/^user:/,"");t["relations.subject_id"]=s(await n.prepare(`DELETE FROM relations r WHERE r.subject_type = 'user' AND r.subject_id = ?
4
4
  AND EXISTS (SELECT 1 FROM relations n WHERE n.subject_type = 'user' AND n.subject_id = ? AND n.resource_type = r.resource_type
5
5
  AND n.resource_id = r.resource_id AND n.relation = r.relation AND n.subject_relation = r.subject_relation)`).run(a,p))+s(await n.prepare("UPDATE relations SET subject_id = ? WHERE subject_type = 'user' AND subject_id = ?").run(p,a)),t["relations.written_by"]=s(await n.prepare("UPDATE relations SET written_by = ? WHERE written_by = ?").run(r,e)),t["revisions.acting_for"]=s(await n.prepare("UPDATE revisions SET acting_for = ? WHERE acting_for = ?").run(r,e));for(const[o,i]of ne)t[`${o}.${i}`]=s(await n.prepareUncached(`UPDATE ${o} SET ${i} = ? WHERE ${i} = ?`).run(r,e));for(const o of ee){const d=s(await n.prepareUncached(`DELETE FROM ${o} WHERE person = ? AND EXISTS (SELECT 1 FROM ${o} WHERE person = ?)`).run(e,r))+s(await n.prepareUncached(`UPDATE ${o} SET person = ? WHERE person = ?`).run(r,e));d!==0&&(t[`${o}.person`]=d)}const u=s(await n.prepare("UPDATE credential_activations SET person = ? WHERE person = ?").run(r,e));return u!==0&&(t["credential_activations.person"]=u),(Object.entries(t).some(([o,i])=>o.startsWith("charges.")&&i!==0)||await re(n,e))&&(await z(n,e,r),t["charge_totals.rebuilt"]=1),t}c(U,"substitutePerson");async function te(n){const e=`SELECT o.id FROM objects o JOIN identities i ON i.object = o.owner JOIN nodes n ON n.node_id = o.id
6
6
  WHERE o.type = 'node' AND i.scheme = 'local-user' AND i.external_id = '${E}'`;return(await n.prepareUncached(`${e} LIMIT 1`).get()!==void 0?s(await n.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${e})`).run((await G(n,"app:terminal")).id)):0)+s(await n.prepare("UPDATE node_tokens SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("UPDATE run_events SET grantee = 'app:terminal' WHERE grantee = ?").run(E))+s(await n.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key IN (SELECT key FROM idempotency_keys WHERE grantee = 'app:terminal')").run(E))+s(await n.prepare("UPDATE idempotency_keys SET grantee = 'app:terminal' WHERE grantee = ?").run(E))}c(te,"rewriteLegacyGrantees");async function ae(n,e,r){const t=[Y,`terminal:${e}`].filter(o=>o!==r),a=t.map(()=>"?").join(", "),p={};p["nodes.grant_id"]=s(await n.prepareUncached(`UPDATE nodes SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t)),p["node_tokens.grant"]=s(await n.prepareUncached(`UPDATE node_tokens SET "grant" = ? WHERE "grant" IN (${a})`).run(r,...t)),p["crons.grant_id"]=s(await n.prepareUncached(`UPDATE crons SET grant_id = ? WHERE grant_id IN (${a})`).run(r,...t));const u=r===null?"'null'::jsonb":"to_jsonb(?::text)";return p["daemon_actions.principal_grant_id"]=s(await n.prepareUncached(`UPDATE daemon_actions SET adapter_json = jsonb_set(adapter_json::jsonb, '{principal,grant_id}', ${u})::text
7
7
  WHERE state IN ('pending', 'handed_off') AND adapter_json::jsonb ->> 'adapter' = 'cron_spawn'
8
- AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await j(async e=>{const r={},t=c((w,T="")=>{for(const[R,f]of Object.entries(w))f!==0&&(r[T+R]=(r[T+R]??0)+f)},"add");let a=await m(e,l);if(a===null)throw new N;let p=null;const u=h();u!==null&&u!==a&&(t(await U(e,a,u),"join."),await _(e,l,u),p=a,a=u);const o=M()??S("user").runtime?.issuer,i=await m(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const d=await m(e,O)!==a;if(d){t({legacy_grantees:await te(e)}),t(await U(e,E,a));const w=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
8
+ AND adapter_json::jsonb #>> '{principal,grant_id}' IN (${a})`).run(...r===null?[]:[r],...t)),p}c(ae,"repointGrantReferences");async function ge(){const n=await j(async e=>{const r={},t=c((w,T="")=>{for(const[N,R]of Object.entries(w))R!==0&&(r[T+N]=(r[T+N]??0)+R)},"add");let a=await m(e,l);if(a===null)throw new f;let p=null;const u=h();u!==null&&u!==a&&(t(await U(e,a,u),"join."),await _(e,l,u),p=a,a=u);const o=M()??S("user").runtime?.issuer,i=await m(e,"install_id");if(i===null)throw new Error("retireLocalPerson: the install id is not stored");const d=await m(e,O)!==a;if(d){t({legacy_grantees:await te(e)}),t(await U(e,E,a));const w=`SELECT o.id FROM objects o JOIN peer_stubs s ON s.object = o.id JOIN identities i ON i.object = o.owner
9
9
  WHERE o.type = 'node' AND o.reception = 2 AND s.envelope_json ->> 'app' IS NULL AND i.scheme = 'app' AND i.external_id = 'app:terminal'`;if(await e.prepareUncached(`${w} LIMIT 1`).get()!==void 0){const T=await J(e,"person","user",a,"user");t({repaired_stubs:s(await e.prepareUncached(`UPDATE objects SET owner = ? WHERE id IN (${w})`).run(T.id))})}t({"nodes.sub_null_terminal":s(await e.prepare(`UPDATE nodes SET sub = ? WHERE sub IS NULL AND node_id IN (
10
10
  SELECT n.node_id FROM nodes n JOIN identities i ON i.object = n.app
11
- WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,N as PersonUnresolvedError,D as isCloudRole,v as markCloudRole,$ as personId,me as personIdAsync,V as resolvePerson,Z as resolvePersonId,ge as retireLocalPerson,b as runAsPerson,y as setPersonId,U as substitutePerson};
11
+ WHERE i.scheme = 'app' AND i.external_id = 'app:terminal')`).run(a))}),t(await ae(e,i,o?null:`terminal:${i}`)),o&&t({local_grant_mirror:await x(e)}),await _(e,O,a)}return o||await F(i,a),{person:a,joinedFrom:p,retired:d,columns:r}});return y(n.person),n}c(ge,"retireLocalPerson");export{E as LEGACY_LOCAL_PERSON,A as PersonOutsideRequestError,f as PersonUnresolvedError,D as isCloudRole,v as markCloudRole,$ as personId,me as personIdAsync,V as resolvePerson,Z as resolvePersonId,ge as retireLocalPerson,b as runAsPerson,y as setPersonId,U as substitutePerson};
@@ -0,0 +1,26 @@
1
+ -- 019-outbound-files.sql — a file an agent hands to the person (`crtr push file`), and the person a share belongs to. One transaction,
2
+ -- additions only: `schema_min_reader` is not touched, so the previous release (version 18) still opens the result: it never names the new
3
+ -- table or column, so its `shares` inserts leave `sub` null and its `SELECT *` reads ignore it.
4
+ --
5
+ -- `files` is one row per handed-over file. Its bytes are the storage upload with the same id (`file_id` = `uploads.upload_id`), so storage
6
+ -- deletes and app removal reach them through `uploads` and `upload_uses`. `sub` is the person a cloud role's run belongs to (null on a Mac);
7
+ -- an app reads a file only when its app, its person and the run's read rule all match. `completed_at` is set once the API has read the stored
8
+ -- object back and found the size and sha256 the agent declared.
9
+ --
10
+ -- `shares.sub` is the person a cloud role's share was made for; null on a Mac and on every row written before this step.
11
+ CREATE TABLE files (
12
+ file_id text PRIMARY KEY,
13
+ run_id text NOT NULL,
14
+ node_id text NOT NULL,
15
+ grantee text NOT NULL,
16
+ sub text,
17
+ name text NOT NULL,
18
+ media_type text NOT NULL,
19
+ size bigint NOT NULL,
20
+ sha256 text NOT NULL,
21
+ created_at text NOT NULL,
22
+ completed_at text
23
+ );
24
+ CREATE INDEX idx_files_run ON files(run_id);
25
+
26
+ ALTER TABLE shares ADD COLUMN sub text;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 18;
4
+ export declare const CANVAS_SCHEMA_VERSION = 19;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=18;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=19;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};