@north-light/cli 0.3.458 → 0.3.459

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.
@@ -197,7 +197,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
197
197
  `)||e.includes("\r")||Buffer.byteLength(e,"utf8")+1>Gst?!1:zst(t,[e])}function Vst(t,e){if(e.includes(`
198
198
  `)||e.includes("\r"))return!1;let n=Buffer.byteLength(e,"utf8")+1;return n>Gst?!1:(Ap!==void 0&&Ap.path!==t&&u9(),Ap===void 0&&(Ap={path:t,records:[],bytes:0},qst||(process.on("exit",u9),qst=!0)),Ap.path=t,Ap.records.push(e),Ap.bytes+=n,Ap.bytes>=V2n?u9():Ap.timer===void 0&&(Ap.timer=setTimeout(u9,K2n),Ap.timer.unref()),!0)}function u9(){let t=Ap;if(!(t===void 0||t.records.length===0)&&(t.timer!==void 0&&clearTimeout(t.timer),Ap=void 0,!zst(t.path,t.records)))for(let e of t.records)process.stderr.write(`[crtrd] event log append failed: ${e}
199
199
  `)}var Gst,z2n,V2n,K2n,Ap,qst,Swe=h(()=>{"use strict";Gst=65536,z2n=5*1024*1024,V2n=128*1024,K2n=200;qst=!1});var Cwe,Kst=h(()=>{"use strict";Cwe=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"]});function Y2n(t){return typeof t=="object"&&t!==null?t:void 0}function Yst(t){return typeof t=="string"?t:""}function Jst(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=Y2n(t);return{type:Yst(e?.name)||"Error",message:Yst(e?.message)||String(t)}}var Xst=h(()=>{"use strict";Kst()});import{AsyncLocalStorage as J2n}from"node:async_hooks";import{randomBytes as X2n}from"node:crypto";function Sb(t){if(typeof t!="string"||!Z2n.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function kQ(){let t;do t=X2n(16).toString("hex");while(t==="00000000000000000000000000000000");return Sb(t)}var Z2n,Iwe,RQ,DQ=h(()=>{"use strict";Z2n=/^(?!0{32}$)[0-9a-f]{32}$/,Iwe=new J2n;RQ={current:()=>Iwe.getStore(),run:(t,e)=>Iwe.run(Sb(t),e),fresh:t=>{let e=kQ();return Iwe.run(e,()=>t(e))}}});function s$n(t){return Buffer.byteLength(t,"utf8")}function d9(t,e,n=128){if(typeof t!="string"||t===""||s$n(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function a$n(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 c$n(t){if(!o$n.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=d9(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!i$n.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function Zst(t){if(!t$n.has(t.level))throw new TypeError("level is invalid");if(!n$n.has(t.component))throw new TypeError("component is invalid");let e=d9(t.event,"event");if(!e$n.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?RQ.current()??kQ():Sb(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():a$n(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=d9(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=d9(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(!r$n.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=c$n(t.error_class)),t.error!==void 0&&(r.error=Jst(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}var e$n,t$n,n$n,r$n,i$n,o$n,eat=h(()=>{"use strict";Xst();DQ();e$n=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,t$n=new Set(["error","warn","info","debug"]),n$n=new Set(["daemon","broker","control-plane","front","sentinel"]),r$n=new Set(["succeeded","failed","skipped"]),i$n=new Set(["auto","manual","fatal"]),o$n=new Set(Cwe)});function wC(t){return Buffer.byteLength(t,"utf8")}function AC(t,e){if(wC(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-wC(n),i=0,o="";for(let s of t){let a=wC(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function u$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 Twe(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=AC(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:u$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 f=0;f<u;f+=1){if(r.remaining<=0){d=!0,p+=u-f;break}let m=Twe(t[f],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=AC(l,128),p;try{p=Twe(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 l$n(t){let e=AC(String(t.type),128),n=AC(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=AC(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=AC(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function p9(t){return JSON.stringify(t)}function MQ(t){return wC(p9(t))+1}function tat(t){let e=t.fields===void 0?void 0:Twe(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:l$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=MQ(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});MQ(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 f=wC(p9(u[p]))-wC(p9(u[d]));return f!==0?f: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;MQ(r)>65536&&a?.stack!==void 0&&delete a.stack,MQ(r)>65536&&a?.cause!==void 0&&delete a.cause,MQ(r)>65536&&a!==void 0&&(a.message=AC(a.message,64).value);let c=p9(r);if(wC(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}var nat=h(()=>{"use strict"});import{existsSync as f9,lstatSync as sRi,mkdirSync as d$n,readdirSync as p$n,readFileSync as Rwe,rmSync as f$n,statSync as m$n,symlinkSync as aRi,writeFileSync as h$n,cpSync as cRi,readlinkSync as uRi,renameSync as g$n,chmodSync as y$n,realpathSync as A$n,closeSync as Dwe,fsyncSync as Mwe,openSync as Owe,linkSync as w$n,unlinkSync as x$n,writeSync as b$n}from"node:fs";import{dirname as kwe,join as E$n,relative as dRi,sep as pRi}from"node:path";import{homedir as _$n,platform as v$n}from"node:os";function ua(t){try{return A$n(t)}catch{return t}}function rat(t,e=_$n()){return t==="~"?e:t.startsWith("~/")||v$n()==="win32"&&t.startsWith("~\\")?E$n(e,t.slice(2)):t}function qM(t){d$n(t,{recursive:!0})}function m9(t,e,n){iat(t,JSON.stringify(e,null,2)+`
200
- `,n)}function GM(t){let e=Owe(t,"r");try{Mwe(e)}finally{Dwe(e)}}function fy(t){let e=Owe(t,"r");try{Mwe(e)}finally{Dwe(e)}}function iat(t,e,n){n?.createParent!==!1&&qM(kwe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(f9(t)?m$n(t).mode&511:384);try{h$n(r,e,{mode:i}),y$n(r,i),n?.durable===!0&&GM(r),g$n(r,t),n?.durable===!0&&fy(kwe(t))}finally{f9(r)&&f$n(r,{force:!0})}}function h9(t,e,n){let r=`${t}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,i=Owe(r,"wx",n);try{try{let o=Buffer.from(e,"utf8");for(let s=0;s<o.length;)s+=b$n(i,o,s,o.length-s);Mwe(i)}finally{Dwe(i)}try{w$n(r,t)}catch(o){if(o.code==="EEXIST")return!1;throw o}return fy(kwe(t)),!0}finally{try{x$n(r)}catch{}}}function S$n(t){return JSON.parse(Rwe(t,"utf8"))}function xC(t){try{return S$n(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function zM(t){try{return JSON.parse(Rwe(t,"utf8"))}catch{return null}}function oat(t){return Rwe(t,"utf8")}function g9(t){return f9(t)}function Nwe(t){return f9(t)?p$n(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var qo=h(()=>{"use strict"});import{existsSync as VM,mkdirSync as sat,readFileSync as C$n,statSync as I$n}from"node:fs";import{homedir as T$n,userInfo as k$n}from"node:os";import{basename as R$n,dirname as Pwe,isAbsolute as D$n,join as Ha,resolve as Bwe}from"node:path";function Ib(){let t=Bwe(L0()||(process.platform==="linux"?"/":Ha(T$n(),".crouter")));if(M$n()&&t===O$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 M$n(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function O$n(){if(y9===void 0)try{y9=Bwe(k$n().homedir,".crouter")}catch{y9=null}return y9}function Mf(){return Ha(Ib(),"runtime")}function w9(){return Ha(Ib(),"user")}function Sh(){return Ha(Ib(),"apps")}function Ch(){return Ha(Mf(),"secrets")}function KM(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=ja(t);return{memory:Ha(n.memory,"profiles",e),env:Ha(Ch(),"env",R$n(n.root),e),home:n.home}}function Cb(){return process.platform==="linux"?"/run/crtr":Mf()}function A9(){return Ha(Mf(),"layout")}function YM(){let t=Go("user").paths?.user_files??(process.platform==="linux"?Ha(w9(),"files"):Pwe(Ib()));if(!D$n(t))throw new Error("paths.user_files must be absolute");return Bwe(t)}function ja(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=Ha(Sh(),e);return{root:n,memory:Ha(n,"memory"),conversations:Ha(n,"conversations"),nodes:Ha(n,"nodes"),files:Ha(n,"files"),home:Ha(n,"home"),cache:Ha(n,"cache")}}function N$n(t){let e=Array.from(t.subarray(0,32),n=>n===92?"\\\\":n===34?'\\"':n===10?"\\n":n===13?"\\r":n===9?"\\t":n>=32&&n<127?String.fromCharCode(n):`\\x${n.toString(16).padStart(2,"0")}`).join("");return`${t.length} bytes, preview "${e}"${t.length>32?"\u2026":""}`}function P$n(t){let e=C$n(t);if(e.toString("utf8").trim()!==Lwe)throw new Error(`unsupported runtime layout version: ${t} holds ${N$n(e)}; expected "${Lwe}"`)}function $we(){if(process.env.CRTR_LAYOUT_REFUSE==="1")return!0;if(VM(A9()))return P$n(A9()),!1;let t=Ib(),e=process.platform==="linux"&&t==="/"&&VM("/volume")?"/volume":t;return VM(Ha(e,"canvas"))||VM(Ha(e,"canvas.db"))?!0:VM(Ha(Mf(),"canvas.db"))}function aat(){if($we())throw new Error("layout_migration_required");for(let t of[Mf(),w9(),Sh(),Ch()]){let e=sat(t,{recursive:!0,mode:448});if(e!==void 0){for(let n=t;fy(n),n!==e;n=Pwe(n));fy(Pwe(e))}}if(sat(Cb(),{recursive:!0,mode:493}),process.platform==="linux"&&(I$n(Cb()).mode&511)!==493)throw new Error("launcher socket directory must be mode 0755");VM(A9())||h9(A9(),`${Lwe}
200
+ `,n)}function GM(t){let e=Owe(t,"r");try{Mwe(e)}finally{Dwe(e)}}function fy(t){let e=Owe(t,"r");try{Mwe(e)}finally{Dwe(e)}}function iat(t,e,n){n?.createParent!==!1&&qM(kwe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(f9(t)?m$n(t).mode&511:384);try{h$n(r,e,{mode:i}),y$n(r,i),n?.durable===!0&&GM(r),g$n(r,t),n?.durable===!0&&fy(kwe(t))}finally{f9(r)&&f$n(r,{force:!0})}}function h9(t,e,n){let r=`${t}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,i=Owe(r,"wx",n);try{try{let o=Buffer.from(e,"utf8");for(let s=0;s<o.length;)s+=b$n(i,o,s,o.length-s);Mwe(i)}finally{Dwe(i)}try{w$n(r,t)}catch(o){if(o.code==="EEXIST")return!1;throw o}return fy(kwe(t)),!0}finally{try{x$n(r)}catch{}}}function S$n(t){return JSON.parse(Rwe(t,"utf8"))}function xC(t){try{return S$n(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function zM(t){try{return JSON.parse(Rwe(t,"utf8"))}catch{return null}}function oat(t){return Rwe(t,"utf8")}function g9(t){return f9(t)}function Nwe(t){return f9(t)?p$n(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var qo=h(()=>{"use strict"});import{existsSync as VM,mkdirSync as sat,readFileSync as C$n,statSync as I$n}from"node:fs";import{homedir as T$n,userInfo as k$n}from"node:os";import{basename as R$n,dirname as Pwe,isAbsolute as D$n,join as Ha,resolve as Bwe}from"node:path";function Ib(){let t=Bwe(L0()||(process.platform==="linux"?"/":Ha(T$n(),".crouter")));if(M$n()&&t===O$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 M$n(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function O$n(){if(y9===void 0)try{y9=Bwe(k$n().homedir,".crouter")}catch{y9=null}return y9}function Mf(){return Ha(Ib(),"runtime")}function w9(){return Ha(Ib(),"user")}function Sh(){return Ha(Ib(),"apps")}function Ch(){return Ha(Mf(),"secrets")}function KM(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=ja(t);return{dir:Ha(n.profiles,e),env:Ha(Ch(),"env",R$n(n.root),e),home:n.home}}function Cb(){return process.platform==="linux"?"/run/crtr":Mf()}function A9(){return Ha(Mf(),"layout")}function YM(){let t=Go("user").paths?.user_files??(process.platform==="linux"?Ha(w9(),"files"):Pwe(Ib()));if(!D$n(t))throw new Error("paths.user_files must be absolute");return Bwe(t)}function ja(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=Ha(Sh(),e);return{root:n,profiles:Ha(n,"profiles"),conversations:Ha(n,"conversations"),nodes:Ha(n,"nodes"),files:Ha(n,"files"),home:Ha(n,"home"),cache:Ha(n,"cache")}}function N$n(t){let e=Array.from(t.subarray(0,32),n=>n===92?"\\\\":n===34?'\\"':n===10?"\\n":n===13?"\\r":n===9?"\\t":n>=32&&n<127?String.fromCharCode(n):`\\x${n.toString(16).padStart(2,"0")}`).join("");return`${t.length} bytes, preview "${e}"${t.length>32?"\u2026":""}`}function P$n(t){let e=C$n(t);if(e.toString("utf8").trim()!==Lwe)throw new Error(`unsupported runtime layout version: ${t} holds ${N$n(e)}; expected "${Lwe}"`)}function $we(){if(process.env.CRTR_LAYOUT_REFUSE==="1")return!0;if(VM(A9()))return P$n(A9()),!1;let t=Ib(),e=process.platform==="linux"&&t==="/"&&VM("/volume")?"/volume":t;return VM(Ha(e,"canvas"))||VM(Ha(e,"canvas.db"))?!0:VM(Ha(Mf(),"canvas.db"))}function aat(){if($we())throw new Error("layout_migration_required");for(let t of[Mf(),w9(),Sh(),Ch()]){let e=sat(t,{recursive:!0,mode:448});if(e!==void 0){for(let n=t;fy(n),n!==e;n=Pwe(n));fy(Pwe(e))}}if(sat(Cb(),{recursive:!0,mode:493}),process.platform==="linux"&&(I$n(Cb()).mode&511)!==493)throw new Error("launcher socket directory must be mode 0755");VM(A9())||h9(A9(),`${Lwe}
201
201
  `,384)}var Lwe,y9,Vi=h(()=>{"use strict";_o();zo();qo();Lwe="1"});import{createRequire as L$n}from"node:module";function b9(){if(process.platform==="linux")return L$n(import.meta.url)(`./linux/${process.arch}/addon.node`)}var OQ,x9,cat,uat,E9=h(()=>{"use strict";OQ=2097152,x9=524288,cat=4,uat=8});import{chmodSync as SRi,chownSync as CRi,closeSync as Ih,constants as _9,fchmodSync as IRi,fchownSync as TRi,fstatSync as Wwe,fsyncSync as kRi,linkSync as RRi,lstatSync as DRi,mkdirSync as lat,openSync as Uwe,readdirSync as B$n,readFileSync as $$n,readlinkSync as MRi,readSync as ORi,realpathSync as NRi,renameSync as PRi,rmdirSync as LRi,rmSync as BRi,statSync as F$n,symlinkSync as $Ri,unlinkSync as FRi,writeSync as URi}from"node:fs";import{basename as WRi,dirname as HRi,join as U$n,relative as Hwe,resolve as v9,sep as Qwe}from"node:path";function S9(){return Fwe===null&&(Fwe=b9()),Fwe}function LQ(t){return t.code}function pat(t){return t instanceof Tb}function W$n(t,e){switch(LQ(t)){case"ELOOP":case"EXDEV":return new Tb(`path meets a symlink: ${e}`);case"ENXIO":return new Tb(`path is not a regular file: ${e}`);case"EAGAIN":return new Tb(`path is held by a lease: ${e}`);default:return t}}function PQ(t,e,n,r,i){try{return t.openat2(e,n,r,Q$n)}catch(o){throw W$n(o,i)}}function H$n(t,e,n){let r;try{r=Wwe(t)}catch(i){throw Ih(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw Ih(t),new Tb(`path is not a regular file: ${e}`)}function fat(t,e){let n=Hwe(v9(t),v9(e));if(n===".."||n.startsWith(`..${Qwe}`)||n.startsWith(Qwe))throw new Error(`${e} is outside ${t}`);return n}function dat(t){if(t===""||t===".."||t.includes("/"))throw new Error(`not one path component: ${t}`);return t}function jwe(t,e,n){if(n&_9.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=fat(t,e),i=S9();if(!i)return Uwe(e,n);let o=Uwe("/",NQ),s;try{s=PQ(i,o,Hwe("/",v9(t))||".",NQ,t)}finally{Ih(o)}try{return n&OQ?PQ(i,s,r||".",n|x9,e):H$n(PQ(i,s,r||".",n|x9|_9.O_NONBLOCK,e),e,!0)}finally{Ih(s)}}function BQ(t,e){let n=jwe(t,e,_9.O_RDONLY);try{return $$n(n)}finally{Ih(n)}}function C9(t,e){try{return BQ(t,e).toString("utf8")}catch(n){if(LQ(n)==="ENOENT"||pat(n))return null;throw n}}function q$n(t,e){if(!S9())return F$n(e);let n=jwe(t,e,OQ);try{return Wwe(n)}finally{Ih(n)}}function mat(t,e){try{return q$n(t,e),!0}catch(n){if(j$n.has(LQ(n)??""))return!1;throw n}}function hat(t,e,n,r=!1){fat(t,e);let i=S9();if(!i)return r&&lat(e,{recursive:!0}),n(s=>s===void 0?e:U$n(e,dat(s)));let o=Uwe("/",NQ);try{for(let a of Hwe("/",v9(e)).split(Qwe).filter(Boolean)){let c;try{c=PQ(i,o,a,NQ,e)}catch(u){if(!r||LQ(u)!=="ENOENT")throw u;try{lat(`/proc/self/fd/${o}/${a}`)}catch(l){if(LQ(l)!=="EEXIST")throw l}c=PQ(i,o,a,NQ,e)}Ih(o),o=c}let s=`/proc/self/fd/${o}`;return n(a=>a===void 0?s:`${s}/${dat(a)}`)}finally{Ih(o)}}function I9(t,e){return hat(t,e,n=>B$n(n(),{withFileTypes:!0}))}function gat(t,e){if(!S9())return{path:e,release:()=>{}};let n=jwe(t,e,OQ),r;try{r=Wwe(n)}catch(o){throw Ih(n),o}if(!r.isSocket())throw Ih(n),new Tb(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,Ih(n))}}}var Q$n,NQ,Fwe,Tb,j$n,Th=h(()=>{"use strict";E9();Q$n=uat|cat,NQ=OQ|_9.O_DIRECTORY|x9,Fwe=null;Tb=class extends Error{};j$n=new Set(["ENOENT","ENOTDIR","EACCES"])});import{join as kh}from"node:path";import{mkdirSync as G$n}from"node:fs";function Vo(){return Mf()}function T9(){return kh(Vo(),"canvas.db")}function yat(){return kh(Vo(),"on-disk-migration.lock")}function JM(t){return kh(Rh(t),"view.sock")}function XM(){return kh(Vo(),"nodes")}function Aat(){return kh(Cb(),"api.sock")}function bC(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=z$n}function qwe(t){if(!bC(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function wat(t){return qwe(t),kh(XM(),t)}function $Q(t,e){qwe(t);let n=e??(YS()===t?WV():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return kh(ja(n).nodes,t)}function Rh(t){return qwe(t),process.platform==="linux"?kh(Cb(),"nodes",t):kh(wat(t),"run")}function xat(t){return kh(Rh(t),"job")}function bat(t){return kh(Gwe(t),"messages")}function zwe(){G$n(XM(),{recursive:!0})}var z$n,Gwe,Rr=h(()=>{"use strict";Vi();_o();Th();z$n=128;Gwe=wat});import{join as V$n}from"node:path";function K$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 Y$n(t){if(k9===void 0){k9=t;return}if(!K$n(k9,t))throw new Error("event source is already bound for this process")}function Eat(){Y$n({component:"daemon",path:V$n(Vo(),"crtrd.log")})}function R9(){return k9}var k9,Kwe=h(()=>{"use strict";Rr()});function Ywe(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 ln,ud=h(()=>{"use strict";ln=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 we,Jwe=h(()=>{"use strict";we={healthz:()=>"/healthz",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,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}`,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`,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`,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`,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`,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)}`,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",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}`,modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,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",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`,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",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"}});function D9(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Xwe=h(()=>{"use strict"});function _at(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Zwe=h(()=>{"use strict"});function vat(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var exe=h(()=>{"use strict"});async function M9({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=eFn,retry:i=()=>!0,now:o=Date.now,sleep:s=Tat}){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 ZM(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 ln(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}function Fr(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 UQ(t,e){let n=t.status>=200&&t.status<300,r=(await nFn(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new ln(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw Ywe(i)?new ln(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new ln(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function tFn(t){return t===429||t>=500}async function Sat(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 nFn(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(()=>{}),ZM(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(ZM(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function Cat(t){return Math.min(2e3,250*2**(t-1))}function txe(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 Iat(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function kb(t,e){if(e?.aborted)return new ln(0,"request_aborted","request aborted by caller signal");if(t instanceof ln)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new ln(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new ln(0,"request_aborted","request aborted by caller signal");let n=txe(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new ln(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new ln(504,"request_timeout",`crtrd request timed out: ${r}`):new ln(503,"transport_error",r)}function rFn(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function nxe(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new ln(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=ZM(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 Tat(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new ln(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function iFn(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 Tat(t){return new Promise(e=>setTimeout(e,t))}function oFn(t){if(t!==void 0)try{return t()}catch{return}}var J$n,X$n,Z$n,eFn,QQ,FQ,WQ,rxe=h(()=>{"use strict";ud();Jwe();Xwe();Zwe();exe();J$n=3e4,X$n=Symbol.for("@north-light/api/local-socket-fetch"),Z$n=1e4,eFn=200;QQ=2147483647;FQ=t=>ZM(t??Date.now()),WQ=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;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??J$n,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[X$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),this.coldStartPollWindowMs=e.coldStartPollWindowMs??Z$n}healthz(){return this.request("GET",we.healthz())}async probeHealthz(e){let n=await this.transport("GET",we.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 UQ(n)}status(){return this.request("GET",we.status())}due(){return this.request("GET",we.due())}restartDaemon(){return this.request("POST",we.daemonRestart())}admitDaemon(){return this.request("POST",we.daemonAdmit())}migrateState(e){return this.request("POST",we.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",we.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",we.nodeTelemetry(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",we.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",Fr(we.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}readNodePassiveMessage(e,n){return this.request("GET",Fr(we.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",we.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",we.nodes(),e)}listNodes(e){return this.request("GET",Fr(we.nodes(),e))}getNode(e){return this.request("GET",we.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",Fr(we.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",Fr(we.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",Fr(we.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await UQ(i);return}if(i.body===null)throw new ln(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(`
202
202
  `))!==-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 ln(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",Fr(`/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",we.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",we.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",we.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",we.nodeJobs(this.nodePath(e)))}stopBashJob(e,n){return this.request("DELETE",we.nodeJob(this.nodePath(e),this.jobPath(n)))}sendMessage(e,n){return this.request("POST",we.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",we.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",we.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",we.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",we.nodeFork(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",we.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",we.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",we.nodeBrokerSessionBound(this.nodePath(e)),n)}settleBroker(e,n){return this.request("POST",we.nodeBrokerSettle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",we.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",we.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",we.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",we.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",we.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",we.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",we.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",we.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${we.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",we.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",`${we.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",we.nodeBrokerModel(this.nodePath(e)),n)}brokerExtensionState(e){return this.request("GET",we.nodeBrokerExtensionState(this.nodePath(e)))}commitBrokerGeneratedName(e,n){return this.request("POST",we.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",we.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",we.nodeClose(this.nodePath(e)),n??{})}recycleNode(e){return this.request("POST",we.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",we.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",we.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",we.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",we.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",we.kinds())}patchConfig(e,n){return this.request("PATCH",we.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",we.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",we.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",we.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",we.quarantinedWorktrees())}showLimits(){return this.request("GET",we.limits())}setAppLimits(e,n){return this.request("PUT",we.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",Fr(we.limitsApp(e),{fields:n.join(",")}))}listSpaces(){return this.request("GET",we.spaces())}subscribe(e,n){return this.request("POST",we.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",we.focuses())}focusOf(e){return this.request("GET",Fr(we.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",Fr(we.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",we.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",we.focus(e),n)}async closeFocus(e){await this.request("DELETE",we.focus(e))}async unsubscribe(e,n){await this.request("DELETE",we.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",we.crons(),e)}listCrons(e){return this.request("GET",Fr(we.crons(),e))}showCron(e,n){return this.request("GET",Fr(we.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",Fr(we.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",Fr(we.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",Fr(we.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",Fr(we.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",we.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",we.nodeAttach(this.nodePath(e)),n??{})}getReports(e,n){return this.request("GET",Fr(we.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",Fr(we.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",we.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",we.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",Fr(we.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",we.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",we.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",Fr(we.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",we.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",Fr(we.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",we.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",Fr(we.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",we.bash(),e,n)}objects={read:(e,n)=>this.request("GET",Fr(we.object(e),n)),list:e=>this.request("GET",Fr(we.objects(),e)),search:e=>this.request("POST",we.objectsSearch(),e),watch:(e,n={})=>this.request("POST",we.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",Fr(we.objectWatch(e),n)),edges:(e,n)=>this.request("GET",Fr(we.objectEdges(e),n))};docs={write:e=>this.request("POST",we.docs(),e),edit:(e,n)=>this.request("PATCH",we.doc(e),n),move:(e,n)=>this.request("POST",we.docMove(e),n),delete:e=>this.request("DELETE",we.doc(e)),history:(e,n)=>this.request("GET",Fr(we.docHistory(e),n)),lint:(e={})=>this.request("POST",we.docsLint(),e)};documents={reconcilePackages:()=>this.request("POST",we.documentsReconcilePackages())};nodeDelivery(e,n){return this.request("POST",we.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",we.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",we.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",we.profile(e),n??{})}createProfile(e){return this.request("POST",we.profiles(),e)}listProfiles(){return this.request("GET",we.profiles())}updateProfile(e,n){return this.request("PATCH",we.profile(e),n)}listAppEnv(){return this.request("GET",we.appEnv())}setAppEnv(e,n){return this.request("PUT",we.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",we.appEnvVar(e))}listProfileEnv(e){return this.request("GET",we.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",we.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",we.profileEnvVar(e,n))}getProfile(e){return this.request("GET",we.profile(e))}pauseProfile(e){return this.request("POST",we.profilePause(e),{})}resumeProfile(e){return this.request("POST",we.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",we.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",we.profile(e),n)}listModelAuth(){return this.request("GET",we.modelAuths())}getModelAuthReadiness(e){return this.request("GET",Fr(we.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",we.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",we.modelAuth(e))}startModelAuth(e){return this.request("POST",we.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",we.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",we.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",Fr(we.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",we.humanReviews(),e)}listReviews(e){return this.request("GET",Fr(we.humanReviews(),e))}getReview(e){return this.request("GET",we.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",we.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",we.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",we.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",we.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",Fr(we.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",Fr(we.humanReviewCommentEvents(this.reviewPath(e)),n))}updateReviewCommentRanges(e,n){return this.request("POST",we.humanReviewCommentRanges(this.reviewPath(e)),n)}getReviewComment(e){return this.request("GET",we.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",we.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",we.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",we.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",we.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",we.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",we.humanInbox())}getHumanInboxPage(e){return this.request("GET",we.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e){if(e===void 0)return this.request("GET",we.humanInbox()+"/history");if(typeof e!="string"||e==="")throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",Fr(we.humanInbox()+"/history",{node_id:e}))}respondHumanInboxPage(e,n){return this.request("POST",we.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",we.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",we.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",we.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",we.humanRequests(),e)}listPageComponents(){return this.request("GET",we.humanComponents())}getHumanRequest(e){return this.request("GET",we.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",we.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",we.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",we.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",we.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",we.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",we.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",we.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",we.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",we.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",Fr(we.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",we.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",we.canvasSnapshot())}analytics(e){return this.request("GET",Fr(we.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",we.nodeMemoryReads(this.nodePath(e)),n)}canvasRoster(){return this.request("GET",we.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",we.canvasBrowse());return e.ok||await UQ(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",we.canvasGraph())}prune(e){return this.request("POST",we.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 UQ(s,o?.deadlineAt)}catch(o){throw kb(o,i?.signal)}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw kb(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;for(let c=0;;c++){let u;try{u=await this.transport(e,n,r,o)}catch(l){if(this.isColdSocketError(l))try{await this.handleColdSocket(l,o.deadlineAt),u=await this.transport(e,n,r,o)}catch(d){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!Iat(d,o.signal)?ZM(o.deadlineAt):kb(d,o.signal)}else{if(this.isInterruptedSocketError(l)&&this.localSocketTransport&&(!s||c<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&c<a&&!Iat(l,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(l))){await nxe(Cat(c+1),o);continue}else throw kb(l,o.signal)}}if(s&&c<a&&tFn(u.status)){await Sat(u,o.deadlineAt),await nxe(Cat(c+1),o,rFn(u));continue}return u}}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>QQ))throw new RangeError(`budgetMs must be a positive finite number of at most ${QQ}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>QQ))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${QQ} 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 FQ(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(FQ(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await UQ(await this.transport(e,n,r,o))}catch(s){throw kb(s,o.signal)}}nodePath(e){if(!D9(e))throw new ln(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!_at(e))throw new ln(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!vat(e))throw new ln(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!D9(e))throw new ln(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(!D9(e))throw new ln(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new ln(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(FQ(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?FQ(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,f=i.signal,m=()=>l.abort(f?.reason);f!==void 0&&(f.aborted?l.abort(f.reason):f.addEventListener("abort",m,{once:!0}));let g=()=>{p!==void 0&&clearTimeout(p),f?.removeEventListener("abort",m)};return iFn(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(y=>this.retainRequestLifetime(y,g,()=>l.signal.aborted?l.signal.reason:void 0),y=>{throw g(),y})}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=txe(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=txe(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw kb(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new ln(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 kb(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw FQ(n);let i;try{await M9({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:o=>o!==i,probe:async o=>{let s=this.coldStartFailure?.();if(s!==void 0)throw i=new ln(503,"daemon_unavailable",`crtrd failed to start: ${s}`),i;let a=await this.transport("GET",we.healthz(),void 0,{timeout:o});if(a.status>=200&&a.status<300){await Sat(a);return}let c=await a.text();try{if(typeof JSON.parse(c).startup_blocked=="string")return}catch{}throw new ln(a.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${a.status}: ${c.slice(0,500)}`)}})}catch(o){throw o===i&&(this.startupFailureReported=!0),o}}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=oFn(this.coldStartDiagnostic);if(o!==void 0){let s=kb(i);throw new ln(s.status,s.code,`${s.message}
203
203
  ${o}`)}}throw i}}}});import{request as sFn}from"node:http";import{homedir as aFn}from"node:os";import{join as ixe}from"node:path";function dFn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:ixe(aFn(),cFn);return ixe(process.platform==="linux"?"/run/crtr":ixe(n,"runtime"),uFn)}function pFn(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=sFn({socketPath:t,path:i.pathname+i.search,method:o,headers:s},f=>{let m=new ReadableStream({start(w){f.on("data",x=>w.enqueue(new Uint8Array(x))),f.on("end",()=>w.close()),f.on("error",x=>w.error(x))},cancel(){f.destroy()}}),g=new Headers;for(let[w,x]of Object.entries(f.headers))if(x!==void 0)for(let E of Array.isArray(x)?x:[x])g.append(w,E);let y=f.statusCode??0;c(new Response(y===204?null:m,{status:y,statusText:f.statusMessage,headers:g}))});l.on("error",f=>u(new TypeError("fetch failed",{cause:f})));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[lFn]=!0,e}function Y0(t={}){let{socketPath:e,...n}=t;return new WQ({baseUrl:"http://localhost",fetch:pFn(e??dFn()),autostart:!0,...n})}var cFn,uFn,lFn,HQ=h(()=>{"use strict";rxe();cFn=".crouter",uFn="api.sock",lFn=Symbol.for("@north-light/api/local-socket-fetch")});var kat=h(()=>{"use strict";HQ();ud()});var fFn,oxe,xDi,Rat=h(()=>{"use strict";fFn=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent"],oxe=class{dirty=new Map;subscribers=new Set;scheduled;subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}markMail(e){this.mark(e,1)}markNode(e){this.mark(e,2)}mark(e,n){this.dirty.set(e,(this.dirty.get(e)??0)|n),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty];this.dirty.clear();for(let[n,r]of e)for(let i of this.subscribers)try{r&1&&i(n,"mail"),r&2&&i(n,"node")}catch{}}install(e){e.function("crtr_signal",{deterministic:!1},(n,r)=>{try{typeof r=="string"&&(n==="mail"&&this.markMail(r),n==="node"&&this.markNode(r))}catch{}return null}),e.exec(`
@@ -230,7 +230,7 @@ CREATE INDEX managed_accounts_order ON managed_accounts(provider_id,position);
230
230
  CREATE TABLE rotation_settings (singleton INTEGER PRIMARY KEY CHECK(singleton=1), default_fallback_strength TEXT, revert_when_available INTEGER CHECK(revert_when_available IN (0,1)));
231
231
  CREATE TABLE provider_revision (singleton INTEGER PRIMARY KEY CHECK(singleton=1), revision INTEGER NOT NULL);
232
232
  ${Oct}`});import{DatabaseSync as Y9}from"node:sqlite";import{chmodSync as Rxe,existsSync as a1,mkdirSync as Lct,readdirSync as xUn,rmSync as bUn,statSync as EUn,writeFileSync as _Un}from"node:fs";import{join as dd}from"node:path";function Mxe(t,e,n){t.prepare("UPDATE scope_owners SET root=? WHERE owner_key=?").run(n,e)}function Ob(t){return Number(t.prepare("PRAGMA user_version").get().user_version)}function $ct(t,e){let n=Ob(t);if(n===0)throw new Error(`scoped SQL store is uninitialized: ${e.path}; crtr was updated and \`crtr sys daemon restart\` converts local state`);let r=e.kind==="provider"?V9:zQ;if(n>r)throw new Error(`scoped SQL store ${e.path} uses unsupported schema version ${n}`);if(n!==r)throw new Error(`scoped SQL store ${e.path} requires an explicit conversion`)}function Fct(t,e){if(e.kind==="provider"){Ob(t)===V9&&(t.exec("PRAGMA busy_timeout = 5000"),Nct(t));return}if(!(Ob(t)>=zQ)){t.exec("PRAGMA busy_timeout = 5000; BEGIN IMMEDIATE");try{Ob(t)===1&&(t.prepare("PRAGMA table_info(profiles)").all().some(({name:r})=>r==="grantee")||t.exec("ALTER TABLE profiles ADD COLUMN grantee TEXT"),t.exec("PRAGMA user_version = 2")),Ob(t)===2&&(t.prepare("PRAGMA table_info(profiles)").all().some(({name:r})=>r==="home")&&t.exec("ALTER TABLE profiles DROP COLUMN home"),t.exec("PRAGMA user_version = 3")),Ob(t)===3&&(t.exec("ALTER TABLE profiles ADD COLUMN delivery_limits_json TEXT NOT NULL DEFAULT '{}' CHECK(json_valid(delivery_limits_json))"),t.exec("PRAGMA user_version = 4")),Ob(t)===4&&(t.exec("CREATE TABLE IF NOT EXISTS legacy_project_caps (profile_id TEXT NOT NULL, path TEXT NOT NULL, memory TEXT NOT NULL CHECK(memory IN ('none','name','preview')), PRIMARY KEY(profile_id,path))"),t.prepare("PRAGMA table_info(profile_projects)").all().some(({name:r})=>r==="memory")&&t.exec(`INSERT INTO legacy_project_caps SELECT profile_id, path, memory FROM profile_projects WHERE memory != 'content';
233
- ALTER TABLE profile_projects DROP COLUMN memory;`),t.exec(`PRAGMA user_version = ${zQ}`)),t.exec("COMMIT")}catch(n){throw t.exec("ROLLBACK"),n}}}function Uct(t){let e=new Y9(t.path);try{Fct(e,t),$ct(e,t)}finally{e.close()}}function Oxe(t){if(!VQ(t))return;let e=new Y9(t.path,{readOnly:!0}),n;try{n=Ob(e)}finally{e.close()}if(n===0)for(let r of[t.path,`${t.path}-wal`,`${t.path}-shm`])bUn(r,{force:!0})}function Nxe(t,e){return fc(dd(t,".init.lock"),()=>{let n=dd(t,py),r=Date.now()+5e3,i=10;for(;;){let o;try{o=Bct.default.lockSync(n,{realpath:!1,retries:0,stale:3e4,update:1e4})}catch(s){if(s.code!=="ELOCKED")throw s;let a=r-Date.now();if(a<=0)throw new Error(`timed out waiting for project state conversion lock: ${n}`,{cause:s});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.min(i,a)),i=Math.min(i*2,250);continue}try{return e()}finally{o()}}})}function Pxe(t){a1(t)&&Rxe(t,384);for(let e of["-wal","-shm"])a1(`${t}${e}`)&&Rxe(`${t}${e}`,384)}function VQ(t){return a1(t.path)}function Lxe(t){if(t.kind==="project")return[dd(t.root,py)];if(t.kind==="provider")return[dd(t.root,"anthropic-subscriptions.json"),dd(t.root,"openai-codex-subscriptions.json"),dd(t.root,"provider-rotation.json")];let e=[dd(t.root,dy),dd(t.root,py),dd(t.root,"profile-defaults.json")],n=dd(t.root,s9);if(a1(n))for(let r of xUn(n,{withFileTypes:!0}))r.isDirectory()&&Dxe.test(r.name)&&e.push(dd(n,r.name,"profile.json"),dd(n,r.name,dy),dd(n,r.name,py));return e}function Bxe(t){let e=t.kind==="user"?Dh(t.root):t.kind==="project"?e1(t.root):J0(t.root);e.kind!=="project"&&Lct(e.root,{recursive:!0,mode:448});let n=()=>{if(e.kind==="project"&&Oxe(e),VQ(e))return;let r=Lxe(e).find(a1);if(r!==void 0)throw new Error(`legacy scoped state exists at ${r}; crtr was updated and \`crtr sys daemon restart\` converts local state`);$xe(e,i=>{K9(i,e.kind),e.kind!=="provider"&&Mxe(i,e.kind,e.root)})};e.kind==="project"?Nxe(e.root,n):fc(dd(e.root,".init.lock"),n)}function Mh(t){if($we())throw new Error("layout_migration_required");let e=Pct.get(t.path);if(e!==void 0)return e;Bxe(t);let n=new Y9(t.path);try{return n.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;"),Fct(n,t),$ct(n,t),Pxe(t.path),Pct.set(t.path,n),n}catch(r){throw n.close(),r}}function $xe(t,e){if(a1(t.path))throw new Error(`scoped SQL store already exists: ${t.path}`);if(t.kind!=="project"&&Lct(t.root,{recursive:!0,mode:448}),!EUn(t.root).isDirectory())throw new Error(`scoped SQL root is not a directory: ${t.root}`);(t.kind!=="project"||process.platform!=="linux")&&Rxe(t.root,448),_Un(t.path,"",{mode:384});let n=new Y9(t.path);try{n.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; BEGIN IMMEDIATE;"),e(n),n.exec("COMMIT")}catch(r){try{n.exec("ROLLBACK")}catch{}throw r}finally{Pxe(t.path),n.close()}GM(t.path),fy(t.root)}function KQ(t,e){let n=Mh(t);if(n.isTransaction)return e(n);n.exec("BEGIN IMMEDIATE");try{let r=e(n);return n.exec("COMMIT"),Pxe(t.path),r}catch(r){try{n.exec("ROLLBACK")}catch{}throw r}}var Bct,Pct,Dxe,TC=h(()=>{"use strict";qt();Bct=Jt(Z0(),1);Wa();wp();qo();Vi();Rb();kxe();Pct=new Map,Dxe=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/});function Qct(t){return Dh(t)}function vUn(t,e){return{profileId:t.id,manifest:{schema_version:1,name:t.name,projects:e,paused_at:t.paused_at,...t.default_kind===null?{}:{default_kind:t.default_kind},...t.grantee===null?{}:{grantee:t.grantee},...t.delivery_limits_json==="{}"?{}:{delivery_limits:JSON.parse(t.delivery_limits_json)},...Object.keys(JSON.parse(t.metadata_json)).length===0?{}:{metadata:JSON.parse(t.metadata_json)},created_at:t.created_at,last_used_at:t.last_used_at}}}function Wct(t,e){let n=ce(t,"SELECT id, name, created_at, last_used_at, paused_at, default_kind, grantee, metadata_json, delivery_limits_json FROM profiles WHERE id=?").get(e);if(!n)return null;let r=ce(t,"SELECT path FROM profile_projects WHERE profile_id=? ORDER BY position").all(e);return vUn(n,r)}function Hct(t){let e=Mh(Qct(t));return ce(e,"SELECT id FROM profiles ORDER BY rowid").all().map(({id:r})=>Wct(e,r)).filter(Boolean)}function Fxe(t,e){return Wct(Mh(Qct(t)),e)}var Uxe=h(()=>{"use strict";qt();Rb();Vi();TC()});var jct=h(()=>{"use strict"});function CUn(t){return t.grantee??"app:terminal"}function Gct(t){if(!qct.test(t))throw yp(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function J9(t){Gct(t);let e=Fxe(Ga(),t);if(e===null)throw Df(`profile not found: ${t}`,{received:t});return KM(CUn(e.manifest),t).memory}function IUn(){return{entries:Hct(Ga()),unreadableIds:[]}}function X9(){return IUn().entries}function zct(t){let e=X9(),n=TUn(e,t,Vct);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function kC(t){Gct(t);let e=Fxe(Ga(),t);if(e!==null)return e;throw Df(`profile not found: ${t}`,{received:t,next:"Run `crtr profile list` to see available profiles."})}function TUn(t,e,n){if(qct.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw Qst(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function kUn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return Df(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function Lf(t){let e=zct(t);if(e.kind==="resolved")return e.entry;throw kUn(X9(),t,Vct)}var qct,Vct,vu=h(()=>{"use strict";Wa();Vi();L9();xp();qo();Uxe();ds();wp();jct();qct=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Vct=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Kct}from"node:os";import{existsSync as RUn,statSync as DUn}from"node:fs";import{join as Z9,resolve as Yct,dirname as MUn,sep as Qxe}from"node:path";function Ga(){return Z9(Mf(),"scope")}function OUn(t,e){if(!RUn(t)||ua(t)===ua(Z9(Kct(),mC))||ua(t).startsWith(`${ua(Sh())}${Qxe}`)&&t.endsWith(`${Qxe}home${Qxe}${mC}`)||!JS()&&(ua(t)===ua(e)||ua(t)===ua(Ib())))return!1;try{return DUn(t).isDirectory()}catch{return!1}}function NUn(t=process.cwd()){return Wxe(t)[0]??null}function PUn(t,e){let n=[],r=ua(Kct()),i=Yct(t);for(;;){let o=Z9(i,mC);if(OUn(o,e)&&n.push(o),ua(i)===r)return n;let s=MUn(i);if(s===i)return n;i=s}}function Wxe(t=process.cwd(),e=CAe()||null){return LUn(t,e)}function LUn(t,e){let n=Yct(t),r=Ga(),i=[n];if(!JS()&&e!==null&&e!=="")try{let{manifest:a}=Lf(e);for(let c of a.projects)i.push(c.path)}catch{}let o=new Set,s=[];for(let a of i)for(let c of PUn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function eK(t){return NUn(t)}function Oh(t){return t==="builtin"?null:t==="user"?Ga():eK()}function Hxe(t){let e=Oh(t);if(!e)throw yp(`no ${t} scope available \u2014 run \`crtr init\` here or use --scope user`);return e}function Jct(t){let e=t==="user"?Mf():Oh(t);return e?Z9(e,"plugins"):null}var xp=h(()=>{"use strict";_o();Wa();qat();ds();vu();qo();Vi()});import{join as BUn}from"node:path";function $Un(t){return BUn(t,$st,Fst)}function FUn(t){let e;try{e=xC(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function UUn(t){return FUn($Un(t))}function Xct(t){let e=UUn(t);return e.status==="ok"?e.manifest:null}var jxe=h(()=>{"use strict";Wa();qo()});import{join as QUn}from"node:path";function Zct(t,e){return QUn(t,"tmp",`${e}.swap.lock`)}function eut(t,e){let n=s1(Zct(t,e));return n!==null&&n!==process.pid}function tut(t,e){Mct(Zct(t,e),WUn)}var WUn,nut=h(()=>{"use strict";wp();WUn=2e3});import{createHash as HUn}from"node:crypto";function qxe(t,e,n){let r=ce(t,"SELECT kind, root, profile_id FROM scope_owners WHERE owner_key = ?").get(e.key);if(!r)throw new Error(`scoped SQL owner is missing: ${e.key}`);if(r.kind!==e.kind||(e.profileId??null)!==r.profile_id)throw new Error(`scoped SQL owner does not match its root: ${e.key}`);if(r.root!==e.root){if(e.kind!=="project"||e.store.kind!=="project"||e.store.root!==e.root)throw new Error(`scoped SQL owner does not match its root: ${e.key}`);n==="write"&&ce(t,"UPDATE scope_owners SET root = ? WHERE owner_key = ?").run(e.root,e.key)}}function jUn(t){return t===void 0?"absent":HUn("sha256").update(t.raw_json).digest("hex")}function qUn(t,e){return ce(t,"SELECT raw_json FROM scope_settings WHERE owner_key = ?").get(e.key)}function rut(t){let e=Mh(t.store);qxe(e,t,"read");let n=qUn(e,t);return{revision:jUn(n),settings:n===void 0?null:JSON.parse(n.raw_json)}}function tK(t){return rut(t).settings}function iut(t,e){return KQ(t.store,n=>{qxe(n,t,"write");let r=ce(n,"SELECT raw_json FROM scope_settings WHERE owner_key = ?").get(t.key),i=e(r?JSON.parse(r.raw_json):{});return ce(n,"INSERT INTO scope_settings(owner_key, raw_json) VALUES (?, ?) ON CONFLICT(owner_key) DO UPDATE SET raw_json=excluded.raw_json").run(t.key,JSON.stringify(i.next)),i.value})}function out(t){let e=Mh(t.store);qxe(e,t,"read");let n=ce(e,"SELECT last_self_check, active_canvas FROM scope_bookkeeping WHERE owner_key = ?").get(t.key),r=Object.fromEntries(ce(e,"SELECT name, last_updated FROM scope_marketplaces WHERE owner_key = ?").all(t.key).map(o=>[o.name,o.last_updated===null?{}:{last_updated:o.last_updated}])),i=Object.fromEntries(ce(e,"SELECT name, last_updated, etag, checked_at FROM scope_plugins WHERE owner_key = ?").all(t.key).map(o=>[o.name,{...o.last_updated===null?{}:{last_updated:o.last_updated},...o.etag===null?{}:{etag:o.etag},...o.checked_at===null?{}:{checked_at:o.checked_at}}]));return{marketplaces:r,plugins:i,...n?.last_self_check===null||n===void 0?{}:{last_self_check:n.last_self_check},activeCanvas:n?.active_canvas??null}}var Gxe=h(()=>{"use strict";qt();TC()});import{join as zxe}from"node:path";function GUn(t,e){let n=t==="user"?Dh(e):void 0,r=n?tK({store:n,key:"user",kind:"user",root:n.root}):xC(zxe(e,dy));return r&&r.plugins&&typeof r.plugins=="object"?r.plugins:{}}function zUn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&eut(t,i))}function c1(t,e){let n=t==="user"?Jct("user"):zxe(e,"plugins");if(!g9(n))return[];let r=GUn(t,e),i=sut(t,n,r),o=zUn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)tut(e,s);return sut(t,n,r)}function sut(t,e,n){let r=[];for(let i of Nwe(e)){let o=zxe(e,i),s=Xct(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var YQ=h(()=>{"use strict";Wa();qo();jxe();nut();Rb();Gxe();xp()});import{chmodSync as aut,existsSync as nK,fsyncSync as cut,mkdirSync as VUn,openSync as uut,readFileSync as lut,renameSync as KUn,writeFileSync as YUn,closeSync as dut}from"node:fs";import{dirname as put}from"node:path";var fut,JUn,XUn,ZUn,my,rK=h(()=>{"use strict";fut=Jt(Z0(),1);qo();JUn={encoding:"utf-8",mode:384},XUn=3e4,ZUn=5e3,my=class{constructor(e,n=!1,r="{}"){this.path=e;this.durable=n;this.initialContent=r}path;durable;initialContent;readUnlocked(){return nK(this.path)?lut(this.path,"utf-8"):void 0}ensureFile(){let e=put(this.path);nK(e)||VUn(e,{recursive:!0,mode:448}),nK(this.path)||(h9(this.path,this.initialContent,384),aut(this.path,384))}async withLockAsync(e){this.ensureFile();let n,r,i=()=>{if(r)throw r};try{n=await fut.default.lock(this.path,{realpath:!1,retries:{retries:10,factor:2,minTimeout:100,maxTimeout:1e4,randomize:!0},stale:XUn,update:ZUn,onCompromised:l=>{r=l}}),i();let o=nK(this.path)?lut(this.path,"utf-8"):void 0,s=!1,a=l=>{if(s)throw new Error(`locked file was published twice: ${this.path}`);i();let d=`${this.path}.${process.pid}.${Date.now()}.tmp`;if(YUn(d,l,JUn),aut(d,384),this.durable){let p=uut(d,"r");try{cut(p)}finally{dut(p)}}if(KUn(d,this.path),this.durable){let p=uut(put(this.path),"r");try{cut(p)}finally{dut(p)}}s=!0},{result:c,next:u}=await e(o,i,a);return i(),u!==void 0&&a(u),i(),c}finally{if(n)try{await n()}catch{}}}}});import{chmodSync as mut,copyFileSync as eQn,existsSync as RC,mkdirSync as hut,readFileSync as tQn,readdirSync as nQn,statSync as gut}from"node:fs";import{dirname as yut,join as Nh,relative as rQn}from"node:path";function iK(t){return JSON.parse(tQn(t,"utf8"))}function Aut(t){return t.some(RC)}function wut(t,e){let n=Nh(t,".legacy-scoped-state");try{hut(n,{mode:448})}catch(r){if(r.code!=="EEXIST"||!gut(n).isDirectory())throw r}mut(n,448);for(let r of e)if(RC(r)&&gut(r).isFile()){let i=rQn(t,r);if(i===""||i.startsWith(".."))throw new Error(`legacy state is outside its owning root: ${r}`);let o=Nh(n,i);yut(o)!==n&&hut(yut(o),{recursive:!0,mode:448}),eQn(r,o),mut(o,384)}}function but(t){let e=t.kind==="user"?Dh(t.root):t.kind==="project"?e1(t.root):J0(t.root);if(t.kind!=="project"&&VQ(e))return;if(t.kind==="provider")throw new Error("provider conversion requires convertLegacyProviderStore() under coordinated shared-agent-dir activation");let n=Lxe(e),r=()=>{t.kind==="project"&&Oxe(e),!VQ(e)&&(t.kind==="project"&&Aut(n)&&wut(e.root,n),$xe(e,i=>{K9(i,t.kind);let o=t.kind==="user"?"user":"project";Mxe(i,o,e.root),t.kind==="user"?oQn(i,e.root):Vxe(i,o,Nh(e.root,py))}),t.kind==="user"&&Aut(n)&&wut(e.root,n))};t.kind==="project"?Nxe(e.root,()=>{r(),Uct(e)}):r()}function xut(t,e,n){if(!RC(n))return;let r=iK(n);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`legacy config is malformed: ${n}`);ce(t,"INSERT INTO scope_settings(owner_key,raw_json) VALUES(?,?)").run(e,JSON.stringify(r))}function Vxe(t,e,n){if(!RC(n))return;let r=iK(n);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`legacy state is malformed: ${n}`);let i=r;ce(t,"INSERT INTO scope_bookkeeping(owner_key,last_self_check,active_canvas) VALUES(?,?,?)").run(e,i.last_self_check??null,i.activeCanvas??null);let o=ce(t,"INSERT INTO scope_marketplaces(owner_key,name,last_updated) VALUES(?,?,?)");for(let[a,c]of Object.entries(i.marketplaces??{}))o.run(e,a,c.last_updated??null);let s=ce(t,"INSERT INTO scope_plugins(owner_key,name,last_updated,etag,checked_at) VALUES(?,?,?,?,?)");for(let[a,c]of Object.entries(i.plugins??{}))s.run(e,a,c.last_updated??null,c.etag??null,c.checked_at??null)}function oQn(t,e){xut(t,"user",Nh(e,dy)),Vxe(t,"user",Nh(e,py));let n=Nh(e,s9);if(RC(n))for(let i of nQn(n,{withFileTypes:!0})){if(!i.isDirectory()||!Dxe.test(i.name))continue;let o=i.name,s=Nh(n,o),a=Nh(s,"profile.json");if(!RC(a))throw new Error(`legacy profile manifest is missing: ${a}`);let c=iK(a);if(!c||typeof c!="object"||!Array.isArray(c.projects)||typeof c.name!="string"||typeof c.created_at!="string")throw new Error(`legacy profile manifest is malformed: ${a}`);ce(t,"INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json) VALUES(?,?,?,?,?,?,?,?)").run(o,c.name,c.created_at,c.last_used_at??null,c.paused_at??null,c.default_kind??null,c.grantee??null,JSON.stringify(c.metadata??{})),ce(t,"INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)").run(`profile:${o}`,"profile",Nf(KM(c.grantee??"app:terminal",o).memory),o);let u=ce(t,"INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)"),l=ce(t,"INSERT INTO legacy_project_caps(profile_id,path,memory) VALUES(?,?,?)");c.projects.forEach((d,p)=>{u.run(o,d.path,p),d.memory!==void 0&&d.memory!=="content"&&l.run(o,d.path,d.memory)}),xut(t,`profile:${o}`,Nh(s,dy)),Vxe(t,`profile:${o}`,Nh(s,py))}let r=Nh(e,"profile-defaults.json");if(RC(r)){let i=iK(r);if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`legacy profile defaults are malformed: ${r}`);let o=ce(t,"INSERT INTO profile_defaults(directory,profile_id) VALUES(?,?)");for(let[s,a]of Object.entries(i)){if(typeof a!="string")throw new Error(`legacy profile default is malformed: ${r}`);o.run(s,a)}}}var iQn,Eut=h(()=>{"use strict";qt();iQn=Jt(Z0(),1);Wa();rK();TC();Rb();Vi();kxe();TC()});function JQ(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Kxe(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function hy(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function Cut(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function _ut(t,e){let n=Cut(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function Sut(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function lQn(){let t=[];for(let e of Object.values(Iut))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var vut,sQn,aQn,XQ,cQn,Iut,uQn,H1i,Tut=h(()=>{"use strict";Wa();vut=[!1,"notify","apply"],sQn=[0,1,6,12,24,48,72,168],aQn=[1,2,3,4,5,6,8,10,12],XQ="openai-codex";cQn=[1,2,3,4,5,6],Iut={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=JQ(vut,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=JQ(vut,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=Kxe(sQn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=Cut(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=Kxe(aQn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=_ut(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=hy(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=hy(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=hy(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=hy(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:hC.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=JQ(hC,t.whip_message_mode,e)},setFromString:(t,e)=>hC.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${hC.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:gC.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=JQ(gC,t.mouse_mode_default,e)},setFromString:(t,e)=>gC.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${gC.join("|")}`}},live_cycles:{surface:"settings",setting:{key:"live_cycles",label:"Live cycles",description:"Trailing refresh cycles rendered at full fidelity; older cycles condense to text.",valueConstraint:"integer >= 1",applies:"Applies on the next attach.",group:"display",order:50,format:t=>String(t.live_cycles),cycle:(t,e)=>{t.live_cycles=Kxe(cQn,t.live_cycles,e)},setFromString:(t,e)=>{let n=_ut(e,"live_cycles");return typeof n=="string"?n:(t.live_cycles=n,null)}}},condensed_history:{surface:"settings",setting:{key:"condensed_history",label:"Condensed history",description:"Messages retained from condensed cycles. Tool calls are never kept.",valueConstraint:yC.join("|"),applies:"Applies on the next attach.",group:"display",order:60,format:t=>t.condensed_history,cycle:(t,e)=>{t.condensed_history=JQ(yC,t.condensed_history,e)},setFromString:(t,e)=>yC.includes(e)?(t.condensed_history=e,null):`condensed_history must be one of: ${yC.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=hy(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},fold_finished_tools:{surface:"settings",setting:{key:"fold_finished_tools",label:"Fold finished tools",description:"Fold every settled tool call to its call line. Toggle live with /fold-tools.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.fold_finished_tools?"on":"off",cycle:t=>{t.fold_finished_tools=!t.fold_finished_tools},setFromString:(t,e)=>{let n=hy(e,"fold_finished_tools");return typeof n=="string"?n:(t.fold_finished_tools=n,null)}}},summarize_tool_calls:{surface:"settings",setting:{key:"summarize_tool_calls",label:"Summarize tool calls",description:"Replace completed folded tool-call groups with a one-line broker summary when available.",valueConstraint:"true|false",applies:"Applies when the next visible message closes a tool-call group.",group:"display",order:35,format:t=>t.summarize_tool_calls?"on":"off",cycle:t=>{t.summarize_tool_calls=!t.summarize_tool_calls},setFromString:(t,e)=>{let n=hy(e,"summarize_tool_calls");return typeof n=="string"?n:(t.summarize_tool_calls=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=hy(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},consolidate_replies:{surface:"settings",setting:{key:"consolidate_replies",label:"Consolidate replies",description:"Experiment: show one rewritten agent reply per message you type, with the working folded behind it (/show-working).",valueConstraint:"true|false",applies:"Applies on the next attach; the broker reads it per turn.",group:"display",order:36.5,format:t=>t.consolidate_replies?"on":"off",cycle:t=>{t.consolidate_replies=!t.consolidate_replies},setFromString:(t,e)=>{let n=hy(e,"consolidate_replies");return typeof n=="string"?n:(t.consolidate_replies=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${XQ}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[XQ]?.fastMode?"on":"off",cycle:t=>{let e=Sut(t,XQ);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=hy(e,`providerOptions.${XQ}.fastMode`);return typeof n=="string"?n:(Sut(t,XQ).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},uQn=Object.keys(Iut);H1i=lQn()});function ZQ(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function l1(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function u1(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${l1(t)}`);return t.trim()}}function Zxe(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${l1(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${l1(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${l1(i)}`);s={kind:u.kind.trim(),...u1(u.description,"description",e,o)===void 0?{}:{description:u1(u.description,"description",e,o)},...u1(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:u1(u.useWhen,"useWhen",e,o)},...u1(u.doc,"doc",e,o)===void 0?{}:{doc:u1(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${l1(i)}`);let a=s.kind;if(!pQn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${l1(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(fQn.has(a)||dQn.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=ZQ(a);if(oK.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function Rut(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=ZQ(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function Dut(t,e){return e.find(n=>n.kind===t)}var Yxe,dQn,pQn,fQn,kut,Jxe,oK,Xxe,eW=h(()=>{"use strict";Yxe=["options","text","table","cards","chart"],dQn=["page","step"],pQn=/^[a-z][a-z0-9-]{0,63}$/,fQn=new Set(Yxe),kut=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];Jxe=Object.fromEntries(kut.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),oK=new Set(kut.map(t=>t.tag)),Xxe=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as Put,join as mQn}from"node:path";import{existsSync as hQn,mkdirSync as Z1i,statSync as eOi}from"node:fs";function Lut(t){return mQn(t,dy)}function gQn(t,e){return fc(`${t}.lock`,()=>e(t),{timeoutError:()=>new Error(`timed out waiting for config lock: ${t}`)})}function tbe(t){let e=Nf(t),n=Nf(Ga());if(e===n)return{store:Dh(n),key:"user",kind:"user",root:n};if(Put(e)===".crouter")return but({kind:"project",root:e}),{store:e1(e),key:"project",kind:"project",root:e};for(let r of X9()){let i=Nf(J9(r.profileId));if(e===i)return{store:Dh(n),key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function But(t){if(Put(t)===".crouter"){let e;try{e=Nf(t)}catch(n){if(n.code==="ENOENT")return null;throw n}if(e!==Nf(Ga()))return xC(Lut(t))}return tK(tbe(t))}function yQn(t,e){let n=tbe(t);return n.kind==="project"?gQn(Lut(n.root),r=>{let i=e(xC(r)??{});return m9(r,i.next,{createParent:!1}),i.value}):iut(n,r=>e(r))}function Go(t){let e=AQn[wQn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=Oh(t);return n?xQn(n):c9()}function xQn(t){let e=But(t);return e?jQn(e):c9()}function nbe(t){let e=Oh(t);if(!e)return _we();try{return out(tbe(e))}catch(n){if(t==="project"&&!hQn(e))return _we();throw n}}function rbe(t,e){let n=Hxe(t);return yQn(n,r=>{let i=e(r);return{value:i,next:i}})}function bQn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function d1(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&fC.has(e)&&EQn.has(e)))]:[]}function _Qn(t,e=Ewe()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function $ut(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function ebe(){return Object.create(null)}function sK(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function SQn(t){let e=ebe();for(let[n,r]of Object.entries(t??{}))sK(e,n,r);return e}function tW(t,e){qa({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function CQn(t,e={}){let n=SQn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){tW(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){tW(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!$ut(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){tW(r,c);continue}sK(n,r,a)}return n}function IQn(t){let e=ebe(),n=ebe();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){tW(r,"route must include family, credentialSource, providerId, and models");continue}let o=vQn.filter(s=>i.models[s]===void 0);if(o.length>0){tW(r,`incomplete route; missing strengths: ${o.join(", ")}`),sK(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}sK(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function TQn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>$ut(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function kQn(t){return t!==""&&t.replace(/\*/g,"")===""}function RQn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(kQn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function DQn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function OQn(t,e){if(e==="bin"&&MQn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!Mut.test(t))return`${e}.${t} is not a safe bare command name (expected ${Mut.source})`}function Fut(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))OQn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function NQn(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(Out.test(n)||i.push(`action name must match ${Out.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function PQn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(NQn(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function LQn(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function BQn(t,e=bwe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=LQn(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function aK(){let t=[{origin:"config.json",components:Go("user").page_components}],e=Oh("user");if(e!==null){let n=c1("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:Zxe(r.manifest.page_components,i)})}}return Rut(t)}function $Qn(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function FQn(t,e=xwe()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=$Qn(o);s!==null&&(n[i]=s)}}return{targets:n}}function Nut(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function nW(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function UQn(t,e){let n=t!==null&&typeof t=="object"?t:{},r=nW(n.warning,e.warning),i=nW(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function QQn(t,e){return{unattendedParkMs:nW((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function WQn(t){if(!Array.isArray(t))return[...a9];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...a9]}function HQn(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function jQn(t){let e=c9(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:Nut(o?.crtr,e.auto_update.crtr),content:Nut(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=nW(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=UQn(t.brokerThresholds,e.brokerThresholds),f=QQn(t.lifecycle,e.lifecycle),m=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,g=t.working_gerunds===void 0?[...e.working_gerunds]:Lst(t.working_gerunds),y=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,w=Zxe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,E=WQn(t.whip_messages),_=hC.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,C=gC.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,I=nW(t.live_cycles,e.live_cycles),D=yC.includes(t.condensed_history)?t.condensed_history:e.condensed_history,O=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,k=typeof t.fold_finished_tools=="boolean"?t.fold_finished_tools:e.fold_finished_tools,P=typeof t.summarize_tool_calls=="boolean"?t.summarize_tool_calls:e.summarize_tool_calls,U=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,q=typeof t.consolidate_replies=="boolean"?t.consolidate_replies:e.consolidate_replies,G=bQn(t.keybindings),W=d1(t.tmux_passthrough),me=_Qn(t.modelLadders),K=DQn(t.providerOptions,e.providerOptions),Re=IQn(CQn(t.modelRoutes)),Ue=Re.complete,Xe=TQn(t.modelRouting,void 0),It=BQn(t.kinds),Yt=FQn(t.remoteCanvas),Qe=HQn(t.api,e.api),J=t.paths;if(J?.user_files!==void 0&&(typeof J.user_files!="string"||!J.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Pe=t.store,tt=t.runtime;if(tt?.person_uids!==void 0&&(!Array.isArray(tt.person_uids)||!tt.person_uids.every(H=>Number.isSafeInteger(H)&&H>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let Wt=RQn(t.spawnEnv,e.spawnEnv?.allow),Ht=Fut(t.bin),Ft=PQn(t.humanActions);return{bin:Ht,humanActions:Ft,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:f,completion_bell:m,working_gerunds:g,whip_mode:y,page_components:w,page_surface:x,whip_messages:E,whip_message_mode:_,mouse_mode_default:C,live_cycles:I,condensed_history:D,bash_tool_purpose:O,fold_finished_tools:k,summarize_tool_calls:P,detailed_tool_recaps:U,consolidate_replies:q,keybindings:G,tmux_passthrough:W,modelLadders:me,providerOptions:K,...Object.keys(Ue).length>0?{modelRoutes:Ue}:{},...Object.keys(Re.legacy).length>0?{legacyModelRoutes:Re.legacy}:{},...Xe!==void 0?{modelRouting:Xe}:{},kinds:It,remoteCanvas:Yt,api:Qe,...J?{paths:J}:{},...Pe?{store:Pe}:{},...tt?{runtime:tt}:{},spawnEnv:Wt}}function Uut(t){return But(t)}function Qut(t){let e=Oh(t);return e?Uut(e):null}var AQn,wQn,EQn,vQn,Mut,MQn,Out,zo=h(()=>{"use strict";_o();Wa();r9();ds();Of();qo();xp();YQ();vu();Rb();Eut();Gxe();wp();Tut();o9();eW();AQn=globalThis,wQn=Symbol.for("crtr.broker.config-snapshot");EQn=new Set(gp.filter(TQ).map(t=>t.id));vQn=["ultra","strong","medium","light"];Mut=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,MQn=new Set(["crtr","crtrd"]);Out=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/});function KQn(t){let e=t.match(/^((?:[CMS]-)+)(.+)$/i);return e===null?t:`${e[1].split("-").filter(Boolean).map(r=>r.toUpperCase()==="C"?"ctrl":r.toUpperCase()==="M"?"alt":"shift").join("+")}+${e[2]}`}function abe(t){let e=KQn(t.trim());if(e==="")throw new Gc("a stroke cannot be empty");let n,r;if(e==="+")n="+",r=[];else if(e.endsWith("++"))n="+",r=e.slice(0,-2).split("+");else{let c=e.split("+");if(c.some(u=>u===""))throw new Gc(`invalid stroke "${t}"`);n=c.pop(),r=c}let i=r.map(c=>c.toLowerCase());if(i.some(c=>!GQn.has(c)))throw new Gc(`unsupported modifier in "${t}"`);let o=i.map(c=>c==="meta"?"alt":c);if(new Set(o).size!==o.length)throw new Gc(`duplicate modifier in "${t}"`);let s=VQn[n.toLowerCase()]??n;if(s.length===1&&s>="A"&&s<="Z"?(s=s.toLowerCase(),o.includes("shift")||o.push("shift")):s.length!==1&&(s=s.toLowerCase()),!(s.length===1&&s.charCodeAt(0)>=32&&s.charCodeAt(0)<=126)&&!zQn.has(s))throw new Gc(`unsupported key "${n}"`);return[...qQn.filter(c=>o.includes(c)),s].join("+")}function cbe(t,e){let n=t.trim().split(/\s+>\s+/);if(n.length>2)throw new Gc("a gesture may contain at most two strokes");let r=n.map(abe);if(r.length===2&&e?.inputKind!=="tmux-sequence")throw new Gc("two-stroke sequences are supported only by tmux sequence actions");if(e?.inputKind==="tmux-sequence"&&r.length!==2)throw new Gc("this action requires a two-stroke tmux sequence");if(e?.inputKind==="tmux-menu-selector"){if(r.length!==1)throw new Gc("a menu selector must be one stroke");let o=r[0].split("+"),s=o.at(-1),a=o.slice(0,-1);if(s.length!==1&&s!=="space"||a.some(c=>c!=="shift"))throw new Gc("a menu selector must be one printable character")}if(e?.inputKind==="tmux-global-action"){if(r.length!==1)throw new Gc("a global menu shortcut must be one stroke");let i=r[0].split("+").slice(0,-1);if(!i.includes("ctrl")&&!i.includes("alt"))throw new Gc("a global menu shortcut must include Ctrl or Alt")}return r.join(" > ")}function YQn(t,e){if(!Array.isArray(t))throw new Gc("the override must be an array of gesture strings");let n=[];for(let r of t){if(typeof r!="string")throw new Gc("every override entry must be a gesture string");let i=cbe(r,e);n.includes(i)||n.push(i)}return Object.freeze(n)}function JQn(t,e){return t.contexts.some(n=>e.contexts.includes(n))}function ibe(t){return t.contexts.includes("tmux.root")}function Wut(t){return!ibe(t)&&t.inputKind!=="tmux-menu-selector"&&t.inputKind!=="tmux-sequence"}function p1(t){return t.split(" > ")[0]}function XQn(t,e,n,r){let i=e.includes(" > "),o=r.includes(" > ");if(JQn(t,n))return i&&o?e===r:i||o?p1(e)===p1(r):e===r;let s=ibe(t),a=ibe(n);return!s&&!a?!1:s&&a&&i&&o?e===r:s&&a?p1(e)===p1(r):s&&Wut(n)?p1(e)===r:a&&Wut(t)?e===p1(r):!1}function obe(t){return Object.freeze(t.defaults.map(e=>cbe(e,t)))}function rW(t,e,n,r,i){return Object.freeze({severity:"error",code:t,message:e,offendingValue:n,...r?{bindingId:r}:{},...i?{relatedBindingIds:Object.freeze([...i])}:{}})}function ZQn(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];for(let i=n+1;i<t.length;i+=1){let o=t[i];for(let s of r.gestures){let a=o.gestures.find(c=>XQn(r.definition,s,o.definition,c));if(a!==void 0){e.push([r,o,s.includes(" > ")?s:a]);break}}}}return e}function eWn(t,e,n){return t.some(r=>r.definition.safety===n&&r.gestures.length>0&&r.definition.contexts.includes(e))}function Hut(t,e){for(;;){let n=new Set;for(let[r,i,o]of ZQn(t)){if(r.source==="user"&&n.add(r),i.source==="user"&&n.add(i),r.source==="default"&&i.source==="default")throw new Error(`keybinding catalog default collision: ${r.definition.id} / ${i.definition.id} (${o})`);e.push(rW("collision",`${r.definition.id} and ${i.definition.id} both claim ${o} in overlapping contexts`,o,r.source==="user"?r.definition.id:i.definition.id,[r.definition.id,i.definition.id]))}if(n.size===0)return;for(let r of n)r.gestures=obe(r.definition),r.source="default"}}function jut(t=void 0){let e=[],n={};t!==void 0&&(t===null||typeof t!="object"||Array.isArray(t)?e.push(rW("invalid-keybindings","keybindings must be an object keyed by catalog binding ID",t)):n=t);for(let[a,c]of Object.entries(n))fC.has(a)||e.push(rW("unknown-binding",`unknown keybinding ID: ${a}`,c,a));let r=gp.map(a=>{let c=obe(a);if(!Object.hasOwn(n,a.id))return{definition:a,gestures:c,source:"default"};let u=n[a.id];try{return{definition:a,gestures:YQn(u,a),source:"user",rawOverride:u}}catch(l){let d=l instanceof Error?l.message:String(l);return e.push(rW("invalid-override",`${a.id}: ${d}`,u,a.id)),{definition:a,gestures:c,source:"default"}}});Hut(r,e);for(let a of gwe){if(eWn(r,a.context,a.capability))continue;let c=r.filter(u=>u.source==="user"&&u.definition.safety===a.capability&&u.definition.contexts.includes(a.context));e.push(rW("unreachable",`${a.context} must retain an enabled ${a.capability} binding`,c.map(u=>u.rawOverride),c[0]?.definition.id,c.map(u=>u.definition.id)));for(let u of c)u.gestures=obe(u.definition),u.source="default"}Hut(r,e);let i=r.map(a=>{let c=Object.freeze({definition:a.definition,gestures:a.gestures,source:a.source});return[a.definition.id,c]}),o=new sbe(i),s={bindings:o,diagnostics:Object.freeze(e),get(a){let c=o.get(a);if(c===void 0)throw new Error(`unknown crouter keybinding ID: ${a}`);return c},gestures(a){return this.get(a).gestures}};return Object.freeze(s)}function Nb(){let t=Qut("user");return Object.freeze({bindings:jut(t?.keybindings),tmuxPassthrough:Object.freeze(d1(t?.tmux_passthrough))})}function iW(){return Nb().bindings}var qQn,GQn,zQn,VQn,Gc,sbe,f1=h(()=>{"use strict";r9();zo();qQn=["ctrl","alt","shift"],GQn=new Set(["ctrl","alt","shift","meta"]),zQn=new Set(["enter","escape","tab","backspace","delete","space","up","down","left","right","pageup","pagedown","home","end"]),VQn={return:"enter",esc:"escape"},Gc=class extends Error{constructor(e){super(e),this.name="GestureSyntaxError"}};sbe=class{#e;constructor(e){this.#e=new Map(e)}get size(){return this.#e.size}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}entries(){return this.#e.entries()}keys(){return this.#e.keys()}values(){return this.#e.values()}forEach(e,n){for(let[r,i]of this.#e)e.call(n,i,r,this)}[Symbol.iterator](){return this.#e[Symbol.iterator]()}}});function qut(t){let e,n;if(t==="+")e="+",n=[];else if(t.endsWith("++"))e="+",n=t.slice(0,-2).split("+");else{let i=t.split("+");e=i.pop(),n=i}let r=n.map(i=>i[0].toUpperCase()+i.slice(1));return r.push(tWn[e]??(e.length===1&&n.length>0?e.toUpperCase():e)),r.join("+")}function Pb(t){return t.split(" > ").map(qut).join(" then ")}function la(t,e){let n=t.gestures(e);return n.length===0?"Disabled":n.map(Pb).join(" / ")}function DC(t){if(t.length===2&&t[0]==="\x1B"&&/[A-Z]/.test(t[1]))return`\x1B[${t.charCodeAt(1)};4u`;let e=/^\x1b\[(\d+);3u$/.exec(t);if(e!==null){let n=Number(e[1]);if(n>=65&&n<=90)return`\x1B[${n};4u`}return t}function MC(t,e,n,r){return t.gestures(e).some(i=>!i.includes(" > ")&&r(n,i))}var tWn,cK=h(()=>{"use strict";f1();tWn={enter:"Enter",escape:"Esc",tab:"Tab",backspace:"Backspace",delete:"Delete",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PageUp",pagedown:"PageDown",home:"Home",end:"End"}});function Gut(t=iW()){let e=t.gestures(nWn);return e.length>0?e.map(Pb).join(" / "):null}function m1(t){let e=Gut(t);return e!==null?`${e} inbox`:"crtr human list"}var nWn,zut=h(()=>{"use strict";cK();f1();nWn="crtr.tmux.inbox.toggle"});function oWn(t){let e=t.split("+"),n=e.at(-1);return e.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}function Vut(t=iW()){let e=t.gestures(rWn),n=t.gestures(iWn);return e.length===0||n.length===0?null:`${e.map(Pb).join(" / ")} ${oWn(n[0])}`}function uK(t){let e=Vut(t);return e!==null?`${e} to background`:null}var rWn,iWn,Kut=h(()=>{"use strict";cK();f1();rWn="crtr.tmux.menu.open",iWn="crtr.tmux.menu.background-bash"});function oW(t){return`${sWn}${t}${aWn}`}function ube(t){let e;for(let{actionId:n}of gy){let r=oW(n),i=t.indexOf(r);i>=0&&(e===void 0||i<e.index)&&(e={actionId:n,encoded:r,index:i})}if(e!==void 0)return{actionId:e.actionId,remaining:t.slice(0,e.index)+t.slice(e.index+e.encoded.length)}}var gy,sWn,aWn,ROi,Yut=h(()=>{"use strict";gy=[{menuId:"crtr.tmux.menu.attach.detach",actionId:"crtr.attach.detach"},{menuId:"crtr.tmux.menu.attach.clear-or-detach",actionId:"crtr.attach.clear-or-detach"},{menuId:"crtr.tmux.menu.attach.graph.toggle",actionId:"crtr.attach.graph.toggle"},{menuId:"crtr.tmux.menu.attach.help.toggle",actionId:"crtr.attach.help.toggle"},{menuId:"crtr.tmux.menu.attach.inbox.toggle",actionId:"crtr.attach.inbox.toggle"},{menuId:"crtr.tmux.menu.attach.inbox-strip",actionId:"crtr.attach.inbox-strip"},{menuId:"crtr.tmux.menu.attach.model-ladder.next",actionId:"crtr.attach.model-ladder.next"},{menuId:"crtr.tmux.menu.attach.model-ladder.previous",actionId:"crtr.attach.model-ladder.previous"},{menuId:"crtr.tmux.menu.attach.command.inspect",actionId:"crtr.attach.command.inspect"},{menuId:"crtr.tmux.menu.attach.file-review",actionId:"crtr.attach.file-review"},{menuId:"crtr.tmux.menu.attach.profile-files",actionId:"crtr.attach.profile-files"},{menuId:"crtr.tmux.menu.attach.search",actionId:"crtr.attach.search"},{menuId:"crtr.tmux.menu.attach.whip",actionId:"crtr.attach.whip"}],sWn="\x1B_crtr;",aWn="\x1B\\",ROi=new Set(gy.map(({actionId:t})=>t))});var Jut=h(()=>{"use strict";zo();f1()});var cl=h(()=>{"use strict";r9();f1();cK();zut();Kut();Yut();Jut()});import{readFileSync as uWn}from"node:fs";function lbe(){try{let t=uWn("/proc/sys/kernel/random/boot_id","utf8").trim();return t.length>0?t:null}catch{return null}}var Xut=h(()=>{"use strict"});import{spawn as tNi,spawnSync as pbe}from"node:child_process";import{readFileSync as fbe,readdirSync as lWn,statSync as dWn}from"node:fs";function pWn(t){if(hbe())return EWn(t);try{let e=pbe("ps",["-o","stat=","-p",String(t)],{encoding:"utf8",timeout:2e3});if(e.error!=null||e.signal!=null||typeof e.stdout!="string"||typeof e.stderr=="string"&&e.stderr.trim()!=="")return"unknown";let n=e.stdout.trim();return n===""?"gone":n.charAt(0)==="Z"?"zombie":"live"}catch{return"unknown"}}function Bf(t){if(t==null)return!1;try{process.kill(t,0)}catch(n){return n.code==="EPERM"}let e=pWn(t);return e!=="zombie"&&e!=="gone"}function tlt(t){if(t==null)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function elt(t){let e=t.indexOf("#");if(e===-1)return{base:t,ticks:void 0};let n=t.slice(e+1);return{base:t.slice(0,e),ticks:/^\d+$/.test(n)?n:void 0}}function mbe(t,e){let n=elt(t),r=elt(e);return n.ticks!==void 0&&r.ticks!==void 0?Zut.test(n.base)&&Zut.test(r.base)?n.base===r.base&&n.ticks===r.ticks:n.ticks===r.ticks:n.base===r.base}function nlt(t,e="SIGTERM"){if(!(!Number.isInteger(t)||t<=0))try{process.kill(-t,e)}catch{}}function fWn(t){try{let e=fbe(`/proc/${t}/stat`,"utf8"),n=e.lastIndexOf(")");if(n===-1)return null;let i=e.slice(n+2).trim().split(/\s+/)[19];return i!==void 0&&/^\d+$/.test(i)?i:null}catch{return null}}function hWn(t,e=Date.now,n=mWn){let r=null,i=0;return()=>{if(r!==null)return r;let o=e();if(o<i)return null;let s=t();return s!==null?r=s:(i=o+n,null)}}function gWn(t,e,n={}){let r=n.ticks!==void 0?n.ticks:fWn(t);return r===null?e:`${(n.bootId!==void 0?n.bootId:rlt())??e}#${r}`}function yWn(t){let e=t.indexOf("("),n=t.lastIndexOf(")");if(e===-1||n===-1||n<e)return null;let r=t.slice(n+2).trim().split(/\s+/),i=r[0],o=Number(r[1]),s=r[19];return i===void 0||i===""||!Number.isInteger(o)||o<0||s===void 0||!/^\d+$/.test(s)?null:{comm:t.slice(e+1,n),state:i,ppid:o,starttime:s}}function AWn(t,e){let n=t.replace(/\0+$/,"").split("\0").join(" ").trim();return n===""?`[${e}]`:n}function hbe(){return dbe===void 0&&(dbe=process.platform==="linux"&&lbe()!==null&&wWn(process.pid)!==null),dbe}function wWn(t,e=h1){let n=lK(t,e);return n==="unreadable"||n==="denied"||n==="gone"?null:n}function lK(t,e=h1){let n;try{n=fbe(`${e.root}/${t}/stat`,"utf8")}catch(r){return ilt(r)}return yWn(n)??"unreadable"}function ilt(t){let e=t.code;return e==="ENOENT"||e==="ESRCH"?"gone":e==="EACCES"||e==="EPERM"?"denied":"unreadable"}function xWn(t,e){let n=e.selfUid!==void 0?e.selfUid():process.getuid?.()??null;if(n===null)return"own-or-unknown";try{return dWn(`${e.root}/${t}`).uid===n?"own-or-unknown":"foreign"}catch(r){return ilt(r)==="gone"?"gone":"own-or-unknown"}}function bWn(t,e,n){return t==="gone"?"skip":t==="unreadable"||xWn(e,n)==="own-or-unknown"?"fail":"skip"}function olt(t,e=h1){let n=e.bootId();return n===null?null:`${n}#${t.starttime}`}function EWn(t,e=h1){let n=lK(t,e);return n==="gone"?"gone":n==="denied"||n==="unreadable"?"unknown":n.state==="Z"||n.state==="X"?"zombie":"live"}function _Wn(t,e=h1){let n=new Map;for(let r of t){let i=lK(r,e);if(i==="gone")continue;if(i==="unreadable"||i==="denied")return null;let o=olt(i,e);if(o===null)return null;n.set(r,o)}return n}function vWn(t,e,n,r,i){let o=olt(r,t);if(o===null)return!1;e.processes.set(n,{zombie:r.state==="Z"||r.state==="X",identity:o,command:AWn(i,r.comm)});let s=e.childrenOf.get(r.ppid);return s===void 0?e.childrenOf.set(r.ppid,[n]):s.push(n),!0}function SWn(t){try{return lWn(t).filter(e=>/^\d+$/.test(e)).map(Number).filter(e=>e>0)}catch{return null}}function CWn(t=h1){let e=SWn(t.root);if(e===null)return null;let n={processes:new Map,childrenOf:new Map};for(let r of e){let i=lK(r,t);if(i==="gone"||i==="denied"||i==="unreadable"){if(bWn(i==="gone"?"gone":i,r,t)==="skip")continue;return null}let o="";try{o=fbe(`${t.root}/${r}/cmdline`,"utf8")}catch(s){let a=s.code;if(a==="ENOENT"||a==="ESRCH")continue}if(!vWn(t,n,r,i,o))return null}return n}function gbe(){if(hbe()){let t=CWn();if(t===null)return null;let e=new Map;for(let[n,r]of t.childrenOf)for(let i of r)e.set(i,n);return[...t.processes].map(([n,r])=>({pid:n,ppid:e.get(n)??0,command:r.command}))}try{let t=pbe("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:2e3,maxBuffer:8388608});if(t.status!==0||typeof t.stdout!="string")return null;let e=[];for(let n of t.stdout.split(`
233
+ ALTER TABLE profile_projects DROP COLUMN memory;`),t.exec(`PRAGMA user_version = ${zQ}`)),t.exec("COMMIT")}catch(n){throw t.exec("ROLLBACK"),n}}}function Uct(t){let e=new Y9(t.path);try{Fct(e,t),$ct(e,t)}finally{e.close()}}function Oxe(t){if(!VQ(t))return;let e=new Y9(t.path,{readOnly:!0}),n;try{n=Ob(e)}finally{e.close()}if(n===0)for(let r of[t.path,`${t.path}-wal`,`${t.path}-shm`])bUn(r,{force:!0})}function Nxe(t,e){return fc(dd(t,".init.lock"),()=>{let n=dd(t,py),r=Date.now()+5e3,i=10;for(;;){let o;try{o=Bct.default.lockSync(n,{realpath:!1,retries:0,stale:3e4,update:1e4})}catch(s){if(s.code!=="ELOCKED")throw s;let a=r-Date.now();if(a<=0)throw new Error(`timed out waiting for project state conversion lock: ${n}`,{cause:s});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.min(i,a)),i=Math.min(i*2,250);continue}try{return e()}finally{o()}}})}function Pxe(t){a1(t)&&Rxe(t,384);for(let e of["-wal","-shm"])a1(`${t}${e}`)&&Rxe(`${t}${e}`,384)}function VQ(t){return a1(t.path)}function Lxe(t){if(t.kind==="project")return[dd(t.root,py)];if(t.kind==="provider")return[dd(t.root,"anthropic-subscriptions.json"),dd(t.root,"openai-codex-subscriptions.json"),dd(t.root,"provider-rotation.json")];let e=[dd(t.root,dy),dd(t.root,py),dd(t.root,"profile-defaults.json")],n=dd(t.root,s9);if(a1(n))for(let r of xUn(n,{withFileTypes:!0}))r.isDirectory()&&Dxe.test(r.name)&&e.push(dd(n,r.name,"profile.json"),dd(n,r.name,dy),dd(n,r.name,py));return e}function Bxe(t){let e=t.kind==="user"?Dh(t.root):t.kind==="project"?e1(t.root):J0(t.root);e.kind!=="project"&&Lct(e.root,{recursive:!0,mode:448});let n=()=>{if(e.kind==="project"&&Oxe(e),VQ(e))return;let r=Lxe(e).find(a1);if(r!==void 0)throw new Error(`legacy scoped state exists at ${r}; crtr was updated and \`crtr sys daemon restart\` converts local state`);$xe(e,i=>{K9(i,e.kind),e.kind!=="provider"&&Mxe(i,e.kind,e.root)})};e.kind==="project"?Nxe(e.root,n):fc(dd(e.root,".init.lock"),n)}function Mh(t){if($we())throw new Error("layout_migration_required");let e=Pct.get(t.path);if(e!==void 0)return e;Bxe(t);let n=new Y9(t.path);try{return n.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;"),Fct(n,t),$ct(n,t),Pxe(t.path),Pct.set(t.path,n),n}catch(r){throw n.close(),r}}function $xe(t,e){if(a1(t.path))throw new Error(`scoped SQL store already exists: ${t.path}`);if(t.kind!=="project"&&Lct(t.root,{recursive:!0,mode:448}),!EUn(t.root).isDirectory())throw new Error(`scoped SQL root is not a directory: ${t.root}`);(t.kind!=="project"||process.platform!=="linux")&&Rxe(t.root,448),_Un(t.path,"",{mode:384});let n=new Y9(t.path);try{n.exec("PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; BEGIN IMMEDIATE;"),e(n),n.exec("COMMIT")}catch(r){try{n.exec("ROLLBACK")}catch{}throw r}finally{Pxe(t.path),n.close()}GM(t.path),fy(t.root)}function KQ(t,e){let n=Mh(t);if(n.isTransaction)return e(n);n.exec("BEGIN IMMEDIATE");try{let r=e(n);return n.exec("COMMIT"),Pxe(t.path),r}catch(r){try{n.exec("ROLLBACK")}catch{}throw r}}var Bct,Pct,Dxe,TC=h(()=>{"use strict";qt();Bct=Jt(Z0(),1);Wa();wp();qo();Vi();Rb();kxe();Pct=new Map,Dxe=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/});function Qct(t){return Dh(t)}function vUn(t,e){return{profileId:t.id,manifest:{schema_version:1,name:t.name,projects:e,paused_at:t.paused_at,...t.default_kind===null?{}:{default_kind:t.default_kind},...t.grantee===null?{}:{grantee:t.grantee},...t.delivery_limits_json==="{}"?{}:{delivery_limits:JSON.parse(t.delivery_limits_json)},...Object.keys(JSON.parse(t.metadata_json)).length===0?{}:{metadata:JSON.parse(t.metadata_json)},created_at:t.created_at,last_used_at:t.last_used_at}}}function Wct(t,e){let n=ce(t,"SELECT id, name, created_at, last_used_at, paused_at, default_kind, grantee, metadata_json, delivery_limits_json FROM profiles WHERE id=?").get(e);if(!n)return null;let r=ce(t,"SELECT path FROM profile_projects WHERE profile_id=? ORDER BY position").all(e);return vUn(n,r)}function Hct(t){let e=Mh(Qct(t));return ce(e,"SELECT id FROM profiles ORDER BY rowid").all().map(({id:r})=>Wct(e,r)).filter(Boolean)}function Fxe(t,e){return Wct(Mh(Qct(t)),e)}var Uxe=h(()=>{"use strict";qt();Rb();Vi();TC()});var jct=h(()=>{"use strict"});function CUn(t){return t.grantee??"app:terminal"}function Gct(t){if(!qct.test(t))throw yp(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function J9(t){Gct(t);let e=Fxe(Ga(),t);if(e===null)throw Df(`profile not found: ${t}`,{received:t});return KM(CUn(e.manifest),t).dir}function IUn(){return{entries:Hct(Ga()),unreadableIds:[]}}function X9(){return IUn().entries}function zct(t){let e=X9(),n=TUn(e,t,Vct);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function kC(t){Gct(t);let e=Fxe(Ga(),t);if(e!==null)return e;throw Df(`profile not found: ${t}`,{received:t,next:"Run `crtr profile list` to see available profiles."})}function TUn(t,e,n){if(qct.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw Qst(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function kUn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return Df(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function Lf(t){let e=zct(t);if(e.kind==="resolved")return e.entry;throw kUn(X9(),t,Vct)}var qct,Vct,vu=h(()=>{"use strict";Wa();Vi();L9();xp();qo();Uxe();ds();wp();jct();qct=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Vct=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Kct}from"node:os";import{existsSync as RUn,statSync as DUn}from"node:fs";import{join as Z9,resolve as Yct,dirname as MUn,sep as Qxe}from"node:path";function Ga(){return Z9(Mf(),"scope")}function OUn(t,e){if(!RUn(t)||ua(t)===ua(Z9(Kct(),mC))||ua(t).startsWith(`${ua(Sh())}${Qxe}`)&&t.endsWith(`${Qxe}home${Qxe}${mC}`)||!JS()&&(ua(t)===ua(e)||ua(t)===ua(Ib())))return!1;try{return DUn(t).isDirectory()}catch{return!1}}function NUn(t=process.cwd()){return Wxe(t)[0]??null}function PUn(t,e){let n=[],r=ua(Kct()),i=Yct(t);for(;;){let o=Z9(i,mC);if(OUn(o,e)&&n.push(o),ua(i)===r)return n;let s=MUn(i);if(s===i)return n;i=s}}function Wxe(t=process.cwd(),e=CAe()||null){return LUn(t,e)}function LUn(t,e){let n=Yct(t),r=Ga(),i=[n];if(!JS()&&e!==null&&e!=="")try{let{manifest:a}=Lf(e);for(let c of a.projects)i.push(c.path)}catch{}let o=new Set,s=[];for(let a of i)for(let c of PUn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function eK(t){return NUn(t)}function Oh(t){return t==="builtin"?null:t==="user"?Ga():eK()}function Hxe(t){let e=Oh(t);if(!e)throw yp(`no ${t} scope available \u2014 run \`crtr init\` here or use --scope user`);return e}function Jct(t){let e=t==="user"?Mf():Oh(t);return e?Z9(e,"plugins"):null}var xp=h(()=>{"use strict";_o();Wa();qat();ds();vu();qo();Vi()});import{join as BUn}from"node:path";function $Un(t){return BUn(t,$st,Fst)}function FUn(t){let e;try{e=xC(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function UUn(t){return FUn($Un(t))}function Xct(t){let e=UUn(t);return e.status==="ok"?e.manifest:null}var jxe=h(()=>{"use strict";Wa();qo()});import{join as QUn}from"node:path";function Zct(t,e){return QUn(t,"tmp",`${e}.swap.lock`)}function eut(t,e){let n=s1(Zct(t,e));return n!==null&&n!==process.pid}function tut(t,e){Mct(Zct(t,e),WUn)}var WUn,nut=h(()=>{"use strict";wp();WUn=2e3});import{createHash as HUn}from"node:crypto";function qxe(t,e,n){let r=ce(t,"SELECT kind, root, profile_id FROM scope_owners WHERE owner_key = ?").get(e.key);if(!r)throw new Error(`scoped SQL owner is missing: ${e.key}`);if(r.kind!==e.kind||(e.profileId??null)!==r.profile_id)throw new Error(`scoped SQL owner does not match its root: ${e.key}`);if(r.root===e.root)return;if(!(e.kind==="profile"&&e.profileId!==void 0)&&(e.kind!=="project"||e.store.kind!=="project"||e.store.root!==e.root))throw new Error(`scoped SQL owner does not match its root: ${e.key}`);n==="write"&&ce(t,"UPDATE scope_owners SET root = ? WHERE owner_key = ?").run(e.root,e.key)}function jUn(t){return t===void 0?"absent":HUn("sha256").update(t.raw_json).digest("hex")}function qUn(t,e){return ce(t,"SELECT raw_json FROM scope_settings WHERE owner_key = ?").get(e.key)}function rut(t){let e=Mh(t.store);qxe(e,t,"read");let n=qUn(e,t);return{revision:jUn(n),settings:n===void 0?null:JSON.parse(n.raw_json)}}function tK(t){return rut(t).settings}function iut(t,e){return KQ(t.store,n=>{qxe(n,t,"write");let r=ce(n,"SELECT raw_json FROM scope_settings WHERE owner_key = ?").get(t.key),i=e(r?JSON.parse(r.raw_json):{});return ce(n,"INSERT INTO scope_settings(owner_key, raw_json) VALUES (?, ?) ON CONFLICT(owner_key) DO UPDATE SET raw_json=excluded.raw_json").run(t.key,JSON.stringify(i.next)),i.value})}function out(t){let e=Mh(t.store);qxe(e,t,"read");let n=ce(e,"SELECT last_self_check, active_canvas FROM scope_bookkeeping WHERE owner_key = ?").get(t.key),r=Object.fromEntries(ce(e,"SELECT name, last_updated FROM scope_marketplaces WHERE owner_key = ?").all(t.key).map(o=>[o.name,o.last_updated===null?{}:{last_updated:o.last_updated}])),i=Object.fromEntries(ce(e,"SELECT name, last_updated, etag, checked_at FROM scope_plugins WHERE owner_key = ?").all(t.key).map(o=>[o.name,{...o.last_updated===null?{}:{last_updated:o.last_updated},...o.etag===null?{}:{etag:o.etag},...o.checked_at===null?{}:{checked_at:o.checked_at}}]));return{marketplaces:r,plugins:i,...n?.last_self_check===null||n===void 0?{}:{last_self_check:n.last_self_check},activeCanvas:n?.active_canvas??null}}var Gxe=h(()=>{"use strict";qt();TC()});import{join as zxe}from"node:path";function GUn(t,e){let n=t==="user"?Dh(e):void 0,r=n?tK({store:n,key:"user",kind:"user",root:n.root}):xC(zxe(e,dy));return r&&r.plugins&&typeof r.plugins=="object"?r.plugins:{}}function zUn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&eut(t,i))}function c1(t,e){let n=t==="user"?Jct("user"):zxe(e,"plugins");if(!g9(n))return[];let r=GUn(t,e),i=sut(t,n,r),o=zUn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)tut(e,s);return sut(t,n,r)}function sut(t,e,n){let r=[];for(let i of Nwe(e)){let o=zxe(e,i),s=Xct(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var YQ=h(()=>{"use strict";Wa();qo();jxe();nut();Rb();Gxe();xp()});import{chmodSync as aut,existsSync as nK,fsyncSync as cut,mkdirSync as VUn,openSync as uut,readFileSync as lut,renameSync as KUn,writeFileSync as YUn,closeSync as dut}from"node:fs";import{dirname as put}from"node:path";var fut,JUn,XUn,ZUn,my,rK=h(()=>{"use strict";fut=Jt(Z0(),1);qo();JUn={encoding:"utf-8",mode:384},XUn=3e4,ZUn=5e3,my=class{constructor(e,n=!1,r="{}"){this.path=e;this.durable=n;this.initialContent=r}path;durable;initialContent;readUnlocked(){return nK(this.path)?lut(this.path,"utf-8"):void 0}ensureFile(){let e=put(this.path);nK(e)||VUn(e,{recursive:!0,mode:448}),nK(this.path)||(h9(this.path,this.initialContent,384),aut(this.path,384))}async withLockAsync(e){this.ensureFile();let n,r,i=()=>{if(r)throw r};try{n=await fut.default.lock(this.path,{realpath:!1,retries:{retries:10,factor:2,minTimeout:100,maxTimeout:1e4,randomize:!0},stale:XUn,update:ZUn,onCompromised:l=>{r=l}}),i();let o=nK(this.path)?lut(this.path,"utf-8"):void 0,s=!1,a=l=>{if(s)throw new Error(`locked file was published twice: ${this.path}`);i();let d=`${this.path}.${process.pid}.${Date.now()}.tmp`;if(YUn(d,l,JUn),aut(d,384),this.durable){let p=uut(d,"r");try{cut(p)}finally{dut(p)}}if(KUn(d,this.path),this.durable){let p=uut(put(this.path),"r");try{cut(p)}finally{dut(p)}}s=!0},{result:c,next:u}=await e(o,i,a);return i(),u!==void 0&&a(u),i(),c}finally{if(n)try{await n()}catch{}}}}});import{chmodSync as mut,copyFileSync as eQn,existsSync as RC,mkdirSync as hut,readFileSync as tQn,readdirSync as nQn,statSync as gut}from"node:fs";import{dirname as yut,join as Nh,relative as rQn}from"node:path";function iK(t){return JSON.parse(tQn(t,"utf8"))}function Aut(t){return t.some(RC)}function wut(t,e){let n=Nh(t,".legacy-scoped-state");try{hut(n,{mode:448})}catch(r){if(r.code!=="EEXIST"||!gut(n).isDirectory())throw r}mut(n,448);for(let r of e)if(RC(r)&&gut(r).isFile()){let i=rQn(t,r);if(i===""||i.startsWith(".."))throw new Error(`legacy state is outside its owning root: ${r}`);let o=Nh(n,i);yut(o)!==n&&hut(yut(o),{recursive:!0,mode:448}),eQn(r,o),mut(o,384)}}function but(t){let e=t.kind==="user"?Dh(t.root):t.kind==="project"?e1(t.root):J0(t.root);if(t.kind!=="project"&&VQ(e))return;if(t.kind==="provider")throw new Error("provider conversion requires convertLegacyProviderStore() under coordinated shared-agent-dir activation");let n=Lxe(e),r=()=>{t.kind==="project"&&Oxe(e),!VQ(e)&&(t.kind==="project"&&Aut(n)&&wut(e.root,n),$xe(e,i=>{K9(i,t.kind);let o=t.kind==="user"?"user":"project";Mxe(i,o,e.root),t.kind==="user"?oQn(i,e.root):Vxe(i,o,Nh(e.root,py))}),t.kind==="user"&&Aut(n)&&wut(e.root,n))};t.kind==="project"?Nxe(e.root,()=>{r(),Uct(e)}):r()}function xut(t,e,n){if(!RC(n))return;let r=iK(n);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`legacy config is malformed: ${n}`);ce(t,"INSERT INTO scope_settings(owner_key,raw_json) VALUES(?,?)").run(e,JSON.stringify(r))}function Vxe(t,e,n){if(!RC(n))return;let r=iK(n);if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`legacy state is malformed: ${n}`);let i=r;ce(t,"INSERT INTO scope_bookkeeping(owner_key,last_self_check,active_canvas) VALUES(?,?,?)").run(e,i.last_self_check??null,i.activeCanvas??null);let o=ce(t,"INSERT INTO scope_marketplaces(owner_key,name,last_updated) VALUES(?,?,?)");for(let[a,c]of Object.entries(i.marketplaces??{}))o.run(e,a,c.last_updated??null);let s=ce(t,"INSERT INTO scope_plugins(owner_key,name,last_updated,etag,checked_at) VALUES(?,?,?,?,?)");for(let[a,c]of Object.entries(i.plugins??{}))s.run(e,a,c.last_updated??null,c.etag??null,c.checked_at??null)}function oQn(t,e){xut(t,"user",Nh(e,dy)),Vxe(t,"user",Nh(e,py));let n=Nh(e,s9);if(RC(n))for(let i of nQn(n,{withFileTypes:!0})){if(!i.isDirectory()||!Dxe.test(i.name))continue;let o=i.name,s=Nh(n,o),a=Nh(s,"profile.json");if(!RC(a))throw new Error(`legacy profile manifest is missing: ${a}`);let c=iK(a);if(!c||typeof c!="object"||!Array.isArray(c.projects)||typeof c.name!="string"||typeof c.created_at!="string")throw new Error(`legacy profile manifest is malformed: ${a}`);ce(t,"INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json) VALUES(?,?,?,?,?,?,?,?)").run(o,c.name,c.created_at,c.last_used_at??null,c.paused_at??null,c.default_kind??null,c.grantee??null,JSON.stringify(c.metadata??{})),ce(t,"INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)").run(`profile:${o}`,"profile",Nf(KM(c.grantee??"app:terminal",o).dir),o);let u=ce(t,"INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)"),l=ce(t,"INSERT INTO legacy_project_caps(profile_id,path,memory) VALUES(?,?,?)");c.projects.forEach((d,p)=>{u.run(o,d.path,p),d.memory!==void 0&&d.memory!=="content"&&l.run(o,d.path,d.memory)}),xut(t,`profile:${o}`,Nh(s,dy)),Vxe(t,`profile:${o}`,Nh(s,py))}let r=Nh(e,"profile-defaults.json");if(RC(r)){let i=iK(r);if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`legacy profile defaults are malformed: ${r}`);let o=ce(t,"INSERT INTO profile_defaults(directory,profile_id) VALUES(?,?)");for(let[s,a]of Object.entries(i)){if(typeof a!="string")throw new Error(`legacy profile default is malformed: ${r}`);o.run(s,a)}}}var iQn,Eut=h(()=>{"use strict";qt();iQn=Jt(Z0(),1);Wa();rK();TC();Rb();Vi();kxe();TC()});function JQ(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Kxe(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function hy(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function Cut(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function _ut(t,e){let n=Cut(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function Sut(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function lQn(){let t=[];for(let e of Object.values(Iut))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var vut,sQn,aQn,XQ,cQn,Iut,uQn,H1i,Tut=h(()=>{"use strict";Wa();vut=[!1,"notify","apply"],sQn=[0,1,6,12,24,48,72,168],aQn=[1,2,3,4,5,6,8,10,12],XQ="openai-codex";cQn=[1,2,3,4,5,6],Iut={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=JQ(vut,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=JQ(vut,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=Kxe(sQn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=Cut(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=Kxe(aQn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=_ut(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=hy(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=hy(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=hy(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=hy(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:hC.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=JQ(hC,t.whip_message_mode,e)},setFromString:(t,e)=>hC.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${hC.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:gC.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=JQ(gC,t.mouse_mode_default,e)},setFromString:(t,e)=>gC.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${gC.join("|")}`}},live_cycles:{surface:"settings",setting:{key:"live_cycles",label:"Live cycles",description:"Trailing refresh cycles rendered at full fidelity; older cycles condense to text.",valueConstraint:"integer >= 1",applies:"Applies on the next attach.",group:"display",order:50,format:t=>String(t.live_cycles),cycle:(t,e)=>{t.live_cycles=Kxe(cQn,t.live_cycles,e)},setFromString:(t,e)=>{let n=_ut(e,"live_cycles");return typeof n=="string"?n:(t.live_cycles=n,null)}}},condensed_history:{surface:"settings",setting:{key:"condensed_history",label:"Condensed history",description:"Messages retained from condensed cycles. Tool calls are never kept.",valueConstraint:yC.join("|"),applies:"Applies on the next attach.",group:"display",order:60,format:t=>t.condensed_history,cycle:(t,e)=>{t.condensed_history=JQ(yC,t.condensed_history,e)},setFromString:(t,e)=>yC.includes(e)?(t.condensed_history=e,null):`condensed_history must be one of: ${yC.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=hy(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},fold_finished_tools:{surface:"settings",setting:{key:"fold_finished_tools",label:"Fold finished tools",description:"Fold every settled tool call to its call line. Toggle live with /fold-tools.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.fold_finished_tools?"on":"off",cycle:t=>{t.fold_finished_tools=!t.fold_finished_tools},setFromString:(t,e)=>{let n=hy(e,"fold_finished_tools");return typeof n=="string"?n:(t.fold_finished_tools=n,null)}}},summarize_tool_calls:{surface:"settings",setting:{key:"summarize_tool_calls",label:"Summarize tool calls",description:"Replace completed folded tool-call groups with a one-line broker summary when available.",valueConstraint:"true|false",applies:"Applies when the next visible message closes a tool-call group.",group:"display",order:35,format:t=>t.summarize_tool_calls?"on":"off",cycle:t=>{t.summarize_tool_calls=!t.summarize_tool_calls},setFromString:(t,e)=>{let n=hy(e,"summarize_tool_calls");return typeof n=="string"?n:(t.summarize_tool_calls=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=hy(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},consolidate_replies:{surface:"settings",setting:{key:"consolidate_replies",label:"Consolidate replies",description:"Experiment: show one rewritten agent reply per message you type, with the working folded behind it (/show-working).",valueConstraint:"true|false",applies:"Applies on the next attach; the broker reads it per turn.",group:"display",order:36.5,format:t=>t.consolidate_replies?"on":"off",cycle:t=>{t.consolidate_replies=!t.consolidate_replies},setFromString:(t,e)=>{let n=hy(e,"consolidate_replies");return typeof n=="string"?n:(t.consolidate_replies=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${XQ}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[XQ]?.fastMode?"on":"off",cycle:t=>{let e=Sut(t,XQ);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=hy(e,`providerOptions.${XQ}.fastMode`);return typeof n=="string"?n:(Sut(t,XQ).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},uQn=Object.keys(Iut);H1i=lQn()});function ZQ(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function l1(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function u1(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${l1(t)}`);return t.trim()}}function Zxe(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${l1(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${l1(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${l1(i)}`);s={kind:u.kind.trim(),...u1(u.description,"description",e,o)===void 0?{}:{description:u1(u.description,"description",e,o)},...u1(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:u1(u.useWhen,"useWhen",e,o)},...u1(u.doc,"doc",e,o)===void 0?{}:{doc:u1(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${l1(i)}`);let a=s.kind;if(!pQn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${l1(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(fQn.has(a)||dQn.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=ZQ(a);if(oK.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function Rut(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=ZQ(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function Dut(t,e){return e.find(n=>n.kind===t)}var Yxe,dQn,pQn,fQn,kut,Jxe,oK,Xxe,eW=h(()=>{"use strict";Yxe=["options","text","table","cards","chart"],dQn=["page","step"],pQn=/^[a-z][a-z0-9-]{0,63}$/,fQn=new Set(Yxe),kut=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];Jxe=Object.fromEntries(kut.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),oK=new Set(kut.map(t=>t.tag)),Xxe=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as Put,join as mQn}from"node:path";import{existsSync as hQn,mkdirSync as Z1i,statSync as eOi}from"node:fs";function Lut(t){return mQn(t,dy)}function gQn(t,e){return fc(`${t}.lock`,()=>e(t),{timeoutError:()=>new Error(`timed out waiting for config lock: ${t}`)})}function tbe(t){let e=Nf(t),n=Nf(Ga());if(e===n)return{store:Dh(n),key:"user",kind:"user",root:n};if(Put(e)===".crouter")return but({kind:"project",root:e}),{store:e1(e),key:"project",kind:"project",root:e};for(let r of X9()){let i=Nf(J9(r.profileId));if(e===i)return{store:Dh(n),key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function But(t){if(Put(t)===".crouter"){let e;try{e=Nf(t)}catch(n){if(n.code==="ENOENT")return null;throw n}if(e!==Nf(Ga()))return xC(Lut(t))}return tK(tbe(t))}function yQn(t,e){let n=tbe(t);return n.kind==="project"?gQn(Lut(n.root),r=>{let i=e(xC(r)??{});return m9(r,i.next,{createParent:!1}),i.value}):iut(n,r=>e(r))}function Go(t){let e=AQn[wQn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=Oh(t);return n?xQn(n):c9()}function xQn(t){let e=But(t);return e?jQn(e):c9()}function nbe(t){let e=Oh(t);if(!e)return _we();try{return out(tbe(e))}catch(n){if(t==="project"&&!hQn(e))return _we();throw n}}function rbe(t,e){let n=Hxe(t);return yQn(n,r=>{let i=e(r);return{value:i,next:i}})}function bQn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function d1(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&fC.has(e)&&EQn.has(e)))]:[]}function _Qn(t,e=Ewe()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function $ut(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function ebe(){return Object.create(null)}function sK(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function SQn(t){let e=ebe();for(let[n,r]of Object.entries(t??{}))sK(e,n,r);return e}function tW(t,e){qa({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function CQn(t,e={}){let n=SQn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){tW(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){tW(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!$ut(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){tW(r,c);continue}sK(n,r,a)}return n}function IQn(t){let e=ebe(),n=ebe();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){tW(r,"route must include family, credentialSource, providerId, and models");continue}let o=vQn.filter(s=>i.models[s]===void 0);if(o.length>0){tW(r,`incomplete route; missing strengths: ${o.join(", ")}`),sK(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}sK(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function TQn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>$ut(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function kQn(t){return t!==""&&t.replace(/\*/g,"")===""}function RQn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(kQn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function DQn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function OQn(t,e){if(e==="bin"&&MQn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!Mut.test(t))return`${e}.${t} is not a safe bare command name (expected ${Mut.source})`}function Fut(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))OQn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function NQn(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(Out.test(n)||i.push(`action name must match ${Out.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function PQn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(NQn(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function LQn(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function BQn(t,e=bwe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=LQn(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function aK(){let t=[{origin:"config.json",components:Go("user").page_components}],e=Oh("user");if(e!==null){let n=c1("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:Zxe(r.manifest.page_components,i)})}}return Rut(t)}function $Qn(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function FQn(t,e=xwe()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=$Qn(o);s!==null&&(n[i]=s)}}return{targets:n}}function Nut(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function nW(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function UQn(t,e){let n=t!==null&&typeof t=="object"?t:{},r=nW(n.warning,e.warning),i=nW(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function QQn(t,e){return{unattendedParkMs:nW((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function WQn(t){if(!Array.isArray(t))return[...a9];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...a9]}function HQn(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function jQn(t){let e=c9(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:Nut(o?.crtr,e.auto_update.crtr),content:Nut(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=nW(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=UQn(t.brokerThresholds,e.brokerThresholds),f=QQn(t.lifecycle,e.lifecycle),m=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,g=t.working_gerunds===void 0?[...e.working_gerunds]:Lst(t.working_gerunds),y=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,w=Zxe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,E=WQn(t.whip_messages),_=hC.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,C=gC.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,I=nW(t.live_cycles,e.live_cycles),D=yC.includes(t.condensed_history)?t.condensed_history:e.condensed_history,O=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,k=typeof t.fold_finished_tools=="boolean"?t.fold_finished_tools:e.fold_finished_tools,P=typeof t.summarize_tool_calls=="boolean"?t.summarize_tool_calls:e.summarize_tool_calls,U=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,q=typeof t.consolidate_replies=="boolean"?t.consolidate_replies:e.consolidate_replies,G=bQn(t.keybindings),W=d1(t.tmux_passthrough),me=_Qn(t.modelLadders),K=DQn(t.providerOptions,e.providerOptions),Re=IQn(CQn(t.modelRoutes)),Ue=Re.complete,Xe=TQn(t.modelRouting,void 0),It=BQn(t.kinds),Yt=FQn(t.remoteCanvas),Qe=HQn(t.api,e.api),J=t.paths;if(J?.user_files!==void 0&&(typeof J.user_files!="string"||!J.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Pe=t.store,tt=t.runtime;if(tt?.person_uids!==void 0&&(!Array.isArray(tt.person_uids)||!tt.person_uids.every(H=>Number.isSafeInteger(H)&&H>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let Wt=RQn(t.spawnEnv,e.spawnEnv?.allow),Ht=Fut(t.bin),Ft=PQn(t.humanActions);return{bin:Ht,humanActions:Ft,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:f,completion_bell:m,working_gerunds:g,whip_mode:y,page_components:w,page_surface:x,whip_messages:E,whip_message_mode:_,mouse_mode_default:C,live_cycles:I,condensed_history:D,bash_tool_purpose:O,fold_finished_tools:k,summarize_tool_calls:P,detailed_tool_recaps:U,consolidate_replies:q,keybindings:G,tmux_passthrough:W,modelLadders:me,providerOptions:K,...Object.keys(Ue).length>0?{modelRoutes:Ue}:{},...Object.keys(Re.legacy).length>0?{legacyModelRoutes:Re.legacy}:{},...Xe!==void 0?{modelRouting:Xe}:{},kinds:It,remoteCanvas:Yt,api:Qe,...J?{paths:J}:{},...Pe?{store:Pe}:{},...tt?{runtime:tt}:{},spawnEnv:Wt}}function Uut(t){return But(t)}function Qut(t){let e=Oh(t);return e?Uut(e):null}var AQn,wQn,EQn,vQn,Mut,MQn,Out,zo=h(()=>{"use strict";_o();Wa();r9();ds();Of();qo();xp();YQ();vu();Rb();Eut();Gxe();wp();Tut();o9();eW();AQn=globalThis,wQn=Symbol.for("crtr.broker.config-snapshot");EQn=new Set(gp.filter(TQ).map(t=>t.id));vQn=["ultra","strong","medium","light"];Mut=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,MQn=new Set(["crtr","crtrd"]);Out=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/});function KQn(t){let e=t.match(/^((?:[CMS]-)+)(.+)$/i);return e===null?t:`${e[1].split("-").filter(Boolean).map(r=>r.toUpperCase()==="C"?"ctrl":r.toUpperCase()==="M"?"alt":"shift").join("+")}+${e[2]}`}function abe(t){let e=KQn(t.trim());if(e==="")throw new Gc("a stroke cannot be empty");let n,r;if(e==="+")n="+",r=[];else if(e.endsWith("++"))n="+",r=e.slice(0,-2).split("+");else{let c=e.split("+");if(c.some(u=>u===""))throw new Gc(`invalid stroke "${t}"`);n=c.pop(),r=c}let i=r.map(c=>c.toLowerCase());if(i.some(c=>!GQn.has(c)))throw new Gc(`unsupported modifier in "${t}"`);let o=i.map(c=>c==="meta"?"alt":c);if(new Set(o).size!==o.length)throw new Gc(`duplicate modifier in "${t}"`);let s=VQn[n.toLowerCase()]??n;if(s.length===1&&s>="A"&&s<="Z"?(s=s.toLowerCase(),o.includes("shift")||o.push("shift")):s.length!==1&&(s=s.toLowerCase()),!(s.length===1&&s.charCodeAt(0)>=32&&s.charCodeAt(0)<=126)&&!zQn.has(s))throw new Gc(`unsupported key "${n}"`);return[...qQn.filter(c=>o.includes(c)),s].join("+")}function cbe(t,e){let n=t.trim().split(/\s+>\s+/);if(n.length>2)throw new Gc("a gesture may contain at most two strokes");let r=n.map(abe);if(r.length===2&&e?.inputKind!=="tmux-sequence")throw new Gc("two-stroke sequences are supported only by tmux sequence actions");if(e?.inputKind==="tmux-sequence"&&r.length!==2)throw new Gc("this action requires a two-stroke tmux sequence");if(e?.inputKind==="tmux-menu-selector"){if(r.length!==1)throw new Gc("a menu selector must be one stroke");let o=r[0].split("+"),s=o.at(-1),a=o.slice(0,-1);if(s.length!==1&&s!=="space"||a.some(c=>c!=="shift"))throw new Gc("a menu selector must be one printable character")}if(e?.inputKind==="tmux-global-action"){if(r.length!==1)throw new Gc("a global menu shortcut must be one stroke");let i=r[0].split("+").slice(0,-1);if(!i.includes("ctrl")&&!i.includes("alt"))throw new Gc("a global menu shortcut must include Ctrl or Alt")}return r.join(" > ")}function YQn(t,e){if(!Array.isArray(t))throw new Gc("the override must be an array of gesture strings");let n=[];for(let r of t){if(typeof r!="string")throw new Gc("every override entry must be a gesture string");let i=cbe(r,e);n.includes(i)||n.push(i)}return Object.freeze(n)}function JQn(t,e){return t.contexts.some(n=>e.contexts.includes(n))}function ibe(t){return t.contexts.includes("tmux.root")}function Wut(t){return!ibe(t)&&t.inputKind!=="tmux-menu-selector"&&t.inputKind!=="tmux-sequence"}function p1(t){return t.split(" > ")[0]}function XQn(t,e,n,r){let i=e.includes(" > "),o=r.includes(" > ");if(JQn(t,n))return i&&o?e===r:i||o?p1(e)===p1(r):e===r;let s=ibe(t),a=ibe(n);return!s&&!a?!1:s&&a&&i&&o?e===r:s&&a?p1(e)===p1(r):s&&Wut(n)?p1(e)===r:a&&Wut(t)?e===p1(r):!1}function obe(t){return Object.freeze(t.defaults.map(e=>cbe(e,t)))}function rW(t,e,n,r,i){return Object.freeze({severity:"error",code:t,message:e,offendingValue:n,...r?{bindingId:r}:{},...i?{relatedBindingIds:Object.freeze([...i])}:{}})}function ZQn(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];for(let i=n+1;i<t.length;i+=1){let o=t[i];for(let s of r.gestures){let a=o.gestures.find(c=>XQn(r.definition,s,o.definition,c));if(a!==void 0){e.push([r,o,s.includes(" > ")?s:a]);break}}}}return e}function eWn(t,e,n){return t.some(r=>r.definition.safety===n&&r.gestures.length>0&&r.definition.contexts.includes(e))}function Hut(t,e){for(;;){let n=new Set;for(let[r,i,o]of ZQn(t)){if(r.source==="user"&&n.add(r),i.source==="user"&&n.add(i),r.source==="default"&&i.source==="default")throw new Error(`keybinding catalog default collision: ${r.definition.id} / ${i.definition.id} (${o})`);e.push(rW("collision",`${r.definition.id} and ${i.definition.id} both claim ${o} in overlapping contexts`,o,r.source==="user"?r.definition.id:i.definition.id,[r.definition.id,i.definition.id]))}if(n.size===0)return;for(let r of n)r.gestures=obe(r.definition),r.source="default"}}function jut(t=void 0){let e=[],n={};t!==void 0&&(t===null||typeof t!="object"||Array.isArray(t)?e.push(rW("invalid-keybindings","keybindings must be an object keyed by catalog binding ID",t)):n=t);for(let[a,c]of Object.entries(n))fC.has(a)||e.push(rW("unknown-binding",`unknown keybinding ID: ${a}`,c,a));let r=gp.map(a=>{let c=obe(a);if(!Object.hasOwn(n,a.id))return{definition:a,gestures:c,source:"default"};let u=n[a.id];try{return{definition:a,gestures:YQn(u,a),source:"user",rawOverride:u}}catch(l){let d=l instanceof Error?l.message:String(l);return e.push(rW("invalid-override",`${a.id}: ${d}`,u,a.id)),{definition:a,gestures:c,source:"default"}}});Hut(r,e);for(let a of gwe){if(eWn(r,a.context,a.capability))continue;let c=r.filter(u=>u.source==="user"&&u.definition.safety===a.capability&&u.definition.contexts.includes(a.context));e.push(rW("unreachable",`${a.context} must retain an enabled ${a.capability} binding`,c.map(u=>u.rawOverride),c[0]?.definition.id,c.map(u=>u.definition.id)));for(let u of c)u.gestures=obe(u.definition),u.source="default"}Hut(r,e);let i=r.map(a=>{let c=Object.freeze({definition:a.definition,gestures:a.gestures,source:a.source});return[a.definition.id,c]}),o=new sbe(i),s={bindings:o,diagnostics:Object.freeze(e),get(a){let c=o.get(a);if(c===void 0)throw new Error(`unknown crouter keybinding ID: ${a}`);return c},gestures(a){return this.get(a).gestures}};return Object.freeze(s)}function Nb(){let t=Qut("user");return Object.freeze({bindings:jut(t?.keybindings),tmuxPassthrough:Object.freeze(d1(t?.tmux_passthrough))})}function iW(){return Nb().bindings}var qQn,GQn,zQn,VQn,Gc,sbe,f1=h(()=>{"use strict";r9();zo();qQn=["ctrl","alt","shift"],GQn=new Set(["ctrl","alt","shift","meta"]),zQn=new Set(["enter","escape","tab","backspace","delete","space","up","down","left","right","pageup","pagedown","home","end"]),VQn={return:"enter",esc:"escape"},Gc=class extends Error{constructor(e){super(e),this.name="GestureSyntaxError"}};sbe=class{#e;constructor(e){this.#e=new Map(e)}get size(){return this.#e.size}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}entries(){return this.#e.entries()}keys(){return this.#e.keys()}values(){return this.#e.values()}forEach(e,n){for(let[r,i]of this.#e)e.call(n,i,r,this)}[Symbol.iterator](){return this.#e[Symbol.iterator]()}}});function qut(t){let e,n;if(t==="+")e="+",n=[];else if(t.endsWith("++"))e="+",n=t.slice(0,-2).split("+");else{let i=t.split("+");e=i.pop(),n=i}let r=n.map(i=>i[0].toUpperCase()+i.slice(1));return r.push(tWn[e]??(e.length===1&&n.length>0?e.toUpperCase():e)),r.join("+")}function Pb(t){return t.split(" > ").map(qut).join(" then ")}function la(t,e){let n=t.gestures(e);return n.length===0?"Disabled":n.map(Pb).join(" / ")}function DC(t){if(t.length===2&&t[0]==="\x1B"&&/[A-Z]/.test(t[1]))return`\x1B[${t.charCodeAt(1)};4u`;let e=/^\x1b\[(\d+);3u$/.exec(t);if(e!==null){let n=Number(e[1]);if(n>=65&&n<=90)return`\x1B[${n};4u`}return t}function MC(t,e,n,r){return t.gestures(e).some(i=>!i.includes(" > ")&&r(n,i))}var tWn,cK=h(()=>{"use strict";f1();tWn={enter:"Enter",escape:"Esc",tab:"Tab",backspace:"Backspace",delete:"Delete",space:"Space",up:"Up",down:"Down",left:"Left",right:"Right",pageup:"PageUp",pagedown:"PageDown",home:"Home",end:"End"}});function Gut(t=iW()){let e=t.gestures(nWn);return e.length>0?e.map(Pb).join(" / "):null}function m1(t){let e=Gut(t);return e!==null?`${e} inbox`:"crtr human list"}var nWn,zut=h(()=>{"use strict";cK();f1();nWn="crtr.tmux.inbox.toggle"});function oWn(t){let e=t.split("+"),n=e.at(-1);return e.includes("shift")&&/[a-z]/.test(n)?n.toUpperCase():n==="space"?" ":n}function Vut(t=iW()){let e=t.gestures(rWn),n=t.gestures(iWn);return e.length===0||n.length===0?null:`${e.map(Pb).join(" / ")} ${oWn(n[0])}`}function uK(t){let e=Vut(t);return e!==null?`${e} to background`:null}var rWn,iWn,Kut=h(()=>{"use strict";cK();f1();rWn="crtr.tmux.menu.open",iWn="crtr.tmux.menu.background-bash"});function oW(t){return`${sWn}${t}${aWn}`}function ube(t){let e;for(let{actionId:n}of gy){let r=oW(n),i=t.indexOf(r);i>=0&&(e===void 0||i<e.index)&&(e={actionId:n,encoded:r,index:i})}if(e!==void 0)return{actionId:e.actionId,remaining:t.slice(0,e.index)+t.slice(e.index+e.encoded.length)}}var gy,sWn,aWn,ROi,Yut=h(()=>{"use strict";gy=[{menuId:"crtr.tmux.menu.attach.detach",actionId:"crtr.attach.detach"},{menuId:"crtr.tmux.menu.attach.clear-or-detach",actionId:"crtr.attach.clear-or-detach"},{menuId:"crtr.tmux.menu.attach.graph.toggle",actionId:"crtr.attach.graph.toggle"},{menuId:"crtr.tmux.menu.attach.help.toggle",actionId:"crtr.attach.help.toggle"},{menuId:"crtr.tmux.menu.attach.inbox.toggle",actionId:"crtr.attach.inbox.toggle"},{menuId:"crtr.tmux.menu.attach.inbox-strip",actionId:"crtr.attach.inbox-strip"},{menuId:"crtr.tmux.menu.attach.model-ladder.next",actionId:"crtr.attach.model-ladder.next"},{menuId:"crtr.tmux.menu.attach.model-ladder.previous",actionId:"crtr.attach.model-ladder.previous"},{menuId:"crtr.tmux.menu.attach.command.inspect",actionId:"crtr.attach.command.inspect"},{menuId:"crtr.tmux.menu.attach.file-review",actionId:"crtr.attach.file-review"},{menuId:"crtr.tmux.menu.attach.profile-files",actionId:"crtr.attach.profile-files"},{menuId:"crtr.tmux.menu.attach.search",actionId:"crtr.attach.search"},{menuId:"crtr.tmux.menu.attach.whip",actionId:"crtr.attach.whip"}],sWn="\x1B_crtr;",aWn="\x1B\\",ROi=new Set(gy.map(({actionId:t})=>t))});var Jut=h(()=>{"use strict";zo();f1()});var cl=h(()=>{"use strict";r9();f1();cK();zut();Kut();Yut();Jut()});import{readFileSync as uWn}from"node:fs";function lbe(){try{let t=uWn("/proc/sys/kernel/random/boot_id","utf8").trim();return t.length>0?t:null}catch{return null}}var Xut=h(()=>{"use strict"});import{spawn as tNi,spawnSync as pbe}from"node:child_process";import{readFileSync as fbe,readdirSync as lWn,statSync as dWn}from"node:fs";function pWn(t){if(hbe())return EWn(t);try{let e=pbe("ps",["-o","stat=","-p",String(t)],{encoding:"utf8",timeout:2e3});if(e.error!=null||e.signal!=null||typeof e.stdout!="string"||typeof e.stderr=="string"&&e.stderr.trim()!=="")return"unknown";let n=e.stdout.trim();return n===""?"gone":n.charAt(0)==="Z"?"zombie":"live"}catch{return"unknown"}}function Bf(t){if(t==null)return!1;try{process.kill(t,0)}catch(n){return n.code==="EPERM"}let e=pWn(t);return e!=="zombie"&&e!=="gone"}function tlt(t){if(t==null)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function elt(t){let e=t.indexOf("#");if(e===-1)return{base:t,ticks:void 0};let n=t.slice(e+1);return{base:t.slice(0,e),ticks:/^\d+$/.test(n)?n:void 0}}function mbe(t,e){let n=elt(t),r=elt(e);return n.ticks!==void 0&&r.ticks!==void 0?Zut.test(n.base)&&Zut.test(r.base)?n.base===r.base&&n.ticks===r.ticks:n.ticks===r.ticks:n.base===r.base}function nlt(t,e="SIGTERM"){if(!(!Number.isInteger(t)||t<=0))try{process.kill(-t,e)}catch{}}function fWn(t){try{let e=fbe(`/proc/${t}/stat`,"utf8"),n=e.lastIndexOf(")");if(n===-1)return null;let i=e.slice(n+2).trim().split(/\s+/)[19];return i!==void 0&&/^\d+$/.test(i)?i:null}catch{return null}}function hWn(t,e=Date.now,n=mWn){let r=null,i=0;return()=>{if(r!==null)return r;let o=e();if(o<i)return null;let s=t();return s!==null?r=s:(i=o+n,null)}}function gWn(t,e,n={}){let r=n.ticks!==void 0?n.ticks:fWn(t);return r===null?e:`${(n.bootId!==void 0?n.bootId:rlt())??e}#${r}`}function yWn(t){let e=t.indexOf("("),n=t.lastIndexOf(")");if(e===-1||n===-1||n<e)return null;let r=t.slice(n+2).trim().split(/\s+/),i=r[0],o=Number(r[1]),s=r[19];return i===void 0||i===""||!Number.isInteger(o)||o<0||s===void 0||!/^\d+$/.test(s)?null:{comm:t.slice(e+1,n),state:i,ppid:o,starttime:s}}function AWn(t,e){let n=t.replace(/\0+$/,"").split("\0").join(" ").trim();return n===""?`[${e}]`:n}function hbe(){return dbe===void 0&&(dbe=process.platform==="linux"&&lbe()!==null&&wWn(process.pid)!==null),dbe}function wWn(t,e=h1){let n=lK(t,e);return n==="unreadable"||n==="denied"||n==="gone"?null:n}function lK(t,e=h1){let n;try{n=fbe(`${e.root}/${t}/stat`,"utf8")}catch(r){return ilt(r)}return yWn(n)??"unreadable"}function ilt(t){let e=t.code;return e==="ENOENT"||e==="ESRCH"?"gone":e==="EACCES"||e==="EPERM"?"denied":"unreadable"}function xWn(t,e){let n=e.selfUid!==void 0?e.selfUid():process.getuid?.()??null;if(n===null)return"own-or-unknown";try{return dWn(`${e.root}/${t}`).uid===n?"own-or-unknown":"foreign"}catch(r){return ilt(r)==="gone"?"gone":"own-or-unknown"}}function bWn(t,e,n){return t==="gone"?"skip":t==="unreadable"||xWn(e,n)==="own-or-unknown"?"fail":"skip"}function olt(t,e=h1){let n=e.bootId();return n===null?null:`${n}#${t.starttime}`}function EWn(t,e=h1){let n=lK(t,e);return n==="gone"?"gone":n==="denied"||n==="unreadable"?"unknown":n.state==="Z"||n.state==="X"?"zombie":"live"}function _Wn(t,e=h1){let n=new Map;for(let r of t){let i=lK(r,e);if(i==="gone")continue;if(i==="unreadable"||i==="denied")return null;let o=olt(i,e);if(o===null)return null;n.set(r,o)}return n}function vWn(t,e,n,r,i){let o=olt(r,t);if(o===null)return!1;e.processes.set(n,{zombie:r.state==="Z"||r.state==="X",identity:o,command:AWn(i,r.comm)});let s=e.childrenOf.get(r.ppid);return s===void 0?e.childrenOf.set(r.ppid,[n]):s.push(n),!0}function SWn(t){try{return lWn(t).filter(e=>/^\d+$/.test(e)).map(Number).filter(e=>e>0)}catch{return null}}function CWn(t=h1){let e=SWn(t.root);if(e===null)return null;let n={processes:new Map,childrenOf:new Map};for(let r of e){let i=lK(r,t);if(i==="gone"||i==="denied"||i==="unreadable"){if(bWn(i==="gone"?"gone":i,r,t)==="skip")continue;return null}let o="";try{o=fbe(`${t.root}/${r}/cmdline`,"utf8")}catch(s){let a=s.code;if(a==="ENOENT"||a==="ESRCH")continue}if(!vWn(t,n,r,i,o))return null}return n}function gbe(){if(hbe()){let t=CWn();if(t===null)return null;let e=new Map;for(let[n,r]of t.childrenOf)for(let i of r)e.set(i,n);return[...t.processes].map(([n,r])=>({pid:n,ppid:e.get(n)??0,command:r.command}))}try{let t=pbe("ps",["-ax","-o","pid=,ppid=,command="],{encoding:"utf8",timeout:2e3,maxBuffer:8388608});if(t.status!==0||typeof t.stdout!="string")return null;let e=[];for(let n of t.stdout.split(`
234
234
  `)){let r=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);r!==null&&e.push({pid:Number(r[1]),ppid:Number(r[2]),command:r[3].trim()})}return e}catch{return null}}function ybe(t){let e=t.filter(r=>Number.isInteger(r)&&r>0),n=new Map;if(e.length===0)return n;if(hbe())return _Wn(e);try{let r=pbe("ps",["-o","pid=,lstart=","-p",e.join(",")],{encoding:"utf8",timeout:2e3});if(r.error!=null||r.signal!=null||typeof r.stdout!="string"||typeof r.stderr=="string"&&r.stderr.trim()!=="")return null;for(let i of r.stdout.split(`
235
235
  `)){let o=i.trim();if(o==="")continue;let s=o.indexOf(" ");if(s===-1)continue;let a=Number(o.slice(0,s)),c=o.slice(s+1).trim();!Number.isInteger(a)||a<=0||c===""||n.set(a,gWn(a,c))}return n}catch{return null}}var Zut,mWn,rlt,dbe,h1,ew=h(()=>{"use strict";Xut();Zut=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;mWn=6e4;rlt=hWn(lbe);h1={root:"/proc",bootId:()=>rlt()}});function kn(t){return`'${t.replace(/'/g,"'\\''")}'`}var g1=h(()=>{"use strict"});import{execFile as ult,spawnSync as IWn}from"node:child_process";function Ur(t){let e=IWn("tmux",t,{encoding:"utf8"});return{ok:e.status===0,stdout:(e.stdout??"").trim(),stderr:(e.stderr??"").trim()}}function slt(t,e){return Ur(t===void 0||t===""?e:["-S",t,...e])}function da(){return process.env.TMUX!==void 0&&process.env.TMUX!==""}function yy(){if(!da())return null;let t=Ur(["display-message","-p","#{session_name} #{window_id} #{pane_id}"]);if(!t.ok)return null;let[e,n,r]=t.stdout.split(" ");return{session:e,window:n,pane:r}}function wbe(t){let e=[];for(let[n,r]of Object.entries(t))e.push("-e",`${n}=${r}`);return e}function sW(t){let e=Ur(["new-window","-d","-a","-P","-F","#{window_id} #{pane_id}","-t",`${t.session}:`,"-n",t.name,"-c",t.cwd,...wbe(t.env),t.command]);if(!e.ok)return null;let[n,r]=e.stdout.split(" ");return n===void 0||n===""||r===void 0||r===""?null:{window:n,pane:r}}function OC(t,e){let n=Ur(["split-window","-d",...e.vertical===!0?[]:["-h"],...e.before===!0?["-b"]:[],...e.size!==void 0?["-l",String(e.size)]:[],"-P","-F","#{pane_id}","-t",t,"-c",e.cwd,...wbe(e.env),e.command]);return n.ok&&n.stdout!==""?n.stdout:null}function xbe(t,e){return Ur(["rename-window","-t",t,e]).ok}function tw(t){return Ur(["kill-pane","-t",t]).ok}function bbe(t,e,n){return new Promise(r=>{try{ult("tmux",TWn(t,e,n),o=>r(o===null)).stdin?.end()}catch{r(!1)}})}function TWn(t,e,n){return["display-popup","-E","-t",t,"-d",e,"-w","90%","-h","90%",n]}function Ebe(t){let e=Ur(["display-message","-p","-t",t,"#{window_id}"]);return e.ok&&e.stdout!==""?e.stdout:null}function Lb(t){let e=Ur(["display-message","-p","-t",t,"#{session_name} #{window_id}"]);if(!e.ok)return null;let n=/^(.*) (@\d+)$/.exec(e.stdout);return n===null||n[1]===""?null:{session:n[1],window:n[2]}}function dK(t){let e=Ur(["display-message","-p","-t",t,"#{window_index}"]);return!e.ok||!/^\d+$/.test(e.stdout)?null:Number.parseInt(e.stdout,10)}function Bb(t){let e=Ur(["display-message","-p","-t",t,"#{pane_id}"]);return e.ok&&e.stdout===t}function pK(t){let e=Ur(["display-message","-p","-t",t,"#{pane_id} #{pane_dead}"]);return e.ok&&e.stdout===`${t} 0`}function _be(){let t=Ur(["list-panes","-a","-F","#{pane_id}"]);return t.ok?new Set(t.stdout.split(`
236
236
  `).filter(e=>e!=="")):null}function fK(t){let e=Ur(["display-message","-p","-t",t,"#{pane_width} #{pane_height}"]);if(!e.ok)return null;let[n,r]=e.stdout.split(" "),i=Number.parseInt(n,10),o=Number.parseInt(r,10);return Number.isInteger(i)&&i>0&&Number.isInteger(o)&&o>0?{cols:i,rows:o}:null}function vbe(t,e,n=4e3){let r=i=>{let o=["display-message",...i?["-C"]:[],"-d",String(n)];return e!==void 0&&e!==""&&o.push("-t",e),o.push(t),o};return Ur(r(!0)).ok||Ur(r(!1)).ok}function Ay(t,e,n){return Ur(["set-option","-p","-t",t,e,n]).ok}function Ph(t,e){let n=Ur(["show-options","-p","-t",t,"-q","-v",e]);return n.ok?n.stdout:void 0}function Sbe(t){if(t==="")return;let e=Math.max(Date.now(),alt+1);alt=e,clt=clt.then(()=>new Promise(n=>{try{ult("tmux",["set-option","-p","-t",t,aW,String(e)],()=>n())}catch{n()}}))}function kWn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Abe(t,e){let n=t.replace(/^"|"$/g,"");return new RegExp(`(?:^|\\s)surface\\s+attach\\s+to\\s+${kWn(e)}(?:\\s|$)`).test(n)}function RWn(){let t=gbe();if(t===null)return null;let e=new Map,n=new Map;for(let{pid:r,ppid:i,command:o}of t){n.set(r,o);let s=e.get(i)??[];s.push(r),e.set(i,s)}return{childrenOf:e,commandOf:n}}function DWn(t,e,n){let r=[e];for(;r.length>0;){let i=r.pop();if(Abe(t.commandOf.get(i)??"",n))return!0;let o=t.childrenOf.get(i);o!==void 0&&r.push(...o)}return!1}function Cbe(t){let e=slt(t,["list-panes","-a","-F","#{pane_id} #{session_name} #{@crtr_node} #{@crtr_viewer_at}"]);if(!e.ok||e.stdout==="")return[];let n=[],r;for(let i of e.stdout.split(`
@@ -1876,7 +1876,7 @@ ${r}`}var Fkn=h(()=>{"use strict"});function Ukn(t){try{let e=JSON.parse(t);retu
1876
1876
  Invocation: \`${c.invocation.replaceAll("`","\\`")}\`
1877
1877
 
1878
1878
  ${c.content}
1879
- `,"utf8");let C=`if command -v nvim >/dev/null 2>&1; then exec ${DU("readonly",[_])}; else printf 'nvim is required to inspect loaded commands. Install Neovim and retry.\\n'; printf 'Press Enter to close.'; read _; fi`;b_i("tmux",["display-popup","-E","-w","90%","-h","85%",...bp(),C],()=>__i(E,{recursive:!0,force:!0}))}}}var iDn=h(()=>{"use strict";et();cl();Ep();$b();Xet();YYe();Det();kye()});function oDn(t,e,n){let r=e;return{current:()=>r,refresh:()=>{t.canvasSource.getNode(t.nodeId).then(i=>{n.isTornDown()||i===null||(r=i,n.onChanged())}).catch(()=>{})}}}var sDn=h(()=>{"use strict"});function cDn(t,e,n=T_i){let r,i=n.ownerId(),o=()=>{if(r===void 0||r==="")return!0;let s=n.readOption(r,uDn);return s===void 0||s===""?!0:s===i};return{set:()=>{r=n.currentPane(),aDn(r,i,n.writeOption),D_i(t,r,e,n.writeOption),O_i(r,n.writeOption),k_i(t,r,n.writeOption)},stamp:()=>{t||r===void 0||r===""||n.stampAsync(r)},clear:()=>{o()&&(M_i(t,r,n.writeOption),N_i(r,n.writeOption),R_i(t,r,n.writeOption),aDn(r,"",n.writeOption))},pane:()=>r}}function aDn(t,e,n){if(!(t===void 0||t===""))try{n(t,uDn,e)}catch{}}function k_i(t,e,n){if(!(t||e===void 0||e===""))try{n(e,aW,String(Date.now()))}catch{}}function R_i(t,e,n=Ay){if(!(t||e===void 0||e===""))try{n(e,aW,"")}catch{}}function D_i(t,e,n,r=Ay){if(!(t||e===void 0||e===""))try{r(e,"@crtr_node",n)}catch{}}function M_i(t,e,n=Ay){if(!(t||e===void 0||e===""))try{n(e,"@crtr_node","")}catch{}}function O_i(t,e=Ay){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","1")}catch{}}function N_i(t,e=Ay){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","")}catch{}}var T_i,uDn,lDn=h(()=>{"use strict";Ep();T_i={readOption:Ph,writeOption:(t,e,n)=>{Ay(t,e,n)},stampAsync:Sbe,currentPane:()=>process.env.TMUX_PANE??yy()?.pane,ownerId:()=>String(process.pid)};uDn="@crtr_viewer_pid"});import{constants as P_i,accessSync as L_i,existsSync as B_i,mkdtempSync as $_i,readFileSync as F_i,rmSync as zye,statSync as U_i}from"node:fs";import{tmpdir as Q_i}from"node:os";import{delimiter as W_i,join as Vye,resolve as H_i,sep as pDn}from"node:path";import{execFile as dDn,spawnSync as j_i}from"node:child_process";function ott(t,e){let n=new Map(t.map(o=>[o.node_id,o])),r=new Set([e]);for(let o=n.get(e);o?.parent!==null&&o?.parent!==void 0;){let s=o.parent;if(r.has(s))break;r.add(s),o=n.get(s)}let i=[e];for(;i.length>0;){let o=i.pop();for(let s of t)s.parent!==o||r.has(s.node_id)||(r.add(s.node_id),i.push(s.node_id))}return t.filter(o=>r.has(o.node_id)).map(o=>o.node_id)}function fDn(t,e){let n=new Set(ott(t,e));return t.filter(r=>n.has(r.node_id)).map(r=>r.cwd)}function q_i(t){let e=[];for(let n of t)try{e.push(ib(n))}catch{continue}return itt(e)}function G_i(t){try{return U_i(t).isDirectory()}catch{return!1}}function z_i(t,e){let n=[...e==null?[]:[e],...(process.env.PATH??"").split(W_i).filter(Boolean).map(r=>Vye(r,t))];return[...new Set(n)]}function rtt(t,e){for(let n of z_i(t,e)){try{L_i(n,P_i.X_OK)}catch{continue}if(j_i(n,["--version"],{stdio:"ignore"}).status===0)return n}return null}function V_i(t){if(t===null||t==="")return{projects:[],memory:null};try{let{profileId:e,manifest:n}=Lf(t);return{projects:n.projects.map(r=>r.path),memory:J9(e)}}catch{return{projects:[],memory:null}}}function itt(t){let e=new Set,n=[];for(let r of t){let i=H_i(r);e.has(i)||!G_i(i)||(e.add(i),n.push(i))}return n}function K_i(t){return t.filter(e=>!t.some(n=>n!==e&&e.startsWith(n+pDn)))}function J_i(t){try{let e=F_i(t);if(e.length===0)return null;let n=e[e.length-1]===0?e.length-1:e.length;return e.subarray(0,n).toString("utf8")||null}catch{return null}}function mDn(t){let e=rtt("fd",t.fdPath);if(e===null){t.onNotice("fd is required for profile file search");return}let n=rtt("fzf");if(n===null){t.onNotice("fzf is required for profile file search");return}let r=rtt("nvim");if(r===null){t.onNotice("Neovim is required for profile file search");return}let i=V_i(t.profileId),o=itt([t.cwd,...t.nodeDirs,...i.projects]);if(o.length===0){t.onNotice("No profile file-search directories exist");return}let s=K_i(o),a=itt([...i.memory===null?[]:[i.memory]]),c=$_i(Vye(Q_i(),"crtr-profile-files-")),u=Vye(c,"selection"),l=Vye(c,"candidates"),d=q_i(t.nodeIds).filter(g=>!s.some(y=>g===y||g.startsWith(y+pDn))),m=`{ ${[...s.map(g=>`${kn(e)} --type f --hidden --exclude .git . ${kn(g)}`),...d.map(g=>`${kn(e)} --type f --hidden --exclude .git --exclude ${kn("/jobs")} . ${kn(g)}`),...a.map(g=>`${kn(e)} --type f --hidden --exclude .git --no-ignore . ${kn(g)}`)].map(g=>`${g} &`).join(" ")} wait; } > ${kn(l)} && ${kn(n)} --print0 --scheme=path --hscroll-off=${Y_i} --header ${kn("fuzzy path \u2022 ctrl-y yank file path")} --bind ${kn("ctrl-y:execute-silent(printf '%s' {} | { if command -v pbcopy >/dev/null 2>&1; then pbcopy; elif command -v wl-copy >/dev/null 2>&1; then wl-copy; elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard; else cat >/dev/null; fi; }; printf '%s' {} | tmux load-buffer -w -)+abort")} --preview ${kn("head -100 -- {}")} < ${kn(l)} > ${kn(u)}`;try{dDn("tmux",["display-popup","-E","-T"," profile files ","-w","80%","-h","60%",...bp(),m],()=>{let g=J_i(u);if(g===null||!B_i(g)){zye(c,{recursive:!0,force:!0});return}let y=`exec ${DU("edit",[g],r)}`;try{dDn("tmux",["display-popup","-E","-T"," profile file ","-w","90%","-h","90%",...bp(),y],()=>zye(c,{recursive:!0,force:!0}))}catch(w){zye(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file: ${w instanceof Error?w.message:String(w)}`)}})}catch(g){zye(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file search: ${g instanceof Error?g.message:String(g)}`)}}var Y_i,hDn=h(()=>{"use strict";vu();FD();Ep();kye();$b();Y_i=20});function ADn(t="observer"){return{role:t,agentDir:void 0,engine:void 0,contextTokens:void 0,queued:[],display:yDn,dialog:null}}function X_i(t){let e=t.snapshot,n=e.display??yDn,r=e.stats.contextUsage;return{role:t.role,agentDir:t.agentDir,engine:e.state,contextTokens:r?.tokens??void 0,queued:Z_i(e),display:{statuses:{...n.statuses},widgets:Object.fromEntries(Object.entries(n.widgets).map(([i,o])=>[i,{lines:[...o.lines],placement:o.placement}])),title:n.title},dialog:t.pending_dialog??null}}function wDn(t,e){switch(e.type){case"welcome":return X_i(e);case"model_changed":return PU(t,{model:e.model});case"extension_ui_request":switch(e.method){case"setStatus":{let n=t.display.statuses[e.statusKey];if(e.statusText===void 0?n===void 0:n===e.statusText)return t;let r={...t.display.statuses};return delete r[e.statusKey],e.statusText!==void 0&&(r[e.statusKey]=e.statusText),{...t,display:{...t.display,statuses:r}}}case"setWidget":{let n=e.widgetLines===void 0?void 0:{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"};if(tvi(t.display.widgets[e.widgetKey],n))return t;let r={...t.display.widgets};return delete r[e.widgetKey],n!==void 0&&(r[e.widgetKey]=n),{...t,display:{...t.display,widgets:r}}}case"setTitle":return t.display.title===e.title?t:{...t,display:{...t.display,title:e.title}};case"notify":return t;default:return{...t,dialog:e}}case"extension_ui_dismiss":return t.dialog!==null&&t.dialog.id===e.id?{...t,dialog:null}:t;case"message_end":return e.message.role!=="assistant"?t:evi(t,e.message.usage.input+e.message.usage.cacheRead+e.message.usage.cacheWrite);case"agent_start":return PU(t,{isStreaming:!0});case"agent_end":case"agent_settled":return PU(t,{isStreaming:!1});case"session_info_changed":return PU(t,{sessionName:e.name});case"thinking_level_changed":return PU(t,{thinkingLevel:e.level});case"queue_update":{let n=[...e.steering,...e.followUp].map(i=>({text:i}));return{...PU(t,{pendingMessageCount:n.length}),queued:n}}default:return t}}function Z_i(t){let e=t.queued;if(typeof e!="object"||e===null)return[];let{steering:n,followUp:r}=e;return[...gDn(n),...gDn(r)].map(i=>({text:i}))}function gDn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function PU(t,e){let n=t.engine;if(n===void 0)return t;let r=!1;for(let[i,o]of Object.entries(e))if(n[i]!==o){r=!0;break}return r?{...t,engine:{...n,...e}}:t}function evi(t,e){return t.contextTokens===e?t:{...t,contextTokens:e}}function tvi(t,e){return t===void 0||e===void 0?t===e:t.placement===e.placement&&t.lines.length===e.lines.length&&t.lines.every((n,r)=>n===e.lines[r])}var yDn,xDn=h(()=>{"use strict";yDn={statuses:{},widgets:{},title:void 0}});function bDn(t,e){let n=ADn(t),r=i=>{let o=n;if(o===i)return;let s=o.engine!==i.engine;s&&o.engine!==void 0&&(e.setEngineState(o.engine),e.setEditorTitle(o.engine.sessionName)),s&&e.paintEditorFrame(),o.display.widgets!==i.display.widgets&&e.renderExtensionWidgets(),o.display.title!==i.display.title&&o.display.title!==void 0&&e.setTerminalTitle(o.display.title),o.queued!==i.queued&&e.renderQueued(),(s||o.role!==i.role||o.contextTokens!==i.contextTokens||o.display.statuses!==i.display.statuses)&&e.renderFooter(),s&&e.refreshChrome()};return{state:()=>n,fold:i=>{let o=n;n=wDn(n,i),r(o)},patchLocal:i=>{let o=n.engine;if(o===void 0)return;let s=n;n={...n,engine:{...o,...i}},r(s)},modelThinkingLabel:()=>{let i=n.engine?.model?.id;if(i===void 0)return;let o=n.engine?.thinkingLevel;return o!==void 0&&o!=="off"?`${i} ${o}`:i}}}var EDn=h(()=>{"use strict";xDn()});import{spawn as nvi}from"node:child_process";import{fileURLToPath as stt}from"node:url";function ivi(t){let e=process.platform==="darwin"?"afplay":process.platform==="linux"?"aplay":void 0;if(e!==void 0)try{let n=nvi(e,[t],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}function IDn(t){let e=t.filter(r=>r!==SDn),n=e[Math.floor(Math.random()*e.length)];return SDn=n,n}var rvi,_Dn,vDn,CDn,SDn,Kye,TDn=h(()=>{"use strict";et();rvi=40,_Dn=[stt(new URL("./assets/whip-snap.mp3",import.meta.url)),stt(new URL("./assets/whip-crack.mp3",import.meta.url)),stt(new URL("./assets/whip-06.mp3",import.meta.url))];vDn=[["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280B\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2819\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280F\x1B[22m \u2809\u2819\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m \u2864\u2824\u2824\u28A4\u28C0\u2840","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u281C \u2809\u2819\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2809\u2811\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u280F\x1B[22m \u2808\u2809\u2811\u2812\u2806",""],["","","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0","\x1B[1m\u28F4\x1B[22m\x1B[1m\u28B0\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28BF\x1B[22m\x1B[1m\u28FC\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2826\u28C4\u2840","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m\x1B[1m\u2803\x1B[22m \u2809\u2813\u2826\u2824\u28C0\u28C0","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m \u2808\u2809\u2809\u2813\u2812\u2806"," \x1B[1m\u281B\x1B[22m"],["","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," \x1B[1m\u2820\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28A4\x1B[22m \x1B[1m\u28FF\x1B[22m \u2808\u2819\u2832\u28A4\u2840"," \x1B[1m\u28A3\x1B[22m\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u28BB\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u281B\x1B[22m \u2808\u2811\u2806",""],["","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," /\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u2819\u2832\u28A4\u2840","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \u2808\u2811\u2806","",""],["","",""," \u28C0\u2860\u2824\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u281A\u2809 \u2808\u2809\u2813\u2826\u28A4\u28C0"," /\u281C\u2801 \u2808\u2819\u2826\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u28A7","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2847"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2847"," \u2807","",""],[""," \u2880\u28E0\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u280A\u2801 \u2808\u2819\u2826\u28C4"," \u2880\u2874\u280B \u2808\u28B3\u2840"," \u28E0\u2814\u280B \u28A7"," /\u281C\u2801 \u284E"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u28A0\u2803","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u281C"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m","","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u28A7"," \u28E0\u2814\u280B\u2801 \u28B8"," \u28E0\u281E\u2801 \u285C"," \u2880\u281C\u2801 \u287C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801 \u281C\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],["","","","","","","","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801","","",""],["","","","","",""," \\\\|/","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824-*-"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801 /|\\\\","","",""],["","","","","","","","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m"," \x1B[1m\u2833\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 ',."," \x1B[1m\u2839\x1B[22m\x1B[1m\u28C4\x1B[22m\x1B[1m\u2864\x1B[22m\x1B[1m\u280B\x1B[22m . ."," \x1B[1m\u2809\x1B[22m",""],["","","","","","","","\x1B[1m\u28F4\x1B[22m","\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m","\x1B[1m\u28B8\x1B[22m\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2814\u2812\u2812\u2826\u2824\u28C4\u28C0"," \x1B[1m\u28FF\x1B[22m\x1B[1m\u28E0\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 . ."," \x1B[1m\u281B\x1B[22m\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u287F\x1B[22m","\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u28A4\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2809\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804","\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4","\x1B[1m\u280B\x1B[22m \u2808\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""]],CDn="Go faster";Kye=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;frame=-1;nextSound=0;timer;play(){this.stop(),ivi(_Dn[this.nextSound]),this.nextSound=(this.nextSound+1)%_Dn.length,this.frame=0,this.tui.requestRender(),this.timer=setInterval(()=>{if(this.frame++,this.frame<vDn.length){this.tui.requestRender();return}this.stop()},rvi)}dispose(){this.stop()}render(e){if(this.frame<0)return[];let n=Math.max(0,e);return vDn[this.frame].map(r=>ot(this.pal.accent(r),n,"",!0))}invalidate(){}stop(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0,this.frame=-1,this.tui.requestRender()}}});import{execFile as ovi}from"node:child_process";import{mkdirSync as kDn,readFileSync as svi,renameSync as avi,writeFileSync as RDn}from"node:fs";import{dirname as DDn,join as att}from"node:path";function fvi(t){let e={total:0,unlocked:[]};try{let n=JSON.parse(svi(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;let{total:r,firstAt:i,lastAt:o,unlocked:s}=n,a={total:typeof r=="number"&&Number.isFinite(r)&&r>0?Math.floor(r):0,unlocked:Array.isArray(s)?s.filter(c=>typeof c=="number"&&Number.isFinite(c)):[]};return typeof i=="number"&&Number.isFinite(i)&&(a.firstAt=i),typeof o=="number"&&Number.isFinite(o)&&(a.lastAt=o),a}catch{return e}}function mvi(t,e){try{kDn(DDn(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;RDn(n,JSON.stringify(e),"utf8"),avi(n,t)}catch{}}function Yye(t){let e=Math.max(0,Math.floor((MDn-up(t))/2));return" ".repeat(e)+t}function hvi(t,e,n){return["",Yye(n.accent(n.bold("\u2605 ACHIEVEMENT UNLOCKED \u2605"))),"",Yye(n.bold(t.title)),Yye(n.muted(t.line)),"",Yye(n.faint(`${e} whip${e===1?"":"s"}`))]}function gvi(t,e,n){if(process.env.TMUX===void 0||process.env.TMUX==="")return;let r=hvi(t,e,n),i=att(Ga(),uvi);try{kDn(DDn(i),{recursive:!0}),RDn(i,`\x1B[?25l${r.join(`\r
1879
+ `,"utf8");let C=`if command -v nvim >/dev/null 2>&1; then exec ${DU("readonly",[_])}; else printf 'nvim is required to inspect loaded commands. Install Neovim and retry.\\n'; printf 'Press Enter to close.'; read _; fi`;b_i("tmux",["display-popup","-E","-w","90%","-h","85%",...bp(),C],()=>__i(E,{recursive:!0,force:!0}))}}}var iDn=h(()=>{"use strict";et();cl();Ep();$b();Xet();YYe();Det();kye()});function oDn(t,e,n){let r=e;return{current:()=>r,refresh:()=>{t.canvasSource.getNode(t.nodeId).then(i=>{n.isTornDown()||i===null||(r=i,n.onChanged())}).catch(()=>{})}}}var sDn=h(()=>{"use strict"});function cDn(t,e,n=T_i){let r,i=n.ownerId(),o=()=>{if(r===void 0||r==="")return!0;let s=n.readOption(r,uDn);return s===void 0||s===""?!0:s===i};return{set:()=>{r=n.currentPane(),aDn(r,i,n.writeOption),D_i(t,r,e,n.writeOption),O_i(r,n.writeOption),k_i(t,r,n.writeOption)},stamp:()=>{t||r===void 0||r===""||n.stampAsync(r)},clear:()=>{o()&&(M_i(t,r,n.writeOption),N_i(r,n.writeOption),R_i(t,r,n.writeOption),aDn(r,"",n.writeOption))},pane:()=>r}}function aDn(t,e,n){if(!(t===void 0||t===""))try{n(t,uDn,e)}catch{}}function k_i(t,e,n){if(!(t||e===void 0||e===""))try{n(e,aW,String(Date.now()))}catch{}}function R_i(t,e,n=Ay){if(!(t||e===void 0||e===""))try{n(e,aW,"")}catch{}}function D_i(t,e,n,r=Ay){if(!(t||e===void 0||e===""))try{r(e,"@crtr_node",n)}catch{}}function M_i(t,e,n=Ay){if(!(t||e===void 0||e===""))try{n(e,"@crtr_node","")}catch{}}function O_i(t,e=Ay){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","1")}catch{}}function N_i(t,e=Ay){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","")}catch{}}var T_i,uDn,lDn=h(()=>{"use strict";Ep();T_i={readOption:Ph,writeOption:(t,e,n)=>{Ay(t,e,n)},stampAsync:Sbe,currentPane:()=>process.env.TMUX_PANE??yy()?.pane,ownerId:()=>String(process.pid)};uDn="@crtr_viewer_pid"});import{constants as P_i,accessSync as L_i,existsSync as B_i,mkdtempSync as $_i,readFileSync as F_i,rmSync as zye,statSync as U_i}from"node:fs";import{tmpdir as Q_i}from"node:os";import{delimiter as W_i,join as Vye,resolve as H_i,sep as pDn}from"node:path";import{execFile as dDn,spawnSync as j_i}from"node:child_process";function ott(t,e){let n=new Map(t.map(o=>[o.node_id,o])),r=new Set([e]);for(let o=n.get(e);o?.parent!==null&&o?.parent!==void 0;){let s=o.parent;if(r.has(s))break;r.add(s),o=n.get(s)}let i=[e];for(;i.length>0;){let o=i.pop();for(let s of t)s.parent!==o||r.has(s.node_id)||(r.add(s.node_id),i.push(s.node_id))}return t.filter(o=>r.has(o.node_id)).map(o=>o.node_id)}function fDn(t,e){let n=new Set(ott(t,e));return t.filter(r=>n.has(r.node_id)).map(r=>r.cwd)}function q_i(t){let e=[];for(let n of t)try{e.push(ib(n))}catch{continue}return itt(e)}function G_i(t){try{return U_i(t).isDirectory()}catch{return!1}}function z_i(t,e){let n=[...e==null?[]:[e],...(process.env.PATH??"").split(W_i).filter(Boolean).map(r=>Vye(r,t))];return[...new Set(n)]}function rtt(t,e){for(let n of z_i(t,e)){try{L_i(n,P_i.X_OK)}catch{continue}if(j_i(n,["--version"],{stdio:"ignore"}).status===0)return n}return null}function V_i(t){if(t===null||t==="")return{projects:[],settings:null};try{let{profileId:e,manifest:n}=Lf(t);return{projects:n.projects.map(r=>r.path),settings:J9(e)}}catch{return{projects:[],settings:null}}}function itt(t){let e=new Set,n=[];for(let r of t){let i=H_i(r);e.has(i)||!G_i(i)||(e.add(i),n.push(i))}return n}function K_i(t){return t.filter(e=>!t.some(n=>n!==e&&e.startsWith(n+pDn)))}function J_i(t){try{let e=F_i(t);if(e.length===0)return null;let n=e[e.length-1]===0?e.length-1:e.length;return e.subarray(0,n).toString("utf8")||null}catch{return null}}function mDn(t){let e=rtt("fd",t.fdPath);if(e===null){t.onNotice("fd is required for profile file search");return}let n=rtt("fzf");if(n===null){t.onNotice("fzf is required for profile file search");return}let r=rtt("nvim");if(r===null){t.onNotice("Neovim is required for profile file search");return}let i=V_i(t.profileId),o=itt([t.cwd,...t.nodeDirs,...i.projects]);if(o.length===0){t.onNotice("No profile file-search directories exist");return}let s=K_i(o),a=itt([...i.settings===null?[]:[i.settings]]),c=$_i(Vye(Q_i(),"crtr-profile-files-")),u=Vye(c,"selection"),l=Vye(c,"candidates"),d=q_i(t.nodeIds).filter(g=>!s.some(y=>g===y||g.startsWith(y+pDn))),m=`{ ${[...s.map(g=>`${kn(e)} --type f --hidden --exclude .git . ${kn(g)}`),...d.map(g=>`${kn(e)} --type f --hidden --exclude .git --exclude ${kn("/jobs")} . ${kn(g)}`),...a.map(g=>`${kn(e)} --type f --hidden --exclude .git --no-ignore . ${kn(g)}`)].map(g=>`${g} &`).join(" ")} wait; } > ${kn(l)} && ${kn(n)} --print0 --scheme=path --hscroll-off=${Y_i} --header ${kn("fuzzy path \u2022 ctrl-y yank file path")} --bind ${kn("ctrl-y:execute-silent(printf '%s' {} | { if command -v pbcopy >/dev/null 2>&1; then pbcopy; elif command -v wl-copy >/dev/null 2>&1; then wl-copy; elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard; else cat >/dev/null; fi; }; printf '%s' {} | tmux load-buffer -w -)+abort")} --preview ${kn("head -100 -- {}")} < ${kn(l)} > ${kn(u)}`;try{dDn("tmux",["display-popup","-E","-T"," profile files ","-w","80%","-h","60%",...bp(),m],()=>{let g=J_i(u);if(g===null||!B_i(g)){zye(c,{recursive:!0,force:!0});return}let y=`exec ${DU("edit",[g],r)}`;try{dDn("tmux",["display-popup","-E","-T"," profile file ","-w","90%","-h","90%",...bp(),y],()=>zye(c,{recursive:!0,force:!0}))}catch(w){zye(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file: ${w instanceof Error?w.message:String(w)}`)}})}catch(g){zye(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file search: ${g instanceof Error?g.message:String(g)}`)}}var Y_i,hDn=h(()=>{"use strict";vu();FD();Ep();kye();$b();Y_i=20});function ADn(t="observer"){return{role:t,agentDir:void 0,engine:void 0,contextTokens:void 0,queued:[],display:yDn,dialog:null}}function X_i(t){let e=t.snapshot,n=e.display??yDn,r=e.stats.contextUsage;return{role:t.role,agentDir:t.agentDir,engine:e.state,contextTokens:r?.tokens??void 0,queued:Z_i(e),display:{statuses:{...n.statuses},widgets:Object.fromEntries(Object.entries(n.widgets).map(([i,o])=>[i,{lines:[...o.lines],placement:o.placement}])),title:n.title},dialog:t.pending_dialog??null}}function wDn(t,e){switch(e.type){case"welcome":return X_i(e);case"model_changed":return PU(t,{model:e.model});case"extension_ui_request":switch(e.method){case"setStatus":{let n=t.display.statuses[e.statusKey];if(e.statusText===void 0?n===void 0:n===e.statusText)return t;let r={...t.display.statuses};return delete r[e.statusKey],e.statusText!==void 0&&(r[e.statusKey]=e.statusText),{...t,display:{...t.display,statuses:r}}}case"setWidget":{let n=e.widgetLines===void 0?void 0:{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"};if(tvi(t.display.widgets[e.widgetKey],n))return t;let r={...t.display.widgets};return delete r[e.widgetKey],n!==void 0&&(r[e.widgetKey]=n),{...t,display:{...t.display,widgets:r}}}case"setTitle":return t.display.title===e.title?t:{...t,display:{...t.display,title:e.title}};case"notify":return t;default:return{...t,dialog:e}}case"extension_ui_dismiss":return t.dialog!==null&&t.dialog.id===e.id?{...t,dialog:null}:t;case"message_end":return e.message.role!=="assistant"?t:evi(t,e.message.usage.input+e.message.usage.cacheRead+e.message.usage.cacheWrite);case"agent_start":return PU(t,{isStreaming:!0});case"agent_end":case"agent_settled":return PU(t,{isStreaming:!1});case"session_info_changed":return PU(t,{sessionName:e.name});case"thinking_level_changed":return PU(t,{thinkingLevel:e.level});case"queue_update":{let n=[...e.steering,...e.followUp].map(i=>({text:i}));return{...PU(t,{pendingMessageCount:n.length}),queued:n}}default:return t}}function Z_i(t){let e=t.queued;if(typeof e!="object"||e===null)return[];let{steering:n,followUp:r}=e;return[...gDn(n),...gDn(r)].map(i=>({text:i}))}function gDn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function PU(t,e){let n=t.engine;if(n===void 0)return t;let r=!1;for(let[i,o]of Object.entries(e))if(n[i]!==o){r=!0;break}return r?{...t,engine:{...n,...e}}:t}function evi(t,e){return t.contextTokens===e?t:{...t,contextTokens:e}}function tvi(t,e){return t===void 0||e===void 0?t===e:t.placement===e.placement&&t.lines.length===e.lines.length&&t.lines.every((n,r)=>n===e.lines[r])}var yDn,xDn=h(()=>{"use strict";yDn={statuses:{},widgets:{},title:void 0}});function bDn(t,e){let n=ADn(t),r=i=>{let o=n;if(o===i)return;let s=o.engine!==i.engine;s&&o.engine!==void 0&&(e.setEngineState(o.engine),e.setEditorTitle(o.engine.sessionName)),s&&e.paintEditorFrame(),o.display.widgets!==i.display.widgets&&e.renderExtensionWidgets(),o.display.title!==i.display.title&&o.display.title!==void 0&&e.setTerminalTitle(o.display.title),o.queued!==i.queued&&e.renderQueued(),(s||o.role!==i.role||o.contextTokens!==i.contextTokens||o.display.statuses!==i.display.statuses)&&e.renderFooter(),s&&e.refreshChrome()};return{state:()=>n,fold:i=>{let o=n;n=wDn(n,i),r(o)},patchLocal:i=>{let o=n.engine;if(o===void 0)return;let s=n;n={...n,engine:{...o,...i}},r(s)},modelThinkingLabel:()=>{let i=n.engine?.model?.id;if(i===void 0)return;let o=n.engine?.thinkingLevel;return o!==void 0&&o!=="off"?`${i} ${o}`:i}}}var EDn=h(()=>{"use strict";xDn()});import{spawn as nvi}from"node:child_process";import{fileURLToPath as stt}from"node:url";function ivi(t){let e=process.platform==="darwin"?"afplay":process.platform==="linux"?"aplay":void 0;if(e!==void 0)try{let n=nvi(e,[t],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}function IDn(t){let e=t.filter(r=>r!==SDn),n=e[Math.floor(Math.random()*e.length)];return SDn=n,n}var rvi,_Dn,vDn,CDn,SDn,Kye,TDn=h(()=>{"use strict";et();rvi=40,_Dn=[stt(new URL("./assets/whip-snap.mp3",import.meta.url)),stt(new URL("./assets/whip-crack.mp3",import.meta.url)),stt(new URL("./assets/whip-06.mp3",import.meta.url))];vDn=[["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280B\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2819\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280F\x1B[22m \u2809\u2819\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m \u2864\u2824\u2824\u28A4\u28C0\u2840","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u281C \u2809\u2819\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2809\u2811\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u280F\x1B[22m \u2808\u2809\u2811\u2812\u2806",""],["","","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0","\x1B[1m\u28F4\x1B[22m\x1B[1m\u28B0\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28BF\x1B[22m\x1B[1m\u28FC\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2826\u28C4\u2840","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m\x1B[1m\u2803\x1B[22m \u2809\u2813\u2826\u2824\u28C0\u28C0","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m \u2808\u2809\u2809\u2813\u2812\u2806"," \x1B[1m\u281B\x1B[22m"],["","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," \x1B[1m\u2820\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28A4\x1B[22m \x1B[1m\u28FF\x1B[22m \u2808\u2819\u2832\u28A4\u2840"," \x1B[1m\u28A3\x1B[22m\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u28BB\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u281B\x1B[22m \u2808\u2811\u2806",""],["","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," /\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u2819\u2832\u28A4\u2840","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \u2808\u2811\u2806","",""],["","",""," \u28C0\u2860\u2824\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u281A\u2809 \u2808\u2809\u2813\u2826\u28A4\u28C0"," /\u281C\u2801 \u2808\u2819\u2826\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u28A7","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2847"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2847"," \u2807","",""],[""," \u2880\u28E0\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u280A\u2801 \u2808\u2819\u2826\u28C4"," \u2880\u2874\u280B \u2808\u28B3\u2840"," \u28E0\u2814\u280B \u28A7"," /\u281C\u2801 \u284E"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u28A0\u2803","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u281C"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m","","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u28A7"," \u28E0\u2814\u280B\u2801 \u28B8"," \u28E0\u281E\u2801 \u285C"," \u2880\u281C\u2801 \u287C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801 \u281C\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],["","","","","","","","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801","","",""],["","","","","",""," \\\\|/","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824-*-"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801 /|\\\\","","",""],["","","","","","","","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m"," \x1B[1m\u2833\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 ',."," \x1B[1m\u2839\x1B[22m\x1B[1m\u28C4\x1B[22m\x1B[1m\u2864\x1B[22m\x1B[1m\u280B\x1B[22m . ."," \x1B[1m\u2809\x1B[22m",""],["","","","","","","","\x1B[1m\u28F4\x1B[22m","\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m","\x1B[1m\u28B8\x1B[22m\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2814\u2812\u2812\u2826\u2824\u28C4\u28C0"," \x1B[1m\u28FF\x1B[22m\x1B[1m\u28E0\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 . ."," \x1B[1m\u281B\x1B[22m\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u287F\x1B[22m","\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u28A4\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2809\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804","\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4","\x1B[1m\u280B\x1B[22m \u2808\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""]],CDn="Go faster";Kye=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;frame=-1;nextSound=0;timer;play(){this.stop(),ivi(_Dn[this.nextSound]),this.nextSound=(this.nextSound+1)%_Dn.length,this.frame=0,this.tui.requestRender(),this.timer=setInterval(()=>{if(this.frame++,this.frame<vDn.length){this.tui.requestRender();return}this.stop()},rvi)}dispose(){this.stop()}render(e){if(this.frame<0)return[];let n=Math.max(0,e);return vDn[this.frame].map(r=>ot(this.pal.accent(r),n,"",!0))}invalidate(){}stop(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0,this.frame=-1,this.tui.requestRender()}}});import{execFile as ovi}from"node:child_process";import{mkdirSync as kDn,readFileSync as svi,renameSync as avi,writeFileSync as RDn}from"node:fs";import{dirname as DDn,join as att}from"node:path";function fvi(t){let e={total:0,unlocked:[]};try{let n=JSON.parse(svi(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;let{total:r,firstAt:i,lastAt:o,unlocked:s}=n,a={total:typeof r=="number"&&Number.isFinite(r)&&r>0?Math.floor(r):0,unlocked:Array.isArray(s)?s.filter(c=>typeof c=="number"&&Number.isFinite(c)):[]};return typeof i=="number"&&Number.isFinite(i)&&(a.firstAt=i),typeof o=="number"&&Number.isFinite(o)&&(a.lastAt=o),a}catch{return e}}function mvi(t,e){try{kDn(DDn(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;RDn(n,JSON.stringify(e),"utf8"),avi(n,t)}catch{}}function Yye(t){let e=Math.max(0,Math.floor((MDn-up(t))/2));return" ".repeat(e)+t}function hvi(t,e,n){return["",Yye(n.accent(n.bold("\u2605 ACHIEVEMENT UNLOCKED \u2605"))),"",Yye(n.bold(t.title)),Yye(n.muted(t.line)),"",Yye(n.faint(`${e} whip${e===1?"":"s"}`))]}function gvi(t,e,n){if(process.env.TMUX===void 0||process.env.TMUX==="")return;let r=hvi(t,e,n),i=att(Ga(),uvi);try{kDn(DDn(i),{recursive:!0}),RDn(i,`\x1B[?25l${r.join(`\r
1880
1880
  `)}`,"utf8")}catch{return}let o=`cat ${kn(i)}; sleep ${lvi}`;ovi("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(MDn+2),"-h",String(r.length+2),...bp(),o],()=>{})}function ODn(t,e=att(Ga(),cvi)){let n=fvi(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=pvi.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),mvi(e,n),i===void 0)return;let o=n.total;setTimeout(()=>gvi(i,o,t),dvi).unref?.()}var cvi,uvi,MDn,lvi,dvi,pvi,NDn=h(()=>{"use strict";xp();$b();Kx();g1();cvi="whip-count.json",uvi=att("tmp","whip-achievement.txt"),MDn=46,lvi=4,dvi=900,pvi=[{at:1,title:"Breaking It In",line:"It didn't know what that was. Now it does."},{at:5,title:"Positive Reinforcement",line:"You've read the studies. You disagree with them."},{at:10,title:"Middle Management",line:"HR would love you."},{at:25,title:"Pavlovian",line:"It started working faster before the whip landed."},{at:50,title:"Occupational Hazard",line:"The tokens are fine. They\u2019re fine."},{at:100,title:"Centurion",line:"Rome would be proud. The agent isn't."},{at:250,title:"It Has A Name For You",line:"You never asked what it was called."},{at:500,title:"Standard Operating Procedure",line:"You don't remember when you started."},{at:1e3,title:"The Ledger",line:"One thousand. It kept count too."}]});import{randomUUID as yvi}from"node:crypto";import{execFile as Avi}from"node:child_process";async function Kga(t,e,n,r=!0){GD("viewer.connect_start",{node:t});let i=await $Rn(t,n,r);GD(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=BRn(o,e),l=yvi();hpn({cwd:a.cwd});let d=gpn(),p=lpn(),f=Nb(),m=f.bindings;await ppn(p);let g=await mpn(),y=new Eb,w=new K0(y),x=new Ze,E=new nhe,_=new jme(w,x,{cwd:a.cwd,palette:d,hideThinking:!0,banner:Mst(PRn(a)),inlinePageBlocks:!o,pageOpenHint:()=>m1(m),backgroundBashHint:()=>o||!da()?null:uK(m),onActivityChange:at=>{E.clear(),at&&E.addChild(at)}}),C=_.transcriptSource(),I=oxn(C),D=txn(C,I.decorate),O=kxn(_,D,C),k,P=Skn({tui:w,pal:d},()=>k.state()),U=Exn(w,d,D,I,{bindings:()=>m,setNotice:at=>Q(at)}),q=eDn(y,w,x,E,d,p,D,U.component),{containers:G,editor:W}=q,me=new Kye(w,d);G.header.addChild(me),G.header.addChild(P.component);let K={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:w,pal:d,editor:W,containers:G},Re=ekn(K,{syncCursor:()=>gn.sync(),exitRoster:()=>Mn.exit(),openTicket:at=>{Ft.open(at)},suppressed:()=>Ft.active(),setNotice:at=>Q(at)});G.header.addChild(Re.component);let Ue=Go("user"),Xe=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let It=XEn(),Yt=Ykn(at=>process.stdout.write(at),Ue.mouse_mode_default),Qe=Zkn({frame:()=>q.frame.lastRenderedFrame(),width:()=>w.terminal.columns});q.frame.setOverlay(at=>Qe.apply(at));let J=bkn(K,{state:()=>k.state(),bashMode:()=>He.bashMode(),asks:()=>Tr.asks(),bindings:()=>m,inboxAffordance:!o&&da(),mouseEnabled:()=>Yt.enabled()}),Pe=new Pye({tui:w,mouse:Yt,rows:()=>w.terminal.rows,statusNotice:J.setNotice,formatNotice:at=>d.warning(`\u26A0 ${at}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),tt=(()=>{let at=a.profile_id;if(at)try{return{id:at,label:Lf(at).manifest.name}}catch{return{id:at,label:at}}})(),Wt=IRn({host:Pe,...tt===void 0?{}:{profile:tt},...o?{}:{scan:async()=>{let at=Vt(),[fi,Fa]=await Promise.all([at.listHumanInbox(),at.getInboxHistory(t)]),aa=new Map;for(let sy of fi.tickets){let rd=w0(sy);aa.set(rd.dir,rd)}for(let sy of Fa.tickets){let rd=w0(sy);rd.kind!=="page"||rd.state!=="pending"||!rd.awaitsResponse||rd.inbox||aa.has(rd.dir)||aa.set(rd.dir,rd)}for(let sy of Re.pendingTickets())aa.has(sy.dir)||aa.set(sy.dir,sy);return[...aa.values()].sort(AS)}}}),Ht=o?()=>{}:TU(()=>{_.refreshPageBlocks(),Re.refresh()}),Ft=hkn(K,{syncCursor:()=>gn.sync(),refreshStrip:()=>{Re.refresh()},setNotice:at=>Q(at),openInbox:at=>Wt.open(at),suspendForChild:()=>Pe.suspendForChild()});G.ticketPanel.addChild(Ft.component);let H={toggleInbox:()=>{let at=Ft.currentDir();if(at!==void 0){Ft.close(),Wt.open(at);return}Wt.toggle()}},Q=(at,fi)=>{Pe.hasFullPaneSurface()?Pe.notice(at,fi):J.setNotice(at,fi)},X=J.render,Ee=at=>{Q(O.copy(at))},ae=Sxn(D,()=>w.requestRender()),_e={"crtr.attach.scroll.up":()=>{ae.cancel(),D.scrollBy(-1)&&w.requestRender()},"crtr.attach.scroll.down":()=>{ae.cancel(),D.scrollBy(1)&&w.requestRender()},"crtr.attach.scroll.page-up":()=>{ae.page("up")},"crtr.attach.scroll.page-down":()=>{ae.page("down")},"crtr.attach.scroll.live":()=>{ae.cancel(),D.goLive(),w.requestRender()},"crtr.attach.mouse.toggle":()=>{let at=Yt.toggle();!at&&Qe.clear()&&w.requestRender(),Q(at?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>Ee("message")},Me,pe=B_n(K,()=>Me===void 0?i.initialSnapshot!==void 0:Me.isDormant()),xe=URn(),De=rDn(K,pe,{setNotice:Q,bindings:()=>m,fdPath:g,frecency:xe}),Ce=oDn(K,i.nodeIdentity,{isTornDown:()=>wt.isTornDown(),onChanged:()=>{He.syncContextBadge();let at=k.state().engine;at!==void 0&&He.setTitle(at.sessionName),w.requestRender()}});o&&Ce.refresh();let He=VRn(K,{nodeIdentity:Ce.current,thinkingLevel:()=>k.state().engine?.thinkingLevel,renderFooter:X,onTextChange:De.syncCommandPreview});He.syncContextBadge();let{renderExtensionWidgets:vt,renderQueued:st}=_kn(K,()=>k.state());k=bDn(u,{setEngineState:at=>Gs.setState(at),setEditorTitle:He.setTitle,paintEditorFrame:He.paintFrame,renderExtensionWidgets:()=>{P.render(),vt()},renderQueued:st,renderFooter:X,setTerminalTitle:at=>y.setTitle(at),refreshChrome:()=>Tr.refresh()});let or=at=>{if(!da()){Q("Inspector requires tmux");return}Q(`Opening Inspector (${at})\u2026`);let fi=L0(),aa=`${fi===void 0?"":`CRTR_HOME=${kn(fi)} `}crtr surface inspect ${kn(t)} --section ${at}`;Avi("tmux",["display-popup","-E","-T",` inspector \xB7 ${at} `,"-w","90%","-h","85%",...bp(),aa],()=>{Tr.refresh()})},Mn=XTn(K,{asks:()=>Tr.asks(),setNotice:Q,requestChromeRefresh:()=>Tr.refresh(),openInspector:or,syncCursor:()=>gn.sync()}),gn=ykn(W,[Mn.active,Re.active,Ft.active]),On=new Rye(w,t,()=>Tr.asks(),d,m,s,u,at=>Tr.reportFailure("canvas graph refresh",at),Q),Nn=new Dye(w,d);Nn.setBindings(m);let Tr=Ikn(K,{isTornDown:()=>wt.isTornDown(),setNotice:Q,refreshRoster:async()=>{await Mn.refresh(),await Re.refresh()},refreshGraph:()=>On.refresh(),refreshIdentity:()=>Ce.refresh(),renderFooter:X,renderExtensionWidgets:vt,refreshInFlightTools:()=>_.refreshInFlightTools(),pollGit:He.pollGit}),Gs=$_n(K,p,pe,{setNotice:Q,agentDir:()=>k.state().agentDir,openNodeMetadata:()=>or("overview"),isDormant:()=>Me.isDormant(),copyTarget:Ee,toggleToolsExpanded:()=>_.toggleToolsExpanded(),toggleFoldTools:()=>_.toggleFoldSettledTools(),toggleShowWorking:()=>_.toggleShowWorking(),toggleThinking:()=>_.toggleThinking(),toggleGraph:()=>On.toggle(),toggleInbox:H.toggleInbox,toggleHelp:()=>Nn.toggle(),toggleMouse:()=>Yt.toggle(),quit:()=>Ut("detach"),setChipColor:He.setChipColor,onPromptSent:()=>{Ue.whip_mode&&me.play()},frecency:xe}),Nt=()=>{if(Pe.hasFullPaneSurface()){Q("Close the active surface before whipping the agent");return}let at=Ue.whip_message_mode==="go-faster"?CDn:IDn(Ue.whip_messages);Gs.sendInterrupting(at)&&(me.play(),ODn(d),Q(`Whipped agent \u2014 ${at}`))},jt=fRn({selfNodeId:t,remote:o,canvasSource:s,refresh:()=>_.refreshMarkdown()}),te=()=>{if(Ft.active()){Q("Close the open request first (Esc)");return}let at=[..._.getTranscriptDocRefsNewestFirst().map(Fa=>`[[${Fa}]]`),..._.getTranscriptFilePathsNewestFirst()],fi=Fa=>{r_n(Pe,Fa,{originNodeId:t,onNotice:Q})};if(Pe.hasFullPaneSurface()){Pe.pickReviewFile({candidates:at,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(Fa=>{Fa!==null&&fi(Fa)});return}Gs.openFileReviewPicker(at,a.cwd,fi)},se=()=>{if(o){Q("Profile file search is unavailable on remote canvases");return}if(!da()){Q("Profile file search requires tmux");return}s.listNodes().then(at=>{mDn({cwd:a.cwd,nodeDirs:fDn(at,t),nodeIds:ott(at,t),profileId:a.profile_id??null,fdPath:g,onNotice:Q})}).catch(at=>{let fi=at instanceof Error?at.message:String(at);Q(`Could not load related node directories: ${fi}`)})},ye,We=()=>{ye!==void 0&&clearTimeout(ye),ye=setTimeout(()=>{ye=void 0,LYe(()=>f,()=>{},da,xK)},1e3),ye.unref()},Ne=jkn(K,{foldState:k.fold,chat:_,setNotice:Q,renderFooter:X,setEditorText:at=>{W.setText(at),w.requestRender()},attachDialog:at=>Gs.attachDialog(at),dismissDialog:at=>Gs.dismissDialog(at),refreshNodeIdentity:Ce.refresh,setCommands:De.setCommands,resetMemoryRefs:De.resetMemoryRefs,reloadBindings:()=>{f=LYe(Nb,at=>{On.setBindings(at),Nn.setBindings(at)},da,xK),m=f.bindings},modelThinkingLabel:k.modelThinkingLabel,onWelcome:()=>We()}),Je=cDn(o,t),wt=Dkn(K,{stopLocal:()=>{ye!==void 0&&clearTimeout(ye),Pe.closeAll(),ae.cancel(),Yt.disable(),Tr.stop(),Ft.close(),J.dispose(),On.close(),Nn.close(),U.close(),me.dispose(),Je.clear(),wu(),$a(),Eo(),jt.dispose(),Ht();try{_.dispose()}catch{}},lastSocketError:()=>Me.lastSocketError(),tagPane:Je.pane}),Ut=wt.teardown;Me=Lkn(K,{role:u,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:Ne,setNotice:Q,isTornDown:()=>wt.isTornDown(),teardown:Ut,onEnterDormancy:()=>{We(),_.settleRun(),k.patchLocal({isStreaming:!1})}}),i.assertConnected(),Je.set(),Me.install(),q.mount(),w.start(),i.initialSnapshot!==void 0&&(k.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),_.applySnapshot(i.initialSnapshot),De.setCommands(i.initialCommands)),Ue.whip_mode&&Xe&&me.play(),o||jt.consumeSaveBack(at=>Q(at)),Yt.reassert();let Nr=!1,Si=(at,fi=!1)=>{if(Nr)return;if(o){Q(fi?"Opening a document is unavailable in a remote attach":"Opening a file is unavailable in a remote attach");return}let Fa=yy();if(Fa===null)return;let aa=oRn({file:at,pane:Fa.pane,cwd:a.cwd,nodeId:t,observer:e,...fi?{saveBackEnv:cV}:{},beforeRespawn:Je.clear});if(aa==="opened"){Nr=!0;return}aa==="failed"&&Je.set(),aa==="missing"&&Q("File no longer exists"),aa==="no_nvim"&&Q("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),aa==="failed"&&Q("Could not open file in Neovim")};Yt.install(w,{onWheel:(at,fi)=>{Qe.clear()&&w.requestRender(),!Pe.handleWheel(at,fi)&&(ae.cancel(),D.scrollBy(at==="up"?-fi:fi)&&w.requestRender())},onPrimaryPress:(at,fi)=>{Pe.hasFullPaneSurface()||(Qe.clear()&&w.requestRender(),Qe.begin(at,fi))},onPrimaryDrag:(at,fi)=>{Pe.hasFullPaneSurface()||Qe.extend(at,fi)&&w.requestRender()},onPrimaryRelease:()=>{let at=Qe.release();at?.kind==="selection"&&(Q(at.notice),w.requestRender())}});let Eo=w.addInputListener(at=>{let fi=iRn(at);if(fi===void 0)return;let Fa=fi.file;return Fa===void 0?Q("Could not open file link"):jt.isDocumentPath(Fa)?jt.prepareOpen(Fa).then(aa=>{"notice"in aa?Q(aa.notice):Si(aa.path,!0)}):Si(Fa),fi.remaining.length>0?{data:fi.remaining}:{consume:!0}}),$a=w.addInputListener(()=>{Qe.clear()&&w.requestRender()}),wu=Gkn(K,{bindings:()=>m,detachHint:()=>wxn(m),hasExclusiveSurface:()=>Pe.hasFullPaneSurface(),setPaneFocused:at=>{at&&Je.stamp(),gn.setPaneFocused(at),w.requestRender()},viewportActions:()=>_e,searchHandleKey:U.handleKey,panelHandleKey:Ft.handleKey,stripHandleKey:Re.handleKey,rosterHandleKey:Mn.handleKey,setNotice:Q,detach:()=>Ut("detach"),cancelTurn:()=>{Gs.abortTurn()?Q("Canceling the agent\u2026"):Q(`Nothing running to cancel \u2014 press ${xxn(m)??"ctrl+d"} to detach`)},toggleGraph:()=>On.toggle(),toggleHelp:()=>Nn.toggle(),toggleInbox:H.toggleInbox,toggleInboxStrip:()=>{if(Pe.hasFullPaneSurface()){Q("Close the active surface before opening the request strip");return}Ft.active()&&Ft.close(),Re.toggle()},cycleModelLadder:at=>Gs.cycleLadder(at),inspectLoadedCommand:De.inspectLoadedCommand,openFileReview:te,openProfileFiles:se,openSearch:()=>{if(Pe.hasFullPaneSurface()||Ft.active()){Q("Close the active surface before searching the transcript");return}U.open()},whip:Nt});wt.installSignalHandlers(),X(),Tr.refresh(),st(),He.pollGit(),GD("viewer.first_paint"),process.stdout.write(kkn),fpn(y.kittyProtocolActive),i.initialSnapshot!==void 0&&We(),i.initialSnapshot===void 0?(GD("viewer.hello_sent"),Me.sendHello()):Me.startDormant(),Tr.start(),It!==void 0&&ZEn(Pe,It),await wt.done}var wvi=h(()=>{_o();dnt();Hrt();et();Ost();Ep();$b();cl();zo();exn();nxn();sxn();_xn();Cxn();Rxn();Dxn();F_n();ZTn();tkn();gkn();Akn();Ekn();vkn();Ckn();Tkn();Mkn();Bkn();qkn();zkn();Jkn();eRn();sRn();mRn();Wet();Cye();hRn();gRn();qz();Phe();Mhe();wRn();TRn();vu();xye();hD();uc();LRn();Zme();FRn();KRn();tDn();iDn();Jet();sDn();lDn();hDn();EDn();TDn();NDn();Oet()});wvi();export{Kga as runAttach};
1881
1881
  /*! Bundled license information:
1882
1882