@north-light/cli 0.3.664 → 0.3.666

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/api/client.d.ts +5 -0
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/environments.d.ts +25 -0
  6. package/dist/api/dto/environments.js +0 -0
  7. package/dist/api/dto/profiles.d.ts +15 -0
  8. package/dist/api/index.d.ts +1 -0
  9. package/dist/api/index.js +1 -1
  10. package/dist/api/routes.d.ts +1 -0
  11. package/dist/api/routes.js +1 -1
  12. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  13. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  14. package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +4 -8
  15. package/dist/clients/attach/viewer.js +10 -10
  16. package/dist/commands/profile/environment.d.ts +2 -0
  17. package/dist/commands/profile/environment.js +2 -0
  18. package/dist/commands/profile/new.js +1 -1
  19. package/dist/commands/profile.js +1 -1
  20. package/dist/core/environment-recipe.d.ts +20 -10
  21. package/dist/core/environment-recipe.js +1 -1
  22. package/dist/core/environment-repos.d.ts +7 -0
  23. package/dist/core/environment-repos.js +1 -0
  24. package/dist/core/environments.d.ts +4 -1
  25. package/dist/core/environments.js +1 -1
  26. package/dist/core/model-auth/api-credential-store.d.ts +5 -1
  27. package/dist/core/model-auth/api-credential-store.js +1 -1
  28. package/dist/core/profiles/manifest.d.ts +7 -1
  29. package/dist/core/profiles/manifest.js +1 -1
  30. package/dist/core/providers/files.js +1 -1
  31. package/dist/core/review/companion.js +1 -1
  32. package/dist/core/runs/operations.js +7 -7
  33. package/dist/core/runtime/provider-credential-gate.js +2 -2
  34. package/dist/core/runtime/runner/blaxel/image-build.d.ts +6 -2
  35. package/dist/core/runtime/runner/blaxel/image-build.js +6 -5
  36. package/dist/core/secrets/blaxel-launch.js +3 -3
  37. package/dist/core/storage/caller-file.d.ts +12 -0
  38. package/dist/core/storage/caller-file.js +1 -0
  39. package/dist/core/storage/client.d.ts +0 -1
  40. package/dist/core/storage/client.js +2 -2
  41. package/dist/core/storage/shares.d.ts +0 -12
  42. package/dist/core/storage/shares.js +1 -1
  43. package/dist/daemon/api/app-listener.js +9 -9
  44. package/dist/daemon/api/environment-of.d.ts +2 -0
  45. package/dist/daemon/api/environment-of.js +3 -3
  46. package/dist/daemon/api/handlers/app-profiles.d.ts +1 -0
  47. package/dist/daemon/api/handlers/app-profiles.js +1 -1
  48. package/dist/daemon/api/handlers/attach.js +1 -1
  49. package/dist/daemon/api/handlers/environments.d.ts +2 -0
  50. package/dist/daemon/api/handlers/environments.js +1 -0
  51. package/dist/daemon/api/handlers/nodes.js +1 -1
  52. package/dist/daemon/api/handlers/profiles.js +1 -1
  53. package/dist/daemon/api/handlers/transfer.d.ts +0 -6
  54. package/dist/daemon/api/handlers/transfer.js +1 -1
  55. package/dist/daemon/api/map.d.ts +2 -1
  56. package/dist/daemon/api/map.js +2 -2
  57. package/dist/daemon/api/operations.d.ts +2 -2
  58. package/dist/daemon/api/operations.js +1 -1
  59. package/dist/daemon/api/server.js +1 -1
  60. package/dist/daemon/crtrd.js +11 -11
  61. package/dist/daemon/due-sources.d.ts +1 -1
  62. package/dist/daemon/due-sources.js +1 -1
  63. package/dist/daemon/due.js +6 -6
  64. package/dist/daemon/reconcilers/idle-sandbox.d.ts +18 -0
  65. package/dist/daemon/reconcilers/idle-sandbox.js +7 -0
  66. package/dist/daemon/reconcilers/recipe-image.js +4 -4
  67. package/docs/apps/guides/files-and-documents.md +2 -6
  68. package/docs/concepts/scopes-and-trust.md +1 -1
  69. package/docs/sdk/release-notes.md +6 -0
  70. package/package.json +2 -2
  71. package/packages/crouter-identity/package.json +1 -1
  72. package/runtime.lock.json +13 -13
  73. package/dist/core/storage/download.d.ts +0 -23
  74. package/dist/core/storage/download.js +0 -1
@@ -85,8 +85,8 @@ ${i}`);return e.join(`
85
85
  `)||e.includes("\r")||Buffer.byteLength(e,"utf8")+1>mZe?!1:fZe(t,[e])}function gZe(t,e){if(e.includes(`
86
86
  `)||e.includes("\r"))return!1;let n=Buffer.byteLength(e,"utf8")+1;return n>mZe?!1:(Kd!==void 0&&Kd.path!==t&&C6(),Kd===void 0&&(Kd={path:t,records:[],bytes:0},hZe||(process.on("exit",C6),hZe=!0)),Kd.path=t,Kd.records.push(e),Kd.bytes+=n,Kd.bytes>=USn?C6():Kd.timer===void 0&&(Kd.timer=setTimeout(C6,$Sn),Kd.timer.unref()),!0)}function C6(){let t=Kd;if(!(t===void 0||t.records.length===0)&&(t.timer!==void 0&&clearTimeout(t.timer),Kd=void 0,!fZe(t.path,t.records,FSn)))for(let e of t.records)process.stderr.write(`[crtrd] event log append failed: ${e}
87
87
  `)}var mZe,OSn,FSn,USn,$Sn,Kd,hZe,oge=y(()=>{"use strict";mZe=65536,OSn=5*1024*1024,FSn=16*1024*1024,USn=128*1024,$Sn=200;hZe=!1});var sge,AZe=y(()=>{"use strict";sge=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"]});function WSn(t){return typeof t=="object"&&t!==null?t:void 0}function yZe(t){return typeof t=="string"?t:""}function wZe(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=WSn(t);return{type:yZe(e?.name)||"Error",message:yZe(e?.message)||String(t)}}var EZe=y(()=>{"use strict";AZe()});import{AsyncLocalStorage as HSn}from"node:async_hooks";import{randomBytes as GSn}from"node:crypto";function v6(t){if(typeof t!="string"||!qSn.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function cge(){let t;do t=GSn(16).toString("hex");while(t==="00000000000000000000000000000000");return v6(t)}var qSn,age,xZe,bZe=y(()=>{"use strict";qSn=/^(?!0{32}$)[0-9a-f]{32}$/,age=new HSn;xZe={current:()=>age.getStore(),run:(t,e)=>age.run(v6(t),e),fresh:t=>{let e=cge();return age.run(e,()=>t(e))}}});function XSn(t){return Buffer.byteLength(t,"utf8")}function S6(t,e,n=128){if(typeof t!="string"||t===""||XSn(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function ZSn(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 e_n(t){if(!JSn.has(t.class))throw new TypeError("error_class.class is invalid");let e={class:t.class};if(t.status!==void 0){if(!Number.isInteger(t.status))throw new TypeError("error_class.status must be an integer");e.status=t.status}if(t.provider!==void 0&&(e.provider=S6(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!YSn.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function CZe(t){if(!zSn.has(t.level))throw new TypeError("level is invalid");if(!VSn.has(t.component))throw new TypeError("component is invalid");let e=S6(t.event,"event");if(!jSn.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?xZe.current()??cge():v6(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():ZSn(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=S6(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=S6(t.stream_id,"stream_id")),t.duration_ms!==void 0){if(!Number.isFinite(t.duration_ms)||t.duration_ms<0)throw new TypeError("duration_ms must be finite and non-negative");r.duration_ms=t.duration_ms}if(t.outcome!==void 0){if(!KSn.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=e_n(t.error_class)),t.error!==void 0&&(r.error=wZe(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}var jSn,zSn,VSn,KSn,YSn,JSn,IZe=y(()=>{"use strict";EZe();bZe();jSn=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,zSn=new Set(["error","warn","info","debug"]),VSn=new Set(["daemon","broker","control-plane","front","sentinel"]),KSn=new Set(["succeeded","failed","skipped"]),YSn=new Set(["auto","manual","fatal"]),JSn=new Set(sge)});function qI(t){return Buffer.byteLength(t,"utf8")}function GI(t,e){if(qI(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-qI(n),i=0,o="";for(let s of t){let a=qI(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function t_n(t){return t===void 0?"[Unsupported undefined]":typeof t=="function"?`[Unsupported function${t.name?` ${t.name}`:""}]`:typeof t=="symbol"?`[Unsupported ${String(t)}]`:`[Unsupported ${t?.constructor?.name??typeof t}]`}function uge(t,e,n,r){if(r.remaining<=0)return{value:"[Omitted]",altered:!0,dropped:0};if(r.remaining-=1,t===null||typeof t=="boolean")return{value:t,altered:!1,dropped:0};if(typeof t=="string"){let i=GI(t,4096);return{value:i.value,altered:i.altered,dropped:0}}if(typeof t=="number")return Number.isFinite(t)?{value:t,altered:!1,dropped:0}:{value:String(t),altered:!0,dropped:0};if(typeof t=="bigint")return{value:t.toString(),altered:!0,dropped:0};if(t instanceof Date)return{value:Number.isNaN(t.getTime())?"Invalid Date":t.toISOString(),altered:!0,dropped:0};if(typeof t!="object"||t===void 0)return{value:t_n(t),altered:!0,dropped:0};if(n.has(t))return{value:"[Circular]",altered:!0,dropped:0};if(e>=4)return{value:"[Max depth]",altered:!0,dropped:0};n.add(t);try{if(Array.isArray(t)){let u=Math.min(t.length,64),l=[],d=t.length>u,p=t.length-u;for(let h=0;h<u;h+=1){if(r.remaining<=0){d=!0,p+=u-h;break}let m=uge(t[h],e+1,n,r);l.push(m.value),d||=m.altered,p+=m.dropped}return{value:l,altered:d,dropped:p}}let i;try{i=Object.keys(t).sort()}catch{return{value:"[Unsupported object]",altered:!0,dropped:0}}let o=i.slice(0,64),s={},a=i.length>o.length,c=i.length-o.length;for(let u=0;u<o.length;u+=1){let l=o[u];if(r.remaining<=0){a=!0,c+=o.length-u;break}let d=GI(l,128),p;try{p=uge(t[l],e+1,n,r)}catch{p={value:"[Unsupported property]",altered:!0,dropped:0}}if(Object.prototype.hasOwnProperty.call(s,d.value)){a=!0,c+=1;continue}s[d.value]=p.value,a||=d.altered||p.altered,c+=p.dropped}return{value:s,altered:a,dropped:c}}finally{n.delete(t)}}function n_n(t){let e=GI(String(t.type),128),n=GI(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=GI(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=GI(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function _6(t){return JSON.stringify(t)}function vF(t){return qI(_6(t))+1}function vZe(t){let e=t.fields===void 0?void 0:uge(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:n_n(t.error),r={v:1,ts:t.ts,level:t.level,event:t.event,component:t.component,operation_id:t.operation_id,...t.node_id===void 0?{}:{node_id:t.node_id},...t.stream_id===void 0?{}:{stream_id:t.stream_id},...t.duration_ms===void 0?{}:{duration_ms:t.duration_ms},...t.outcome===void 0?{}:{outcome:t.outcome},...t.attempt===void 0?{}:{attempt:t.attempt},...t.error_class===void 0?{}:{error_class:t.error_class},...n===void 0?{}:{error:n.value},...e===void 0?{}:{fields:e.value}},i=vF(r),o=e?.altered===!0||n?.altered===!0||i>65536,s=e?.dropped??0;for(o&&Object.assign(r,{record_truncated:!0,original_bytes:i,dropped_fields_count:s});vF(r)>65536&&r.fields!==void 0;){let u=r.fields,l=Object.keys(u);if(l.length===0){delete r.fields;break}l.sort((d,p)=>{let h=qI(_6(u[p]))-qI(_6(u[d]));return h!==0?h:p<d?-1:p>d?1:0}),delete u[l[0]],s+=1,r.record_truncated=!0,r.original_bytes=i,r.dropped_fields_count=s}let a=r.error;vF(r)>65536&&a?.stack!==void 0&&delete a.stack,vF(r)>65536&&a?.cause!==void 0&&delete a.cause,vF(r)>65536&&a!==void 0&&(a.message=GI(a.message,64).value);let c=_6(r);if(qI(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}var SZe=y(()=>{"use strict"});import{AsyncLocalStorage as r_n}from"node:async_hooks";function kZe(t){lge=t}function k6(){return _Ze}function dge(){let t=i_n.getStore();if(t!==void 0)return t;if(_Ze)throw new _F;if(lge===void 0)throw new SF;return lge}var SF,_F,lge,_Ze,i_n,XR=y(()=>{"use strict";SF=class extends Error{code="person_unresolved";constructor(){super("the install's person is not resolved yet"),this.name="PersonUnresolvedError"}},_F=class extends Error{code="person_outside_request";constructor(){super("no person: a cloud role reads the person only inside a request, from its token"),this.name="PersonOutsideRequestError"}},_Ze=!1,i_n=new r_n});import{existsSync as T6,lstatSync as TEi,mkdirSync as o_n,readdirSync as s_n,readFileSync as RZe,rmSync as a_n,statSync as c_n,symlinkSync as REi,writeFileSync as u_n,cpSync as BEi,readlinkSync as DEi,renameSync as l_n,chmodSync as d_n,realpathSync as p_n,closeSync as BZe,fsyncSync as DZe,openSync as MZe,linkSync as MEi,unlinkSync as PEi,writeSync as NEi}from"node:fs";import{dirname as TZe,join as h_n,relative as QEi,sep as OEi}from"node:path";import{homedir as m_n,platform as f_n}from"node:os";function Ym(t){try{return p_n(t)}catch{return t}}function PZe(t,e=m_n()){return t==="~"?e:t.startsWith("~/")||f_n()==="win32"&&t.startsWith("~\\")?h_n(e,t.slice(2)):t}function R6(t){o_n(t,{recursive:!0})}function ZR(t,e,n){pge(t,JSON.stringify(e,null,2)+`
88
- `,n)}function g_n(t){let e=MZe(t,"r");try{DZe(e)}finally{BZe(e)}}function NZe(t){let e=MZe(t,"r");try{DZe(e)}finally{BZe(e)}}function pge(t,e,n){n?.createParent!==!1&&R6(TZe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(T6(t)?c_n(t).mode&511:384);try{u_n(r,e,{mode:i}),d_n(r,i),n?.durable===!0&&g_n(r),l_n(r,t),n?.durable===!0&&NZe(TZe(t))}finally{T6(r)&&a_n(r,{force:!0})}}function A_n(t){return JSON.parse(RZe(t,"utf8"))}function jI(t){try{return A_n(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function zI(t){try{return JSON.parse(RZe(t,"utf8"))}catch{return null}}function hge(t){return T6(t)}function mge(t){return T6(t)?s_n(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var $l=y(()=>{"use strict"});import{homedir as y_n,userInfo as w_n}from"node:os";import{basename as E_n,dirname as GEi,isAbsolute as qEi,join as Yd,resolve as LZe}from"node:path";function D6(){let t=LZe(Q0()||(process.platform==="linux"?"/":Yd(y_n(),".crouter")));if(x_n()&&t===b_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 x_n(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function b_n(){if(B6===void 0)try{B6=LZe(w_n().homedir,".crouter")}catch{B6=null}return B6}function vg(){return Yd(D6(),"runtime")}function fge(){return Yd(D6(),"apps")}function $0(){return Yd(vg(),"secrets")}function QZe(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=kF(t);return{dir:Yd(n.profiles,e),env:Yd($0(),"env",E_n(n.root),e),home:n.home}}function gge(){return process.platform==="linux"?"/run/crtr":vg()}function kF(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=Yd(fge(),e);return{root:n,profiles:Yd(n,"profiles"),conversations:Yd(n,"conversations"),nodes:Yd(n,"nodes"),files:Yd(n,"files"),home:Yd(n,"home"),cache:Yd(n,"cache")}}var B6,W0=y(()=>{"use strict";du();Jd();XR();$l()});import{chmodSync as XEi,chownSync as ZEi,closeSync as cE,constants as M6,fchmodSync as exi,fchownSync as txi,fstatSync as $Ze,fsyncSync as nxi,linkSync as rxi,lstatSync as ixi,mkdirSync as oxi,openSync as OZe,readdirSync as sxi,readFileSync as C_n,readlinkSync as axi,readSync as cxi,realpathSync as uxi,renameSync as lxi,rmdirSync as dxi,rmSync as pxi,statSync as hxi,symlinkSync as mxi,unlinkSync as fxi,writeSync as gxi}from"node:fs";import{basename as yxi,dirname as wxi,join as Exi,relative as WZe,resolve as wge,sep as FZe}from"node:path";import{loadLinuxNative as I_n,O_CLOEXEC as Ege,O_PATH as xge,RESOLVE_BENEATH as v_n,RESOLVE_NO_SYMLINKS as S_n}from"../../native/linux.js";function HZe(){return Age===null&&(Age=I_n()),Age}function k_n(t){return t.code}function T_n(t,e){switch(k_n(t)){case"ELOOP":case"EXDEV":return new VI(`path meets a symlink: ${e}`);case"ENXIO":return new VI(`path is not a regular file: ${e}`);case"EAGAIN":return new VI(`path is held by a lease: ${e}`);default:return t}}function yge(t,e,n,r,i){try{return t.openat2(e,n,r,__n)}catch(o){throw T_n(o,i)}}function R_n(t,e,n){let r;try{r=$Ze(t)}catch(i){throw cE(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw cE(t),new VI(`path is not a regular file: ${e}`)}function B_n(t,e){let n=WZe(wge(t),wge(e));if(n===".."||n.startsWith(`..${FZe}`)||n.startsWith(FZe))throw new Error(`${e} is outside ${t}`);return n}function GZe(t,e,n){if(n&M6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=B_n(t,e),i=HZe();if(!i)return OZe(e,n);let o=OZe("/",UZe),s;try{s=yge(i,o,WZe("/",wge(t))||".",UZe,t)}finally{cE(o)}try{return n&xge?yge(i,s,r||".",n|Ege,e):R_n(yge(i,s,r||".",n|Ege|M6.O_NONBLOCK,e),e,!0)}finally{cE(s)}}function bge(t,e){let n=GZe(t,e,M6.O_RDONLY);try{return C_n(n)}finally{cE(n)}}function qZe(t,e){if(!HZe())return{path:e,release:()=>{}};let n=GZe(t,e,xge),r;try{r=$Ze(n)}catch(o){throw cE(n),o}if(!r.isSocket())throw cE(n),new VI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,cE(n))}}}var __n,UZe,Age,VI,TF=y(()=>{"use strict";__n=v_n|S_n,UZe=xge|M6.O_DIRECTORY|Ege,Age=null;VI=class extends Error{}});import{join as Sg}from"node:path";function oc(){return vg()}function jZe(){return Sg(oc(),"on-disk-migration.lock")}function eB(t){return Sg(tB(t),"view.sock")}function D_n(){return Sg(oc(),"nodes")}function zZe(){return Sg(gge(),"api.sock")}function VZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=M_n}function Cge(t){if(!VZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function P_n(t){return Cge(t),Sg(D_n(),t)}function N_n(t,e){Cge(t);let n=e??(xfe()===t?_Je():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return Sg(kF(n).nodes,t)}function tB(t){return Cge(t),process.platform==="linux"?Sg(gge(),"nodes",t):Sg(P_n(t),"run")}function JZe(t,e){return Sg(N_n(t,e),"context")}function XZe(t){return Sg(tB(t),"job")}var M_n,KZe,YZe,Hl=y(()=>{"use strict";W0();du();TF();M_n=128;KZe="broker-released",YZe="cli-relay-generation"});import{join as L_n}from"node:path";function Q_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 O_n(t){if(P6===void 0){P6=t;return}if(!Q_n(P6,t))throw new Error("event source is already bound for this process")}function ZZe(){O_n({component:"daemon",path:L_n(oc(),"crtrd.log")})}function N6(){return P6}var P6,Ige=y(()=>{"use strict";Hl()});function eet(t){return t instanceof Xt?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||t.code==="northlight_unreachable")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}function vge(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var Xt,_g=y(()=>{"use strict";Xt=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}}});var se,Sge=y(()=>{"use strict";se={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonDrain:()=>"/v1/daemon/drain",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,executionStart:t=>`/v1/executions/${t}/start`,executionImportUnpacked:t=>`/v1/executions/${t}/import-unpacked`,environmentGitCredential:t=>`/v1/environments/${t}/git-credential`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeFiles:t=>`/v1/nodes/${t}/files`,nodeFileComplete:(t,e)=>`/v1/nodes/${t}/files/${encodeURIComponent(e)}/complete`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobReport:(t,e)=>`/v1/nodes/${t}/jobs/${e}/report`,nodeJobOutput:(t,e)=>`/v1/nodes/${t}/jobs/${e}/output`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerCycle:t=>`/v1/nodes/${t}/broker/cycle`,nodeBrokerIdle:t=>`/v1/nodes/${t}/broker/idle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeSummaries:t=>`/v1/nodes/${t}/records/summaries`,nodeAttachments:t=>`/v1/nodes/${t}/attachments`,nodeAttachment:(t,e)=>`/v1/nodes/${t}/attachments/${e}`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerStructuredRequest:t=>`/v1/nodes/${t}/broker/structured-request`,nodeBrokerGoal:t=>`/v1/nodes/${t}/broker/goal`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,charges:()=>"/v1/charges",spendLimits:()=>"/v1/spend-limits",spendLimit:t=>`/v1/spend-limits/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",canvasBrowse:()=>"/v1/canvas/browse",canvasAnalytics:()=>"/v1/canvas/analytics",canvasGraph:()=>"/v1/canvas/graph",canvasPrune:()=>"/v1/canvas/prune",humanReviews:()=>"/v1/human/reviews",humanReview:t=>`/v1/human/reviews/${t}`,humanReviewSubmit:t=>`/v1/human/reviews/${t}/submit`,humanReviewCancel:t=>`/v1/human/reviews/${t}/cancel`,humanReviewDocument:t=>`/v1/human/reviews/${t}/document`,humanReviewComments:t=>`/v1/human/reviews/${t}/comments`,humanReviewCommentEvents:t=>`/v1/human/reviews/${t}/comment-events`,humanReviewCommentRanges:t=>`/v1/human/reviews/${t}/comment-ranges`,humanComment:t=>`/v1/human/comments/${t}`,humanCommentEdit:t=>`/v1/human/comments/${t}/edit`,humanCommentResolve:t=>`/v1/human/comments/${t}/resolve`,humanCommentReopen:t=>`/v1/human/comments/${t}/reopen`,humanCommentDelete:t=>`/v1/human/comments/${t}/delete`,humanCommentFork:t=>`/v1/human/comments/${t}/fork`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:t=>`/v1/human/inbox/${t}`,humanInboxRespond:t=>`/v1/human/inbox/${t}/respond`,humanInboxProgress:t=>`/v1/human/inbox/${t}/progress`,humanInboxResponse:t=>`/v1/human/inbox/${t}/response`,humanInboxCancel:t=>`/v1/human/inbox/${t}/cancel`,humanInboxFeedbackResolve:(t,e)=>`/v1/human/inbox/${t}/feedback-comments/${e}/resolve`,humanRequests:()=>"/v1/human/requests",humanComponents:()=>"/v1/human/components",humanRequest:t=>`/v1/human/requests/${t}`,humanRequestReplace:t=>`/v1/human/requests/${t}/replace`,humanRequestRespond:t=>`/v1/human/requests/${t}/respond`,humanRequestDismiss:t=>`/v1/human/requests/${t}/dismiss`,humanRequestCancel:t=>`/v1/human/requests/${t}/cancel`,profiles:()=>"/v1/profiles",profile:t=>`/v1/profiles/${t}`,profilePause:t=>`/v1/profiles/${t}/pause`,profileResume:t=>`/v1/profiles/${t}/resume`,profileMetadata:t=>`/v1/profiles/${t}/metadata`,appEnv:()=>"/v1/apps/self/env",appEnvVar:t=>`/v1/apps/self/env/${encodeURIComponent(t)}`,profileEnv:t=>`/v1/profiles/${t}/env`,profileEnvVar:(t,e)=>`/v1/profiles/${t}/env/${e}`,settings:()=>"/v1/settings",modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthAccount:(t,e)=>`/v1/model-auth/${t}/accounts/${encodeURIComponent(e)}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",exec:()=>"/v1/exec",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectShares:t=>`/v1/objects/${encodeURIComponent(t)}/shares`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",schemas:()=>"/v1/schemas",relations:()=>"/v1/relations",check:()=>"/v1/check",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"}});function L6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var _ge=y(()=>{"use strict"});function tet(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var kge=y(()=>{"use strict"});function net(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Tge=y(()=>{"use strict"});async function O6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=W_n,retry:i=()=>!0,now:o=Date.now,sleep:s=aet}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}function nB(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new Xt(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}function kr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function KI(t,e){let n=t.status>=200&&t.status<300,r=(await set(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new Xt(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw vge(i)?new Xt(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new Xt(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function G_n(t){return t==="GET"||t==="HEAD"}async function q_n(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await set(t.clone(),Math.min(e??1/0,Date.now()+5e3)),r=JSON.parse(n).error;return r?.origin==="router"&&r.details?.forwarded===!1&&(r.details.runtime_state==="creating"||r.details.runtime_state==="recovering")}catch{return!1}}function j_n(t){return t===429||t>=500}async function Rge(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function set(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),nB(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(nB(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function ret(t){return Math.min(2e3,250*2**(t-1))}function Bge(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function iet(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function uE(t,e){if(e?.aborted)return new Xt(0,"request_aborted","request aborted by caller signal");if(t instanceof Xt)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new Xt(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new Xt(0,"request_aborted","request aborted by caller signal");let n=Bge(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new Xt(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new Xt(504,"request_timeout",`crtrd request timed out: ${r}`):new Xt(503,"transport_error",r)}function z_n(t,e){return t==="GET"||t==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new Xt(e.status,e.code,`${e.message}; the ${t} request was sent, so it may or may not have been applied`,{outcome:"unknown"},e.headers)}function oet(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function Q6(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new Xt(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=nB(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return aet(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new Xt(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function V_n(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function aet(t){return new Promise(e=>setTimeout(e,t))}function K_n(t){if(t!==void 0)try{return t()}catch{return}}var F_n,U_n,$_n,W_n,BF,RF,kg,H_n,F6=y(()=>{"use strict";_g();Sge();_ge();kge();Tge();F_n=3e4,U_n=Symbol.for("@north-light/api/local-socket-fetch"),$_n=1e4,W_n=200;BF=2147483647;RF=t=>nB(t??Date.now()),kg=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??F_n,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[U_n]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??$_n}healthz(){return this.request("GET",se.healthz())}async probeHealthz(e){let n=await this.transport("GET",se.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return KI(n)}async ready(){let e=await this.transport("GET",se.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return KI(e)}status(){return this.request("GET",se.status())}due(){return this.request("GET",se.due())}restartDaemon(){return this.request("POST",se.daemonRestart())}drainDaemon(e={}){let n=e.settle_limit_ms??0;return this.request("POST",se.daemonDrain(),e,{timeout:n+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",se.daemonDrain())}admitDaemon(){return this.request("POST",se.daemonAdmit())}migrateState(e){return this.request("POST",se.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",se.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",se.nodeTelemetry(this.nodePath(e)),n)}async putNodeSummaries(e,n){await this.request("PUT",se.nodeSummaries(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",se.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",kr(se.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}listNodeAttachments(e){return this.request("GET",se.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,n){let r=await this.send("GET",se.nodeAttachment(this.nodePath(e),n));return r.ok||await KI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",se.nodeFiles(this.nodePath(e)),n)}completeNodeFile(e,n){return this.request("POST",se.nodeFileComplete(this.nodePath(e),n))}readNodePassiveMessage(e,n){return this.request("GET",kr(se.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",se.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",se.nodes(),e)}listNodes(e){return this.request("GET",kr(se.nodes(),e))}getNode(e){return this.request("GET",se.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",kr(se.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",kr(se.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",kr(se.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await KI(i);return}if(i.body===null)throw new Xt(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
89
- `))!==-1;){let d=a.slice(0,l);a=a.slice(l+1),d!==""&&(yield JSON.parse(d))}}if(a+=s.decode(),a.trim()!=="")throw new Xt(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,n){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,n):this.request("POST","/v1/structured-requests",e,n)}getStructuredRequest(e,{wait:n=0,budgetMs:r}={}){if(!Number.isInteger(n)||n<0||n>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",kr(`/v1/structured-requests/${this.requestPath(e)}`,{wait:n}),void 0,{budgetMs:r})}cancelStructuredRequest(e,n){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},n)}registerOutcomeDelivery(e,n){return this.request("PUT",se.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",se.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",se.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",se.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,n,r={}){let i=new URLSearchParams;r.tail_lines!==void 0&&i.set("tail_lines",String(r.tail_lines)),r.max_bytes!==void 0&&i.set("max_bytes",String(r.max_bytes));let o=i.size===0?"":`?${i.toString()}`;return this.request("GET",`${se.nodeJobOutput(this.nodePath(e),this.jobPath(n))}${o}`)}stopBashJob(e,n){return this.request("DELETE",se.nodeJob(this.nodePath(e),this.jobPath(n)))}async patchBashJob(e,n,r){await this.request("PATCH",se.nodeJob(this.nodePath(e),this.jobPath(n)),r)}async reportBashJob(e,n,r){await this.request("POST",se.nodeJobReport(this.nodePath(e),this.jobPath(n)),r)}sendMessage(e,n){return this.request("POST",se.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",se.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",se.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",se.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",se.nodeFork(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",se.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",se.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",se.nodeBrokerSessionBound(this.nodePath(e)),n)}settleBroker(e,n){return this.request("POST",se.nodeBrokerSettle(this.nodePath(e)),n)}startBrokerCycle(e,n){return this.request("POST",se.nodeBrokerCycle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",se.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",se.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",se.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",se.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",se.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",se.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",se.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",se.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",se.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${se.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",se.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${se.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",se.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",se.executionStart(e))}executionImportUnpacked(e){return this.request("POST",se.executionImportUnpacked(e),{})}gitCredential(e,n){return this.request("POST",se.environmentGitCredential(e),n)}brokerExtensionState(e){return this.request("GET",se.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",se.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",se.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",se.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",se.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",se.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",se.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",se.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",se.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",se.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",se.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",se.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",se.kinds())}patchConfig(e,n){return this.request("PATCH",se.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",se.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",se.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",se.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",se.quarantinedWorktrees())}showLimits(){return this.request("GET",se.limits())}setAppLimits(e,n){return this.request("PUT",se.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(se.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(se.charges(),e))}listSpendLimits(){return this.request("GET",se.spendLimits())}setSpendLimit(e,n){return this.request("PUT",se.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",se.spendLimit(e))}listSpaces(){return this.request("GET",se.spaces())}subscribe(e,n){return this.request("POST",se.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",se.focuses())}focusOf(e){return this.request("GET",kr(se.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(se.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",se.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",se.focus(e),n)}async closeFocus(e){await this.request("DELETE",se.focus(e))}async unsubscribe(e,n){await this.request("DELETE",se.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",se.crons(),e)}listCrons(e){return this.request("GET",kr(se.crons(),e))}showCron(e,n){return this.request("GET",kr(se.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(se.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(se.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(se.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(se.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",se.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",se.nodeAttach(this.nodePath(e)),n??{})}getReports(e,n){return this.request("GET",kr(se.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",kr(se.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",se.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",se.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",kr(se.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",se.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",se.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",kr(se.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",se.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",kr(se.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",se.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",kr(se.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",se.bash(),e,n)}objects={read:(e,n)=>this.request("GET",kr(se.object(e),n)),list:e=>this.request("GET",kr(se.objects(),e)),search:e=>this.request("POST",se.objectsSearch(),e),watch:(e,n={})=>this.request("POST",se.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",kr(se.objectWatch(e),n)),edges:(e,n)=>this.request("GET",kr(se.objectEdges(e),n))};docs={write:e=>this.request("POST",se.docs(),e),edit:(e,n)=>this.request("PATCH",se.doc(e),n),move:(e,n)=>this.request("POST",se.docMove(e),n),delete:e=>this.request("DELETE",se.doc(e)),history:(e,n)=>this.request("GET",kr(se.docHistory(e),n)),lint:(e={})=>this.request("POST",se.docsLint(),e)};documents={browserAccess:()=>this.request("GET",se.documentsBrowserAccess()),reconcilePackages:e=>this.request("POST",se.documentsReconcilePackages(),e)};plugins={appToken:e=>this.request("GET",se.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",se.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",se.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",se.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",se.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",se.profile(e),n??{})}createProfile(e){return this.request("POST",se.profiles(),e)}listProfiles(){return this.request("GET",se.profiles())}updateProfile(e,n){return this.request("PATCH",se.profile(e),n)}listAppEnv(){return this.request("GET",se.appEnv())}setAppEnv(e,n){return this.request("PUT",se.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",se.appEnvVar(e))}listProfileEnv(e){return this.request("GET",se.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",se.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",se.profileEnvVar(e,n))}getProfile(e){return this.request("GET",se.profile(e))}pauseProfile(e){return this.request("POST",se.profilePause(e),{})}resumeProfile(e){return this.request("POST",se.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",se.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",se.profile(e),n)}getSettings(){return this.request("GET",se.settings())}putSettings(e){return this.request("PUT",se.settings(),e)}listModelAuth(){return this.request("GET",se.modelAuths())}getModelAuthReadiness(e){return this.request("GET",kr(se.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",se.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",se.modelAuth(e))}patchModelAuthAccount(e,n,r){return this.request("PATCH",se.modelAuthAccount(e,n),r)}removeModelAuthAccount(e,n){return this.request("DELETE",se.modelAuthAccount(e,n))}startModelAuth(e){return this.request("POST",se.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",se.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",se.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",kr(se.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",se.humanReviews(),e)}listReviews(e){return this.request("GET",kr(se.humanReviews(),e))}getReview(e){return this.request("GET",se.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",se.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",se.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",se.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",se.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",kr(se.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",kr(se.humanReviewCommentEvents(this.reviewPath(e)),n))}updateReviewCommentRanges(e,n){return this.request("POST",se.humanReviewCommentRanges(this.reviewPath(e)),n)}getReviewComment(e){return this.request("GET",se.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",se.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",se.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",se.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",se.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",se.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",se.humanInbox())}getHumanInboxPage(e){return this.request("GET",se.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,n={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",kr(se.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",se.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",se.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",se.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",se.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",se.humanRequests(),e)}listPageComponents(){return this.request("GET",se.humanComponents())}getHumanRequest(e){return this.request("GET",se.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",se.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",se.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",se.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",se.humanRequestCancel(this.requestPath(e)),n)}resolvePageFeedbackComment(e,n,r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(n)}`);return this.request("POST",se.humanInboxFeedbackResolve(this.ticketId(e),n),{node_id:r})}async dashboard(e){let n=e?.under!==void 0?{under:e.under}:void 0,[r,i]=await Promise.all([this.listNodes(n),this.status()]);return{nodes:r,counts:i.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",se.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",se.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",se.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",se.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",kr(se.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",se.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",se.canvasSnapshot())}analytics(e){return this.request("GET",kr(se.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",se.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",kr(se.canvasLiveRoots(),e))}canvasRoster(){return this.request("GET",se.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",se.canvasBrowse());return e.ok||await KI(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",se.canvasGraph())}prune(e){return this.request("POST",se.canvasPrune(),e)}async request(e,n,r,i){try{let o=i===void 0?void 0:this.resolveBudget(i),s=await this.send(e,n,r,o);return await KI(s,o?.deadlineAt)}catch(o){throw z_n(e,uE(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw uE(i,r?.signal)}}async send(e,n,r,i={}){let o=this.resolveBudget(i),s=e==="GET"||e==="HEAD"||e==="DELETE",a=o.maxRetries??this.maxRetries,c=Math.min(o.deadlineAt??1/0,Date.now()+H_n);for(let u=0;;u++){let l;try{l=await this.transport(e,n,r,o)}catch(d){if(this.isColdSocketError(d)||this.isInterruptedSocketError(d)){let p=this.availabilityFailure?.();if(p!==void 0)throw p}if(this.isColdSocketError(d))try{await this.handleColdSocket(d,o.deadlineAt),l=await this.transport(e,n,r,o)}catch(p){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!iet(p,o.signal)?nB(o.deadlineAt):uE(p,o.signal)}else{if(this.isInterruptedSocketError(d)&&this.localSocketTransport&&(!s||u<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&u<a&&!iet(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await Q6(ret(u+1),o);continue}else throw uE(d,o.signal)}}if(G_n(e)&&a>0&&l.status===503&&await q_n(l,o.deadlineAt)){let d=Math.max(250,(oet(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await Rge(l,o.deadlineAt),await Q6(d,{signal:o.signal});continue}if(s&&u<a&&j_n(l.status)){await Rge(l,o.deadlineAt),await Q6(ret(u+1),o,oet(l));continue}return l}}resolveBudget(e){let{budgetMs:n,deadlineAt:r,...i}=e;if(n===void 0&&r===void 0)return i;if(n!==void 0&&(!Number.isFinite(n)||n<=0||n>BF))throw new RangeError(`budgetMs must be a positive finite number of at most ${BF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>BF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${BF} ms from now`);return{...i,deadlineAt:Math.min(r??1/0,n===void 0?1/0:Date.now()+n)}}async awaitWithinBudget(e,n){if(n===void 0)return e;let r=n-Date.now();if(r<=0)throw RF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(RF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await KI(await this.transport(e,n,r,o))}catch(s){throw uE(s,o.signal)}}nodePath(e){if(!L6(e))throw new Xt(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!tet(e))throw new Xt(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!net(e))throw new Xt(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!L6(e))throw new Xt(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!L6(e))throw new Xt(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new Xt(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,n,r,i={}){let o=i.deadlineAt===void 0?void 0:i.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(RF(i.deadlineAt));let s=r===void 0?void 0:JSON.stringify(r),a={accept:"application/json",...this.headers,...i.headers};s!==void 0&&(a["content-type"]="application/json");let c=i.timeout??this.timeoutMs,u=o===void 0?c:c>0?Math.min(c,o):o,l=new AbortController,d=o!==void 0&&(c<=0||o<=c),p=u>0?setTimeout(()=>l.abort(d?RF(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,h=i.signal,m=()=>l.abort(h?.reason);h!==void 0&&(h.aborted?l.abort(h.reason):h.addEventListener("abort",m,{once:!0}));let f=()=>{p!==void 0&&clearTimeout(p),h?.removeEventListener("abort",m)};return V_n(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>this.retainRequestLifetime(g,f,()=>l.signal.aborted?l.signal.reason:void 0),g=>{throw f(),g})}retainRequestLifetime(e,n,r){if(e.body===null)return n(),e;let i=e.body.getReader(),o=!1,s=()=>{o||(o=!0,n())},a=new ReadableStream({async pull(c){try{let{done:u,value:l}=await i.read();u?(s(),c.close()):c.enqueue(l)}catch(u){s(),c.error(r()??u)}},async cancel(c){s(),await i.cancel(c)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){let n=Bge(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=Bge(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw uE(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new Xt(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,n,r,i)}catch(o){throw uE(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw RF(n);let i,o;try{await O6({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:s=>s!==i&&s!==o,probe:async s=>{let a=this.availabilityFailure?.();if(a!==void 0)throw o=a,a;let c=this.coldStartFailure?.();if(c!==void 0)throw i=new Xt(503,"daemon_unavailable",`crtrd failed to start: ${c}`),i;let u=await this.transport("GET",se.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await Rge(u);return}let l=await u.text();try{if(typeof JSON.parse(l).startup_blocked=="string")return}catch{}throw new Xt(u.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${u.status}: ${l.slice(0,500)}`)}})}catch(s){throw s===i&&(this.startupFailureReported=!0),s}}async handleColdSocket(e,n){let r=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;r&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),n));try{await this.awaitAvailability(e,n)}catch(i){if(r&&!this.startupFailureReported){let o=K_n(this.coldStartDiagnostic);if(o!==void 0){let s=uE(i);throw new Xt(s.status,s.code,`${s.message}
88
+ `,n)}function g_n(t){let e=MZe(t,"r");try{DZe(e)}finally{BZe(e)}}function NZe(t){let e=MZe(t,"r");try{DZe(e)}finally{BZe(e)}}function pge(t,e,n){n?.createParent!==!1&&R6(TZe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(T6(t)?c_n(t).mode&511:384);try{u_n(r,e,{mode:i}),d_n(r,i),n?.durable===!0&&g_n(r),l_n(r,t),n?.durable===!0&&NZe(TZe(t))}finally{T6(r)&&a_n(r,{force:!0})}}function A_n(t){return JSON.parse(RZe(t,"utf8"))}function jI(t){try{return A_n(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function zI(t){try{return JSON.parse(RZe(t,"utf8"))}catch{return null}}function hge(t){return T6(t)}function mge(t){return T6(t)?s_n(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var $l=y(()=>{"use strict"});import{homedir as y_n,userInfo as w_n}from"node:os";import{basename as E_n,dirname as GEi,isAbsolute as qEi,join as Yd,resolve as LZe}from"node:path";function D6(){let t=LZe(Q0()||(process.platform==="linux"?"/":Yd(y_n(),".crouter")));if(x_n()&&t===b_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 x_n(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}function b_n(){if(B6===void 0)try{B6=LZe(w_n().homedir,".crouter")}catch{B6=null}return B6}function vg(){return Yd(D6(),"runtime")}function fge(){return Yd(D6(),"apps")}function $0(){return Yd(vg(),"secrets")}function QZe(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=kF(t);return{dir:Yd(n.profiles,e),env:Yd($0(),"env",E_n(n.root),e),home:n.home}}function gge(){return process.platform==="linux"?"/run/crtr":vg()}function kF(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=Yd(fge(),e);return{root:n,profiles:Yd(n,"profiles"),conversations:Yd(n,"conversations"),nodes:Yd(n,"nodes"),files:Yd(n,"files"),home:Yd(n,"home"),cache:Yd(n,"cache")}}var B6,W0=y(()=>{"use strict";du();Jd();XR();$l()});import{chmodSync as XEi,chownSync as ZEi,closeSync as cE,constants as M6,fchmodSync as exi,fchownSync as txi,fstatSync as $Ze,fsyncSync as nxi,linkSync as rxi,lstatSync as ixi,mkdirSync as oxi,openSync as OZe,readdirSync as sxi,readFileSync as C_n,readlinkSync as axi,readSync as cxi,realpathSync as uxi,renameSync as lxi,rmdirSync as dxi,rmSync as pxi,statSync as hxi,symlinkSync as mxi,unlinkSync as fxi,writeSync as gxi}from"node:fs";import{basename as yxi,dirname as wxi,join as Exi,relative as WZe,resolve as wge,sep as FZe}from"node:path";import{loadLinuxNative as I_n,O_CLOEXEC as Ege,O_PATH as xge,RESOLVE_BENEATH as v_n,RESOLVE_NO_SYMLINKS as S_n}from"../../native/linux.js";function HZe(){return Age===null&&(Age=I_n()),Age}function k_n(t){return t.code}function T_n(t,e){switch(k_n(t)){case"ELOOP":case"EXDEV":return new VI(`path meets a symlink: ${e}`);case"ENXIO":return new VI(`path is not a regular file: ${e}`);case"EAGAIN":return new VI(`path is held by a lease: ${e}`);default:return t}}function yge(t,e,n,r,i){try{return t.openat2(e,n,r,__n)}catch(o){throw T_n(o,i)}}function R_n(t,e,n){let r;try{r=$Ze(t)}catch(i){throw cE(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw cE(t),new VI(`path is not a regular file: ${e}`)}function B_n(t,e){let n=WZe(wge(t),wge(e));if(n===".."||n.startsWith(`..${FZe}`)||n.startsWith(FZe))throw new Error(`${e} is outside ${t}`);return n}function GZe(t,e,n){if(n&M6.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=B_n(t,e),i=HZe();if(!i)return OZe(e,n);let o=OZe("/",UZe),s;try{s=yge(i,o,WZe("/",wge(t))||".",UZe,t)}finally{cE(o)}try{return n&xge?yge(i,s,r||".",n|Ege,e):R_n(yge(i,s,r||".",n|Ege|M6.O_NONBLOCK,e),e,!0)}finally{cE(s)}}function bge(t,e){let n=GZe(t,e,M6.O_RDONLY);try{return C_n(n)}finally{cE(n)}}function qZe(t,e){if(!HZe())return{path:e,release:()=>{}};let n=GZe(t,e,xge),r;try{r=$Ze(n)}catch(o){throw cE(n),o}if(!r.isSocket())throw cE(n),new VI(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,cE(n))}}}var __n,UZe,Age,VI,TF=y(()=>{"use strict";__n=v_n|S_n,UZe=xge|M6.O_DIRECTORY|Ege,Age=null;VI=class extends Error{}});import{join as Sg}from"node:path";function oc(){return vg()}function jZe(){return Sg(oc(),"on-disk-migration.lock")}function eB(t){return Sg(tB(t),"view.sock")}function D_n(){return Sg(oc(),"nodes")}function zZe(){return Sg(gge(),"api.sock")}function VZe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=M_n}function Cge(t){if(!VZe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function P_n(t){return Cge(t),Sg(D_n(),t)}function N_n(t,e){Cge(t);let n=e??(xfe()===t?_Je():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return Sg(kF(n).nodes,t)}function tB(t){return Cge(t),process.platform==="linux"?Sg(gge(),"nodes",t):Sg(P_n(t),"run")}function JZe(t,e){return Sg(N_n(t,e),"context")}function XZe(t){return Sg(tB(t),"job")}var M_n,KZe,YZe,Hl=y(()=>{"use strict";W0();du();TF();M_n=128;KZe="broker-released",YZe="cli-relay-generation"});import{join as L_n}from"node:path";function Q_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 O_n(t){if(P6===void 0){P6=t;return}if(!Q_n(P6,t))throw new Error("event source is already bound for this process")}function ZZe(){O_n({component:"daemon",path:L_n(oc(),"crtrd.log")})}function N6(){return P6}var P6,Ige=y(()=>{"use strict";Hl()});function eet(t){return t instanceof Xt?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted"||t.code==="northlight_unreachable")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}function vge(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var Xt,_g=y(()=>{"use strict";Xt=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}}});var se,Sge=y(()=>{"use strict";se={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonDrain:()=>"/v1/daemon/drain",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,executionStart:t=>`/v1/executions/${t}/start`,executionImportUnpacked:t=>`/v1/executions/${t}/import-unpacked`,environmentGitCredential:t=>`/v1/environments/${t}/git-credential`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeFiles:t=>`/v1/nodes/${t}/files`,nodeFileComplete:(t,e)=>`/v1/nodes/${t}/files/${encodeURIComponent(e)}/complete`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobReport:(t,e)=>`/v1/nodes/${t}/jobs/${e}/report`,nodeJobOutput:(t,e)=>`/v1/nodes/${t}/jobs/${e}/output`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerCycle:t=>`/v1/nodes/${t}/broker/cycle`,nodeBrokerIdle:t=>`/v1/nodes/${t}/broker/idle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeSummaries:t=>`/v1/nodes/${t}/records/summaries`,nodeAttachments:t=>`/v1/nodes/${t}/attachments`,nodeAttachment:(t,e)=>`/v1/nodes/${t}/attachments/${e}`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerStructuredRequest:t=>`/v1/nodes/${t}/broker/structured-request`,nodeBrokerGoal:t=>`/v1/nodes/${t}/broker/goal`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,charges:()=>"/v1/charges",spendLimits:()=>"/v1/spend-limits",spendLimit:t=>`/v1/spend-limits/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",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}`,profileEnvironment:t=>`/v1/profiles/${t}/environment`,settings:()=>"/v1/settings",modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthAccount:(t,e)=>`/v1/model-auth/${t}/accounts/${encodeURIComponent(e)}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",exec:()=>"/v1/exec",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectShares:t=>`/v1/objects/${encodeURIComponent(t)}/shares`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",schemas:()=>"/v1/schemas",relations:()=>"/v1/relations",check:()=>"/v1/check",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"}});function L6(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var _ge=y(()=>{"use strict"});function tet(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var kge=y(()=>{"use strict"});function net(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var Tge=y(()=>{"use strict"});async function O6({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=W_n,retry:i=()=>!0,now:o=Date.now,sleep:s=aet}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}function nB(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new Xt(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}function kr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function KI(t,e){let n=t.status>=200&&t.status<300,r=(await set(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new Xt(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw vge(i)?new Xt(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new Xt(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function G_n(t){return t==="GET"||t==="HEAD"}async function q_n(t,e){try{if(Number(t.headers.get("content-length")??0)>8192)return!1;let n=await set(t.clone(),Math.min(e??1/0,Date.now()+5e3)),r=JSON.parse(n).error;return r?.origin==="router"&&r.details?.forwarded===!1&&(r.details.runtime_state==="creating"||r.details.runtime_state==="recovering")}catch{return!1}}function j_n(t){return t===429||t>=500}async function Rge(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function set(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),nB(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(nB(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function ret(t){return Math.min(2e3,250*2**(t-1))}function Bge(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function iet(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function uE(t,e){if(e?.aborted)return new Xt(0,"request_aborted","request aborted by caller signal");if(t instanceof Xt)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new Xt(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new Xt(0,"request_aborted","request aborted by caller signal");let n=Bge(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new Xt(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new Xt(504,"request_timeout",`crtrd request timed out: ${r}`):new Xt(503,"transport_error",r)}function z_n(t,e){return t==="GET"||t==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new Xt(e.status,e.code,`${e.message}; the ${t} request was sent, so it may or may not have been applied`,{outcome:"unknown"},e.headers)}function oet(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function Q6(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new Xt(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=nB(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return aet(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new Xt(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function V_n(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function aet(t){return new Promise(e=>setTimeout(e,t))}function K_n(t){if(t!==void 0)try{return t()}catch{return}}var F_n,U_n,$_n,W_n,BF,RF,kg,H_n,F6=y(()=>{"use strict";_g();Sge();_ge();kge();Tge();F_n=3e4,U_n=Symbol.for("@north-light/api/local-socket-fetch"),$_n=1e4,W_n=200;BF=2147483647;RF=t=>nB(t??Date.now()),kg=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??F_n,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[U_n]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??$_n}healthz(){return this.request("GET",se.healthz())}async probeHealthz(e){let n=await this.transport("GET",se.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return KI(n)}async ready(){let e=await this.transport("GET",se.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return KI(e)}status(){return this.request("GET",se.status())}due(){return this.request("GET",se.due())}restartDaemon(){return this.request("POST",se.daemonRestart())}drainDaemon(e={}){let n=e.settle_limit_ms??0;return this.request("POST",se.daemonDrain(),e,{timeout:n+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",se.daemonDrain())}admitDaemon(){return this.request("POST",se.daemonAdmit())}migrateState(e){return this.request("POST",se.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",se.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",se.nodeTelemetry(this.nodePath(e)),n)}async putNodeSummaries(e,n){await this.request("PUT",se.nodeSummaries(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",se.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",kr(se.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}listNodeAttachments(e){return this.request("GET",se.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,n){let r=await this.send("GET",se.nodeAttachment(this.nodePath(e),n));return r.ok||await KI(r),new Uint8Array(await r.arrayBuffer())}createNodeFile(e,n){return this.request("POST",se.nodeFiles(this.nodePath(e)),n)}completeNodeFile(e,n){return this.request("POST",se.nodeFileComplete(this.nodePath(e),n))}readNodePassiveMessage(e,n){return this.request("GET",kr(se.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",se.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",se.nodes(),e)}listNodes(e){return this.request("GET",kr(se.nodes(),e))}getNode(e){return this.request("GET",se.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",kr(se.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",kr(se.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",kr(se.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await KI(i);return}if(i.body===null)throw new Xt(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
89
+ `))!==-1;){let d=a.slice(0,l);a=a.slice(l+1),d!==""&&(yield JSON.parse(d))}}if(a+=s.decode(),a.trim()!=="")throw new Xt(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,n){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,n):this.request("POST","/v1/structured-requests",e,n)}getStructuredRequest(e,{wait:n=0,budgetMs:r}={}){if(!Number.isInteger(n)||n<0||n>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",kr(`/v1/structured-requests/${this.requestPath(e)}`,{wait:n}),void 0,{budgetMs:r})}cancelStructuredRequest(e,n){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},n)}registerOutcomeDelivery(e,n){return this.request("PUT",se.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",se.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",se.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",se.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,n,r={}){let i=new URLSearchParams;r.tail_lines!==void 0&&i.set("tail_lines",String(r.tail_lines)),r.max_bytes!==void 0&&i.set("max_bytes",String(r.max_bytes));let o=i.size===0?"":`?${i.toString()}`;return this.request("GET",`${se.nodeJobOutput(this.nodePath(e),this.jobPath(n))}${o}`)}stopBashJob(e,n){return this.request("DELETE",se.nodeJob(this.nodePath(e),this.jobPath(n)))}async patchBashJob(e,n,r){await this.request("PATCH",se.nodeJob(this.nodePath(e),this.jobPath(n)),r)}async reportBashJob(e,n,r){await this.request("POST",se.nodeJobReport(this.nodePath(e),this.jobPath(n)),r)}sendMessage(e,n){return this.request("POST",se.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",se.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",se.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",se.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",se.nodeFork(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",se.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",se.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",se.nodeBrokerSessionBound(this.nodePath(e)),n)}settleBroker(e,n){return this.request("POST",se.nodeBrokerSettle(this.nodePath(e)),n)}startBrokerCycle(e,n){return this.request("POST",se.nodeBrokerCycle(this.nodePath(e)),n)}async postBrokerIdle(e,n){await this.request("POST",se.nodeBrokerIdle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",se.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",se.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",se.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",se.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",se.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",se.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",se.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",se.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${se.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",se.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${se.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",se.nodeBrokerModel(this.nodePath(e)),n)}executionStart(e){return this.request("GET",se.executionStart(e))}executionImportUnpacked(e){return this.request("POST",se.executionImportUnpacked(e),{})}gitCredential(e,n){return this.request("POST",se.environmentGitCredential(e),n)}brokerExtensionState(e){return this.request("GET",se.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",se.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,n){return this.request("POST",se.nodeBrokerGoal(this.nodePath(e)),n)}commitBrokerGeneratedName(e,n){return this.request("POST",se.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",se.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",se.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",se.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",se.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",se.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",se.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",se.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",se.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",se.kinds())}patchConfig(e,n){return this.request("PATCH",se.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",se.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",se.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",se.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",se.quarantinedWorktrees())}showLimits(){return this.request("GET",se.limits())}setAppLimits(e,n){return this.request("PUT",se.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",kr(se.limitsApp(e),{fields:n.join(",")}))}listCharges(e={}){return this.request("GET",kr(se.charges(),e))}listSpendLimits(){return this.request("GET",se.spendLimits())}setSpendLimit(e,n){return this.request("PUT",se.spendLimit(e),n)}removeSpendLimit(e){return this.request("DELETE",se.spendLimit(e))}listSpaces(){return this.request("GET",se.spaces())}subscribe(e,n){return this.request("POST",se.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",se.focuses())}focusOf(e){return this.request("GET",kr(se.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",kr(se.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",se.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",se.focus(e),n)}async closeFocus(e){await this.request("DELETE",se.focus(e))}async unsubscribe(e,n){await this.request("DELETE",se.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",se.crons(),e)}listCrons(e){return this.request("GET",kr(se.crons(),e))}showCron(e,n){return this.request("GET",kr(se.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",kr(se.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",kr(se.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",kr(se.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",kr(se.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",se.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",se.nodeAttach(this.nodePath(e)),n??{})}getReports(e,n){return this.request("GET",kr(se.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",kr(se.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",se.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",se.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",kr(se.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",se.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",se.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",kr(se.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",se.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",kr(se.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",se.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",kr(se.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",se.bash(),e,n)}objects={read:(e,n)=>this.request("GET",kr(se.object(e),n)),list:e=>this.request("GET",kr(se.objects(),e)),search:e=>this.request("POST",se.objectsSearch(),e),watch:(e,n={})=>this.request("POST",se.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",kr(se.objectWatch(e),n)),edges:(e,n)=>this.request("GET",kr(se.objectEdges(e),n))};docs={write:e=>this.request("POST",se.docs(),e),edit:(e,n)=>this.request("PATCH",se.doc(e),n),move:(e,n)=>this.request("POST",se.docMove(e),n),delete:e=>this.request("DELETE",se.doc(e)),history:(e,n)=>this.request("GET",kr(se.docHistory(e),n)),lint:(e={})=>this.request("POST",se.docsLint(),e)};documents={browserAccess:()=>this.request("GET",se.documentsBrowserAccess()),reconcilePackages:e=>this.request("POST",se.documentsReconcilePackages(),e)};plugins={appToken:e=>this.request("GET",se.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",se.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",se.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",se.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",se.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",se.profile(e),n??{})}createProfile(e){return this.request("POST",se.profiles(),e)}listProfiles(){return this.request("GET",se.profiles())}updateProfile(e,n){return this.request("PATCH",se.profile(e),n)}listAppEnv(){return this.request("GET",se.appEnv())}setAppEnv(e,n){return this.request("PUT",se.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",se.appEnvVar(e))}listProfileEnv(e){return this.request("GET",se.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",se.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",se.profileEnvVar(e,n))}getProfileEnvironment(e){return this.request("GET",se.profileEnvironment(e))}setProfileEnvironment(e,n){return this.request("PUT",se.profileEnvironment(e),n)}getProfile(e){return this.request("GET",se.profile(e))}pauseProfile(e){return this.request("POST",se.profilePause(e),{})}resumeProfile(e){return this.request("POST",se.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",se.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",se.profile(e),n)}getSettings(){return this.request("GET",se.settings())}putSettings(e){return this.request("PUT",se.settings(),e)}listModelAuth(){return this.request("GET",se.modelAuths())}getModelAuthReadiness(e){return this.request("GET",kr(se.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",se.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",se.modelAuth(e))}patchModelAuthAccount(e,n,r){return this.request("PATCH",se.modelAuthAccount(e,n),r)}removeModelAuthAccount(e,n){return this.request("DELETE",se.modelAuthAccount(e,n))}startModelAuth(e){return this.request("POST",se.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",se.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",se.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",kr(se.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",se.humanReviews(),e)}listReviews(e){return this.request("GET",kr(se.humanReviews(),e))}getReview(e){return this.request("GET",se.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",se.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",se.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",se.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",se.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",kr(se.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",kr(se.humanReviewCommentEvents(this.reviewPath(e)),n))}updateReviewCommentRanges(e,n){return this.request("POST",se.humanReviewCommentRanges(this.reviewPath(e)),n)}getReviewComment(e){return this.request("GET",se.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",se.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",se.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",se.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",se.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",se.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",se.humanInbox())}getHumanInboxPage(e){return this.request("GET",se.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,n={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",kr(se.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",se.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",se.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",se.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",se.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",se.humanRequests(),e)}listPageComponents(){return this.request("GET",se.humanComponents())}getHumanRequest(e){return this.request("GET",se.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",se.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",se.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",se.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",se.humanRequestCancel(this.requestPath(e)),n)}resolvePageFeedbackComment(e,n,r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(n)}`);return this.request("POST",se.humanInboxFeedbackResolve(this.ticketId(e),n),{node_id:r})}async dashboard(e){let n=e?.under!==void 0?{under:e.under}:void 0,[r,i]=await Promise.all([this.listNodes(n),this.status()]);return{nodes:r,counts:i.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",se.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",se.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",se.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",se.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",kr(se.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",se.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",se.canvasSnapshot())}analytics(e){return this.request("GET",kr(se.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",se.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",kr(se.canvasLiveRoots(),e))}canvasRoster(){return this.request("GET",se.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",se.canvasBrowse());return e.ok||await KI(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",se.canvasGraph())}prune(e){return this.request("POST",se.canvasPrune(),e)}async request(e,n,r,i){try{let o=i===void 0?void 0:this.resolveBudget(i),s=await this.send(e,n,r,o);return await KI(s,o?.deadlineAt)}catch(o){throw z_n(e,uE(o,i?.signal))}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw uE(i,r?.signal)}}async send(e,n,r,i={}){let o=this.resolveBudget(i),s=e==="GET"||e==="HEAD"||e==="DELETE",a=o.maxRetries??this.maxRetries,c=Math.min(o.deadlineAt??1/0,Date.now()+H_n);for(let u=0;;u++){let l;try{l=await this.transport(e,n,r,o)}catch(d){if(this.isColdSocketError(d)||this.isInterruptedSocketError(d)){let p=this.availabilityFailure?.();if(p!==void 0)throw p}if(this.isColdSocketError(d))try{await this.handleColdSocket(d,o.deadlineAt),l=await this.transport(e,n,r,o)}catch(p){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!iet(p,o.signal)?nB(o.deadlineAt):uE(p,o.signal)}else{if(this.isInterruptedSocketError(d)&&this.localSocketTransport&&(!s||u<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&u<a&&!iet(d,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(d))){await Q6(ret(u+1),o);continue}else throw uE(d,o.signal)}}if(G_n(e)&&a>0&&l.status===503&&await q_n(l,o.deadlineAt)){let d=Math.max(250,(oet(l)??0)*1e3)+Math.random()*250;if(Date.now()+d>=c)return l;await Rge(l,o.deadlineAt),await Q6(d,{signal:o.signal});continue}if(s&&u<a&&j_n(l.status)){await Rge(l,o.deadlineAt),await Q6(ret(u+1),o,oet(l));continue}return l}}resolveBudget(e){let{budgetMs:n,deadlineAt:r,...i}=e;if(n===void 0&&r===void 0)return i;if(n!==void 0&&(!Number.isFinite(n)||n<=0||n>BF))throw new RangeError(`budgetMs must be a positive finite number of at most ${BF}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>BF))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${BF} ms from now`);return{...i,deadlineAt:Math.min(r??1/0,n===void 0?1/0:Date.now()+n)}}async awaitWithinBudget(e,n){if(n===void 0)return e;let r=n-Date.now();if(r<=0)throw RF(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(RF(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await KI(await this.transport(e,n,r,o))}catch(s){throw uE(s,o.signal)}}nodePath(e){if(!L6(e))throw new Xt(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!tet(e))throw new Xt(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!net(e))throw new Xt(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!L6(e))throw new Xt(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!L6(e))throw new Xt(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new Xt(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,n,r,i={}){let o=i.deadlineAt===void 0?void 0:i.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(RF(i.deadlineAt));let s=r===void 0?void 0:JSON.stringify(r),a={accept:"application/json",...this.headers,...i.headers};s!==void 0&&(a["content-type"]="application/json");let c=i.timeout??this.timeoutMs,u=o===void 0?c:c>0?Math.min(c,o):o,l=new AbortController,d=o!==void 0&&(c<=0||o<=c),p=u>0?setTimeout(()=>l.abort(d?RF(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,h=i.signal,m=()=>l.abort(h?.reason);h!==void 0&&(h.aborted?l.abort(h.reason):h.addEventListener("abort",m,{once:!0}));let f=()=>{p!==void 0&&clearTimeout(p),h?.removeEventListener("abort",m)};return V_n(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>this.retainRequestLifetime(g,f,()=>l.signal.aborted?l.signal.reason:void 0),g=>{throw f(),g})}retainRequestLifetime(e,n,r){if(e.body===null)return n(),e;let i=e.body.getReader(),o=!1,s=()=>{o||(o=!0,n())},a=new ReadableStream({async pull(c){try{let{done:u,value:l}=await i.read();u?(s(),c.close()):c.enqueue(l)}catch(u){s(),c.error(r()??u)}},async cancel(c){s(),await i.cancel(c)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){let n=Bge(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=Bge(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw uE(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new Xt(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,n,r,i)}catch(o){throw uE(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw RF(n);let i,o;try{await O6({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:s=>s!==i&&s!==o,probe:async s=>{let a=this.availabilityFailure?.();if(a!==void 0)throw o=a,a;let c=this.coldStartFailure?.();if(c!==void 0)throw i=new Xt(503,"daemon_unavailable",`crtrd failed to start: ${c}`),i;let u=await this.transport("GET",se.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await Rge(u);return}let l=await u.text();try{if(typeof JSON.parse(l).startup_blocked=="string")return}catch{}throw new Xt(u.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${u.status}: ${l.slice(0,500)}`)}})}catch(s){throw s===i&&(this.startupFailureReported=!0),s}}async handleColdSocket(e,n){let r=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;r&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),n));try{await this.awaitAvailability(e,n)}catch(i){if(r&&!this.startupFailureReported){let o=K_n(this.coldStartDiagnostic);if(o!==void 0){let s=uE(i);throw new Xt(s.status,s.code,`${s.message}
90
90
  ${o}`)}}throw i}}};H_n=6e4});function cet(){return Y_n??void 0}var Y_n,uet=y(()=>{"use strict";Y_n=null});import{request as J_n}from"node:http";import{homedir as X_n}from"node:os";import{join as Dge}from"node:path";function nkn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:Dge(X_n(),Z_n);return Dge(process.platform==="linux"?"/run/crtr":Dge(n,"runtime"),ekn)}function rkn(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=J_n({socketPath:t,path:i.pathname+i.search,method:o,headers:s},h=>{let m=new ReadableStream({start(A){h.on("data",x=>A.enqueue(new Uint8Array(x))),h.on("end",()=>A.close()),h.on("error",x=>A.error(x))},cancel(){h.destroy()}}),f=new Headers;for(let[A,x]of Object.entries(h.headers))if(x!==void 0)for(let b of Array.isArray(x)?x:[x])f.append(A,b);let g=h.statusCode??0;c(new Response(g===204?null:m,{status:g,statusText:h.statusMessage,headers:f}))});l.on("error",h=>u(new TypeError("fetch failed",{cause:h})));let d=r.signal,p=()=>{l.destroy(),u(d?.reason??new DOMException("The operation was aborted.","AbortError"))};if(d!=null){if(d.aborted){p();return}d.addEventListener("abort",p,{once:!0})}a!==void 0&&l.write(a),l.end()})};return e[tkn]=!0,e}function lE(t={}){let{socketPath:e,...n}=t;return new kg({baseUrl:"http://localhost",fetch:rkn(e??nkn()),autostart:!0,...n})}var Z_n,ekn,tkn,U6=y(()=>{"use strict";F6();Z_n=".crouter",ekn="api.sock",tkn=Symbol.for("@north-light/api/local-socket-fetch")});import{readFileSync as ikn}from"node:fs";import{dirname as okn,join as det}from"node:path";import{fileURLToPath as skn}from"node:url";function Mge(){if($6!==null)return $6;let t=det(okn(skn(import.meta.url)),"..","..");return $6=JSON.parse(ikn(det(t,"package.json"),"utf8")).version,$6}var $6,Pge=y(()=>{"use strict";$6=null});var pet=y(()=>{"use strict";MF();_g()});var Lge=Q(het=>{"use strict";het.parse=function(t,e){return new Nge(t,e).parse()};var Nge=class t{constructor(e,n){this.source=e,this.transform=n||akn,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var n;(this.recorded.length>0||e)&&(n=this.recorded.join(""),n==="NULL"&&!e&&(n=null),n!==null&&(n=this.transform(n)),this.entries.push(n),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var n,r,i;for(this.consumeDimensions();!this.isEof();)if(n=this.nextCharacter(),n.value==="{"&&!i)this.dimension++,this.dimension>1&&(r=new t(this.source.substr(this.position-1),this.transform),this.entries.push(r.parse(!0)),this.position+=r.position-2);else if(n.value==="}"&&!i){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else n.value==='"'&&!n.escaped?(i&&this.newEntry(!0),i=!i):n.value===","&&!i?this.newEntry():this.record(n.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};function akn(t){return t}});var Qge=Q((ibi,met)=>{var ckn=Lge();met.exports={create:function(t,e){return{parse:function(){return ckn.parse(t,e)}}}}});var Aet=Q((obi,get)=>{"use strict";var ukn=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,lkn=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,dkn=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,pkn=/^-?infinity$/;get.exports=function(e){if(pkn.test(e))return Number(e.replace("i","I"));var n=ukn.exec(e);if(!n)return hkn(e)||null;var r=!!n[8],i=parseInt(n[1],10);r&&(i=fet(i));var o=parseInt(n[2],10)-1,s=n[3],a=parseInt(n[4],10),c=parseInt(n[5],10),u=parseInt(n[6],10),l=n[7];l=l?1e3*parseFloat(l):0;var d,p=mkn(e);return p!=null?(d=new Date(Date.UTC(i,o,s,a,c,u,l)),Oge(i)&&d.setUTCFullYear(i),p!==0&&d.setTime(d.getTime()-p)):(d=new Date(i,o,s,a,c,u,l),Oge(i)&&d.setFullYear(i)),d};function hkn(t){var e=lkn.exec(t);if(e){var n=parseInt(e[1],10),r=!!e[4];r&&(n=fet(n));var i=parseInt(e[2],10)-1,o=e[3],s=new Date(n,i,o);return Oge(n)&&s.setFullYear(n),s}}function mkn(t){if(t.endsWith("+00"))return 0;var e=dkn.exec(t.split(" ")[1]);if(e){var n=e[1];if(n==="Z")return 0;var r=n==="-"?-1:1,i=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return i*r*1e3}}function fet(t){return-(t-1)}function Oge(t){return t>=0&&t<100}});var wet=Q((sbi,yet)=>{yet.exports=gkn;var fkn=Object.prototype.hasOwnProperty;function gkn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)fkn.call(n,r)&&(t[r]=n[r])}return t}});var bet=Q((abi,xet)=>{"use strict";var Akn=wet();xet.exports=rB;function rB(t){if(!(this instanceof rB))return new rB(t);Akn(this,Tkn(t))}var ykn=["seconds","minutes","hours","days","months","years"];rB.prototype.toPostgres=function(){var t=ykn.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var n=this[e]||0;return e==="seconds"&&this.milliseconds&&(n=(n+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),n+" "+e},this).join(" ")};var wkn={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},Ekn=["years","months","days"],xkn=["hours","minutes","seconds"];rB.prototype.toISOString=rB.prototype.toISO=function(){var t=Ekn.map(n,this).join(""),e=xkn.map(n,this).join("");return"P"+t+"T"+e;function n(r){var i=this[r]||0;return r==="seconds"&&this.milliseconds&&(i=(i+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),i+wkn[r]}};var Fge="([+-]?\\d+)",bkn=Fge+"\\s+years?",Ckn=Fge+"\\s+mons?",Ikn=Fge+"\\s+days?",vkn="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",Skn=new RegExp([bkn,Ckn,Ikn,vkn].map(function(t){return"("+t+")?"}).join("\\s*")),Eet={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},_kn=["hours","minutes","seconds","milliseconds"];function kkn(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}function Tkn(t){if(!t)return{};var e=Skn.exec(t),n=e[8]==="-";return Object.keys(Eet).reduce(function(r,i){var o=Eet[i],s=e[o];return!s||(s=i==="milliseconds"?kkn(s):parseInt(s,10),!s)||(n&&~_kn.indexOf(i)&&(s*=-1),r[i]=s),r},{})}});var vet=Q((cbi,Iet)=>{"use strict";var Cet=Buffer.from||Buffer;Iet.exports=function(e){if(/^\\x/.test(e))return Cet(e.substr(2),"hex");for(var n="",r=0;r<e.length;)if(e[r]!=="\\")n+=e[r],++r;else if(/[0-7]{3}/.test(e.substr(r+1,3)))n+=String.fromCharCode(parseInt(e.substr(r+1,3),8)),r+=4;else{for(var i=1;r+i<e.length&&e[r+i]==="\\";)i++;for(var o=0;o<Math.floor(i/2);++o)n+="\\";r+=Math.floor(i/2)*2}return Cet(n,"binary")}});var Met=Q((ubi,Det)=>{var PF=Lge(),NF=Qge(),W6=Aet(),ket=bet(),Tet=vet();function H6(t){return function(n){return n===null?n:t(n)}}function Ret(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}function Rkn(t){return t?PF.parse(t,Ret):null}function Bkn(t){return parseInt(t,10)}function Uge(t){return t?PF.parse(t,H6(Bkn)):null}function Dkn(t){return t?PF.parse(t,H6(function(e){return Bet(e).trim()})):null}var Mkn=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=Gge(n)),n});return e.parse()},$ge=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=parseFloat(n)),n});return e.parse()},lh=function(t){if(!t)return null;var e=NF.create(t);return e.parse()},Wge=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=W6(n)),n});return e.parse()},Pkn=function(t){if(!t)return null;var e=NF.create(t,function(n){return n!==null&&(n=ket(n)),n});return e.parse()},Nkn=function(t){return t?PF.parse(t,H6(Tet)):null},Hge=function(t){return parseInt(t,10)},Bet=function(t){var e=String(t);return/^\d+$/.test(e)?e:t},_et=function(t){return t?PF.parse(t,H6(JSON.parse)):null},Gge=function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},Lkn=function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",n="",r=!1,i=2;i<t.length-1;i++){if(r||(e+=t[i]),t[i]===")"){r=!0;continue}else if(!r)continue;t[i]!==","&&(n+=t[i])}var o=Gge(e);return o.radius=parseFloat(n),o},Qkn=function(t){t(20,Bet),t(21,Hge),t(23,Hge),t(26,Hge),t(700,parseFloat),t(701,parseFloat),t(16,Ret),t(1082,W6),t(1114,W6),t(1184,W6),t(600,Gge),t(651,lh),t(718,Lkn),t(1e3,Rkn),t(1001,Nkn),t(1005,Uge),t(1007,Uge),t(1028,Uge),t(1016,Dkn),t(1017,Mkn),t(1021,$ge),t(1022,$ge),t(1231,$ge),t(1014,lh),t(1015,lh),t(1008,lh),t(1009,lh),t(1040,lh),t(1041,lh),t(1115,Wge),t(1182,Wge),t(1185,Wge),t(1186,ket),t(1187,Pkn),t(17,Tet),t(114,JSON.parse.bind(JSON)),t(3802,JSON.parse.bind(JSON)),t(199,_et),t(3807,_et),t(3907,lh),t(2951,lh),t(791,lh),t(1183,lh),t(1270,lh)};Det.exports={init:Qkn}});var Net=Q((lbi,Pet)=>{"use strict";var Gl=1e6;function Okn(t){var e=t.readInt32BE(0),n=t.readUInt32BE(4),r="";e<0&&(e=~e+(n===0),n=~n+1>>>0,r="-");var i="",o,s,a,c,u,l;{if(o=e%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}{if(o=e%Gl,e=e/Gl>>>0,s=4294967296*o+n,n=s/Gl>>>0,a=""+(s-Gl*n),n===0&&e===0)return r+a+i;for(c="",u=6-a.length,l=0;l<u;l++)c+="0";i=c+a+i}return o=e%Gl,s=4294967296*o+n,a=""+s%Gl,r+a+i}Pet.exports=Okn});var Uet=Q((dbi,Fet)=>{var Fkn=Net(),as=function(t,e,n,r,i){n=n||0,r=r||!1,i=i||function(h,m,f){return h*Math.pow(2,f)+m};var o=n>>3,s=function(h){return r?~h&255:h},a=255,c=8-n%8;e<c&&(a=255<<8-e&255,c=e),n&&(a=a>>n%8);var u=0;n%8+e>=8&&(u=i(0,s(t[o])&a,c));for(var l=e+n>>3,d=o+1;d<l;d++)u=i(u,s(t[d]),8);var p=(e+n)%8;return p>0&&(u=i(u,s(t[l])>>8-p,p)),u},Oet=function(t,e,n){var r=Math.pow(2,n-1)-1,i=as(t,1),o=as(t,n,1);if(o===0)return 0;var s=1,a=function(u,l,d){u===0&&(u=1);for(var p=1;p<=d;p++)s/=2,(l&1<<d-p)>0&&(u+=s);return u},c=as(t,e,n+1,!1,a);return o==Math.pow(2,n+1)-1?c===0?i===0?1/0:-1/0:NaN:(i===0?1:-1)*Math.pow(2,o-r)*c},Ukn=function(t){return as(t,1)==1?-1*(as(t,15,1,!0)+1):as(t,15,1)},Let=function(t){return as(t,1)==1?-1*(as(t,31,1,!0)+1):as(t,31,1)},$kn=function(t){return Oet(t,23,8)},Wkn=function(t){return Oet(t,52,11)},Hkn=function(t){var e=as(t,16,32);if(e==49152)return NaN;for(var n=Math.pow(1e4,as(t,16,16)),r=0,i=[],o=as(t,16),s=0;s<o;s++)r+=as(t,16,64+16*s)*n,n/=1e4;var a=Math.pow(10,as(t,16,48));return(e===0?1:-1)*Math.round(r*a)/a},Qet=function(t,e){var n=as(e,1),r=as(e,63,1),i=new Date((n===0?1:-1)*r/1e3+9466848e5);return t||i.setTime(i.getTime()+i.getTimezoneOffset()*6e4),i.usec=r%1e3,i.getMicroSeconds=function(){return this.usec},i.setMicroSeconds=function(o){this.usec=o},i.getUTCMicroSeconds=function(){return this.usec},i},LF=function(t){for(var e=as(t,32),n=as(t,32,32),r=as(t,32,64),i=96,o=[],s=0;s<e;s++)o[s]=as(t,32,i),i+=32,i+=32;var a=function(u){var l=as(t,32,i);if(i+=32,l==4294967295)return null;var d;if(u==23||u==20)return d=as(t,l*8,i),i+=l*8,d;if(u==25)return d=t.toString(this.encoding,i>>3,(i+=l<<3)>>3),d;console.log("ERROR: ElementType not implemented: "+u)},c=function(u,l){var d=[],p;if(u.length>1){var h=u.shift();for(p=0;p<h;p++)d[p]=c(u,l);u.unshift(h)}else for(p=0;p<u[0];p++)d[p]=a(l);return d};return c(o,r)},Gkn=function(t){return t.toString("utf8")},qkn=function(t){return t===null?null:as(t,8)>0},jkn=function(t){t(20,Fkn),t(21,Ukn),t(23,Let),t(26,Let),t(1700,Hkn),t(700,$kn),t(701,Wkn),t(16,qkn),t(1114,Qet.bind(null,!1)),t(1184,Qet.bind(null,!0)),t(1e3,LF),t(1007,LF),t(1016,LF),t(1008,LF),t(1009,LF),t(25,Gkn)};Fet.exports={init:jkn}});var Wet=Q((pbi,$et)=>{$et.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var FF=Q(OF=>{var zkn=Met(),Vkn=Uet(),Kkn=Qge(),Ykn=Wet();OF.getTypeParser=Jkn;OF.setTypeParser=Xkn;OF.arrayParser=Kkn;OF.builtins=Ykn;var QF={text:{},binary:{}};function Het(t){return String(t)}function Jkn(t,e){return e=e||"text",QF[e]&&QF[e][t]||Het}function Xkn(t,e,n){typeof e=="function"&&(n=e,e="text"),QF[e][t]=n}zkn.init(function(t,e){QF.text[t]=e});Vkn.init(function(t,e){QF.binary[t]=e})});var UF=Q((mbi,qge)=>{"use strict";var Get;try{Get=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}qge.exports={host:"localhost",user:Get,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,client_encoding:"",ssl:!1,sslnegotiation:void 0,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var iB=FF(),Zkn=iB.getTypeParser(20,"text"),eTn=iB.getTypeParser(1016,"text");qge.exports.__defineSetter__("parseInt8",function(t){iB.setTypeParser(20,"text",t?iB.getTypeParser(23,"text"):Zkn),iB.setTypeParser(1016,"text",t?iB.getTypeParser(1007,"text"):eTn)})});var YI=Q((fbi,jet)=>{"use strict";var tTn=UF(),nTn=J("util"),{isDate:rTn}=J("util/types"),iTn=nTn.deprecate(()=>{},"Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.","PG_INVALID_DATE");function oTn(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function qet(t){let e="{";for(let n=0;n<t.length;n++){n>0&&(e+=",");let r=t[n];r==null?e+="NULL":Array.isArray(r)?e+=qet(r):ArrayBuffer.isView(r)?(r instanceof Buffer||(r=Buffer.from(r.buffer,r.byteOffset,r.byteLength)),e+="\\\\x"+r.toString("hex")):e+=oTn(G6(r))}return e+="}",e}var G6=function(t,e){return t==null?null:typeof t=="object"?t instanceof Buffer?t:ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):rTn(t)?(isNaN(t.getTime())&&iTn(),tTn.parseInputDatesAsUTC?cTn(t):aTn(t)):Array.isArray(t)?qet(t):sTn(t,e):t.toString()};function sTn(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),G6(t.toPostgres(G6),e)}return JSON.stringify(t)}function aTn(t){let e=-t.getTimezoneOffset(),n=t.getFullYear(),r=n<1;r&&(n=Math.abs(n)+1);let i=String(n).padStart(4,"0")+"-"+String(t.getMonth()+1).padStart(2,"0")+"-"+String(t.getDate()).padStart(2,"0")+"T"+String(t.getHours()).padStart(2,"0")+":"+String(t.getMinutes()).padStart(2,"0")+":"+String(t.getSeconds()).padStart(2,"0")+"."+String(t.getMilliseconds()).padStart(3,"0");return e<0?(i+="-",e*=-1):i+="+",i+=String(Math.floor(e/60)).padStart(2,"0")+":"+String(e%60).padStart(2,"0"),r&&(i+=" BC"),i}function cTn(t){let e=t.getUTCFullYear(),n=e<1;n&&(e=Math.abs(e)+1);let r=String(e).padStart(4,"0")+"-"+String(t.getUTCMonth()+1).padStart(2,"0")+"-"+String(t.getUTCDate()).padStart(2,"0")+"T"+String(t.getUTCHours()).padStart(2,"0")+":"+String(t.getUTCMinutes()).padStart(2,"0")+":"+String(t.getUTCSeconds()).padStart(2,"0")+"."+String(t.getUTCMilliseconds()).padStart(3,"0");return r+="+00:00",n&&(r+=" BC"),r}function uTn(t,e,n){return t=typeof t=="string"?{text:t}:lTn(t),e&&(typeof e=="function"?t.callback=e:t.values=e),n&&(t.callback=n),t}function lTn(t){return t==null?t:Object.defineProperties(Object.create(Object.getPrototypeOf(t)),Object.getOwnPropertyDescriptors(t))}var dTn=function(t){return'"'+t.replace(/"/g,'""')+'"'},pTn=function(t){let e=!1,n="'";if(t==null||typeof t!="string")return"''";for(let r=0;r<t.length;r++){let i=t[r];i==="'"?n+=i+i:i==="\\"?(n+=i+i,e=!0):n+=i}return n+="'",e===!0&&(n=" E"+n),n};jet.exports={prepareValue:function(e){return G6(e)},normalizeQueryConfig:uTn,escapeIdentifier:dTn,escapeLiteral:pTn}});var Vge=Q((gbi,Ket)=>{var zet=J("crypto");Ket.exports={postgresMd5PasswordHash:mTn,randomBytes:hTn,deriveKey:yTn,sha256:fTn,hashByName:gTn,hmacSha256:ATn,md5:jge};var Vet=zet.webcrypto||globalThis.crypto,JI=Vet.subtle,zge=new TextEncoder;function hTn(t){return Vet.getRandomValues(Buffer.alloc(t))}async function jge(t){try{return zet.createHash("md5").update(t,"utf-8").digest("hex")}catch{let n=typeof t=="string"?zge.encode(t):t,r=await JI.digest("MD5",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}}async function mTn(t,e,n){let r=await jge(e+t);return"md5"+await jge(Buffer.concat([Buffer.from(r),n]))}async function fTn(t){return await JI.digest("SHA-256",t)}async function gTn(t,e){return await JI.digest(t,e)}async function ATn(t,e){let n=await JI.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await JI.sign("HMAC",n,zge.encode(e))}async function yTn(t,e,n){let r=await JI.importKey("raw",zge.encode(t),"PBKDF2",!1,["deriveBits"]),i={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:n};return await JI.deriveBits(i,r,256,["deriveBits"])}});var Xet=Q((Abi,Jet)=>{function XI(t,e){return new Error("SASL channel binding: "+t+" when parsing public certificate "+e.toString("base64"))}function Kge(t,e){let n=t[e++];if(n<128)return{length:n,index:e};let r=n&127;if(r>4)throw XI("bad length",t);n=0;for(let i=0;i<r;i++)n=n<<8|t[e++];return{length:n,index:e}}function Yet(t,e){if(t[e++]!==6)throw XI("non-OID data",t);let{length:n,index:r}=Kge(t,e);e=r;let i=e+n,o=t[e++],s=(o/40>>0)+"."+o%40;for(;e<i;){let a=0;for(;e<i;){let c=t[e++];if(a=a<<7|c&127,c<128)break}s+="."+a}return{oid:s,index:e}}function $F(t,e){if(t[e++]!==48)throw XI("non-sequence data",t);return Kge(t,e)}function wTn(t,e){e===void 0&&(e=0),e=$F(t,e).index;let{length:n,index:r}=$F(t,e);e=r+n,e=$F(t,e).index;let{oid:i,index:o}=Yet(t,e);switch(i){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(e=o,e=$F(t,e).index,t[e++]!==160)throw XI("non-tag data",t);e=Kge(t,e).index,e=$F(t,e).index;let{oid:s}=Yet(t,e);switch(s){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw XI("unknown hash OID "+s,t)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw XI("Ed448 certificate channel binding is not currently supported by Postgres")}throw XI("unknown OID "+i,t)}Jet.exports={signatureAlgorithmHashFromCertificate:wTn}});var ntt=Q((ybi,ttt)=>{"use strict";var dE=Vge(),{signatureAlgorithmHashFromCertificate:ETn}=Xet();function xTn(t){let e=/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g,n=/[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g;return t.replace(e," ").replace(n,"").normalize("NFKC")}var Yge=1e5;function bTn(t,e,n=Yge){let r=["SCRAM-SHA-256"];e&&r.unshift("SCRAM-SHA-256-PLUS");let i=r.find(a=>t.includes(a));if(!i)throw new Error("SASL: Only mechanism(s) "+r.join(" and ")+" are supported");if(i==="SCRAM-SHA-256-PLUS"&&typeof e.getPeerCertificate!="function")throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let o=dE.randomBytes(18).toString("base64");return{mechanism:i,clientNonce:o,response:(i==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":e?"y":"n")+",,n=*,r="+o,message:"SASLInitialResponse",scramMaxIterations:n}}async function CTn(t,e,n,r){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof n!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let i=STn(n);if(i.nonce.startsWith(t.clientNonce)){if(i.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");let o=typeof t.scramMaxIterations=="number"?t.scramMaxIterations:Yge;if(o!==0&&i.iteration>o)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count "+i.iteration+" exceeds scramMaxIterations of "+o);let s="n=*,r="+t.clientNonce,a="r="+i.nonce+",s="+i.salt+",i="+i.iteration,c=r?"eSws":"biws";if(t.mechanism==="SCRAM-SHA-256-PLUS"){let b=r.getPeerCertificate().raw,v=ETn(b);(v==="MD5"||v==="SHA-1")&&(v="SHA-256");let S=await dE.hashByName(v,b);c=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(S)]).toString("base64")}let u="c="+c+",r="+i.nonce,l=s+","+a+","+u,d=Buffer.from(i.salt,"base64"),p=await dE.deriveKey(xTn(e),d,i.iteration),h=await dE.hmacSha256(p,"Client Key"),m=await dE.sha256(h),f=await dE.hmacSha256(m,l),g=kTn(Buffer.from(h),Buffer.from(f)).toString("base64"),A=await dE.hmacSha256(p,"Server Key"),x=await dE.hmacSha256(A,l);t.message="SASLResponse",t.serverSignature=Buffer.from(x).toString("base64"),t.response=u+",p="+g}function ITn(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:n}=_Tn(e);if(n!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function vTn(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,n)=>t.charCodeAt(n)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function Zet(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}function ett(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let n=e[0],r=e.substring(2);return[n,r]}))}function STn(t){let e=ett(t),n=e.get("r");if(n){if(!vTn(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let r=e.get("s");if(r){if(!Zet(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let i=e.get("i");if(i){if(!/^[1-9][0-9]*$/.test(i))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let o=parseInt(i,10);return{nonce:n,salt:r,iteration:o}}function _Tn(t){let e=ett(t),n=e.get("e"),r=e.get("v");if(n)throw new Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${n}"`);if(r){if(!Zet(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}function kTn(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((n,r)=>t[r]^e[r]))}ttt.exports={startSession:bTn,continueSession:CTn,finalizeSession:ITn,DEFAULT_MAX_SCRAM_ITERATIONS:Yge}});var j6=Q((wbi,rtt)=>{"use strict";var TTn=FF();function q6(t){this._types=t||TTn,this.text={},this.binary={}}q6.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};q6.prototype.setTypeParser=function(t,e,n){typeof e=="function"&&(n=e,e="text"),this.getOverrides(e)[t]=n};q6.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};rtt.exports=q6});var stt=Q((Ebi,ott)=>{"use strict";function oB(t,e={}){if(t.charAt(0)==="/"){let c=t.split(" ");return{host:c[0],database:c[1]}}let n=Object.create(null),r,i=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/%25(\d\d)/g,"%$1"));try{try{r=new URL(t,"postgres://base")}catch{r=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),i=!0}}catch(c){throw c.input&&(c.input="*****REDACTED*****"),c}for(let c of r.searchParams.entries())n[c[0]]=c[1];if(n.user=n.user||decodeURIComponent(r.username),n.password=n.password||decodeURIComponent(r.password),r.protocol=="socket:")return n.host=decodeURI(r.pathname),n.database=r.searchParams.get("db"),n.client_encoding=r.searchParams.get("encoding"),n;let o=(i?"":r.hostname).replace(/^\[(.+)\]$/,"$1");n.host?o&&/^%2f/i.test(o)&&(r.pathname=o+r.pathname):n.host=decodeURIComponent(o),n.port||(n.port=r.port);let s=r.pathname.slice(1)||null;n.database=s?decodeURI(s):null,(n.ssl==="true"||n.ssl==="1")&&(n.ssl=!0),n.ssl==="0"&&(n.ssl=!1),(n.sslcert||n.sslkey||n.sslrootcert||n.sslmode)&&(n.ssl={}),n.sslnegotiation==="direct"&&n.ssl===void 0&&(n.ssl=!0);let a=n.sslcert||n.sslkey||n.sslrootcert?J("fs"):null;if(n.sslcert&&(n.ssl.cert=a.readFileSync(n.sslcert).toString()),n.sslkey&&(n.ssl.key=a.readFileSync(n.sslkey).toString()),n.sslrootcert&&(n.ssl.ca=a.readFileSync(n.sslrootcert).toString()),e.useLibpqCompat&&n.uselibpqcompat)throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(n.uselibpqcompat==="true"||e.useLibpqCompat)switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":{n.ssl.rejectUnauthorized=!1;break}case"require":{n.sslrootcert?n.ssl.checkServerIdentity=function(){}:n.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!n.ssl.ca)throw new Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");n.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(n.sslmode){case"disable":{n.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{n.sslmode!=="verify-full"&&Jge(n.sslmode);break}case"no-verify":{n.ssl.rejectUnauthorized=!1;break}}return n}function RTn(t){return Object.entries(t).reduce((n,[r,i])=>(i!=null&&(n[r]=i),n),Object.create(null))}function itt(t){return Object.entries(t).reduce((n,[r,i])=>{if(r==="ssl"){let o=i;typeof o=="boolean"&&(n[r]=o),typeof o=="object"&&(n[r]=RTn(o))}else if(i!=null)if(r==="port"){if(i!==""){let o=parseInt(i,10);if(isNaN(o))throw new Error(`Invalid ${r}: ${i}`);n[r]=o}}else n[r]=i;return n},Object.create(null))}function BTn(t){return itt(oB(t))}function Jge(t){!Jge.warned&&typeof process<"u"&&process.emitWarning&&(Jge.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
91
91
  In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
92
92
 
@@ -1575,9 +1575,9 @@ ${i}`}function Fgn(t,e,n){return t.children.filter(i=>qw(i)&&i.tag==="li").map((
1575
1575
  `)}done(){return this.buffers.join("").replace(/\n{3,}/g,`
1576
1576
 
1577
1577
  `).replace(/[ \t]+\n/g,`
1578
- `).trim()}};function BO(t){let e=new kKe,n=[],r=[],i=[],o=0,s=!1,a=!1,c=0,u=()=>" ".repeat(Math.max(0,n.length-1));for(let l of xai(t)){if(l.kind==="text"){if(i.length>0)continue;if(o>0){e.write(l.text);continue}let f=$gn(l.text).replace(/\s+/g," ");if(f.trim()===""){/\s/.test(f)&&e.write(" ");continue}e.write(Ugn(f));continue}let{name:d,closing:p,attrs:h}=l;if(mai.has(d)){if(p){let f=i.lastIndexOf(d);f>=0&&(i.length=f)}else l.selfClosing||i.push(d);continue}if(i.length>0)continue;let m=/^h([1-6])$/.exec(d);if(m!==null){e.block(),p||e.write(`${"#".repeat(Number(m[1]))} `);continue}if(d==="pre"){p?(o=Math.max(0,o-1),e.line(),e.write("```"),e.block()):(e.block(),e.write("```\n"),o++);continue}if(d==="br"){e.line();continue}if(d==="hr"){e.block(),e.write("---"),e.block();continue}if(d==="ul"||d==="ol"){p?n.pop():(e.block(),n.push({ordered:d==="ol",index:0})),p&&e.block();continue}if(d==="li"){if(p)continue;let f=n[n.length-1];e.line(),f===void 0?e.write("- "):(f.index++,e.write(`${u()}${f.ordered?`${f.index}. `:"- "}`));continue}if(d==="dt"||d==="dd"){e.line(),p||e.write(d==="dt"?"":" ");continue}if(d==="tr"){p?(e.write(c>0?" |":""),a&&c>0&&(e.line(),e.write(`|${" --- |".repeat(c)}`)),e.line()):(e.line(),a=!1,c=0);continue}if(d==="td"||d==="th"){if(p){if(!s)continue;s=!1,e.write(e.pop().replace(/\s+/g," ").trim())}else d==="th"&&(a=!0),c++,e.write(c===1?"| ":" | "),e.push(),s=!0;continue}if(d==="a"){if(p){if(r.length===0)continue;let A=r.pop();if(A===null)continue;let x=e.pop().replace(/\s+/g," ").trim();x!==""&&e.write(`[${x}](${A})`);continue}let f=h.get("href"),g=f!==void 0&&f!==""&&!f.startsWith("#");r.push(g?f:null),g&&e.push();continue}if(d==="code"&&o===0){e.write("`");continue}if(d==="strong"||d==="b"){e.write("**");continue}if(d==="em"||d==="i"){e.write("*");continue}if(d==="img"){let f=h.get("alt");f!==void 0&&f!==""&&e.write(Ugn(f));continue}if(d==="blockquote"){e.block(),p||e.write("> ");continue}if(fai.has(d)&&!gai.has(d)){e.block();continue}}return e.done()}import{closeSync as Xci,existsSync as Zci,fstatSync as eui,openSync as tui,readFileSync as bAn,readSync as nui}from"node:fs";import{dirname as rui,join as WKe}from"node:path";import{gunzipSync as iui}from"node:zlib";F6();_g();Sge();tv();_ge();var Wgn=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid"];kge();Tge();WAe();U6();import{renameSync as n4s,rmSync as vai}from"node:fs";uh();$l();W0();pu();import{join as Hgn}from"node:path";uh();pu();var bai="northlight_unreachable",Cai="Check this computer's internet connection, then retry.";function Iai(t){let e=t?.cause,n=t;for(let r of[e?.code,e?.message,n?.code,n?.message])if(typeof r=="string"&&r!=="")return r;return String(t)}function Y3(t,e){let n=`crtr cannot reach Northlight (${new URL(e).host}): ${Iai(t)}.`;return new ss(bai,n,Vi.NETWORK,{next:Cai})}var Sai=()=>Hgn($0(),"person-credential"),RKe=()=>Hgn($0(),"person-bearer.json");var _ai=3e4;var Ggn=t=>t.replace(/\/+$/,""),qpe=t=>new ss("not_signed_in",t,Vi.USAGE,{next:"Run `crtr sys signin`, then retry."});function BKe(){let t=zI(Sai());if(!(t===null||typeof t.secret!="string"||typeof t.directoryUrl!="string"))return{directoryUrl:t.directoryUrl,secret:t.secret}}function TKe(t,e){let n=t!==null&&typeof t=="object"?t:{},r=n.error;if(r!==null&&typeof r=="object"){let i=r;return{code:String(i.code??"error"),message:String(i.message??`HTTP ${e}`)}}return typeof r=="string"?{code:r,message:String(n.error_description??n.message??r)}:{code:"error",message:`the directory answered HTTP ${e}`}}async function kai(t,e,n,r){let i;try{i=await fetch(`${Ggn(t)}${e}`,{method:"POST",headers:{"content-type":"application/json",...r===void 0?{}:{authorization:`Bearer ${r}`}},body:JSON.stringify(n),signal:AbortSignal.timeout(3e4)})}catch(a){throw Y3(a,t)}let o=await i.text(),s={};try{s=o===""?{}:JSON.parse(o)}catch{}return{status:i.status,body:s}}var Tai=(t,e)=>{let n=TKe(e,t);throw IF(`the directory refused: ${n.message}`,{code:n.code})};var Rai=new Set(["credential_revoked","credential_expired","credential_unknown"]);async function Bai(t,e,n=!1){let r=await kai(t,"/v1/developer/token",{},e);if(r.status===401&&Rai.has(TKe(r.body,401).code))throw n&&vai(RKe(),{force:!0}),qpe(`the sign-in on this computer is no longer valid (${TKe(r.body,401).code})`);r.status!==200&&Tai(r.status,r.body);let i=r.body;if(typeof i.access_token!="string"||typeof i.expires_in!="number")throw IF("the directory answered without a bearer token");let o=i.account;return{access_token:i.access_token,expires_in:i.expires_in,...typeof o?.id=="string"&&typeof o.display=="string"?{account:{id:o.id,display:o.display}}:{}}}function Dai(t,e){ZR(RKe(),{directoryUrl:t,access_token:e.access_token,expires_at_ms:Date.now()+e.expires_in*1e3},{mode:384})}async function jpe(t){let e=BKe();if(e===void 0)throw qpe("this computer is not signed in");let n=Ggn(t??e.directoryUrl),r=zI(RKe());if(r!==null&&r.directoryUrl===n&&typeof r.access_token=="string"&&r.expires_at_ms-Date.now()>_ai)return r.access_token;let i=await Bai(n,e.secret,!0);return Dai(n,i),i.access_token}function qgn(t,e){return async(n,r)=>{let i=new Headers(r?.headers);i.set("authorization",`Bearer ${await jpe(t)}`);try{return await fetch(n,{...r,headers:i})}catch(o){throw r?.signal?.aborted===!0?o:Y3(o,e)}}}W0();uh();$l();pu();import{chmodSync as d4s,existsSync as jgn,mkdirSync as p4s,readFileSync as zgn,rmSync as h4s,writeFileSync as m4s}from"node:fs";import{dirname as g4s,join as Vgn}from"node:path";var Mai=()=>Vgn(vg(),"machine.json");function AR(){let t=Mai();if(!jgn(t))return;let e=JSON.parse(zgn(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, runId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,runId:e.runId,directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}var Pai=()=>Vgn(vg(),"import","move.json");function Nai(){let t=Pai();if(!jgn(t))return;let e=JSON.parse(zgn(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var Kgn=()=>Nai()?.state==="committed",Ygn=t=>new ss("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,Vi.USAGE,{next:"Run `crtr sys signin` to finish."});uh();pu();du();var D4s=256*1024;var Zp=class extends ss{payload;constructor(e,n=Vi.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};function Lai(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Qai={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"};function DKe(t,e,n={}){if(t.code==="daemon_restarting")return new ss("daemon_restarting",t.message,Vi.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="layout_migration_required")return new ss("layout_migration_required",t.message,Vi.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(t.code==="daemon_unavailable")return new ss("daemon_unavailable",t.message,Vi.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});if(t.code==="northlight_unreachable"){let a=t.details?.next;return new ss("northlight_unreachable",t.message,Vi.NETWORK,{next:typeof a=="string"&&a!==""?a:"Check this computer's internet connection, then retry."})}if(t.code==="model_sign_in_required"){let a=t.details?.url;return new Zp({error:t.code,message:t.message,next:typeof a=="string"?`Ask the person to sign in at ${a}, then retry.`:"Ask the person to sign in to an AI subscription on their Northlight account, then retry.",...typeof a=="string"?{details:{url:a}}:{}},Vi.USAGE)}let r=t.details,i=Oai(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new ss(a,t.message,Vi.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??Qai[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??(r?.outcome==="unknown"?"The change may already be applied: check the current state before repeating it, and do not report it failed.":void 0)??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404&&i.code===void 0?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new Zp(s,Fai(s.error,t.status))}function Oai(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),Lai(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function Fai(t,e){return t==="not_found"||e===404?Vi.NOT_FOUND:t==="ambiguous"?Vi.AMBIGUOUS:Vi.USAGE}Hl();import{spawn as wci,execFileSync as rGs}from"node:child_process";import{createRequire as Eci}from"node:module";import{dirname as NKe,join as PO}from"node:path";import{fileURLToPath as xci,pathToFileURL as LKe}from"node:url";import{existsSync as pAn,lstatSync as bci,mkdirSync as Cci,openSync as hAn,closeSync as mAn,fstatSync as fAn,readSync as Ici}from"node:fs";Ige();pu();nv();mE();import{copyFileSync as Uai,mkdirSync as Vpe,existsSync as zpe,readFileSync as $ai,writeFileSync as Zgn,chmodSync as Wai,readdirSync as Hai,renameSync as yR,realpathSync as J3,unlinkSync as Gai,rmSync as qai,linkSync as Jgn}from"node:fs";import{homedir as eAn}from"node:os";import{dirname as tAn,join as xs}from"node:path";import{execFile as jai,spawn as zai,spawnSync as Ype}from"node:child_process";var Jpe="crouter";function MO(){return xs(eAn(),UI,"host")}function nAn(){return xs(MO(),Jpe)}function PKe(){return xs(MO(),".source.json")}function Vai(t){let e=tAn(t);for(let n of[e,xs(e,"..","lib")]){if(!zpe(n))continue;let r=Hai(n).find(i=>i.startsWith("libnode.")&&i.endsWith(".dylib"));if(r!==void 0)return xs(n,r)}return null}function Xgn(t,e,n){let r=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;Uai(t,r),n!==void 0&&Wai(r,n),yR(r,e)}function MKe(t=PKe()){try{return JSON.parse($ai(t,"utf8"))}catch{return null}}var Kai=3e4;function Yai(t){let e=xs(eAn(),UI),n=xs(e,"host.lock");return Vpe(e,{recursive:!0}),iv(n,t,{timeoutMs:Kai,timeoutError:()=>new Error(`timed out waiting for branded host lock: ${n}`)})}function Jai(t={}){let e=t.configured?.trim();return e?[e]:[t.discovered?.trim()||"-"]}function Xai(){if(process.platform!=="darwin")return null;let t=Ype("security",["find-identity","-v","-p","codesigning"],{stdio:["pipe","pipe","pipe"]});if(t.status!==0)return null;let n=(t.stdout??"").toString().split(`
1578
+ `).trim()}};function BO(t){let e=new kKe,n=[],r=[],i=[],o=0,s=!1,a=!1,c=0,u=()=>" ".repeat(Math.max(0,n.length-1));for(let l of xai(t)){if(l.kind==="text"){if(i.length>0)continue;if(o>0){e.write(l.text);continue}let f=$gn(l.text).replace(/\s+/g," ");if(f.trim()===""){/\s/.test(f)&&e.write(" ");continue}e.write(Ugn(f));continue}let{name:d,closing:p,attrs:h}=l;if(mai.has(d)){if(p){let f=i.lastIndexOf(d);f>=0&&(i.length=f)}else l.selfClosing||i.push(d);continue}if(i.length>0)continue;let m=/^h([1-6])$/.exec(d);if(m!==null){e.block(),p||e.write(`${"#".repeat(Number(m[1]))} `);continue}if(d==="pre"){p?(o=Math.max(0,o-1),e.line(),e.write("```"),e.block()):(e.block(),e.write("```\n"),o++);continue}if(d==="br"){e.line();continue}if(d==="hr"){e.block(),e.write("---"),e.block();continue}if(d==="ul"||d==="ol"){p?n.pop():(e.block(),n.push({ordered:d==="ol",index:0})),p&&e.block();continue}if(d==="li"){if(p)continue;let f=n[n.length-1];e.line(),f===void 0?e.write("- "):(f.index++,e.write(`${u()}${f.ordered?`${f.index}. `:"- "}`));continue}if(d==="dt"||d==="dd"){e.line(),p||e.write(d==="dt"?"":" ");continue}if(d==="tr"){p?(e.write(c>0?" |":""),a&&c>0&&(e.line(),e.write(`|${" --- |".repeat(c)}`)),e.line()):(e.line(),a=!1,c=0);continue}if(d==="td"||d==="th"){if(p){if(!s)continue;s=!1,e.write(e.pop().replace(/\s+/g," ").trim())}else d==="th"&&(a=!0),c++,e.write(c===1?"| ":" | "),e.push(),s=!0;continue}if(d==="a"){if(p){if(r.length===0)continue;let A=r.pop();if(A===null)continue;let x=e.pop().replace(/\s+/g," ").trim();x!==""&&e.write(`[${x}](${A})`);continue}let f=h.get("href"),g=f!==void 0&&f!==""&&!f.startsWith("#");r.push(g?f:null),g&&e.push();continue}if(d==="code"&&o===0){e.write("`");continue}if(d==="strong"||d==="b"){e.write("**");continue}if(d==="em"||d==="i"){e.write("*");continue}if(d==="img"){let f=h.get("alt");f!==void 0&&f!==""&&e.write(Ugn(f));continue}if(d==="blockquote"){e.block(),p||e.write("> ");continue}if(fai.has(d)&&!gai.has(d)){e.block();continue}}return e.done()}import{closeSync as Xci,existsSync as Zci,fstatSync as eui,openSync as tui,readFileSync as bAn,readSync as nui}from"node:fs";import{dirname as rui,join as WKe}from"node:path";import{gunzipSync as iui}from"node:zlib";F6();_g();Sge();tv();_ge();var Wgn=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid"];kge();Tge();WAe();U6();import{renameSync as r4s,rmSync as vai}from"node:fs";uh();$l();W0();pu();import{join as Hgn}from"node:path";uh();pu();var bai="northlight_unreachable",Cai="Check this computer's internet connection, then retry.";function Iai(t){let e=t?.cause,n=t;for(let r of[e?.code,e?.message,n?.code,n?.message])if(typeof r=="string"&&r!=="")return r;return String(t)}function Y3(t,e){let n=`crtr cannot reach Northlight (${new URL(e).host}): ${Iai(t)}.`;return new ss(bai,n,Vi.NETWORK,{next:Cai})}var Sai=()=>Hgn($0(),"person-credential"),RKe=()=>Hgn($0(),"person-bearer.json");var _ai=3e4;var Ggn=t=>t.replace(/\/+$/,""),qpe=t=>new ss("not_signed_in",t,Vi.USAGE,{next:"Run `crtr sys signin`, then retry."});function BKe(){let t=zI(Sai());if(!(t===null||typeof t.secret!="string"||typeof t.directoryUrl!="string"))return{directoryUrl:t.directoryUrl,secret:t.secret}}function TKe(t,e){let n=t!==null&&typeof t=="object"?t:{},r=n.error;if(r!==null&&typeof r=="object"){let i=r;return{code:String(i.code??"error"),message:String(i.message??`HTTP ${e}`)}}return typeof r=="string"?{code:r,message:String(n.error_description??n.message??r)}:{code:"error",message:`the directory answered HTTP ${e}`}}async function kai(t,e,n,r){let i;try{i=await fetch(`${Ggn(t)}${e}`,{method:"POST",headers:{"content-type":"application/json",...r===void 0?{}:{authorization:`Bearer ${r}`}},body:JSON.stringify(n),signal:AbortSignal.timeout(3e4)})}catch(a){throw Y3(a,t)}let o=await i.text(),s={};try{s=o===""?{}:JSON.parse(o)}catch{}return{status:i.status,body:s}}var Tai=(t,e)=>{let n=TKe(e,t);throw IF(`the directory refused: ${n.message}`,{code:n.code})};var Rai=new Set(["credential_revoked","credential_expired","credential_unknown"]);async function Bai(t,e,n=!1){let r=await kai(t,"/v1/developer/token",{},e);if(r.status===401&&Rai.has(TKe(r.body,401).code))throw n&&vai(RKe(),{force:!0}),qpe(`the sign-in on this computer is no longer valid (${TKe(r.body,401).code})`);r.status!==200&&Tai(r.status,r.body);let i=r.body;if(typeof i.access_token!="string"||typeof i.expires_in!="number")throw IF("the directory answered without a bearer token");let o=i.account;return{access_token:i.access_token,expires_in:i.expires_in,...typeof o?.id=="string"&&typeof o.display=="string"?{account:{id:o.id,display:o.display}}:{}}}function Dai(t,e){ZR(RKe(),{directoryUrl:t,access_token:e.access_token,expires_at_ms:Date.now()+e.expires_in*1e3},{mode:384})}async function jpe(t){let e=BKe();if(e===void 0)throw qpe("this computer is not signed in");let n=Ggn(t??e.directoryUrl),r=zI(RKe());if(r!==null&&r.directoryUrl===n&&typeof r.access_token=="string"&&r.expires_at_ms-Date.now()>_ai)return r.access_token;let i=await Bai(n,e.secret,!0);return Dai(n,i),i.access_token}function qgn(t,e){return async(n,r)=>{let i=new Headers(r?.headers);i.set("authorization",`Bearer ${await jpe(t)}`);try{return await fetch(n,{...r,headers:i})}catch(o){throw r?.signal?.aborted===!0?o:Y3(o,e)}}}W0();uh();$l();pu();import{chmodSync as p4s,existsSync as jgn,mkdirSync as h4s,readFileSync as zgn,rmSync as m4s,writeFileSync as f4s}from"node:fs";import{dirname as A4s,join as Vgn}from"node:path";var Mai=()=>Vgn(vg(),"machine.json");function AR(){let t=Mai();if(!jgn(t))return;let e=JSON.parse(zgn(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, runId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,runId:e.runId,directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}var Pai=()=>Vgn(vg(),"import","move.json");function Nai(){let t=Pai();if(!jgn(t))return;let e=JSON.parse(zgn(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var Kgn=()=>Nai()?.state==="committed",Ygn=t=>new ss("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,Vi.USAGE,{next:"Run `crtr sys signin` to finish."});uh();pu();du();var M4s=256*1024;var Zp=class extends ss{payload;constructor(e,n=Vi.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};function Lai(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Qai={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"};function DKe(t,e,n={}){if(t.code==="daemon_restarting")return new ss("daemon_restarting",t.message,Vi.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="layout_migration_required")return new ss("layout_migration_required",t.message,Vi.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(t.code==="daemon_unavailable")return new ss("daemon_unavailable",t.message,Vi.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});if(t.code==="northlight_unreachable"){let a=t.details?.next;return new ss("northlight_unreachable",t.message,Vi.NETWORK,{next:typeof a=="string"&&a!==""?a:"Check this computer's internet connection, then retry."})}if(t.code==="model_sign_in_required"){let a=t.details?.url;return new Zp({error:t.code,message:t.message,next:typeof a=="string"?`Ask the person to sign in at ${a}, then retry.`:"Ask the person to sign in to an AI subscription on their Northlight account, then retry.",...typeof a=="string"?{details:{url:a}}:{}},Vi.USAGE)}let r=t.details,i=Oai(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new ss(a,t.message,Vi.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??Qai[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??(r?.outcome==="unknown"?"The change may already be applied: check the current state before repeating it, and do not report it failed.":void 0)??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404&&i.code===void 0?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new Zp(s,Fai(s.error,t.status))}function Oai(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),Lai(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function Fai(t,e){return t==="not_found"||e===404?Vi.NOT_FOUND:t==="ambiguous"?Vi.AMBIGUOUS:Vi.USAGE}Hl();import{spawn as wci,execFileSync as iGs}from"node:child_process";import{createRequire as Eci}from"node:module";import{dirname as NKe,join as PO}from"node:path";import{fileURLToPath as xci,pathToFileURL as LKe}from"node:url";import{existsSync as pAn,lstatSync as bci,mkdirSync as Cci,openSync as hAn,closeSync as mAn,fstatSync as fAn,readSync as Ici}from"node:fs";Ige();pu();nv();mE();import{copyFileSync as Uai,mkdirSync as Vpe,existsSync as zpe,readFileSync as $ai,writeFileSync as Zgn,chmodSync as Wai,readdirSync as Hai,renameSync as yR,realpathSync as J3,unlinkSync as Gai,rmSync as qai,linkSync as Jgn}from"node:fs";import{homedir as eAn}from"node:os";import{dirname as tAn,join as xs}from"node:path";import{execFile as jai,spawn as zai,spawnSync as Ype}from"node:child_process";var Jpe="crouter";function MO(){return xs(eAn(),UI,"host")}function nAn(){return xs(MO(),Jpe)}function PKe(){return xs(MO(),".source.json")}function Vai(t){let e=tAn(t);for(let n of[e,xs(e,"..","lib")]){if(!zpe(n))continue;let r=Hai(n).find(i=>i.startsWith("libnode.")&&i.endsWith(".dylib"));if(r!==void 0)return xs(n,r)}return null}function Xgn(t,e,n){let r=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;Uai(t,r),n!==void 0&&Wai(r,n),yR(r,e)}function MKe(t=PKe()){try{return JSON.parse($ai(t,"utf8"))}catch{return null}}var Kai=3e4;function Yai(t){let e=xs(eAn(),UI),n=xs(e,"host.lock");return Vpe(e,{recursive:!0}),iv(n,t,{timeoutMs:Kai,timeoutError:()=>new Error(`timed out waiting for branded host lock: ${n}`)})}function Jai(t={}){let e=t.configured?.trim();return e?[e]:[t.discovered?.trim()||"-"]}function Xai(){if(process.platform!=="darwin")return null;let t=Ype("security",["find-identity","-v","-p","codesigning"],{stdio:["pipe","pipe","pipe"]});if(t.status!==0)return null;let n=(t.stdout??"").toString().split(`
1579
1579
  `).map(r=>r.match(/\)\s+[A-Fa-f0-9]{40}\s+"([^"]+)"/)?.[1]??null).filter(r=>r!==null);return n.find(r=>r.startsWith("Apple Development:"))??n.find(r=>r.startsWith("Developer ID Application:"))??n[0]??null}function Zai(t,e){let n=Ype("codesign",["-s",e,"--deep","--force",t],{stdio:["pipe","pipe","pipe"]});return{ok:n.status===0,stderr:(n.stderr??"").toString().trim()}}function eci(t){if(process.platform!=="darwin")return;let e=Jai({configured:process.env.CRTR_CODESIGN_IDENTITY,discovered:Xai()}),n="";for(let r of e){let i=Zai(t,r);if(i.ok)return;n=i.stderr}throw n&&!n.includes("valid on disk")&&ql({event:"host.codesign.failed",level:"debug",error:n}),new Error(`codesign failed for ${t}: ${n||"codesign did not exit successfully"}`)}function tci(t,e,n=eci){e!==null&&n(e),n(t)}function DO(t,e=5e3){try{return Ype(t,["-e",""],{stdio:"ignore",timeout:e}).status===0}catch{return!1}}function nci(t={}){return Yai(()=>{let e=MO(),n=nAn(),r=J3(t.execPath??process.execPath);if(zpe(n)&&J3(n)===r){if(DO(n))return n;let h=sci();if(h===null)throw new Error(`branded host cannot start and no working node was found to rebuild it from: ${n}`);r=h}let i=MKe(),o=Vai(r),s=o!==null?o.split("/").pop():null,a=h=>zpe(n)&&h!==null&&h.version===2&&(h.libnode===null||zpe(xs(e,h.libnode))),c=h=>a(h)&&h.source===r&&h.libnode===s;if(c(i)&&DO(n))return n;Vpe(e,{recursive:!0});let u=xs(e,`.reconcile.${process.pid}.${Math.random().toString(36).slice(2)}`),l=xs(u,"previous");Vpe(u);let d=!1,p=a(i)&&DO(n);try{let h=xs(u,Jpe),m=s!==null?xs(u,s):null;if(o!==null&&m!==null&&Xgn(o,m),Xgn(r,h,493),tci(h,m),!DO(h))throw new Error(`rebuilt branded host failed its startup check: ${h}`);if(p&&ici(l,n,i),d=!0,m!==null&&yR(m,xs(e,s)),yR(h,n),rci({version:2,source:r,libnode:s}),!c(MKe())||!DO(n))throw new Error(`published branded host tuple failed validation: ${n}`);if(i?.libnode!=null&&i.libnode!==s)try{Gai(xs(e,i.libnode))}catch{}return n}catch(h){throw d&&p&&oci(l,n,i),h}finally{qai(u,{recursive:!0,force:!0})}})}function rci(t){let e=PKe(),n=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;Zgn(n,JSON.stringify(t)),yR(n,e)}function ici(t,e,n){Vpe(t),Jgn(e,xs(t,Jpe)),n.libnode!==null&&Jgn(xs(MO(),n.libnode),xs(t,n.libnode)),Zgn(xs(t,".source.json"),JSON.stringify(n))}function oci(t,e,n){if(n.libnode!==null&&yR(xs(t,n.libnode),xs(MO(),n.libnode)),yR(xs(t,Jpe),e),yR(xs(t,".source.json"),PKe()),!DO(e))throw new Error(`failed to restore previous branded host tuple: ${e}`)}function Kpe(t){try{let e=J3(MO());return tAn(J3(t))===e}catch{return!1}}function rAn(){let t=["/opt/homebrew/bin/node","/usr/local/bin/node"];Kpe(process.execPath)||t.push(process.execPath);for(let i of(process.env.PATH??"").split(":"))i!==""&&t.push(xs(i,"node"));let e=MKe();e!==null&&typeof e.source=="string"&&t.push(e.source);let n=new Set,r=[];for(let i of t){let o;try{o=J3(i)}catch{continue}n.has(o)||Kpe(o)||(n.add(o),r.push(o))}return r}var iAn=["-p","process.versions.modules"];function oAn(t){return t!==null&&t.trim()===process.versions.modules}function sci(){for(let t of rAn())try{let e=Ype(t,iAn,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]});if(e.status===0&&oAn(e.stdout))return t}catch{}return null}function sAn(t,e,n){return new Promise(r=>{try{jai(t,e,{encoding:"utf8",timeout:n},(i,o)=>r(i===null?o:null))}catch{r(null)}})}async function aci(){for(let t of rAn())if(oAn(await sAn(t,iAn,5e3)))return t;return null}var cci=15e3,uci=6e4,$d={checkedAt:0,fallback:null,probing:null,lastHealAt:0};function lci(t){if(import.meta.url.endsWith(".ts"))return;let e=Date.now();if(!(e-$d.lastHealAt<uci)){$d.lastHealAt=e;try{let n=`import(${JSON.stringify(import.meta.url)}).then((m) => m.ensureBrandedHost())`,r=zai(t,["--input-type=module","-e",n],{detached:!0,stdio:"ignore"});r.on("error",()=>{}),r.unref()}catch{}}}function dci(t){return $d.probing!==null||($d.probing=(async()=>{try{if(await sAn(t,["-e",""],5e3)!==null){$d.fallback=null;return}let e=await aci();e!==$d.fallback&&e!==null&&ql({event:"host.fallback.node",level:"warn",fields:{host:t,node:e}}),$d.fallback=e,e!==null&&lci(e)}finally{$d.checkedAt=Date.now(),$d.probing=null}})()),$d.probing}function pci(t=process.execPath){return Kpe(t)?(Date.now()-$d.checkedAt>cci&&$d.probing===null&&dci(t),$d.fallback??t):t}function aAn(){if(process.env.CRTR_BRANDED_HOST==="0"||process.platform!=="darwin"||import.meta.url.endsWith(".ts"))return process.execPath;if(Kpe(process.execPath))return pci();try{return nci()}catch(t){return ql({event:"host.fallback.node",level:"warn",error:t,fields:{host:nAn(),node:process.execPath}}),process.execPath}}Hl();import{existsSync as hci,readFileSync as mci}from"node:fs";import{join as fci}from"node:path";du();function gci(){return TJe()??fci(oc(),"crtrd.pid")}function wR(){let t=gci();if(!hci(t))return null;let e=mci(t,"utf8").trim(),n=Number(e);return Number.isFinite(n)&&n>0?n:null}function cAn(){let t=wR();return t!==null&&Jm(t)}mE();Hl();du();Hl();import{join as Aci}from"node:path";mE();function yci(){return Aci(oc(),"join.lock")}function Xpe(){let t=pB(yci());return t!==null&&Jm(t)?t:null}function uAn(){return Xpe()!==null}function lAn(t){return new Zp({error:"join_in_progress",message:t===null?"`crtr sys join` is running and holds the daemon down until it finishes":`\`crtr sys join\` (pid ${t}) is running and holds the daemon down until it finishes`,next:"Wait for the join to finish; it starts the daemon again itself. If it is stuck, `crtr sys daemon start --force`."})}async function dAn(t,e=100){let n=Date.now()+t;for(;;){let r=Xpe();if(r===null||r===process.pid||Date.now()>=n)return;await new Promise(i=>setTimeout(i,e))}}U6();var vci=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function Sci(){let t={...process.env};for(let e of vci)delete t[e];return t}function _ci(){for(let t=NKe(xci(import.meta.url));;t=NKe(t)){if(pAn(PO(t,"bin","runtime-generation-manifest.mjs")))return t;if(NKe(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}async function kci(){let t=_ci(),e=LKe(PO(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:n}=await import(e);try{bci(PO(n(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",LKe(Eci(import.meta.url).resolve("tsx/esm")).href,PO(t,"src","daemon","crtrd-cli.ts")]}let r=LKe(PO(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:i}=await import(r),o=i("daemon");if(!o.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${o.error}`);return[o.runtime.entryPath]}var Tci=3*6e4,gAn=2e4,FKe=10,OKe=1e3;async function UKe(t=OKe){let e=Math.min(t,OKe);return lE({autostart:!1,timeoutMs:e}).probeHealthz(e)}function Rci(t){let e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;let n=t.code,r=t.cause,i=typeof n=="string"?n:r?.code;return typeof i=="string"&&!e.includes(i)?`${e}: ${i}`:e}async function Bci(t=OKe){let e=await UKe(t);if(e.startup_phase==="blocked"){let n=wR()??process.pid;throw new NO(n,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}function $Ke(t){return new Promise(e=>{setTimeout(e,t)})}var Z3=class extends Error{stderrTail;constructor(e,n){super(n===""?e:`${e}
1580
- ${n}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=n}},the=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}},NO=class extends Error{constructor(e,n){super(`daemon ${e} is running but normal startup is blocked: ${n}`),this.name="DaemonStartupBlockedError"}},ez=class extends Error{constructor(e,n){super(n===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${n}, not prepared`),this.name="DaemonNotPreparedError"}};async function Dci(t,e=3e5,n={},r="ready"){let i=n.readPidfile??wR,o=n.isPidAlive??Jm,s=n.childExited,a=n.isDaemonServing,c=n.probeDaemonServing??(async m=>{if(a!==void 0){if(await a())return;throw new Error("crtrd health check reported not ready")}await Bci(m)}),u=n.probeDaemonHealth??UKe,l=n.sleepMs??$Ke,d=n.now??Date.now,p=null,h=null;return await O6({windowMs:e,pollIntervalMs:FKe,now:d,sleep:l,retry:m=>m!==h,probe:async m=>{let f=i();if(f===null||!o(f)){let A=s?.();throw A!=null&&(A.signal!==null?h=new Z3(`daemon ${t} exited before becoming ready (by ${A.signal})`,n.childStderrTail?.()??""):A.code!==0&&(h=new Z3(`daemon ${t} exited before becoming ready (with exit code ${A.code??"?"})`,n.childStderrTail?.()??"")),h!==null)?h:new Error(`daemon ${t} has no live pidfile owner`)}if(r==="ready"){try{await c(m)}catch(A){throw A instanceof NO&&(h=A),A}p=f;return}let g=await u(m);if(g.startup_phase==="prepared"){p=f;return}throw g.startup_phase==="blocked"?(h=new NO(f,g.startup_blocked??"on-disk migration is blocked"),h):g.startup_phase==="ready"?(h=new ez(f,g.startup_phase),h):new Error(`daemon ${f} is ${g.startup_phase??"not reporting a startup phase"}; waiting for prepared`)}}),p===t?null:p}async function Mci(t,e=gAn,n={}){let r=n.readPidfile??wR,i=n.isPidAlive??Jm,o=n.sleepMs??$Ke,s=n.now??Date.now,a=s()+e;for(;s()<=a;){if(!i(t)&&r()!==t)return;await o(FKe)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}var Pci=2e3,Nci=5e3;async function Lci(t,e=gAn,n={}){let r=n.isPidAlive??Jm,i=n.sleepMs??$Ke,o=n.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Mci(t,e,n),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}let s=o()+Pci;for(;o()<=s;){if(!r(t))return"killed";await i(FKe)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}function Qci(t,e,n=2048){let r;try{r=hAn(t,"r");let{size:i}=fAn(r),o=Math.max(e,i-n),s=i-o;if(s<=0)return"";let a=Buffer.alloc(s);return Ici(r,a,0,s,o),a.toString("utf8").trim()}catch{return""}finally{if(r!==void 0)try{mAn(r)}catch{}}}async function Oci(t={}){if(process.platform==="linux"&&pAn("/run/crtr/launcher.sock")&&!Jm(wR()??-1)&&AR()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");let e=t.targetPhase??"ready",n=wR();if(n!==null&&Jm(n))try{let p=await UKe();if(e==="prepared"){if(p.startup_phase==="prepared")return{started:!1,existing_pid:n,startup_phase:p.startup_phase};throw new ez(n,p.startup_phase)}return p.ok?{started:!1,existing_pid:n,...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}:{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:p.startup_blocked??"crtrd health check reported not ready",...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}}catch(p){if(p instanceof ez)throw p;return{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:Rci(p)}}Cci(oc(),{recursive:!0});let r=await kci().catch(p=>{throw new the(p)});t.waitForJoinLock===!0&&await dAn(Tci);let i=Xpe();if(i!==null&&i!==process.pid&&t.ignoreJoinLock!==!0)throw lAn(i);let o=PO(oc(),"crtrd.err"),s=hAn(o,"a"),a=(()=>{try{return fAn(s).size}catch{return 0}})();N6()===void 0&&ZZe();let c=wci(aAn(),[...r,"--canvas-home",oc(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:Sci()});mAn(s);let u=c.pid;if(u===void 0)throw new Error("daemon spawn did not return a pid");let l=null;c.once("exit",(p,h)=>{l={code:p,signal:h}}),c.unref();let d;try{d=await Dci(u,3e5,{childExited:()=>l,childStderrTail:()=>Qci(o,a)},e)}catch(p){let h=pB(jZe())===u;if(l===null&&!h&&!(p instanceof NO))try{await Lci(u,Nci)}catch{}throw p}return d!==null?{started:!1,existing_pid:d,startup_phase:e}:{started:!0,pid:u,startup_phase:e}}function nhe(){return RJe()||process.argv.includes("--no-autostart")}var Fci=5e3,Uci=6e4,QKe=!1,X3,Zpe=0,ehe=0;function $ci(t){return Math.min(Fci*2**(t-1),Uci)}function Wci(){X3=void 0,Zpe=0,ehe=0}function AAn(){return X3}function yAn(t={}){let e=t.isDaemonRunning??cAn,n=t.spawnDaemon??Oci,r=t.now??Date.now;if(!nhe()&&!uAn()&&!QKe&&!(r()<ehe)){if(e()){Wci();return}X3=void 0,QKe=!0,n().then(()=>{X3=void 0,Zpe=0,ehe=0},i=>{(i instanceof Z3||i instanceof the)&&(X3=i.message),Zpe+=1,ehe=r()+$ci(Zpe)}).finally(()=>{QKe=!1})}}Jd();uh();Jd();rv();W0();$l();import{existsSync as Hci,readFileSync as Gci,statSync as CGs}from"node:fs";import{join as qci}from"node:path";var jci="secrets.json";function zci(t){return qci(t===tp()?$0():t,jci)}function Vci(t){let e=G0(t);if(!e)return{relayTokens:{}};let n=zci(e);if(!Hci(n))return{relayTokens:{}};try{let r=JSON.parse(Gci(n,"utf8")),i=Array.isArray(r.scopedApiTokens)?r.scopedApiTokens.filter(o=>typeof o?.token=="string"&&o.token!==""&&typeof o.grantee=="string"&&/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o.grantee)&&Array.isArray(o.scopes)&&typeof o.created=="string"):[];return{relayTokens:r.relayTokens??{},...typeof r.apiToken=="string"&&r.apiToken!==""?{apiToken:r.apiToken}:{},...i.length>0?{scopedApiTokens:i}:{}}}catch{return{relayTokens:{}}}}function wAn(t,e){return Vci(e).relayTokens[t]}function rhe(t,e="user"){let n=Wl(e),r=n.remoteCanvas.targets[t];if(r===void 0){let o=Object.keys(n.remoteCanvas.targets);throw JR(`no remote canvas target named '${t}'`+(o.length>0?` \u2014 configured: ${o.join(", ")}`:" \u2014 none configured yet")+`. Add one with \`crtr canvas config add ${t} --preview <url> --relay-token -\`.`)}let i=wAn(r.relayTokenRef,e);if(i===void 0||i==="")throw JR(`target '${t}' has no stored relay token \u2014 add it with \`crtr canvas config add ${t} --relay-token -\`.`);return{previewEndpoint:r.previewEndpoint,relayToken:i}}function EAn(t,e,n=5e3){let r=/^[\x20-\x7e]+$/.test(e);return async function(o,s){if(!r)return{ok:!1,stdout:"",stderr:"remote source: invalid stored relay token"};let a={kind:"exec",bin:o,args:s},c=new AbortController,u=setTimeout(()=>c.abort(),n),l;try{l=await fetch(new URL("/__crtr/source",t),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(a),signal:c.signal})}catch{return c.signal.aborted?{ok:!1,stdout:"",stderr:`remote source: timeout after ${n}ms`}:{ok:!1,stdout:"",stderr:"remote source: network error"}}finally{clearTimeout(u)}return l.ok?await l.json():{ok:!1,stdout:"",stderr:`remote source: HTTP ${l.status} ${l.statusText}`}}}var ihe=1e3;function Nl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Kci(t){if(!Nl(t))return!1;let e=t.node;if(!Nl(e)||typeof e.node_id!="string"||!Array.isArray(t.reports)||!Array.isArray(t.managers))return!1;let n=t.artifacts;if(!Nl(n)||typeof n.report!="number"||typeof n.doc!="number"||typeof n.roadmap!="number"||typeof t.pending_crons!="number")return!1;let r=t.paths;if(!Nl(r)||typeof r.context_dir!="string"||"session_file"in r&&r.session_file!==null&&typeof r.session_file!="string"||typeof t.follow_up!="string")return!1;let i=t.fault;if(i!=null){if(!Nl(i)||typeof i.link!="string"||typeof i.kind!="string"||typeof i.since!="string")return!1;let o=i.retry;if(!Nl(o)||typeof o.disposition!="string")return!1}return!0}function xAn(t){return Nl(t)&&typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.status=="string"&&typeof t.active=="boolean"}function Yci(t){return Nl(t)&&typeof t.from_id=="string"&&typeof t.to_id=="string"&&typeof t.active=="boolean"&&typeof t.created=="string"}function Jci(t){return Nl(t)?typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.mode=="string"&&typeof t.lifecycle=="string"&&typeof t.status=="string"&&typeof t.cwd=="string"&&typeof t.created=="string":!1}var gI=class{constructor(e,n){this.previewEndpoint=e;this.relayToken=n;this.exec=EAn(e,n)}previewEndpoint;relayToken;exec;nodeCache=new Map;rosterCache=new Map;topologyCache=null;viewCache=new Map;async execJson(e){let n;try{n=await this.exec("crtr",["--json",...e])}catch{return null}if(!n.ok||n.exitCode!==void 0&&n.exitCode!==0)return null;try{return JSON.parse(n.stdout.trim())}catch{return null}}async fetchShow(e){let n=this.nodeCache.get(e);if(n&&Date.now()-n.at<ihe)return n.value;let r=await this.execJson(["node","inspect","show",e]),i=Kci(r)?{...r,fault:r.fault??null,reports:r.reports.filter(xAn),managers:r.managers.filter(xAn)}:null;return this.nodeCache.set(e,{value:i,at:Date.now()}),i}topology(){if(this.topologyCache!==null&&Date.now()-this.topologyCache.at<ihe)return this.topologyCache.value;let e=this.loadTopology();return this.topologyCache={value:e,at:Date.now()},e}async loadTopology(){let e=await this.exec("crtr",["--json","canvas","roster"]);if(!e.ok||e.exitCode!==void 0&&e.exitCode!==0)throw new Error("remote canvas topology is unavailable");let n;try{n=JSON.parse(e.stdout.trim())}catch{throw new Error("remote canvas topology is invalid")}if(!Nl(n)||!Array.isArray(n.edges)||!n.edges.every(Yci))throw new Error("remote canvas topology is invalid");let r=n.edges,i={subscriptions:new Map,subscribers:new Map};for(let o of r){let s={node_id:o.to_id,active:o.active,created:o.created},a={node_id:o.from_id,active:o.active,created:o.created},c=i.subscriptions.get(o.from_id);c===void 0?i.subscriptions.set(o.from_id,[s]):c.push(s);let u=i.subscribers.get(o.to_id);u===void 0?i.subscribers.set(o.to_id,[a]):u.push(a)}return i}async rawShow(e){return this.fetchShow(e)}async getNode(e){return(await this.fetchShow(e))?.node??null}async getRow(e){let n=(await this.fetchShow(e))?.node;return n?{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,profile_id:n.profile_id??null,scopes:n.scopes??null,isolated:n.isolated===!0,parent:n.parent??null,created:n.created,intent:n.intent??null,frozen_at:n.frozen_at??null,terminal_reason:n.terminal_reason??null,pi_pid:n.pi_pid??null,pi_pid_identity:n.pi_pid_identity??null,window:n.window??null,tmux_session:n.tmux_session??null,pane:n.pane??null,fault:n.fault??null,streaming:n.streaming===!0}:null}async listNodes(e){let n=JSON.stringify([e?.status??null,e?.under??null]),r=this.rosterCache.get(n);if(r&&Date.now()-r.at<ihe)return r.value;let i=["node","inspect","list"];e?.status&&i.push("--status",(Array.isArray(e.status)?e.status:[e.status]).join(",")),e?.under&&i.push("--under",e.under);let o=await this.execJson(i),a=(Nl(o)&&Array.isArray(o.nodes)?o.nodes:[]).filter(Jci).map(c=>({...c,isolated:c.isolated===!0}));return this.rosterCache.set(n,{value:a,at:Date.now()}),a}async subscriptionsOf(e){return(await this.topology()).subscriptions.get(e)??[]}async subscribersOf(e){return(await this.topology()).subscribers.get(e)??[]}async view(e){let n=this.viewCache.get(e);if(n&&Date.now()-n.at<ihe)return n.value;let r=new Set([e]),i=[],o=(await this.subscriptionsOf(e)).map(s=>s.node_id);for(;o.length>0;){let s=o.shift();if(!r.has(s)){r.add(s),i.push(s);for(let a of await this.subscriptionsOf(s))r.has(a.node_id)||o.push(a.node_id)}}return this.viewCache.set(e,{value:i,at:Date.now()}),i}async ticketCountsForNodes(e){if(e.length===0)return{};let n=await this.execJson(["canvas","attention","map","--nodes",e.join(",")]);return Nl(n)&&Nl(n.counts)?n.counts:{}}async ticketCountsForView(e){let n=await this.execJson(["canvas","attention","map","--view",e]);return Nl(n)&&Nl(n.counts)?n.counts:{}}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(r=>r.active);for(let r of n){let i=await this.getRow(r.node_id);if(i&&(i.status==="active"||i.status==="idle"))return!0}return!1}};Hl();du();uh();pu();function ohe(t){return{...t,fault:t.fault??null}}function HKe(t,e){throw t instanceof Xt?DKe(t,e):t}var oui="crtr_run_",sui=4096,aui=20;function cui(){let t;try{t=tui(WKe(oc(),"crtrd.log"),"r");let{size:e}=eui(t),n=Math.max(0,e-sui),r=e-n;if(r<=0)return;let i=Buffer.alloc(r);nui(t,i,0,r,n);let s=i.toString("utf8").split(`
1580
+ ${n}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=n}},the=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e),{cause:e}),this.name="DaemonLaunchError"}},NO=class extends Error{constructor(e,n){super(`daemon ${e} is running but normal startup is blocked: ${n}`),this.name="DaemonStartupBlockedError"}},ez=class extends Error{constructor(e,n){super(n===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${n}, not prepared`),this.name="DaemonNotPreparedError"}};async function Dci(t,e=3e5,n={},r="ready"){let i=n.readPidfile??wR,o=n.isPidAlive??Jm,s=n.childExited,a=n.isDaemonServing,c=n.probeDaemonServing??(async m=>{if(a!==void 0){if(await a())return;throw new Error("crtrd health check reported not ready")}await Bci(m)}),u=n.probeDaemonHealth??UKe,l=n.sleepMs??$Ke,d=n.now??Date.now,p=null,h=null;return await O6({windowMs:e,pollIntervalMs:FKe,now:d,sleep:l,retry:m=>m!==h,probe:async m=>{let f=i();if(f===null||!o(f)){let A=s?.();throw A!=null&&(A.signal!==null?h=new Z3(`daemon ${t} exited before becoming ready (by ${A.signal})`,n.childStderrTail?.()??""):A.code!==0&&(h=new Z3(`daemon ${t} exited before becoming ready (with exit code ${A.code??"?"})`,n.childStderrTail?.()??"")),h!==null)?h:new Error(`daemon ${t} has no live pidfile owner`)}if(r==="ready"){try{await c(m)}catch(A){throw A instanceof NO&&(h=A),A}p=f;return}let g=await u(m);if(g.startup_phase==="prepared"){p=f;return}throw g.startup_phase==="blocked"?(h=new NO(f,g.startup_blocked??"on-disk migration is blocked"),h):g.startup_phase==="ready"?(h=new ez(f,g.startup_phase),h):new Error(`daemon ${f} is ${g.startup_phase??"not reporting a startup phase"}; waiting for prepared`)}}),p===t?null:p}async function Mci(t,e=gAn,n={}){let r=n.readPidfile??wR,i=n.isPidAlive??Jm,o=n.sleepMs??$Ke,s=n.now??Date.now,a=s()+e;for(;s()<=a;){if(!i(t)&&r()!==t)return;await o(FKe)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}var Pci=2e3,Nci=5e3;async function Lci(t,e=gAn,n={}){let r=n.isPidAlive??Jm,i=n.sleepMs??$Ke,o=n.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Mci(t,e,n),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}let s=o()+Pci;for(;o()<=s;){if(!r(t))return"killed";await i(FKe)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}function Qci(t,e,n=2048){let r;try{r=hAn(t,"r");let{size:i}=fAn(r),o=Math.max(e,i-n),s=i-o;if(s<=0)return"";let a=Buffer.alloc(s);return Ici(r,a,0,s,o),a.toString("utf8").trim()}catch{return""}finally{if(r!==void 0)try{mAn(r)}catch{}}}async function Oci(t={}){if(process.platform==="linux"&&pAn("/run/crtr/launcher.sock")&&!Jm(wR()??-1)&&AR()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");let e=t.targetPhase??"ready",n=wR();if(n!==null&&Jm(n))try{let p=await UKe();if(e==="prepared"){if(p.startup_phase==="prepared")return{started:!1,existing_pid:n,startup_phase:p.startup_phase};throw new ez(n,p.startup_phase)}return p.ok?{started:!1,existing_pid:n,...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}:{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:p.startup_blocked??"crtrd health check reported not ready",...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}}catch(p){if(p instanceof ez)throw p;return{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:Rci(p)}}Cci(oc(),{recursive:!0});let r=await kci().catch(p=>{throw new the(p)});t.waitForJoinLock===!0&&await dAn(Tci);let i=Xpe();if(i!==null&&i!==process.pid&&t.ignoreJoinLock!==!0)throw lAn(i);let o=PO(oc(),"crtrd.err"),s=hAn(o,"a"),a=(()=>{try{return fAn(s).size}catch{return 0}})();N6()===void 0&&ZZe();let c=wci(aAn(),[...r,"--canvas-home",oc(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:Sci()});mAn(s);let u=c.pid;if(u===void 0)throw new Error("daemon spawn did not return a pid");let l=null;c.once("exit",(p,h)=>{l={code:p,signal:h}}),c.unref();let d;try{d=await Dci(u,3e5,{childExited:()=>l,childStderrTail:()=>Qci(o,a)},e)}catch(p){let h=pB(jZe())===u;if(l===null&&!h&&!(p instanceof NO))try{await Lci(u,Nci)}catch{}throw p}return d!==null?{started:!1,existing_pid:d,startup_phase:e}:{started:!0,pid:u,startup_phase:e}}function nhe(){return RJe()||process.argv.includes("--no-autostart")}var Fci=5e3,Uci=6e4,QKe=!1,X3,Zpe=0,ehe=0;function $ci(t){return Math.min(Fci*2**(t-1),Uci)}function Wci(){X3=void 0,Zpe=0,ehe=0}function AAn(){return X3}function yAn(t={}){let e=t.isDaemonRunning??cAn,n=t.spawnDaemon??Oci,r=t.now??Date.now;if(!nhe()&&!uAn()&&!QKe&&!(r()<ehe)){if(e()){Wci();return}X3=void 0,QKe=!0,n().then(()=>{X3=void 0,Zpe=0,ehe=0},i=>{(i instanceof Z3||i instanceof the)&&(X3=i.message),Zpe+=1,ehe=r()+$ci(Zpe)}).finally(()=>{QKe=!1})}}Jd();uh();Jd();rv();W0();$l();import{existsSync as Hci,readFileSync as Gci,statSync as IGs}from"node:fs";import{join as qci}from"node:path";var jci="secrets.json";function zci(t){return qci(t===tp()?$0():t,jci)}function Vci(t){let e=G0(t);if(!e)return{relayTokens:{}};let n=zci(e);if(!Hci(n))return{relayTokens:{}};try{let r=JSON.parse(Gci(n,"utf8")),i=Array.isArray(r.scopedApiTokens)?r.scopedApiTokens.filter(o=>typeof o?.token=="string"&&o.token!==""&&typeof o.grantee=="string"&&/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o.grantee)&&Array.isArray(o.scopes)&&typeof o.created=="string"):[];return{relayTokens:r.relayTokens??{},...typeof r.apiToken=="string"&&r.apiToken!==""?{apiToken:r.apiToken}:{},...i.length>0?{scopedApiTokens:i}:{}}}catch{return{relayTokens:{}}}}function wAn(t,e){return Vci(e).relayTokens[t]}function rhe(t,e="user"){let n=Wl(e),r=n.remoteCanvas.targets[t];if(r===void 0){let o=Object.keys(n.remoteCanvas.targets);throw JR(`no remote canvas target named '${t}'`+(o.length>0?` \u2014 configured: ${o.join(", ")}`:" \u2014 none configured yet")+`. Add one with \`crtr canvas config add ${t} --preview <url> --relay-token -\`.`)}let i=wAn(r.relayTokenRef,e);if(i===void 0||i==="")throw JR(`target '${t}' has no stored relay token \u2014 add it with \`crtr canvas config add ${t} --relay-token -\`.`);return{previewEndpoint:r.previewEndpoint,relayToken:i}}function EAn(t,e,n=5e3){let r=/^[\x20-\x7e]+$/.test(e);return async function(o,s){if(!r)return{ok:!1,stdout:"",stderr:"remote source: invalid stored relay token"};let a={kind:"exec",bin:o,args:s},c=new AbortController,u=setTimeout(()=>c.abort(),n),l;try{l=await fetch(new URL("/__crtr/source",t),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(a),signal:c.signal})}catch{return c.signal.aborted?{ok:!1,stdout:"",stderr:`remote source: timeout after ${n}ms`}:{ok:!1,stdout:"",stderr:"remote source: network error"}}finally{clearTimeout(u)}return l.ok?await l.json():{ok:!1,stdout:"",stderr:`remote source: HTTP ${l.status} ${l.statusText}`}}}var ihe=1e3;function Nl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Kci(t){if(!Nl(t))return!1;let e=t.node;if(!Nl(e)||typeof e.node_id!="string"||!Array.isArray(t.reports)||!Array.isArray(t.managers))return!1;let n=t.artifacts;if(!Nl(n)||typeof n.report!="number"||typeof n.doc!="number"||typeof n.roadmap!="number"||typeof t.pending_crons!="number")return!1;let r=t.paths;if(!Nl(r)||typeof r.context_dir!="string"||"session_file"in r&&r.session_file!==null&&typeof r.session_file!="string"||typeof t.follow_up!="string")return!1;let i=t.fault;if(i!=null){if(!Nl(i)||typeof i.link!="string"||typeof i.kind!="string"||typeof i.since!="string")return!1;let o=i.retry;if(!Nl(o)||typeof o.disposition!="string")return!1}return!0}function xAn(t){return Nl(t)&&typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.status=="string"&&typeof t.active=="boolean"}function Yci(t){return Nl(t)&&typeof t.from_id=="string"&&typeof t.to_id=="string"&&typeof t.active=="boolean"&&typeof t.created=="string"}function Jci(t){return Nl(t)?typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.mode=="string"&&typeof t.lifecycle=="string"&&typeof t.status=="string"&&typeof t.cwd=="string"&&typeof t.created=="string":!1}var gI=class{constructor(e,n){this.previewEndpoint=e;this.relayToken=n;this.exec=EAn(e,n)}previewEndpoint;relayToken;exec;nodeCache=new Map;rosterCache=new Map;topologyCache=null;viewCache=new Map;async execJson(e){let n;try{n=await this.exec("crtr",["--json",...e])}catch{return null}if(!n.ok||n.exitCode!==void 0&&n.exitCode!==0)return null;try{return JSON.parse(n.stdout.trim())}catch{return null}}async fetchShow(e){let n=this.nodeCache.get(e);if(n&&Date.now()-n.at<ihe)return n.value;let r=await this.execJson(["node","inspect","show",e]),i=Kci(r)?{...r,fault:r.fault??null,reports:r.reports.filter(xAn),managers:r.managers.filter(xAn)}:null;return this.nodeCache.set(e,{value:i,at:Date.now()}),i}topology(){if(this.topologyCache!==null&&Date.now()-this.topologyCache.at<ihe)return this.topologyCache.value;let e=this.loadTopology();return this.topologyCache={value:e,at:Date.now()},e}async loadTopology(){let e=await this.exec("crtr",["--json","canvas","roster"]);if(!e.ok||e.exitCode!==void 0&&e.exitCode!==0)throw new Error("remote canvas topology is unavailable");let n;try{n=JSON.parse(e.stdout.trim())}catch{throw new Error("remote canvas topology is invalid")}if(!Nl(n)||!Array.isArray(n.edges)||!n.edges.every(Yci))throw new Error("remote canvas topology is invalid");let r=n.edges,i={subscriptions:new Map,subscribers:new Map};for(let o of r){let s={node_id:o.to_id,active:o.active,created:o.created},a={node_id:o.from_id,active:o.active,created:o.created},c=i.subscriptions.get(o.from_id);c===void 0?i.subscriptions.set(o.from_id,[s]):c.push(s);let u=i.subscribers.get(o.to_id);u===void 0?i.subscribers.set(o.to_id,[a]):u.push(a)}return i}async rawShow(e){return this.fetchShow(e)}async getNode(e){return(await this.fetchShow(e))?.node??null}async getRow(e){let n=(await this.fetchShow(e))?.node;return n?{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,profile_id:n.profile_id??null,scopes:n.scopes??null,isolated:n.isolated===!0,parent:n.parent??null,created:n.created,intent:n.intent??null,frozen_at:n.frozen_at??null,terminal_reason:n.terminal_reason??null,pi_pid:n.pi_pid??null,pi_pid_identity:n.pi_pid_identity??null,window:n.window??null,tmux_session:n.tmux_session??null,pane:n.pane??null,fault:n.fault??null,streaming:n.streaming===!0}:null}async listNodes(e){let n=JSON.stringify([e?.status??null,e?.under??null]),r=this.rosterCache.get(n);if(r&&Date.now()-r.at<ihe)return r.value;let i=["node","inspect","list"];e?.status&&i.push("--status",(Array.isArray(e.status)?e.status:[e.status]).join(",")),e?.under&&i.push("--under",e.under);let o=await this.execJson(i),a=(Nl(o)&&Array.isArray(o.nodes)?o.nodes:[]).filter(Jci).map(c=>({...c,isolated:c.isolated===!0}));return this.rosterCache.set(n,{value:a,at:Date.now()}),a}async subscriptionsOf(e){return(await this.topology()).subscriptions.get(e)??[]}async subscribersOf(e){return(await this.topology()).subscribers.get(e)??[]}async view(e){let n=this.viewCache.get(e);if(n&&Date.now()-n.at<ihe)return n.value;let r=new Set([e]),i=[],o=(await this.subscriptionsOf(e)).map(s=>s.node_id);for(;o.length>0;){let s=o.shift();if(!r.has(s)){r.add(s),i.push(s);for(let a of await this.subscriptionsOf(s))r.has(a.node_id)||o.push(a.node_id)}}return this.viewCache.set(e,{value:i,at:Date.now()}),i}async ticketCountsForNodes(e){if(e.length===0)return{};let n=await this.execJson(["canvas","attention","map","--nodes",e.join(",")]);return Nl(n)&&Nl(n.counts)?n.counts:{}}async ticketCountsForView(e){let n=await this.execJson(["canvas","attention","map","--view",e]);return Nl(n)&&Nl(n.counts)?n.counts:{}}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(r=>r.active);for(let r of n){let i=await this.getRow(r.node_id);if(i&&(i.status==="active"||i.status==="idle"))return!0}return!1}};Hl();du();uh();pu();function ohe(t){return{...t,fault:t.fault??null}}function HKe(t,e){throw t instanceof Xt?DKe(t,e):t}var oui="crtr_run_",sui=4096,aui=20;function cui(){let t;try{t=tui(WKe(oc(),"crtrd.log"),"r");let{size:e}=eui(t),n=Math.max(0,e-sui),r=e-n;if(r<=0)return;let i=Buffer.alloc(r);nui(t,i,0,r,n);let s=i.toString("utf8").split(`
1581
1581
  `).filter(a=>a.trim()!=="").slice(-aui).join(`
1582
1582
  `).trim();return s===""?void 0:`crtrd.log (tail):
1583
1583
  ${s}`}catch{return}finally{if(t!==void 0)try{Xci(t)}catch{}}}function uui(){if(process.env.CRTR_API_SOCKET)return;let t=process.env.CRTR_API_TOKEN,e=process.env.CRTR_API_URL;if(t!==void 0&&t.startsWith(oui)&&e)return{client:o=>new kg({baseUrl:e,headers:{authorization:`Bearer ${t}`},...o!==void 0?{timeoutMs:o}:{}})};let n=AR();if(n===void 0)return;if(BKe()===void 0)throw qpe("this computer is imported into Northlight, so crtr needs your sign-in");let r=qgn(n.directoryUrl,n.apiUrl),i=(o,s)=>r(o,s).catch(a=>{throw a instanceof ss?CAn(a):a});return{client:o=>dui(new kg({baseUrl:n.apiUrl,fetch:i,...o!==void 0?{timeoutMs:o}:{}}),n.apiUrl)}}function lui(){return!!process.env.CRTR_API_SOCKET&&(AR()!==void 0||SJe())}function dui(t,e){return new Proxy(t,{get(n,r){let i=Reflect.get(n,r,n);return typeof i!="function"?i:(...o)=>{let s=i.apply(n,o);return s instanceof Promise?s.catch(a=>{throw a instanceof Xt&&a.code==="request_timeout"?CAn(Y3(a,e)):a}):s}}})}function CAn(t){let e=typeof t.details?.next=="string"?t.details.next:void 0;return new Xt(t.exitCode===Vi.NETWORK?503:401,t.code,t.message,{error:t.code,message:t.message,...e===void 0?{}:{next:e}})}function pui(){return Kgn()?Ygn():void 0}function Ft(t){if(t?.local!==!0){let r=pui();if(r!==void 0)throw r}if(t?.local===!0&&lui())throw new ss("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",Vi.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});let e=t?.local===!0?void 0:uui();if(e!==void 0)return e.client(t?.timeoutMs);let n=process.env.CRTR_API_SOCKET;if(n){let r=()=>{if(!Zci(n))try{let o=rui(n),s=bAn(WKe(o,KZe),"utf8"),a=bAn(WKe(o,YZe),"utf8");if(s===a&&s!=="")return new Xt(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(o){if(o.code!=="ENOENT")throw o}},i=r();if(i!==void 0)throw DKe(i,"Run the command from the node's own turn instead.");return lE({autostart:!1,availabilityFailure:r,coldStartPollWindowMs:(nhe()?BJe():void 0)??3e5,...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}})}return nhe()?lE({autostart:!1,...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}):lE({...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{},onColdSocket:async()=>{yAn()},coldStartDiagnostic:cui,coldStartFailure:AAn,coldStartPollWindowMs:3e5})}var hui=2e3,LO=class{client;rosterCache=null;rosterInFlight=null;constructor(e=Ft()){this.client=e}async roster(){let e=Date.now();return this.rosterCache!==null&&e-this.rosterCache.at<hui?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(n=>{let r={snapshot:n,subscriptions:new Map,subscribers:new Map};for(let i of n.edges){let o={node_id:i.to_id,active:i.active,created:i.created},s={node_id:i.from_id,active:i.active,created:i.created},a=r.subscriptions.get(i.from_id);a===void 0?r.subscriptions.set(i.from_id,[o]):a.push(o);let c=r.subscribers.get(i.to_id);c===void 0?r.subscribers.set(i.to_id,[s]):c.push(s)}return this.rosterCache={at:Date.now(),index:r},r}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(e){try{return await e()}catch(n){if(n instanceof Xt&&n.status===404)return null;throw n}}async getNode(e){let n=await this.orNull(()=>this.client.getNode(e));return n===null?null:ohe(n)}async getRow(e){let n=await this.orNull(()=>this.client.getNode(e));return n===null?null:ohe(n)}async listNodes(e){let n=e?.status,r=e?.under===void 0?{}:{under:e.under,under_inclusive:!0},i;if(Array.isArray(n)){let o=new Set(n);i=(await this.client.listNodes(r)).filter(a=>o.has(a.status))}else i=await this.client.listNodes({...n!==void 0?{status:n}:{},...r});return i.map(o=>ohe(o))}async browseSnapshot(){let e=await this.client.canvasBrowseCompressed(),n=JSON.parse(iui(e).toString("utf8")),r={subscriptions:new Map,subscribers:new Map};for(let i of n.edges){let o=r.subscriptions.get(i.from_id)??[];o.push({node_id:i.to_id,active:i.active,created:i.created}),r.subscriptions.set(i.from_id,o);let s=r.subscribers.get(i.to_id)??[];s.push({node_id:i.from_id,active:i.active,created:i.created}),r.subscribers.set(i.to_id,s)}return this.rosterCache={at:Date.now(),index:r},n.nodes.map(i=>ohe(i))}async panelRoster(){let e=await this.roster();return e.snapshot!==void 0?e.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(e){return this.roster().then(n=>n.subscriptions.get(e)??[])}async subscribersOf(e){return this.roster().then(n=>n.subscribers.get(e)??[])}async view(e){let n=new Set([e]),r=[],i=(await this.subscriptionsOf(e)).map(o=>o.node_id);for(;i.length>0;){let o=i.shift();if(!n.has(o)){n.add(o),r.push(o);for(let s of await this.subscriptionsOf(o))n.has(s.node_id)||i.push(s.node_id)}}return r}async ticketCountsForNodes(e){return(await this.client.attentionCounts([...e])).counts}async ticketCountsForView(e){return this.ticketCountsForNodes([e,...await this.view(e)])}async newestReport(e){return(await this.client.getReports(e,{limit:1}))[0]??null}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(r=>r.active);for(let r of n){let i=await this.getRow(r.node_id);if(i&&(i.status==="active"||i.status==="idle"))return!0}return!1}};function IAn(t,e=LI()){let n=t?.scope??"user";if(e){if(t?.canvasName!==void 0)throw uZe("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new LO}let r=t?.canvasName??grt(n).activeCanvas??null;if(!r)return new LO;let{previewEndpoint:i,relayToken:o}=rhe(r,n);return new gI(i,o)}function mui(t){return{dir:t.request_dir,id:t.request_id,inboxTicketId:t.ticket_id,kind:"page",title:t.title,subtitle:t.subtitle??"",dialect:t.dialect,placement:t.placement,inbox:t.inbox,steps:t.steps,slotKinds:t.slot_kinds,awaitsResponse:t.awaits_response,source:t.source,emittedAt:t.emitted_at,recommendedOptions:(t.recommended_options??[]).map(e=>({slotId:e.slot_id,optionId:e.option_id,label:e.label})),...t.fast_action===void 0?{}:{fastAction:{kind:t.fast_action.kind,responses:t.fast_action.responses}},state:t.state,...t.answer_digest===void 0?{}:{answerDigest:t.answer_digest}}}function fui(t){return{dir:t.request_dir,id:t.request_id,inboxTicketId:t.ticket_id,kind:"review",title:t.title,subtitle:t.subtitle,blockedSince:t.blocked_since,source:t.source}}function wg(t){return t.kind==="page"?mui(t):fui(t)}function ER(t){return{manifest:gR(t.page),document:t.source_document,progress:t.progress===null?null:t.progress.responses,state:t.state,revision:t.revision}}function vAn(t){let e=t.result;if(!(e===null||e.kind!=="page"))return e.summary.replace(/\s+/g," ").trim()}function QO(t){let e=t.result;return e!==null&&e.kind==="canceled"?"ticket was already canceled":e!==null&&e.kind==="page"?"ticket was already resolved: page submitted":"ticket was already resolved"}function AI(t,e){let n=r=>r.kind==="page"?r.emittedAt:r.blockedSince;return n(e).localeCompare(n(t))||t.id.localeCompare(e.id)}var gui=new Set(["c","r","e","a","n","p","q","j","k","u","d"," "]);function OO(t){let e=t.config.label;return typeof e=="string"&&e!==""?e:t.unvalidated===!0?t.kind:t.kind==="options"?"Options":t.kind==="text"?"Text":t.kind==="table"?"Table":t.kind==="cards"?"Cards":t.kind==="chart"?"Chart":t.kind}function eh(t){return!(t.unvalidated===!0||t.kind==="cards"&&t.config.cards===void 0)}function FO(t){if(!eh(t))return[];let e=[];if(t.kind==="options"){let r=t.config;e=r.options.map(i=>({kind:"select",group:"option",id:i.id,label:i.label,...i.description===void 0?{}:{description:i.description},mode:r.mode})),r.allowFreetext===!0&&e.push({kind:"freetext",label:r.freetextLabel??"Something else"})}else if(t.kind==="cards"){let r=t.config;e=(r.cards??[]).map(i=>({kind:"select",group:"card",id:i.id,label:i.subtitle===void 0?i.title:`${i.title} \u2014 ${i.subtitle}`,...i.body===void 0?{}:{description:i.body},mode:r.mode}))}else if(t.kind==="text")e.push({kind:"edit",label:"Edit"}),e.push({kind:"accept",label:"Accept as-is"});else if(t.kind==="table"){let r=t.config;if(r.rowSelect!=="none"){let i=r.columns[0];e.push(...(r.rows??[]).map(o=>({kind:"select",group:"row",id:o.id,label:i===void 0?o.id:String(o.cells[i.id]??o.id),mode:r.rowSelect})))}r.columnSelect!=="none"&&e.push(...r.columns.map(i=>({kind:"select",group:"column",id:i.id,label:i.label,mode:r.columnSelect})))}let n=new Set;return e.map(r=>{if(r.kind!=="select")return r;let i;for(let o of[...r.label.toLowerCase()].filter(s=>/[a-z]/.test(s)))if(!n.has(o)&&!gui.has(o)){i=o;break}if(i===void 0){for(let o=1;o<=9;o++)if(!n.has(String(o))){i=String(o);break}}return i!==void 0&&n.add(i),{...r,...i===void 0?{}:{shortcut:i}}})}function SAn(t,e=!1){if(t==null)return"";let n=String(t).replaceAll("|","\\|").replaceAll(`
@@ -1585,7 +1585,7 @@ ${s}`}catch{return}finally{if(t!==void 0)try{Xci(t)}catch{}}}function uui(){if(p
1585
1585
  `)}function GKe(t,e,n){if(e.id===void 0)return!1;try{return Bgn(t.manifest,{[e.id]:n}),!0}catch{return!1}}function jw(t,e){return!eh(e)||e.id===void 0||!t.responses.has(e.id)?!1:GKe(t,e,t.responses.get(e.id))}function yI(t){if(t.manifest.slots.some(e=>Oc(e)&&!eh(e)))return!1;try{return Rgn(t.manifest,Object.fromEntries(t.responses)),!0}catch{return!1}}function UO(t){switch(t.kind){case"option":return`option:${t.optionId}`;case"row":return`row:${t.rowId}`}}function $O(t){return eh(t)?t.kind==="options"?t.config.options.map(e=>({kind:"option",optionId:e.id})):t.kind==="table"?(t.config.rows??[]).map(e=>({kind:"row",rowId:e.id})):[]:[]}et();var th="\x1B[",Qe=`${th}0m`,bs=`${th}1m`,ut=`${th}2m`,kAn=`${th}3m`,TAn=`${th}31m`,wI=`${th}32m`,aa=`${th}33m`,Cs=`${th}36m`,ahe=`${th}90m`,nz=`${th}7m`,Aui=/\x1b\[[0-9;?]*[a-zA-Z]|\x1b[@-_]|[\x00-\x08\x0B\x0E-\x1F\x7F-\x9F]/g;function ti(t){return typeof t!="string"?"":t.replace(Aui,"")}function Ll(t){return ti(t).replace(/\s+/g," ").trim()}function zw(t,e="\u2500"){return t<1?"":e.repeat(t)}function nh(t,e){if(e<1)return"";if(sa(t)<=e)return t;let n=[...t],r=0,i="";for(let o of n){let s=sa(o);if(r+s+1>e)break;i+=o,r+=s}return i+"\u2026"}function che(t,e){let n=t.replace(/\n/g," ").replace(/✅/g,"\u2713").replace(/❌/g,"\u2717").replace(new RegExp("\\p{Emoji_Presentation}","gu"),"");if(e<4)return n.slice(0,e);if(sa(n)<=e)return n;let i=n;for(;sa(i)>e-1&&i.length>0;){let o=i.lastIndexOf(" ",i.length-2);o>e*.4?i=i.slice(0,o):i=i.slice(0,i.length-1)}return i+"\u2026"}function yui(t,e){let n=0,r="";for(let i of t){let o=sa(i);if(n+o>e)break;r+=i,n+=o}return r===""&&t.length>0&&(r=[...t][0]),r}function cu(t,e){if(e<1)return[t];let n=[],r=t.split(`
1586
1586
  `);for(let i=0;i<r.length;i++){let o=r[i];if(o===""){n.push("");continue}let s=o.split(/[ \t]+/).filter(Boolean),a="";for(let c of s){for(;sa(c)>e;){a&&(n.push(a),a="");let l=yui(c,e);n.push(l),c=c.slice(l.length)}let u=a?`${a} ${c}`:c;sa(u)<=e?a=u:(a&&n.push(a),a=c)}a&&n.push(a)}return n.length>0?n:[""]}function T0(t,e,n){let r=Math.max(0,Math.floor((e-n)/2));if(r===0)return t;let i=" ".repeat(r);return t.map(o=>o===""?"":i+o)}function Go(t){return ke(t)}var qKe=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b_[^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[a-zA-Z]|\x1b[@-^]/g,jKe=/\x1b\]8;[^;\x07\x1b]*;([^\x07\x1b]*)(\x07|\x1b\\)/g,_An=new Intl.Segmenter(void 0,{granularity:"grapheme"});function wui(t){let e=[],n=0;qKe.lastIndex=0;for(let r=qKe.exec(t);r!==null;r=qKe.exec(t)){for(let i of _An.segment(t.slice(n,r.index)))e.push({ansi:!1,text:i.segment,width:Go(i.segment)});e.push({ansi:!0,text:r[0]}),n=r.index+r[0].length}for(let r of _An.segment(t.slice(n)))e.push({ansi:!1,text:r.segment,width:Go(r.segment)});return e}function RAn(t,e,n){if(n<1)return"";let r=Math.max(0,e),i=r+n,o="",s="",a=!1,c=0;for(let l of wui(t)){if(l.ansi){c<r?o+=l.text:(s+=l.text,a=!0);continue}if(c>=i)break;let d=l.width;if(d===0){c>=r&&(s+=l.text);continue}if(c+d<=r){c+=d;continue}if(c<r){s+=" ".repeat(c+d-r),c+=d;continue}if(c+d>i){s+=" ".repeat(i-c),c=i;break}s+=l.text,c+=d}if(s==="")return"";o!==""&&(s=o+s,a=!0);let u=Eui(s);return a?s+u+Qe:s}function Eui(t){let e="";jKe.lastIndex=0;for(let n=jKe.exec(t);n!==null;n=jKe.exec(t))e=n[1]===""?"":`\x1B]8;;${n[2]}`;return e}function Na(t,e){return e<1?"":Go(t)<=e?t:RAn(t,0,e)}function uhe(t,e,n){if(n<1)return"";let r=Go(t);if(r<=n)return t;let i=r-n,o=Math.max(0,Math.min(e,i)),s=o>0,a=o<i,c=n-(s?1:0)-(a?1:0),u=c>0?RAn(t,o+(s?1:0),c):"";return`${s?`${ut}\u2039${Qe}`:""}${u}${a?`${ut}\u203A${Qe}`:""}`}function lhe(t,e,n,r){let i=a=>Rle(Mle(a),n,r);if(t.dialect==="html")return e===""?[`${ut}HTML page \u2014 open in Northlight to read this${Qe}`]:i(e);let o=e===""?[]:i(e),s=-1;for(let a of t.slots){t.steps>1&&a.step!==s&&(o.length>0&&o.push(""),o.push(`${bs}Step ${a.step+1}/${t.steps}${Qe}`),s=a.step),o.length>0&&o.push("");for(let u of cu(Ll(OO(a)),n))o.push(`${bs}${u}${Qe}`);let c=a.config.body;if(typeof c=="string"&&c!==""&&o.push(...i(c)),!eh(a)){o.push(`${ut}${ti(a.kind)} \u2014 open in Northlight to answer this${Qe}`);continue}if(a.kind==="text")o.push(...i(a.config.initialText));else if(a.kind==="table")o.push(...i(she(a.config)));else if(a.kind==="cards"){for(let u of a.config.cards??[])if(o.push(` \u2022 ${nh(ti(Ll(u.subtitle===void 0?u.title:`${u.title} \u2014 ${u.subtitle}`)),Math.max(10,n-4))}`),u.body!==void 0)for(let l of cu(ti(u.body),Math.max(10,n-6)))o.push(` ${ut}${l}${Qe}`)}else if(a.kind==="options"){for(let u of a.config.options)if(o.push(` \u2022 ${nh(ti(Ll(u.label)),Math.max(10,n-4))}`),u.description!==void 0)for(let l of cu(ti(u.description),Math.max(10,n-6)))o.push(` ${ut}${l}${Qe}`)}else if(a.kind==="chart"){let u=a.config,l=u.title??`${u.x??""} vs ${(u.y??[]).map(d=>d.label??d.field).join(", ")}`;o.push(`${ut}chart \u2014 ${ti(u.kind??"chart")}: ${ti(l)}${Qe}`)}}return o}var BAn=16;function DAn(t){if(t===null||typeof t!="object")return;let e=t.details;if(e===null||typeof e!="object")return;let n=e.crtrPreview;if(n===null||typeof n!="object")return;let r=n;if(r.path!=="human send")return;let i=r.result;if(i===null||typeof i!="object")return;let o=i,s=o.page_id;if(typeof s=="string"&&o.placement==="inline")return{pageId:s}}function xui(t){return t.document_media_type==="text/html"?BO(t.source_document):RO(t.source_document,t.page)}var dhe=class{constructor(e,n){this.pageId=e;this.openHint=n}pageId;openHint;expanded=!1;generation=0;stamp;snapshot;status="loading";cache;get settled(){return this.snapshot?.state==="resolved"||this.snapshot?.state==="canceled"}async refresh(){let e;try{e=(await Ft().getHumanRequest(this.pageId)).page}catch{e=void 0}if(e===void 0)return this.settle("unavailable",void 0,void 0);let n=`${e.revision}|${e.state}`;if(this.status==="ready"&&n===this.stamp)return!1;let r;try{r={manifest:e.page,displayMarkdown:xui(e),state:e.state,...e.state==="resolved"?bui(vAn(e)):{}}}catch{return this.settle("unavailable",void 0,n)}return this.settle("ready",r,n)}setExpanded(e){e!==this.expanded&&(this.expanded=e,this.cache=void 0)}render(e){let n=e>0?e:80,r=this.cache;if(r!==void 0&&r.width===n&&r.generation===this.generation&&r.expanded===this.expanded)return r.lines;let i=this.compose(n);return this.cache={width:n,generation:this.generation,expanded:this.expanded,lines:i},i}invalidate(){this.cache=void 0}settle(e,n,r){return e===this.status&&e==="unavailable"?!1:(this.status=e,this.snapshot=n,this.stamp=r,this.generation++,this.cache=void 0,!0)}compose(e){let n=this.snapshot;if(n===void 0){let a=this.status==="loading"?"[page] loading\u2026":"[page] no longer available";return["",` ${ut}${a}${Qe}`,""]}let r=Math.min(Math.max(20,e-4),100),i=["",` ${bs}${Cs}${nh(ti(Ll(n.manifest.title)),r)}${Qe}`];if(n.manifest.subtitle)for(let a of cu(ti(n.manifest.subtitle),r))i.push(` ${ut}${a}${Qe}`);let o=lhe(n.manifest,n.displayMarkdown,r,Math.max(20,e-4));if(o.length>0){i.push("");let a=this.expanded||o.length<=BAn?o:o.slice(0,BAn);for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} lines \u2014 ctrl+o to expand${Qe}`)}let s=this.footerLine(n,r);return s!==void 0&&i.push("",` ${s}`),i.push(""),i}footerLine(e,n){switch(e.state){case"pending":return Wpe(e.manifest)?`${aa}\u25B8 awaiting your answer${Qe} ${ut}\u2014 ${ti(this.openHint())}${Qe}`:`${ut}\u25E6 queued in your inbox \u2014 ${ti(this.openHint())}${Qe}`;case"resolved":return e.answerDigest===void 0?`${wI}\u2713 answered${Qe}`:`${wI}\u2713 answered${Qe} ${ut}\u2014 ${nh(ti(e.answerDigest),Math.max(10,n-12))}${Qe}`;case"canceled":return`${ut}\u2298 canceled${Qe}`;case"passive":return}}};function bui(t){return t===void 0?{}:{answerDigest:t}}Pa();et();var Cui=new Set(["canvas roster","canvas snapshot","node inspect snapshot","node inspect show","sys context sysprompt"]);function PAn(t){for(let e of Cui){let n=e.split(" ");if(n.length<=t.length&&n.every((r,i)=>t[i]===r))return!0}return!1}var Iui=61529,NAn=String.fromCodePoint(Iui),Wm={bash:String.fromCodePoint(61728),read:String.fromCodePoint(61788),write:String.fromCodePoint(61639),edit:String.fromCodePoint(61508)},vui={canvas:61672,capture:61501,device:61705,doc:61485,human:61447,node:61842,pkg:61874,profile:62141,push:61678,"exa-search":61442,surface:61704,sys:61459},Sui={"canvas dashboard":61668,"canvas snapshot":61488,"canvas browse":61774,"canvas attention count":62098,"canvas attention list":61498,"canvas attention map":62073,"canvas revive":61473,"node lifecycle revive":61473,"canvas list":61498,"canvas read":61485,"canvas search":61442,"canvas history search":61442,"canvas history grep":61616,"sys daemon start":61515,"sys daemon status":61713,"sys daemon stop":61517,"canvas chord":61441,"surface tmux-spread":61449,"canvas issue new":61832,"canvas prune":61636,"human send":61529,"human review":61508,"human show":61704,"human cancel":61453,"human list":61498,"human resolve":61452,"doc write":61504,"doc edit":61508,"doc history":61914,"doc lint":61770,"node new":61543,"node message send":61664,"node message request":61664,"cron add":61463,"node wait deadline":61463,"node subscription add":61683,"node subscription remove":61942,"node promote":61698,"node yield":62093,"surface node focus":61531,"surface node cycle":61473,"node inspect list":61498,"node inspect show":61550,"node inspect snapshot":61488,"node inspect context":61564,"node lifecycle recycle":61880,"node lifecycle close":61453,"node lifecycle demote":61699,"node config":61459,"cron list":61463,"cron cancel":61534,"pkg plugin install":61465,"pkg plugin remove":61460,"pkg plugin enable":61452,"pkg plugin disable":61534,"pkg plugin update":61473,"pkg plugin list":61498,"pkg plugin show":61550,"pkg market add":61543,"pkg market remove":61460,"pkg market update":61473,"pkg market list":61498,"pkg market browse":61774,"push update":61587,"push final":61726,"exa-search web":61612,"exa-search answer":61557,"exa-search contents":61686,"surface attach to":61926,"sys config get":61465,"sys config set":61504,"sys config path":61563,"sys settings":61459,"sys setup":61613,"sys doctor":61681,"sys context sysprompt":61788,"sys context prompt-review":61442,"sys feedback":61557,"sys update":61473,"sys version":61483,"sys sync":61561};function LAn(t){let e;for(let[r,i]of Object.entries(Sui)){let o=r.split(" ");o.length<=t.length&&o.every((s,a)=>t[a]===s)&&(e===void 0||o.length>e.words)&&(e={words:o.length,cp:i})}if(e!==void 0)return String.fromCodePoint(e.cp);let n=t.length>0?vui[t[0]]:void 0;return n!==void 0?String.fromCodePoint(n):"\u25C6"}function WO(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function phe(t){let e=WO(WO(t)?.details);if(e===void 0)return[];let n=e.crtrPreviews;return(Array.isArray(n)?n:[e.crtrPreview]).flatMap(i=>{let o=WO(i);if(o===void 0||typeof o.path!="string")return[];let s=o.jsonl;return[{path:o.path,result:WO(o.result),jsonl:Array.isArray(s)?s.flatMap(a=>{let c=WO(a);return c===void 0?[]:[c]}):void 0,error:WO(o.error)}]})}var _ui=4;function EI(t){return t.result}function $m(t,e){let n=t[e];return typeof n=="string"&&n!==""?n:void 0}function VKe(t,e){return typeof t[e]=="boolean"?t[e]:void 0}function xR(t,e){return typeof t[e]=="number"&&Number.isFinite(t[e])?t[e]:void 0}function kui(t,e){let n=t[e];return Array.isArray(n)&&n.every(r=>r!==null&&typeof r=="object"&&!Array.isArray(r))?n:void 0}function Tui(t,e){return t.length>e?`${t.slice(0,e).trimEnd()}\u2026`:t}function Rui(t,e,n=5){let r=t.map(s=>$m(s,e));if(r.some(s=>s===void 0))return;let i=r.slice(0,n),o=r.length-i.length;return o>0?`${i.join(", ")}, \u2026 ${o} more`:i.join(", ")}function Bui(t){let e=t.error;if(e===void 0)return null;let n=$m(e,"error"),r=$m(e,"message");return n===void 0||r===void 0?null:[{text:n,tone:"error"},{text:Tui(r,160),tone:"muted"}]}function Dui(t){let e=EI(t);if(e===void 0)return null;let n=$m(e,"deleted")??$m(e,"remote");if(n!==void 0)return[{text:n.trim().split(`
1587
1587
  `)[0]??"",tone:"warning"}];let r=$m(e,"readMetadata")??$m(e,"object");if(r===void 0)return null;let i=r.split(`
1588
- `).filter(o=>o.trim()!==""&&!o.startsWith("<auto-loaded-context")&&!o.startsWith("</auto-loaded-context"));return i.length===0?null:[{text:i[0]},...i.slice(1,_ui).map(o=>({text:o,tone:"muted"}))]}function Mui(t,e=!1){return n=>{let r=EI(n),i=r===void 0?void 0:xR(r,"count")??xR(r,"total");return i===void 0?null:i===0&&e?[{text:`PASS \xB7 no ${t}`,tone:"success"}]:[{text:`${i} ${t}`,tone:i===0?"muted":"plain"}]}}function Vw(t,e="items"){return n=>{let r=EI(n);if(r===void 0)return null;let i=kui(r,e),o=xR(r,"total")??i?.length;if(i===void 0||o===void 0)return null;let s=[{text:`${o} ${t}`,tone:o===0?"muted":"plain"}],a=Rui(i,"name");return a!==void 0&&a!==""&&s.push({text:a,tone:"muted"}),s}}function Pui(t){let n=EI(t)?.counts;if(n===null||typeof n!="object"||Array.isArray(n))return null;let r=Object.entries(n);if(r.some(([,s])=>typeof s!="number"))return null;let i=r.reduce((s,[,a])=>s+a,0);if(i===0)return[{text:"PASS \xB7 no pending asks",tone:"success"}];let o=r.filter(([,s])=>s>0).sort((s,a)=>a[1]-s[1])[0];return o===void 0?null:[{text:`${i} asks`,tone:"warning"},{text:`hottest: ${o[0]} (${o[1]})`,tone:"muted"}]}function zKe(t,e,n){return r=>{let i=EI(r);if(i===void 0)return null;let o=VKe(i,t);if(o===void 0)return null;let s=xR(i,"pid")??xR(i,"existing_pid");return[{text:o?`${e}${s===void 0?"":` \xB7 pid ${s}`}`:n,tone:o?"success":"muted"}]}}function Nui(t){let e=EI(t);if(e===void 0||$m(e,"page_id")===void 0)return null;let n=VKe(e,"reply");return n===void 0?null:[{text:n?"page sent \u2192 waiting on human":"announcement sent",tone:n?"accent":"success"}]}function Lui(t){let e=EI(t);if(e===void 0)return null;let n=VKe(e,"resolved"),r=$m(e,"job_id");return n===void 0||r===void 0?null:[{text:`${n?"resolved":"not resolved"} ${r}`,tone:n?"success":"warning"}]}function MAn(t){let e=EI(t);if(e===void 0)return null;let n=$m(e,"status");return n===void 0?null:[{text:n,tone:["done","success","submitted","filed"].includes(n)?"success":n==="failed"?"error":"plain"}]}function Qui(t){let e=t.jsonl;if(e===void 0)return null;let n=e.filter(r=>$m(r,"name")!==void 0&&xR(r,"projects_count")!==void 0);return n.length===0&&e.length>0?null:[{text:`${n.length} profile${n.length===1?"":"s"}`},...n.slice(0,5).map(r=>({text:`${$m(r,"name")} \xB7 ${xR(r,"projects_count")} projects`,tone:"muted"}))]}var Oui=[{path:"canvas read",run:Dui},{path:"canvas list",run:Vw("objects")},{path:"canvas search",run:Vw("hits")},{path:"canvas attention count",run:Mui("pending asks",!0)},{path:"canvas attention list",run:Vw("pending asks")},{path:"canvas attention map",run:Pui},{path:"human send",run:Nui},{path:"human list",run:Vw("pending")},{path:"human resolve",run:Lui},{path:"pkg plugin list",run:Vw("plugins")},{path:"pkg market list",run:Vw("marketplaces")},{path:"pkg market browse",run:Vw("plugins")},{path:"canvas dashboard",run:Vw("nodes","rows")},{path:"node inspect list",run:Vw("nodes","nodes")},{path:"sys daemon start",run:zKe("started","started","already running")},{path:"sys daemon status",run:zKe("running","running","not running")},{path:"sys daemon stop",run:zKe("stopped","stopped","was not running")},{path:"sys update",run:MAn},{path:"sys feedback",run:MAn},{path:"profile list",run:Qui}];function QAn(t,e=[]){let n=Bui(t);return n!==null?n:Oui.find(({path:i})=>i===t.path)?.run(t,e)??null}Pa();et();import{homedir as Wui}from"node:os";import{isAbsolute as Hui,resolve as Gui}from"node:path";import{pathToFileURL as qui}from"node:url";import{loadLinuxNative as Uui}from"../../native/linux.js";var Sqs=Uui();TF();var $ui=280;function OAn(t){if(typeof t!="string"||/[\p{Cc}\p{Cf}]/u.test(t))return null;let e=t.trim();return e===""?null:Buffer.byteLength(e,"utf8")<=$ui?e:null}function rz(t){let e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;let n=Math.floor(e/60),r=e%60;if(n<60)return`${n}m ${String(r).padStart(2,"0")}s`;let i=Math.floor(n/60),o=n%60;return`${i}h ${String(o).padStart(2,"0")}m`}function FAn(t){return(t.split(`
1588
+ `).filter(o=>o.trim()!==""&&!o.startsWith("<auto-loaded-context")&&!o.startsWith("</auto-loaded-context"));return i.length===0?null:[{text:i[0]},...i.slice(1,_ui).map(o=>({text:o,tone:"muted"}))]}function Mui(t,e=!1){return n=>{let r=EI(n),i=r===void 0?void 0:xR(r,"count")??xR(r,"total");return i===void 0?null:i===0&&e?[{text:`PASS \xB7 no ${t}`,tone:"success"}]:[{text:`${i} ${t}`,tone:i===0?"muted":"plain"}]}}function Vw(t,e="items"){return n=>{let r=EI(n);if(r===void 0)return null;let i=kui(r,e),o=xR(r,"total")??i?.length;if(i===void 0||o===void 0)return null;let s=[{text:`${o} ${t}`,tone:o===0?"muted":"plain"}],a=Rui(i,"name");return a!==void 0&&a!==""&&s.push({text:a,tone:"muted"}),s}}function Pui(t){let n=EI(t)?.counts;if(n===null||typeof n!="object"||Array.isArray(n))return null;let r=Object.entries(n);if(r.some(([,s])=>typeof s!="number"))return null;let i=r.reduce((s,[,a])=>s+a,0);if(i===0)return[{text:"PASS \xB7 no pending asks",tone:"success"}];let o=r.filter(([,s])=>s>0).sort((s,a)=>a[1]-s[1])[0];return o===void 0?null:[{text:`${i} asks`,tone:"warning"},{text:`hottest: ${o[0]} (${o[1]})`,tone:"muted"}]}function zKe(t,e,n){return r=>{let i=EI(r);if(i===void 0)return null;let o=VKe(i,t);if(o===void 0)return null;let s=xR(i,"pid")??xR(i,"existing_pid");return[{text:o?`${e}${s===void 0?"":` \xB7 pid ${s}`}`:n,tone:o?"success":"muted"}]}}function Nui(t){let e=EI(t);if(e===void 0||$m(e,"page_id")===void 0)return null;let n=VKe(e,"reply");return n===void 0?null:[{text:n?"page sent \u2192 waiting on human":"announcement sent",tone:n?"accent":"success"}]}function Lui(t){let e=EI(t);if(e===void 0)return null;let n=VKe(e,"resolved"),r=$m(e,"job_id");return n===void 0||r===void 0?null:[{text:`${n?"resolved":"not resolved"} ${r}`,tone:n?"success":"warning"}]}function MAn(t){let e=EI(t);if(e===void 0)return null;let n=$m(e,"status");return n===void 0?null:[{text:n,tone:["done","success","submitted","filed"].includes(n)?"success":n==="failed"?"error":"plain"}]}function Qui(t){let e=t.jsonl;if(e===void 0)return null;let n=e.filter(r=>$m(r,"name")!==void 0&&xR(r,"projects_count")!==void 0);return n.length===0&&e.length>0?null:[{text:`${n.length} profile${n.length===1?"":"s"}`},...n.slice(0,5).map(r=>({text:`${$m(r,"name")} \xB7 ${xR(r,"projects_count")} projects`,tone:"muted"}))]}var Oui=[{path:"canvas read",run:Dui},{path:"canvas list",run:Vw("objects")},{path:"canvas search",run:Vw("hits")},{path:"canvas attention count",run:Mui("pending asks",!0)},{path:"canvas attention list",run:Vw("pending asks")},{path:"canvas attention map",run:Pui},{path:"human send",run:Nui},{path:"human list",run:Vw("pending")},{path:"human resolve",run:Lui},{path:"pkg plugin list",run:Vw("plugins")},{path:"pkg market list",run:Vw("marketplaces")},{path:"pkg market browse",run:Vw("plugins")},{path:"canvas dashboard",run:Vw("nodes","rows")},{path:"node inspect list",run:Vw("nodes","nodes")},{path:"sys daemon start",run:zKe("started","started","already running")},{path:"sys daemon status",run:zKe("running","running","not running")},{path:"sys daemon stop",run:zKe("stopped","stopped","was not running")},{path:"sys update",run:MAn},{path:"sys feedback",run:MAn},{path:"profile list",run:Qui}];function QAn(t,e=[]){let n=Bui(t);return n!==null?n:Oui.find(({path:i})=>i===t.path)?.run(t,e)??null}Pa();et();import{homedir as Wui}from"node:os";import{isAbsolute as Hui,resolve as Gui}from"node:path";import{pathToFileURL as qui}from"node:url";import{loadLinuxNative as Uui}from"../../native/linux.js";var _qs=Uui();TF();var $ui=280;function OAn(t){if(typeof t!="string"||/[\p{Cc}\p{Cf}]/u.test(t))return null;let e=t.trim();return e===""?null:Buffer.byteLength(e,"utf8")<=$ui?e:null}function rz(t){let e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;let n=Math.floor(e/60),r=e%60;if(n<60)return`${n}m ${String(r).padStart(2,"0")}s`;let i=Math.floor(n/60),o=n%60;return`${i}h ${String(o).padStart(2,"0")}m`}function FAn(t){return(t.split(`
1589
1589
  `).map(n=>n.trim()).find(n=>n!=="")??"").replace(/\s+/g," ")}var UAn=/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/;function $An(t){let e=t;for(;UAn.test(e);)e=e.replace(UAn,"");return e}function hhe(t){return typeof t=="string"?t:""}var jui=5e3;function zui(t,e,n,r){if(e===void 0||Date.now()-e<jui)return[];let i=n?.()??null;return i===null?[]:[ot(` ${t.fg("muted",`\u29D7 ${i}`)}`,r,"\u2026")]}var Eg=class{folded=!1;component;setFolded(e){this.folded=e}capture(e){return this.component=e,e}callComponent(){return this.component}};function Vui(t){return t.length===0?0:(t.match(/\n/g)?.length??0)+(t.endsWith(`
1590
1590
  `)?0:1)}function Kui(t,e){if(!t)return"";let n=[];return t.added>0&&n.push(e.fg("toolDiffAdded",`+${t.added}`)),t.removed>0&&n.push(e.fg("toolDiffRemoved",`-${t.removed}`)),n.length>0?` ${n.join(" ")}`:""}function Yui(t,e){return t===void 0?"":` ${e.fg("toolDiffAdded",`+${t}`)}`}function YKe(t,e,n,r,i){return`${GAn(Wm[t],t,n)} ${HAn(e,n,r)}${Kui(i,n)}`}function Jui(t){let e=Wui();return t.startsWith(e)?`~${t.slice(e.length)}`:t}function HAn(t,e,n){if(!t)return e.fg("toolOutput","...");let r=Jui(t);if(!mo().hyperlinks)return r;let i=Hui(t)?t:Gui(n,t);return $c(r,qui(i).href)}function GAn(t,e,n){return`${n.fg("accent",t)} ${n.fg("toolTitle",n.bold(e))}`}var KKe=class{child;prefix;constructor(e,n){this.child=e,this.prefix=n}update(e,n){this.child=e,this.prefix=n}invalidate(){this.child.invalidate()}render(e){let n=ke(this.prefix),r=this.child.render(Math.max(1,e-n));return r.length===0?[ot(this.prefix.trimEnd(),e,"")]:r.map((i,o)=>o===0?ot(`${this.prefix}${i}`,e,""):i)}};function qAn(t,e=new Eg){let n=C8(t);return{name:"read",label:"read",description:"Render read calls with a crtr icon header in the attach viewer.",parameters:{},renderCall(r,i,o){let s=r,a=hhe(s?.file_path??s?.path),c="";if(s?.offset!==void 0||s?.limit!==void 0){let d=typeof s?.offset=="number"?s.offset:1,p=typeof s?.limit=="number"?d+s.limit-1:void 0;c=i.fg("warning",`:${d}${p!==void 0?`-${p}`:""}`)}let u=`${GAn(Wm.read,"read",i)} ${HAn(a,i,o.cwd??t)}${c}`,l=o.lastComponent??new ve("",0,0);return l.setText(u),e.capture(l)},renderResult(r,i,o,s){return n.renderResult(r,i,o,s)}}}function jAn(t,e=new Eg){let n=I8(t),r,i;return{name:"write",label:"write",description:"Render write calls with a crtr icon header in the attach viewer.",parameters:{},renderCall(o,s,a){if(e.folded){let u=o,l=a.isError?void 0:Vui(hhe(u?.content)),d=YKe("write",hhe(u?.file_path??u?.path),s,a.cwd??t)+Yui(l,s);return e.capture(new ve(d,0,0))}r=n.renderCall(o,s,{...a,lastComponent:r});let c=`${s.fg("accent",Wm.write)} `;return i?i.update(r,c):i=new KKe(r,c),e.capture(i)},renderResult(o,s,a,c){return n.renderResult(o,s,a,c)}}}var Xui=/^(&&|\|\||\||;|>>|>|<|2>&1|&)$/;function Zui(t){return t.match(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+/g)??[]}function WAn(t,e){let n=Zui(t),r=!0;return n.map(o=>Xui.test(o)?(r=!0,e.fg("syntaxOperator",o)):r&&!o.includes("=")?(r=!1,e.fg("syntaxFunction",e.bold(o))):(r=!1,o.startsWith("-")?e.fg("muted",o):/^["']/.test(o)?e.fg("syntaxString",o):e.fg("toolOutput",o))).join(" ")}var iz=class{command="";purpose;expanded=!1;folded=!1;timeout;theme;startedAt;hint;invalidate(){}update(e,n,r,i,o,s,a,c){this.theme=e,this.command=n,this.purpose=r,this.expanded=i,this.folded=o,this.timeout=s,this.startedAt=a,this.hint=c}backgroundHintLines(e){let n=this.theme;return n===void 0?[]:zui(n,this.startedAt,this.hint,e)}render(e){let n=this.theme;if(!n)return[];let r=n.fg("accent",Wm.bash);if(this.purpose!==void 0)return[ot(`${r} ${n.fg("toolOutput",this.purpose)}`,e,"\u2026")];let i=this.command.split(`
1591
1591
  `).map(p=>p.trim()).filter(p=>p.length>0),o=this.folded?i.map($An):i,s=this.timeout?n.fg("muted",` (timeout ${this.timeout}s)`):"";if(o.length===0)return[`${r} ${n.fg("toolOutput","...")}`];if(this.expanded){let p=ke(`${r} `),h=" ".repeat(p),m=Math.max(1,e-p),f=[];for(let g=0;g<o.length;g++){let A=WAn(o[g],n);g===o.length-1&&(A+=s);let x=jo(A,m);for(let b=0;b<x.length;b++)f.push(`${g===0&&b===0?`${r} `:h}${x[b]}`)}return f.map(g=>ot(g,e,""))}let a=o.length>1?n.fg("muted",` +${o.length-1} lines`):"",c=ke(`${r} `)+ke(a)+ke(s),u=Math.max(8,e-c),l=o[0],d=l.length>u?`${l.slice(0,Math.max(1,u-1))}\u2026`:l;return[ot(`${r} ${WAn(d,n)}${a}${s}`,e)]}};function zAn(t,e){return t instanceof iz?t.backgroundHintLines(e):[]}function VAn(t,e=new Eg,n){let r=p8(t);return{name:"bash",label:"bash",description:"Render plain bash calls as a compact styled command line in the attach viewer.",parameters:{},renderCall(i,o,s){let a=i,c=s.state;c&&s.executionStarted&&c.startedAt===void 0&&(c.startedAt=Date.now(),c.endedAt=void 0);let u=s.lastComponent instanceof iz?s.lastComponent:new iz,l=c?.startedAt!==void 0&&c.endedAt===void 0;return u.update(o,hhe(a?.command),e.folded?OAn(a?.purpose)??void 0:void 0,!!s.expanded&&!e.folded,e.folded,typeof a?.timeout=="number"?a.timeout:void 0,l?c?.startedAt:void 0,n),e.capture(u)},renderResult(i,o,s,a){return r.renderResult(i,o,s,a)}}}var eli=20,JKe=eli-3,KAn=/<<-?\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\1/g,r0n=/(?:^|[\n;&|()]\s*)(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)*(?:[^\s;&|()]+\/)?(?:crtr|crouter)(?=\s|$)/,i0n="crtr-output";function o0n(t){let e=t.split(`
@@ -1625,7 +1625,7 @@ ${Fli(e)}
1625
1625
 
1626
1626
  `)}inactiveFormBlocks(){let e=new Set;if(this.repliesOnly())this.condensedBlocks.messages&&e.add(this.condensedBlocks.messages);else{this.condensedBlocks.turns&&e.add(this.condensedBlocks.turns);for(let n of this.turns)e.add(n.reply)}return e}registerCopyBlock(e,n,r){let i=this.condensedCopyBlocks.get(this.appendTarget);if(i){let s=i.findIndex(a=>a.block===e);s===-1?i.push({block:e,kind:n,text:r}):i[s].text=r;return}let o=this.copyIndex.get(e);o===void 0?(this.copyIndex.set(e,this.copyBlockRecords.length),this.copyBlockRecords.push({block:e,kind:n,text:r})):this.copyBlockRecords[o].text=r}unregisterCopyBlock(e){let n=this.condensedCopyBlocks.get(this.appendTarget);if(n){let i=n.findIndex(o=>o.block===e);i!==-1&&n.splice(i,1);return}let r=this.copyIndex.get(e);if(r!==void 0){this.copyBlockRecords.splice(r,1),this.copyIndex.delete(e);for(let i=r;i<this.copyBlockRecords.length;i++)this.copyIndex.set(this.copyBlockRecords[i].block,i)}}appendCondensedBlock({component:e,copyBlocks:n},r){this.outsideTurns++;try{this.append(e)}finally{this.outsideTurns--}this.condensedBlocks[r]=e,this.historyContainer.setHidden(e,r==="turns"!==this.repliesOnly()),this.registerCopyBlock(e,"condensed",n.map(i=>i.text).filter(i=>i.trim()!=="").join(`
1627
1627
 
1628
- `))}toolResultText(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"content"in e){let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("")}try{let n=JSON.stringify(e);return typeof n=="string"?n:""}catch{return""}}pushTranscriptText(e){let n=e.trim();if(n==="")return;let r=[...new Set(xpn(n).reverse())];if(r.length>0){let s=[...r,...this.transcriptDocRefs.filter(a=>!r.includes(a))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...s)}let i=i7e([n],this.cwd);if(i.length===0)return;let o=[...i,...this.transcriptFilePaths.filter(s=>!i.includes(s))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...o)}pushTranscriptValue(e){try{let n=typeof e=="string"?e:JSON.stringify(e);typeof n=="string"&&this.pushTranscriptText(n)}catch{}}userMessageText(e){let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text").map(r=>r.text).join(""):""}};var Jdi="\x1B[2m\u2338 image \u2014 scroll to view\x1B[22m",pz={first:-1,last:-1,lastFullyVisible:-1};function Xdi(t){return t.some(e=>e.includes("\x1B_G")||e.includes("\x1B]1337;File="))}function Zdi(t,e,n){let r=0,i=t.blockCount();for(;r<i;){let o=Math.floor((r+i)/2);t.blockStart(o,n)+t.blockHeight(o,n)>e?i=o:r=o+1}return r}function G0n(t,e){let n={follow:!0,anchor:void 0},r,i=0,o=pz,s;function a(l,d,p){let h=Math.max(0,p-d);if(n.follow)return h;if(!n.anchor)return n.follow=!0,h;let m=t.anchorLine(n.anchor,l);return m===void 0?(n.follow=!0,n.anchor=void 0,h):Math.min(Math.max(0,m),h)}function c(l,d,p,h){let m=Math.min(p,h+d);if(h>=m)return{top:h,bottom:m,total:p,blocks:pz};let f=t.blockCount(),g=Zdi(t,h,l),A=-1,x=-1,b=-1;for(;g<f;){let v=t.blockStart(g,l);if(v>=m)break;let S=t.blockHeight(g,l),_=v+S;_>h&&(A===-1&&(A=g),x=g,v>=h&&_<=m&&(b=g)),g++}return{top:h,bottom:m,total:p,blocks:A===-1?pz:{first:A,last:x,lastFullyVisible:b}}}function u(){if(r===void 0||i<=0)return;let l=t.totalHeight(r),d=a(r,i,l);return c(r,i,l,d)}return{renderSlice(l,d){let p=Math.max(0,d);if(r=l,i=p,p===0)return o=pz,s=t.revision(),[];let h=t.totalHeight(l),m=a(l,p,h),f=c(l,p,h,m),g=[];for(let x=f.blocks.first;x!==-1&&x<=f.blocks.last;x++){let b=t.blockStart(x,l),v=t.blockLines(x,l),S=t.blockHeight(x,l),_=b+S,T=Math.max(0,f.top-b),M=Math.min(S,f.bottom-b);if(T>=M)continue;if((b<f.top||_>f.bottom)&&Xdi(v))g.push(...Array(M-T).fill(Jdi));else if(e===void 0)g.push(...v.slice(T,M));else for(let B=T;B<M;B++)g.push(e(b+B,v[B],l))}let A=g.length>=p?g.slice(0,p):[...Array(p-g.length).fill(""),...g];return o=f.blocks,s=t.revision(),A},scrollBy(l){if(r===void 0||i<=0||l===0)return!1;let d=n.follow,p=n.anchor,h=t.totalHeight(r),m=a(r,i,h),f=Math.max(0,h-i),g=Math.min(Math.max(0,m+l),f);return g>=f?(n.follow=!0,n.anchor=void 0):(n.follow=!1,n.anchor=t.anchorAt(g,r),n.anchor||(n.follow=!0)),n.follow!==d||n.anchor!==p},pageRows(){return Math.max(0,i-1)},goLive(){n.follow=!0,n.anchor=void 0},scrollToLine(l){if(r===void 0||i<=0)return;let d=t.totalHeight(r),p=Math.max(0,d-i),h=Math.min(Math.max(0,l-Math.floor(i/3)),p);if(h>=p){n.follow=!0,n.anchor=void 0;return}n.follow=!1,n.anchor=t.anchorAt(h,r),n.anchor||(n.follow=!0)},topLine(){if(!(r===void 0||i<=0))return a(r,i,t.totalHeight(r))},isLive(){return n.follow},visibleBlocks(){let l=t.revision();return s===l||(o=u()?.blocks??pz,s=l),o},invalidate(){t.invalidate()}}}var epi=new Intl.Segmenter(void 0,{granularity:"grapheme"}),tpi="\x1B[7m",npi="\x1B[27m";function rpi(t,e){let n=t[e+1];if(n!==void 0){if(n==="]"||n==="_"||n==="P"||n==="^"){let r=t.indexOf("\x07",e+2),i=t.indexOf("\x1B\\",e+2),o=r===-1?i:i===-1?r:Math.min(r,i);return o===-1?void 0:{text:t.slice(e,o+(o===r?1:2)),end:o+(o===r?1:2)}}if(n==="["){let r=e+2;for(;r<t.length&&(t.charCodeAt(r)<64||t.charCodeAt(r)>126);)r++;return r>=t.length?void 0:{text:t.slice(e,r+1),end:r+1}}return{text:t.slice(e,e+2),end:e+2}}}function The(t,e){let n=0,r=0;for(;r<t.length;){if(t[r]==="\x1B"){let s=rpi(t,r);if(s===void 0)break;e.onEscape?.(s.text),r=s.end;continue}let i=t.indexOf("\x1B",r),o=t.slice(r,i===-1?void 0:i);for(let s of epi.segment(o)){let a=sa(s.segment);e.onGlyph?.({text:s.segment,cell:n,width:a}),n+=a}r=i===-1?t.length:i}return n}function q0n(t,e,n){let r="";return The(t,{onGlyph:i=>{i.cell>=e&&i.cell<n&&(r+=i.text)}}),r}var ipi={on:tpi,off:npi};function c7e(t,e,n,r,i=ipi){let o=Math.min(n,r);if(o<=e||e<0)return t;let s="",a=!1,c=[],u=()=>{a||(s+=i.on,a=!0)},l=()=>{a&&(s+=i.restore===!0?`\x1B[0m${c.join("")}`:i.off,a=!1)},d=The(t,{onEscape:p=>{s+=p,p.endsWith("m")&&(p==="\x1B[0m"||p==="\x1B[m"?c.length=0:c.push(p),a&&(s+=i.on))},onGlyph:p=>{p.cell>=e&&p.cell<o?u():l(),s+=p.text}});if(l(),d<o){let p=Math.max(0,e-d),h=o-Math.max(e,d);s+=" ".repeat(p)+i.on+" ".repeat(h)+(i.restore===!0?"\x1B[0m":i.off)}return s}function j0n(t,e,n,r){return c7e(t,e,n,r)}var opi={on:"\x1B[107m\x1B[30m",off:"",restore:!0},spi={on:"\x1B[48;5;214m\x1B[30m",off:"",restore:!0};function api(t){let e="",n=[],r=The(t,{onGlyph:i=>{for(let o=0;o<i.text.length;o++)n.push(i.cell);e+=i.text}});return{text:e,cells:n,width:r}}function cpi(t){return t!==t.toLowerCase()}function upi(t,e,n,r,i){let o=n?t.text:t.text.toLowerCase(),s=n?e:e.toLowerCase(),a=o.indexOf(s);for(;a!==-1;){let c=a+s.length,u=t.cells[a]??0,l=c<t.cells.length?t.cells[c]:t.width;l>u&&i.push({line:r,from:u,to:l}),a=o.indexOf(s,a+Math.max(1,s.length))}}function z0n(t){let e="",n=0,r=[],i=new Map,o,s;function a(c){let u=`${c}:${t.revision()}:${e}`;if(o===u)return r;let l=[];if(e!==""){let p=cpi(e),h=t.blockCount();for(let m=0;m<h;m++){let f=t.blockStart(m,c),g=t.blockLines(m,c);for(let A=0;A<g.length;A++){let x=g[A];x.toLowerCase().includes(e.toLowerCase())&&upi(api(x),e,p,f+A,l)}}}let d=new Map;for(let p of l){let h=d.get(p.line);h?h.push(p):d.set(p.line,[p])}if(r=l,i=d,o=u,s!==void 0){let p=s;s=void 0;let h=l.findIndex(m=>m.line>=p);n=h===-1?Math.max(0,l.length-1):h}else n>=l.length&&(n=Math.max(0,l.length-1));return r}return{setQuery(c,u){c!==e&&(e=c,s=u,o=void 0)},query(){return e},matches(c){return a(c)},current(c){return a(c)[n]},status(c){let u=a(c);return{index:u.length===0?0:n+1,total:u.length}},step(c,u){let l=a(c);if(l.length!==0)return n=(n+u+l.length)%l.length,l[n]},selectNear(c,u){let l=a(c);if(l.length===0)return;let d=l.findIndex(p=>p.line>=u);return n=d===-1?l.length-1:d,l[n]},decorate(c,u,l){if(e==="")return u;let d=a(l),p=i.get(c);if(p===void 0)return u;let h=d[n],m=u;for(let f of p)m=c7e(m,f.from,f.to,l,f===h?spi:opi);return m}}}et();Hl();TF();import{join as xpi}from"node:path";var V0n="38;5;243";var lpi={active:"\u25CF",idle:"\u25CB",done:"\u2713",dead:"\u2717",canceled:"\u2298"},dpi={active:"32",idle:"33",done:"36",dead:"31",canceled:V0n},ppi="\u27F3",hpi="92",mpi="\u25CC",fpi="94",gpi="\u26A0",Api="33";function K0n(t){switch(t){case"rate-limit":return"rate-limited";case"overloaded":return"overloaded";case"connection":return"down";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"wedged":return"wedged";case"model-not-found":return"model-not-found";default:return"other"}}function Y0n(t){return t.frozen_at!=null&&t.pi_pid==null}function IR(t,e){return e.hanging!=null?{glyph:gpi,color:Api,word:K0n(e.hanging.kind),bold:!0}:e.frozen===!0?{glyph:mpi,color:fpi,word:"frozen"}:e.streaming===!0?{glyph:ppi,color:hpi,word:"live",bold:!0}:{glyph:lpi[t]??"?",color:dpi[t]}}function ypi(t,e){let n=Date.parse(t);if(Number.isNaN(n))return"now";let r=n-e;return r<=0?"now":r>=6e4?`${Math.max(1,Math.round(r/6e4))}m`:`${Math.max(1,Math.ceil(r/1e3))}s`}function wpi(t){return t.retry.disposition!=="auto"}function Epi(t,e=Date.now()){let n=t.retry;if(!wpi(t)){if(n.by==="client")return"redialing";let r=typeof n.attempt=="number"&&typeof n.max=="number"?`auto-retry ${n.attempt}/${n.max}`:"auto-retrying";return n.nextAt?`${r}, next ${ypi(n.nextAt,e)}`:r}return"needs you"}function J0n(t,e=Date.now()){return`${t.link} ${K0n(t.kind)} \xB7 ${Epi(t,e)}`}var X0n=30,rh="\x1B[",qr=`${rh}0m`,hz=`${rh}1m`,uu=`${rh}2m`,CI=`${rh}7m`,Z0n=`${rh}48;5;22m`,Rhe=`${rh}32m`,Ljs=`${rh}31m`,mz=`${rh}33m`,Qjs=`${rh}36m`,Ojs=`${rh}90m`;function bpi(t){return t.status!=="active"&&t.status!=="idle"?!1:t.streaming===!0}function Bhe(t){if(t===null)return"?";let e=IR(t.status,{streaming:bpi(t),frozen:Y0n(t),hanging:t.fault??null});return`${rh}${e.color}m${e.glyph}${qr}`}var eyn=/\x1b\[[0-9;]*m/g;function vR(t){return t.replace(eyn,"")}function Hd(t){return t.replace(eyn,"").length}function Yw(t,e=Gm()){if(Hd(t)<=e)return t;let n="",r=0,i=0;for(;i<t.length&&r<e-1;){if(t[i]==="\x1B"){let o=/^\x1b\[[0-9;]*m/.exec(t.slice(i));if(o){n+=o[0],i+=o[0].length;continue}}n+=t[i],r++,i++}return`${n}\u2026${qr}`}function Gm(){return Math.max(20,Math.min((process.stdout.columns??80)-2,180))}function Jw(t,e,n){let r=Yw(t,e),i=r.replace(/\x1b\[0m/g,`${qr}${n}`),o=Math.max(0,e-Hd(r));return`${n}${i}${" ".repeat(o)}${qr}`}function Cpi(t){return t<1e3?`${t}`:`${Math.round(t/1e3)}k`}function Dhe(t,e=!1){return Cpi(e?0:t?.telemetry_context_tokens??0)}function Mhe(t,e=!1){if(e||t?.status!=="active")return"";let n=(t.telemetry_last_activity??"").trim();return n===""?"":` ${uu}\xB7 ${n}${qr}`}function Phe(t){let e=t?.cycles??0;return e>0?` ${uu}\u27F3${e}${qr}`:""}function SR(t,e){if(t===null)return Nhe(e);let n=t.name&&t.name!==t.kind?t.name:"";if(n!=="")return n;let r=(t.description??"").trim();return r!==""?r:t.name}function Nhe(t){return t.slice(0,8)}function Ipi(t,e,n=!1){if(n||e?.status!=="active")return!1;try{let r=JSON.parse(bge(tB(t),xpi(XZe(t),"attach.json")).toString("utf8"));return typeof r.viewers=="number"&&r.viewers>0}catch{return!1}}function tyn(t,e,n,r=!1){return r?!1:n.has(t)?!0:Ipi(t,e,r)}function Lhe(t,e){let n=e[t]??0;return n>0?` ${mz}\u2691${n}${qr}`:""}var Fjs=`${uu}jk move \xB7 hl fold \xB7 \u21B5 focus \xB7 e expand \xB7 x kill \xB7 m mgr \xB7 esc${qr}`;et();var vpi=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message","crtr.attach.verbosity.less"];function _R(t,e,n){return av(t,e,sv(n),(r,i)=>nt(r,i))}function u7e(t,e){e[t]()}function nyn(t,e,n){for(let{actionId:r}of Tg)if(_R(t,r,e))return u7e(r,n),!0;return!1}function ryn(t,e,n){for(let r of vpi)if(_R(t,r,e))return n[r](),!0;return!1}function iyn(t){for(let e of["crtr.attach.clear-or-detach","crtr.attach.detach"])if(t.gestures(e).length>0)return da(t,e)}function oyn(t){return t.gestures("crtr.attach.detach").length>0?da(t,"crtr.attach.detach"):void 0}function l7e(t,e,n,r){let i=t();if(e(i.bindings),n())try{r(i.bindings,i.tmuxPassthrough)}catch{}return i}function syn(t){if(t!==""){for(let e of t){let n=e.codePointAt(0);if(n<32||n===127)return}return t}}function ayn(t,e,n,r,i){let o="closed",s=0,a="",c=()=>t.terminal.columns,u=g=>{g!==void 0&&n.scrollToLine(g.line),t.requestRender()},l=()=>{r.setQuery(a,s),u(r.current(c()))},d=()=>{o="closed",a="",r.setQuery("",void 0),t.requestRender()},p=()=>{o==="closed"&&(s=n.topLine()??0),o="editing",a=r.query(),t.requestRender()},h=g=>{let A=r.step(c(),g);if(A===void 0){i.setNotice(`No matches for \u201C${r.query()}\u201D`);return}u(A)};return{component:{render(g){if(o==="closed")return[];let{index:A,total:x}=r.status(g),b=o==="editing"?`${e.accent("\u2315")} ${a}${e.accent("\u258C")}`:`${e.accent("\u2315")} ${a}`,v=x===0?r.query()===""?e.faint("type to search what is on screen"):e.error("no matches"):e.info(`${A}/${x}`),S=o==="editing"?e.faint("enter browse \xB7 esc cancel"):e.faint([`${da(i.bindings(),"crtr.attach.search.next")} next`,`${da(i.bindings(),"crtr.attach.search.previous")} prev`,`${da(i.bindings(),"crtr.attach.search.edit")} edit`,`${da(i.bindings(),"crtr.attach.search.close")} close`].join(" \xB7 ")),_=`${v} ${S}`,T=g-Hd(b)-Hd(_)-2;return[T<1?ot(` ${b}`,g,"",!0):` ${b}${" ".repeat(T)}${_} `]},invalidate(){}},open:p,close:d,handleKey:g=>{if(o==="closed")return!1;let A=i.bindings();if(_R(A,"crtr.attach.search.close",g))return d(),!0;if(o==="editing"){if(g==="")return d(),!0;if(g==="\r"||g===`
1628
+ `))}toolResultText(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"content"in e){let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("")}try{let n=JSON.stringify(e);return typeof n=="string"?n:""}catch{return""}}pushTranscriptText(e){let n=e.trim();if(n==="")return;let r=[...new Set(xpn(n).reverse())];if(r.length>0){let s=[...r,...this.transcriptDocRefs.filter(a=>!r.includes(a))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...s)}let i=i7e([n],this.cwd);if(i.length===0)return;let o=[...i,...this.transcriptFilePaths.filter(s=>!i.includes(s))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...o)}pushTranscriptValue(e){try{let n=typeof e=="string"?e:JSON.stringify(e);typeof n=="string"&&this.pushTranscriptText(n)}catch{}}userMessageText(e){let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text").map(r=>r.text).join(""):""}};var Jdi="\x1B[2m\u2338 image \u2014 scroll to view\x1B[22m",pz={first:-1,last:-1,lastFullyVisible:-1};function Xdi(t){return t.some(e=>e.includes("\x1B_G")||e.includes("\x1B]1337;File="))}function Zdi(t,e,n){let r=0,i=t.blockCount();for(;r<i;){let o=Math.floor((r+i)/2);t.blockStart(o,n)+t.blockHeight(o,n)>e?i=o:r=o+1}return r}function G0n(t,e){let n={follow:!0,anchor:void 0},r,i=0,o=pz,s;function a(l,d,p){let h=Math.max(0,p-d);if(n.follow)return h;if(!n.anchor)return n.follow=!0,h;let m=t.anchorLine(n.anchor,l);return m===void 0?(n.follow=!0,n.anchor=void 0,h):Math.min(Math.max(0,m),h)}function c(l,d,p,h){let m=Math.min(p,h+d);if(h>=m)return{top:h,bottom:m,total:p,blocks:pz};let f=t.blockCount(),g=Zdi(t,h,l),A=-1,x=-1,b=-1;for(;g<f;){let v=t.blockStart(g,l);if(v>=m)break;let S=t.blockHeight(g,l),_=v+S;_>h&&(A===-1&&(A=g),x=g,v>=h&&_<=m&&(b=g)),g++}return{top:h,bottom:m,total:p,blocks:A===-1?pz:{first:A,last:x,lastFullyVisible:b}}}function u(){if(r===void 0||i<=0)return;let l=t.totalHeight(r),d=a(r,i,l);return c(r,i,l,d)}return{renderSlice(l,d){let p=Math.max(0,d);if(r=l,i=p,p===0)return o=pz,s=t.revision(),[];let h=t.totalHeight(l),m=a(l,p,h),f=c(l,p,h,m),g=[];for(let x=f.blocks.first;x!==-1&&x<=f.blocks.last;x++){let b=t.blockStart(x,l),v=t.blockLines(x,l),S=t.blockHeight(x,l),_=b+S,T=Math.max(0,f.top-b),M=Math.min(S,f.bottom-b);if(T>=M)continue;if((b<f.top||_>f.bottom)&&Xdi(v))g.push(...Array(M-T).fill(Jdi));else if(e===void 0)g.push(...v.slice(T,M));else for(let B=T;B<M;B++)g.push(e(b+B,v[B],l))}let A=g.length>=p?g.slice(0,p):[...Array(p-g.length).fill(""),...g];return o=f.blocks,s=t.revision(),A},scrollBy(l){if(r===void 0||i<=0||l===0)return!1;let d=n.follow,p=n.anchor,h=t.totalHeight(r),m=a(r,i,h),f=Math.max(0,h-i),g=Math.min(Math.max(0,m+l),f);return g>=f?(n.follow=!0,n.anchor=void 0):(n.follow=!1,n.anchor=t.anchorAt(g,r),n.anchor||(n.follow=!0)),n.follow!==d||n.anchor!==p},pageRows(){return Math.max(0,i-1)},goLive(){n.follow=!0,n.anchor=void 0},scrollToLine(l){if(r===void 0||i<=0)return;let d=t.totalHeight(r),p=Math.max(0,d-i),h=Math.min(Math.max(0,l-Math.floor(i/3)),p);if(h>=p){n.follow=!0,n.anchor=void 0;return}n.follow=!1,n.anchor=t.anchorAt(h,r),n.anchor||(n.follow=!0)},topLine(){if(!(r===void 0||i<=0))return a(r,i,t.totalHeight(r))},isLive(){return n.follow},visibleBlocks(){let l=t.revision();return s===l||(o=u()?.blocks??pz,s=l),o},invalidate(){t.invalidate()}}}var epi=new Intl.Segmenter(void 0,{granularity:"grapheme"}),tpi="\x1B[7m",npi="\x1B[27m";function rpi(t,e){let n=t[e+1];if(n!==void 0){if(n==="]"||n==="_"||n==="P"||n==="^"){let r=t.indexOf("\x07",e+2),i=t.indexOf("\x1B\\",e+2),o=r===-1?i:i===-1?r:Math.min(r,i);return o===-1?void 0:{text:t.slice(e,o+(o===r?1:2)),end:o+(o===r?1:2)}}if(n==="["){let r=e+2;for(;r<t.length&&(t.charCodeAt(r)<64||t.charCodeAt(r)>126);)r++;return r>=t.length?void 0:{text:t.slice(e,r+1),end:r+1}}return{text:t.slice(e,e+2),end:e+2}}}function The(t,e){let n=0,r=0;for(;r<t.length;){if(t[r]==="\x1B"){let s=rpi(t,r);if(s===void 0)break;e.onEscape?.(s.text),r=s.end;continue}let i=t.indexOf("\x1B",r),o=t.slice(r,i===-1?void 0:i);for(let s of epi.segment(o)){let a=sa(s.segment);e.onGlyph?.({text:s.segment,cell:n,width:a}),n+=a}r=i===-1?t.length:i}return n}function q0n(t,e,n){let r="";return The(t,{onGlyph:i=>{i.cell>=e&&i.cell<n&&(r+=i.text)}}),r}var ipi={on:tpi,off:npi};function c7e(t,e,n,r,i=ipi){let o=Math.min(n,r);if(o<=e||e<0)return t;let s="",a=!1,c=[],u=()=>{a||(s+=i.on,a=!0)},l=()=>{a&&(s+=i.restore===!0?`\x1B[0m${c.join("")}`:i.off,a=!1)},d=The(t,{onEscape:p=>{s+=p,p.endsWith("m")&&(p==="\x1B[0m"||p==="\x1B[m"?c.length=0:c.push(p),a&&(s+=i.on))},onGlyph:p=>{p.cell>=e&&p.cell<o?u():l(),s+=p.text}});if(l(),d<o){let p=Math.max(0,e-d),h=o-Math.max(e,d);s+=" ".repeat(p)+i.on+" ".repeat(h)+(i.restore===!0?"\x1B[0m":i.off)}return s}function j0n(t,e,n,r){return c7e(t,e,n,r)}var opi={on:"\x1B[107m\x1B[30m",off:"",restore:!0},spi={on:"\x1B[48;5;214m\x1B[30m",off:"",restore:!0};function api(t){let e="",n=[],r=The(t,{onGlyph:i=>{for(let o=0;o<i.text.length;o++)n.push(i.cell);e+=i.text}});return{text:e,cells:n,width:r}}function cpi(t){return t!==t.toLowerCase()}function upi(t,e,n,r,i){let o=n?t.text:t.text.toLowerCase(),s=n?e:e.toLowerCase(),a=o.indexOf(s);for(;a!==-1;){let c=a+s.length,u=t.cells[a]??0,l=c<t.cells.length?t.cells[c]:t.width;l>u&&i.push({line:r,from:u,to:l}),a=o.indexOf(s,a+Math.max(1,s.length))}}function z0n(t){let e="",n=0,r=[],i=new Map,o,s;function a(c){let u=`${c}:${t.revision()}:${e}`;if(o===u)return r;let l=[];if(e!==""){let p=cpi(e),h=t.blockCount();for(let m=0;m<h;m++){let f=t.blockStart(m,c),g=t.blockLines(m,c);for(let A=0;A<g.length;A++){let x=g[A];x.toLowerCase().includes(e.toLowerCase())&&upi(api(x),e,p,f+A,l)}}}let d=new Map;for(let p of l){let h=d.get(p.line);h?h.push(p):d.set(p.line,[p])}if(r=l,i=d,o=u,s!==void 0){let p=s;s=void 0;let h=l.findIndex(m=>m.line>=p);n=h===-1?Math.max(0,l.length-1):h}else n>=l.length&&(n=Math.max(0,l.length-1));return r}return{setQuery(c,u){c!==e&&(e=c,s=u,o=void 0)},query(){return e},matches(c){return a(c)},current(c){return a(c)[n]},status(c){let u=a(c);return{index:u.length===0?0:n+1,total:u.length}},step(c,u){let l=a(c);if(l.length!==0)return n=(n+u+l.length)%l.length,l[n]},selectNear(c,u){let l=a(c);if(l.length===0)return;let d=l.findIndex(p=>p.line>=u);return n=d===-1?l.length-1:d,l[n]},decorate(c,u,l){if(e==="")return u;let d=a(l),p=i.get(c);if(p===void 0)return u;let h=d[n],m=u;for(let f of p)m=c7e(m,f.from,f.to,l,f===h?spi:opi);return m}}}et();Hl();TF();import{join as xpi}from"node:path";var V0n="38;5;243";var lpi={active:"\u25CF",idle:"\u25CB",done:"\u2713",dead:"\u2717",canceled:"\u2298"},dpi={active:"32",idle:"33",done:"36",dead:"31",canceled:V0n},ppi="\u27F3",hpi="92",mpi="\u25CC",fpi="94",gpi="\u26A0",Api="33";function K0n(t){switch(t){case"rate-limit":return"rate-limited";case"overloaded":return"overloaded";case"connection":return"down";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"wedged":return"wedged";case"model-not-found":return"model-not-found";default:return"other"}}function Y0n(t){return t.frozen_at!=null&&t.pi_pid==null}function IR(t,e){return e.hanging!=null?{glyph:gpi,color:Api,word:K0n(e.hanging.kind),bold:!0}:e.frozen===!0?{glyph:mpi,color:fpi,word:"frozen"}:e.streaming===!0?{glyph:ppi,color:hpi,word:"live",bold:!0}:{glyph:lpi[t]??"?",color:dpi[t]}}function ypi(t,e){let n=Date.parse(t);if(Number.isNaN(n))return"now";let r=n-e;return r<=0?"now":r>=6e4?`${Math.max(1,Math.round(r/6e4))}m`:`${Math.max(1,Math.ceil(r/1e3))}s`}function wpi(t){return t.retry.disposition!=="auto"}function Epi(t,e=Date.now()){let n=t.retry;if(!wpi(t)){if(n.by==="client")return"redialing";let r=typeof n.attempt=="number"&&typeof n.max=="number"?`auto-retry ${n.attempt}/${n.max}`:"auto-retrying";return n.nextAt?`${r}, next ${ypi(n.nextAt,e)}`:r}return"needs you"}function J0n(t,e=Date.now()){return`${t.link} ${K0n(t.kind)} \xB7 ${Epi(t,e)}`}var X0n=30,rh="\x1B[",qr=`${rh}0m`,hz=`${rh}1m`,uu=`${rh}2m`,CI=`${rh}7m`,Z0n=`${rh}48;5;22m`,Rhe=`${rh}32m`,Qjs=`${rh}31m`,mz=`${rh}33m`,Ojs=`${rh}36m`,Fjs=`${rh}90m`;function bpi(t){return t.status!=="active"&&t.status!=="idle"?!1:t.streaming===!0}function Bhe(t){if(t===null)return"?";let e=IR(t.status,{streaming:bpi(t),frozen:Y0n(t),hanging:t.fault??null});return`${rh}${e.color}m${e.glyph}${qr}`}var eyn=/\x1b\[[0-9;]*m/g;function vR(t){return t.replace(eyn,"")}function Hd(t){return t.replace(eyn,"").length}function Yw(t,e=Gm()){if(Hd(t)<=e)return t;let n="",r=0,i=0;for(;i<t.length&&r<e-1;){if(t[i]==="\x1B"){let o=/^\x1b\[[0-9;]*m/.exec(t.slice(i));if(o){n+=o[0],i+=o[0].length;continue}}n+=t[i],r++,i++}return`${n}\u2026${qr}`}function Gm(){return Math.max(20,Math.min((process.stdout.columns??80)-2,180))}function Jw(t,e,n){let r=Yw(t,e),i=r.replace(/\x1b\[0m/g,`${qr}${n}`),o=Math.max(0,e-Hd(r));return`${n}${i}${" ".repeat(o)}${qr}`}function Cpi(t){return t<1e3?`${t}`:`${Math.round(t/1e3)}k`}function Dhe(t,e=!1){return Cpi(e?0:t?.telemetry_context_tokens??0)}function Mhe(t,e=!1){if(e||t?.status!=="active")return"";let n=(t.telemetry_last_activity??"").trim();return n===""?"":` ${uu}\xB7 ${n}${qr}`}function Phe(t){let e=t?.cycles??0;return e>0?` ${uu}\u27F3${e}${qr}`:""}function SR(t,e){if(t===null)return Nhe(e);let n=t.name&&t.name!==t.kind?t.name:"";if(n!=="")return n;let r=(t.description??"").trim();return r!==""?r:t.name}function Nhe(t){return t.slice(0,8)}function Ipi(t,e,n=!1){if(n||e?.status!=="active")return!1;try{let r=JSON.parse(bge(tB(t),xpi(XZe(t),"attach.json")).toString("utf8"));return typeof r.viewers=="number"&&r.viewers>0}catch{return!1}}function tyn(t,e,n,r=!1){return r?!1:n.has(t)?!0:Ipi(t,e,r)}function Lhe(t,e){let n=e[t]??0;return n>0?` ${mz}\u2691${n}${qr}`:""}var Ujs=`${uu}jk move \xB7 hl fold \xB7 \u21B5 focus \xB7 e expand \xB7 x kill \xB7 m mgr \xB7 esc${qr}`;et();var vpi=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message","crtr.attach.verbosity.less"];function _R(t,e,n){return av(t,e,sv(n),(r,i)=>nt(r,i))}function u7e(t,e){e[t]()}function nyn(t,e,n){for(let{actionId:r}of Tg)if(_R(t,r,e))return u7e(r,n),!0;return!1}function ryn(t,e,n){for(let r of vpi)if(_R(t,r,e))return n[r](),!0;return!1}function iyn(t){for(let e of["crtr.attach.clear-or-detach","crtr.attach.detach"])if(t.gestures(e).length>0)return da(t,e)}function oyn(t){return t.gestures("crtr.attach.detach").length>0?da(t,"crtr.attach.detach"):void 0}function l7e(t,e,n,r){let i=t();if(e(i.bindings),n())try{r(i.bindings,i.tmuxPassthrough)}catch{}return i}function syn(t){if(t!==""){for(let e of t){let n=e.codePointAt(0);if(n<32||n===127)return}return t}}function ayn(t,e,n,r,i){let o="closed",s=0,a="",c=()=>t.terminal.columns,u=g=>{g!==void 0&&n.scrollToLine(g.line),t.requestRender()},l=()=>{r.setQuery(a,s),u(r.current(c()))},d=()=>{o="closed",a="",r.setQuery("",void 0),t.requestRender()},p=()=>{o==="closed"&&(s=n.topLine()??0),o="editing",a=r.query(),t.requestRender()},h=g=>{let A=r.step(c(),g);if(A===void 0){i.setNotice(`No matches for \u201C${r.query()}\u201D`);return}u(A)};return{component:{render(g){if(o==="closed")return[];let{index:A,total:x}=r.status(g),b=o==="editing"?`${e.accent("\u2315")} ${a}${e.accent("\u258C")}`:`${e.accent("\u2315")} ${a}`,v=x===0?r.query()===""?e.faint("type to search what is on screen"):e.error("no matches"):e.info(`${A}/${x}`),S=o==="editing"?e.faint("enter browse \xB7 esc cancel"):e.faint([`${da(i.bindings(),"crtr.attach.search.next")} next`,`${da(i.bindings(),"crtr.attach.search.previous")} prev`,`${da(i.bindings(),"crtr.attach.search.edit")} edit`,`${da(i.bindings(),"crtr.attach.search.close")} close`].join(" \xB7 ")),_=`${v} ${S}`,T=g-Hd(b)-Hd(_)-2;return[T<1?ot(` ${b}`,g,"",!0):` ${b}${" ".repeat(T)}${_} `]},invalidate(){}},open:p,close:d,handleKey:g=>{if(o==="closed")return!1;let A=i.bindings();if(_R(A,"crtr.attach.search.close",g))return d(),!0;if(o==="editing"){if(g==="")return d(),!0;if(g==="\r"||g===`
1629
1629
  `)return r.status(c()).total===0?(i.setNotice(a===""?"Type something to search for":`No matches for \u201C${a}\u201D`),!0):(o="browsing",t.requestRender(),!0);if(g==="\x7F"||g==="\b")return a=[...a].slice(0,-1).join(""),l(),!0;let x=syn(g);return x===void 0?!1:(a+=x,l(),!0)}return _R(A,"crtr.attach.search.next",g)||g==="\r"||g===`
1630
1630
  `?(h(1),!0):_R(A,"crtr.attach.search.previous",g)?(h(-1),!0):_R(A,"crtr.attach.search.edit",g)?(p(),!0):(syn(g)!==void 0&&d(),!1)}}}import{performance as cyn}from"node:perf_hooks";var d7e=100,Spi=25,_pi=.5,kpi=.15;function Tpi(t){return 1-(1-t)*(1-t)}function uyn(t,e){let n,r=0,i=0,o=0,s=()=>{n!==void 0&&clearTimeout(n),n=void 0,i=0,o=0},a=u=>{let l=Math.max(0,r+d7e-u);n=setTimeout(()=>{n=void 0,c(cyn.now(),!0)},Math.min(Spi,l))},c=(u,l)=>{let d=Math.min(1,(u-r)/d7e),p=Math.round(i*Tpi(d)),h=p-o;if(h!==0){if(!t.scrollBy(h))return s();o=p,e()}if(d===1)return s();l&&a(u)};return{page(u){let l=cyn.now();n!==void 0&&(clearTimeout(n),n=void 0,c(l,!1));let d=i-o,p=Math.max(1,Math.round(t.pageRows()*_pi)),h=(u==="up"?-1:1)*p;if(i=d+h,o=0,i===0)return s();r=l-d7e*kpi,c(l,!0)},cancel:s}}import{spawnSync as lyn}from"node:child_process";var dyn=3e3;function Rpi(){if(process.platform==="darwin")return[["pbcopy",[]]];let t=!!process.env.WAYLAND_DISPLAY||process.env.XDG_SESSION_TYPE==="wayland",e=["xclip",["-selection","clipboard"]],n=["wl-copy",[]];return t?[n,e]:[e,n]}function p7e(t){for(let[e,n]of Rpi()){let r=lyn(e,n,{input:t,timeout:dyn,encoding:"utf-8"});if(r.error){if(r.error.code==="ENOENT")continue;continue}if(r.status===0)return!0}return!1}function Qhe(t){let e=p7e(t),n=!1;if(process.env.TMUX!==void 0){let r=lyn("tmux",["load-buffer","-w","-"],{input:t,timeout:dyn,encoding:"utf-8"});n=!r.error&&r.status===0}return{system:e,tmux:n}}function jO(t){return t!==void 0&&t.trim()!==""}function Bpi(t){return t.split(`
1631
1631
  `).length}function Dpi(t,e){if(t&&e)return"clipboard + tmux buffer";if(t)return"clipboard";if(e)return"tmux buffer"}function Mpi(t,e,n){let{first:r,last:i,lastFullyVisible:o}=e.visibleBlocks(),s=a=>{let c=n.blockAt(a);return c?t.blockText(c):void 0};for(let a=Math.min(i,o);a>=r;a--){let c=s(a);if(jO(c))return c}for(let a=i;a>=r;a--){let c=s(a);if(jO(c))return c}}function pyn(t,e,n){return{copy(r){let i,o;switch(r){case"message":{let u=Mpi(t,e,n);jO(u)&&(i={text:u,label:"message"}),o="Nothing to copy \u2014 no visible message";break}case"last-assistant":{let u=t.getLastAssistantText();jO(u)&&(i={text:u,label:"last assistant message"}),o="Nothing to copy \u2014 no assistant message yet";break}case"tool":{let u=t.getLastToolOutputText();jO(u)&&(i={text:u,label:"tool output"}),o="Nothing to copy \u2014 no tool output yet";break}case"transcript":{let u=t.getTranscriptPlainText();jO(u)&&(i={text:u,label:"transcript"}),o="Nothing to copy \u2014 transcript is empty";break}}if(!i)return o;let{system:s,tmux:a}=Qhe(i.text),c=Dpi(s,a);return c?`Copied ${i.label} (${Bpi(i.text)} lines) \u2014 ${c}`:"Copy failed \u2014 no clipboard tool found"}}}et();var Ohe=class extends Ze{render(e){let n=super.render(e);return n[0]===""?n.slice(1):n}};import{spawn as tfi}from"node:child_process";import{readFileSync as nfi,unlinkSync as rfi,writeFileSync as ifi}from"node:fs";import{tmpdir as ofi}from"node:os";import{join as sfi}from"node:path";function hyn(t,e){let n=t.trim();if(!n)return{kind:"empty"};if(n.startsWith("/"))return{kind:"slash",trimmed:n};if(e.isDormant&&e.canWakeDormant)return{kind:"dormant",text:t,trimmed:n};if(n.startsWith("!")){let r=n.startsWith("!!"),i=n.slice(r?2:1).trim();return i===""?{kind:"empty"}:{kind:"bash",command:i,excludeFromContext:r,trimmed:n}}return e.isStreaming?{kind:"steer",text:t,trimmed:n}:{kind:"prompt",text:t,trimmed:n}}var Ppi=/[A-Za-z0-9_:-]/,Npi=/[A-Za-z0-9]/,Lpi=/[ \t\n\r\f\v]/;function h7e(t){return Ppi.test(t)}function Qpi(t){return Lpi.test(t)}function myn(t,e){return e===0||Qpi(t[e-1])}function Fhe(t){let e=[],n=t.length;for(let r=0;r<n;r++){if(t[r]!=="/"||!myn(t,r))continue;let i=r+1;for(;i<n&&h7e(t[i]);)i++;if(i===r+1)continue;let o=i;for(;o>r+1&&!Npi.test(t[o-1]);)o--;if(o===r+1)continue;let s=t.slice(r,o),a=s.slice(1).replace(/:/g,"/");e.push({start:r,end:o,raw:s,candidate:a})}return e}function m7e(t){return"/"+t.replace(/\//g,":")}function fyn(t,e){let n=t.length,r=Math.max(0,Math.min(e,n)),i=r;for(;i>0&&h7e(t[i-1]);)i--;let o=i-1;if(o<0||t[o]!=="/"||!myn(t,o))return null;let s=o+1;for(;s<n&&h7e(t[s]);)s++;return{start:o,end:s,surfacePrefix:t.slice(o,r)}}import{execFile as zO}from"node:child_process";var f7e=[{name:"settings",description:"Open settings menu"},{name:"model",description:"Select model (opens selector UI)"},{name:"scoped-models",description:"Enable/disable models for Ctrl+P cycling"},{name:"export",description:"Export session (HTML default, or specify path: .html/.jsonl)"},{name:"import",description:"Import and resume a session from a JSONL file"},{name:"share",description:"Share session as a secret GitHub gist"},{name:"copy",description:"Copy last agent message to clipboard"},{name:"name",description:"Set session display name"},{name:"session",description:"Show session info and stats"},{name:"changelog",description:"Show changelog entries"},{name:"hotkeys",description:"Show all keyboard shortcuts"},{name:"fork",description:"Create a new fork from a previous user message"},{name:"clone",description:"Duplicate the current session at the current position"},{name:"tree",description:"Navigate session tree (switch branches)"},{name:"login",description:"Configure provider authentication"},{name:"logout",description:"Remove provider authentication"},{name:"new",description:"Start a new session"},{name:"compact",description:"Manually compact the session context"},{name:"resume",description:"Resume a different session"},{name:"reload",description:"Reload keybindings, extensions, skills, prompts, and themes"},{name:"quit",description:"Quit pi"}];function gyn(t){let e=t.remote,n=t.role,r=new Set;return e||(r.add("local-canvas-inspect"),r.add("canvas-inbox")),n==="controller"&&(r.add("engine-drive"),r.add("dequeue")),n==="controller"&&!e&&(r.add("wake-dormant"),r.add("auth"),r.add("canvas-resume"),r.add("local-host")),{role:n,remote:e,nodeId:t.nodeId,profileId:t.profileId,permittedOperations:r,permits:i=>r.has(i),refusal:(i,o)=>{let s=o===void 0?"":`/${o} `;if(t.isBrokerOffline?.()===!0&&(i==="engine-drive"||i==="dequeue"||i==="auth"))return`${s}needs a live broker; this node is parked \u2014 submit a message to wake it`;if(!r.has(i))return e&&(i==="canvas-resume"||i==="local-canvas-inspect"||i==="canvas-inbox")?`${s}Not available with --canvas because it acts on this machine's local canvas`:e&&n==="controller"?`${s}Not available with --canvas because it acts on this machine, not the remote node`:`${s}is not available to a read-only observer attach (--observer) \u2014 it would drive this node`}}}function Ayn(t){switch(t.type){case"prompt":case"steer":case"follow_up":case"abort":case"bash":case"set_model":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"new_session":case"switch_session":case"fork":case"set_session_name":case"navigate_tree":case"reload":case"export":case"clone":case"share":case"reload_auth":return"engine-drive";default:return}}function g7e(t,e,n){if(n)switch(t){case"resume":return"canvas-resume";case"context":case"node-metadata":return"local-canvas-inspect";case"plugins":return;case"inbox":return"canvas-inbox";case"clear":case"resume-session":case"tutorial":return"engine-drive";case"promote":case"rename":case"mcp":return"local-host";default:return}if(e)switch(t){case"copy":case"session":case"changelog":case"hotkeys":case"quit":return;case"login":case"logout":return"auth";default:return"engine-drive"}}var gz=[{name:"tutorial",description:"The guided crouter tutorial \u2014 your agent teaches it, one lesson at a time"},{name:"menu",description:"Open the crouter action menu \u2014 the same menu as Alt+C, for when Option/Alt does not work in your terminal"},{name:"clear",description:"Clear the conversation and free context \u2014 a fresh, empty session (like /new)"},{name:"graph",description:"Toggle the canvas GRAPH view (your local subscription tree)"},{name:"inbox",description:"Toggle the human inbox \u2014 pending asks and reviews for you"},{name:"promote",description:"Promote this node to an orchestrator \u2014 /promote, or /promote <kind> to specialize"},{name:"resume",description:"Open the canvas navigator and swap THIS pane onto the chosen node; parked residents wake only on submitted input"},{name:"resume-session",description:"Switch this node onto one of its saved pi sessions \u2014 picker, or /resume-session <session-path>"},{name:"context",description:"Browse the files in this node\u2019s and its subscriptions\u2019 context dirs in a read-only nvim popup"},{name:"plugins",description:"Open the interactive plugin browser for this machine"},{name:"node-metadata",description:"Inspect this node \u2014 identity, lifecycle, runtime, graph, output, paths, and agent surfaces"},{name:"mcp",description:"MCP servers \u2014 status from the adapter\u2019s config/cache; Enter (or /mcp <server>) connects, reconnects, or re-auths"},{name:"rename",description:"Rename this node everywhere \u2014 node row, viewer window, session chip, tmux pane: /rename <name>"},{name:"color",description:"Color this node \u2014 tmux pane outline + name chip: /color <color> (red, blue, #rrggbb, \u2026) or /color none"},{name:"mouse",description:"Toggle mouse wheel scrolling and drag-select \u2014 off restores tmux drag-select and copy-mode mouse"},{name:"copy-message",description:"Copy the newest message visible in the transcript viewport"},{name:"copy-tool",description:"Copy the newest tool call output"},{name:"copy-transcript",description:"Copy every copyable transcript block"},{name:"more-detail",description:"Show the transcript one verbosity level more open, in this viewer only (Ctrl+O)"},{name:"less-detail",description:"Show the transcript one verbosity level more collapsed, in this viewer only (Ctrl+Shift+O)"}],byn=new Map([["resume-node","resume"]]),A7e=new Set([...gz.map(t=>t.name),...byn.keys()]),Opi=new Set(["black","red","green","yellow","blue","magenta","cyan","white","brightred","brightgreen","brightyellow","brightblue","brightmagenta","brightcyan","orange","grey","gray","default"]),Cyn=new Set(["trust"]),yyn=new Set(Object.keys({off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0})),y7e=new Set(f7e.map(t=>t.name));function w7e(t){return t.capabilities.nodeId}function Fpi(t){return t.capabilities.profileId}function wyn(t,e){let n=g7e(t,y7e.has(t),A7e.has(t));return n===void 0?void 0:e.capabilities.refusal(n,t)}function Iyn(){return new Set([...y7e,...A7e,...Cyn])}function Upi(t){let e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e===null?void 0:{name:e[1],arg:e[2].trim()}}function E7e(t){return t.trimStart().startsWith("/")}function vyn(t,e){let n=Upi(t);if(n===void 0)return!1;let{arg:r}=n,i=byn.get(n.name)??n.name;if(Cyn.has(i))return e.notify(`/${i} is not supported in attach (Phase 4)`),!0;if(A7e.has(i)){let s=wyn(i,e);return s!==void 0?(e.notify(s),!0):Wpi(i,r,e)}if(!y7e.has(i))return!1;let o=wyn(i,e);if(o!==void 0)return e.notify(o),!0;switch(i){case"new":return e.send({type:"new_session"}),!0;case"reload":return e.send({type:"reload"}),!0;case"compact":return e.send({type:"compact",instructions:r||void 0}),!0;case"quit":return e.onQuit?(e.onQuit(),!0):(e.send({type:"bye"}),e.notify("Detaching \u2014 the engine keeps running"),!0);case"name":return r?(e.send({type:"set_session_name",name:r}),!0):$he(e,"/name <display name>");case"export":{let{path:s,format:a}=Zpi(r,e.cwd??process.cwd());return e.send({type:"export",path:s,format:a}),e.notify(`Exporting session \u2192 ${s}`),!0}case"import":return r?(e.send({type:"switch_session",path:r}),!0):$he(e,"/import <path-to-session.jsonl>");case"model":return r?(e.send({type:"set_model",model:r}),!0):Uhe(e.openModelPicker,e,"model","/model <provider/id>");case"fork":return r?(e.send({type:"fork",entryId:r}),!0):Uhe(e.openForkPicker,e,"fork point","/fork <entryId>");case"tree":return r?(e.send({type:"navigate_tree",targetId:r}),!0):Uhe(e.openTreePicker,e,"tree","/tree <entryId>");case"scoped-models":return e.openScopedModelsPicker?(e.openScopedModelsPicker(),!0):(e.notify("The scoped-models view needs the read-op channel, which this viewer has not wired"),!0);case"settings":return Xpi(r,e);case"session":return e.notify(ehi(e.state)),!0;case"copy":return e.onCopy?(e.onCopy(),!0):(e.notify("/copy is not available in this viewer"),!0);case"login":return e.openLoginPicker?(e.openLoginPicker(),!0):(e.notify("/login is not available in this viewer"),!0);case"logout":return e.openLogoutPicker?(e.openLogoutPicker(),!0):(e.notify("/logout is not available in this viewer"),!0);case"share":return e.send({type:"share"}),e.notify("Sharing session\u2026"),!0;case"clone":return e.send({type:"clone"}),e.notify("Cloning session\u2026"),!0;case"changelog":return e.notify("/changelog: see https://github.com/earendil-works/pi for release notes (no bundled changelog in this build)"),!0;case"hotkeys":return e.onHelp?(e.onHelp(),!0):(e.notify("/hotkeys is not available in this viewer"),!0);default:return e.notify(`/${i} is not available in attach (Phase 4)`),!0}}function $pi(t,e){let n=a=>{let c=g7e(a,!1,!0);return c===void 0||e.permits(c)},r=gz.filter(a=>n(a.name)),i=new Map(gz.map(a=>[a.name,a])),o=t.flatMap(a=>{let c=i.get(a.name);return c===void 0?[a]:n(a.name)?[c]:[]}),s=new Set(t.map(a=>a.name));return[...o,...r.filter(a=>!s.has(a.name))]}function Syn(t,e){return $pi(t??f7e,e).map(n=>({name:n.name,description:n.description}))}function Wpi(t,e,n){switch(t){case"clear":return n.send({type:"new_session"}),!0;case"graph":return n.onGraph?n.onGraph():n.notify("The GRAPH overlay is not wired into the viewer yet"),!0;case"inbox":return n.onInbox?n.onInbox():n.notify("The inbox surface is not wired into the viewer yet"),!0;case"menu":return Vpi(n);case"tutorial":return n.send({type:"prompt",text:"The user asked for the crouter tutorial. Run `crtr sys tutorial -h`, pick the track that matches what they want to learn, and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before you move on."}),!0;case"promote":return Hpi(e,n),!0;case"resume":return e?$he(n,"/resume \u2014 no argument; use /resume-session <path> to switch pi sessions"):zpi(n);case"resume-session":return e?(n.send({type:"switch_session",path:e}),!0):Uhe(n.openSessionPicker,n,"session","/resume-session <session-path>");case"mcp":return n.openMcpPicker?n.openMcpPicker(e||void 0):n.notify("The MCP panel is not wired into this viewer"),!0;case"context":return Kpi(n);case"plugins":return Ypi(n);case"node-metadata":return n.onNodeMetadata?n.onNodeMetadata():n.notify("Node metadata is not wired into this viewer"),!0;case"rename":return Gpi(e,n),!0;case"color":return jpi(e,n);case"more-detail":return n.onMoreDetail?n.onMoreDetail():n.notify("Verbosity is not wired into this viewer"),!0;case"less-detail":return n.onLessDetail?n.onLessDetail():n.notify("Verbosity is not wired into this viewer"),!0;case"mouse":return n.onToggleMouse?n.onToggleMouse():n.notify("Mouse reporting is not wired into this viewer"),!0;case"copy-message":return n.onCopyTarget?n.onCopyTarget("message"):n.notify("/copy-message is not available in this viewer"),!0;case"copy-tool":return n.onCopyTarget?n.onCopyTarget("tool"):n.notify("/copy-tool is not available in this viewer"),!0;case"copy-transcript":return n.onCopyTarget?n.onCopyTarget("transcript"):n.notify("/copy-transcript is not available in this viewer"),!0;default:return n.notify(`/${t} is not available in attach`),!0}}function Hpi(t,e){let n=w7e(e).trim();if(n===""){e.notify("/promote: no node to promote (viewer has no node id)");return}let r=t.trim().toLowerCase();e.notify(r?`Promoting \u2192 ${r}\u2026`:"Promoting\u2026");let i=["node","promote","--node",n,"--json"];r!==""&&i.push("--kind",r),zO("crtr",i,{timeout:15e3,maxBuffer:4*1024*1024},(s,a)=>{let c=null,u=null;try{c=JSON.parse(a)}catch{c=null}if(s&&c===null){let d=typeof s.stdout=="string"?s.stdout:"";try{let p=JSON.parse(d);u=typeof p.message=="string"?p.message:null}catch{u=null}u===null&&(u=s.message)}if(c===null){e.notify(`promote failed: ${u??"unknown error"}`);return}let l=(c.roadmap_ref??"").trim();e.notify(`Promoted to ${c.kind??"orchestrator"} orchestrator \u2014 authoring roadmap${l!==""?` (${l})`:""}.`),e.send({type:"prompt",text:"You have just been promoted to an orchestrator. Your new-role guidance is arriving \u2014 read it, author your roadmap, and start delegating."})}).stdin?.end()}function Gpi(t,e){let n=w7e(e).trim();if(n===""){e.notify("/rename: no node to rename (viewer has no node id)");return}if(t===""){e.notify("Usage: /rename <name>");return}e.send({type:"set_session_name",name:t});let r=process.env.TMUX_PANE;process.env.TMUX!==void 0&&r!==void 0&&r!==""&&zO("tmux",["select-pane","-t",r,"-T",t],()=>{}),zO("crtr",["node","config","--node",n,"--name",t,"--json"],{timeout:15e3,maxBuffer:4*1024*1024},(i,o)=>{if(i){let s=null;try{let a=JSON.parse(o);s=typeof a.message=="string"?a.message:null}catch{s=null}e.notify(`rename failed: ${s??i.message}`);return}e.notify(`Renamed node \u2192 ${t}`)})}function fz(t){return new Promise(e=>{zO("tmux",t,{timeout:5e3},(n,r)=>e(n?"":r))})}async function qpi(t,e,n){if(n){await fz(["set-option","-p","-u","-t",t,"@crtr_color"]);return}await fz(["set-option","-p","-t",t,"@crtr_color",e]);for(let r of["pane-border-style","pane-active-border-style"]){let i=(await fz(["show-options","-wqv","-t",t,r])).trim();if(i.includes("@crtr_color"))continue;let o=i!==""?i:(await fz(["show-options","-gqv",r])).trim();o===""&&(o=r==="pane-active-border-style"?"fg=green":"default");let s=`#{?#{!=:#{@crtr_color},},fg=#{@crtr_color},${o.replace(/,/g,"#,")}}`;await fz(["set-option","-w","-t",t,r,s])}}function jpi(t,e){let n=t.trim().toLowerCase();if(n==="")return e.notify("Usage: /color <color> \u2014 a name (red, blue, orange\u2026), colourN, or #rrggbb; /color none to clear"),!0;let r=n==="none"||n==="clear";if(!(r||Opi.has(n)||/^colour\d{1,3}$/.test(n)||/^#[0-9a-f]{6}$/.test(n)))return e.notify(`Invalid color "${n}" \u2014 use a tmux colour name (${["red","green","yellow","blue","magenta","cyan","orange"].join(", ")}, \u2026), colourN, or #rrggbb`),!0;let o=process.env.TMUX_PANE,s=process.env.TMUX!==void 0&&o!==void 0&&o!=="";return s&&qpi(o,n,r),e.onColor?.(r?null:n),e.notify(r?"Node color cleared":`Node colored ${n}${s?"":" (chip only \u2014 no tmux pane)"}`),!0}function zpi(t){let e=process.env.TMUX_PANE;if(process.env.TMUX===void 0||e===void 0||e==="")return t.notify("/resume needs tmux"),!0;let n=cn(t.cwd??process.cwd()),r=Fpi(t),i=r===void 0||r===""?"":` --profile-id ${cn(r)}`,o=`crtr canvas browse --return-pane ${e} --cwd ${n}${i}`;return x7e(o,{w:"97%",h:"95%"}),!0}function Vpi(t){let e=process.env.TMUX_PANE;if(process.env.TMUX===void 0||e===void 0||e==="")return t.notify("/menu needs tmux \u2014 the crouter action menu is a tmux menu"),!0;try{zO("tmux",["display-menu","-t",e,...Jit().slice(1)],n=>{n&&t.notify(`/menu failed: ${n.message.split(`
@@ -1653,7 +1653,7 @@ ${e.message}`,["Yes","No"],l=>c({type:"extension_ui_response",id:e.id,confirmed:
1653
1653
  `)?t.slice(0,-1):t;return`${r}${e}
1654
1654
  ${i}
1655
1655
  ${r}
1656
- `}function _hi(t,e){let n=e+2,r=o=>Math.max(1,Math.min(o-1,e)),i=t.spans.map(o=>o!==null&&(o[0]<=1||o[1]>=n));return{lines:t.lines,rows:t.rows.map((o,s)=>i[s]===!0?null:o),spans:t.spans.map((o,s)=>o===null||i[s]===!0?null:[r(o[0]),r(o[1])]),blocks:t.blocks.map(o=>({type:o.type,start:r(o.start),end:r(o.end)}))}}function Xyn(t,e,n){let r=Kw(t).length;return _hi(Sle(Shi(t,e),n),r)}function Whe(t){let e=[],n=new Array(t.lines.length).fill(null);for(let r=0;r<t.lines.length;r++){let i=t.spans[r]??null;if(i===null){let s=t.rows[r]??null,a=s!==null?t.blocks[s]:void 0;if(a===void 0)continue;i=[a.start,a.end]}let o=e[e.length-1];o!==void 0&&o.lastRow===r-1&&o.start===i[0]&&o.end===i[1]?o.lastRow=r:e.push({start:i[0],end:i[1],firstRow:r,lastRow:r}),n[r]=e.length-1}if(e.length===0){e.push({start:t.blocks[0]?.start??1,end:t.blocks[t.blocks.length-1]?.end??1,firstRow:0,lastRow:Math.max(0,t.lines.length-1)});for(let r=0;r<n.length;r++)n[r]=0}return{units:e,rowUnits:n}}function kR(t,e){let n=-1;for(let r=0;r<t.length;r++){let i=t[r];i.start<=e&&i.end>=e&&(n===-1||i.end-i.start<t[n].end-t[n].start)&&(n=r)}if(n!==-1)return n;for(let r=0;r<t.length;r++)if(t[r].start>e)return r;return Math.max(0,t.length-1)}function R7e(t,e){for(let n=0;n<t.length;n++)if(t[n].start===e.start&&t[n].end===e.end)return n;return kR(t,e.start)}function Az(t,e,n){let r=-1,i=-1;if(t.forEach((o,s)=>{o.start<=n&&o.end>=e&&(r===-1&&(r=s),i=s)}),r===-1){let o=kR(t,e);return{lo:o,hi:o}}return{lo:r,hi:i}}_g();Hl();import{basename as khi,dirname as Zyn,join as Thi}from"node:path";import{mkdirSync as Rhi,watch as Bhi,writeFileSync as G3s}from"node:fs";function B7e(t){return Thi(oc(),"signals",t)}function Hhe(t,e){let n=B7e(t);try{Rhi(Zyn(n),{recursive:!0,mode:448});let r=Bhi(Zyn(n),(i,o)=>{String(o)===khi(n)&&e()});return()=>r.close()}catch(r){return console.error(`activity-signal: failed to watch "${t}": ${r instanceof Error?r.message:String(r)}`),()=>{}}}function ewn(t){return Hhe("review-activity",t)}var yz=class extends Error{code;details;constructor(e,n,r){super(n),this.name="ReviewDocumentError",this.code=e,this.details=r}};function twn(t,e){return{async anchorBase(){let n=await e(()=>Ft().getReviewDocumentBase(t));return{file:n.file,text:n.anchor_base_text,docHash:n.anchor_base_sha256}},async list(){return(await e(()=>Ft().listReviewComments(t,{status:"all"}))).comments.map(Mhi)},async create(n){return(await VO(()=>e(()=>Ft().createReviewComment(t,{text:n.text,anchor:{line:n.line,end_line:n.endLine},doc_hash:n.docHash,actor_node_id:null})))).comment.comment_id},async edit(n){await VO(()=>e(()=>Ft().editReviewComment(n.id,{text:n.text,if_revision:n.ifRevision,actor_node_id:null})))},async resolve(n){await VO(()=>e(()=>Ft().resolveReviewComment(n,{actor_node_id:null})))},async reopen(n){await VO(()=>e(()=>Ft().reopenReviewComment(n,{actor_node_id:null})))},async remove(n){await VO(()=>e(()=>Ft().deleteReviewComment(n,{actor_node_id:null})))},async remapRanges(n){await VO(()=>e(()=>Ft().updateReviewCommentRanges(t,{from_doc_hash:n.fromDocHash,to_doc_hash:n.toDocHash,entries:n.entries.map(r=>"detached"in r?{comment_id:r.id,detached:!0}:{comment_id:r.id,anchor:{line:r.anchor.line,end_line:r.anchor.endLine}})})))},async fork(n){let r=await e(()=>Ft().forkReviewComment(n));return{nodeId:r.node_id,cwd:r.cwd}},onChanged(n){return ewn(n)}}}function Mhi(t){let e={line:t.anchor.line,endLine:t.anchor.end_line};return{id:t.comment_id,revision:t.revision,...e,lineText:t.anchor_line_text,comment:t.text,status:t.status,authorKind:t.author.kind,createdAt:t.created_at,anchorStatus:t.anchor_state==="detached"?"detached":"live",...t.anchor_state==="detached"?{originalRange:e}:{}}}async function VO(t){try{return await t()}catch(e){throw e instanceof Xt&&Phi(e.code)?new yz(e.code,e.message,e.details):e}}function Phi(t){return t==="stale_document"||t==="stale_comment"||t==="range_batch_incomplete"||t==="range_batch_stale"}du();function D7e(t){switch(t){case"active":return 0;case"idle":return 1;case"done":return 2;case"canceled":return 3;case"dead":return 4;default:return 5}}function nwn(t){return t==="active"||t==="idle"}function rwn(t){return t.lifecycle!=="resident"||t.finalized}function wz(){let t=Q0();return t!==void 0?{CRTR_HOME:t}:{}}function own(){return{...wz(),CRTR_ATTACH_WAKE_PARKED:"0"}}function Ghe(t){let e=w0e();if(e!==null){for(let n of e)if(Xm(n,"@crtr_node")===t)return n}}function iwn(t,e,n,r,i){let o=cv(t,{cwd:n,env:own(),command:`crtr surface attach to ${e}`});if(o===null)return{focused:!1,session:null,inPlace:!1,revived:i};let s=AE(o);return s!==null&&bV(s.window,"even-horizontal"),iU(o),{focused:!0,session:s?.session??r,inPlace:!1,revived:i}}async function qhe(t,e,n){let r=n.pane??process.env.TMUX_PANE??Rg()?.pane;if(r===void 0||r==="")return{focused:!1,session:null,inPlace:!1,revived:!1};let o=(await t.ensureAttach(e,{resume:!0,revive:!0,wakeParked:!1})).revived,s=AE(r)?.session??null;if(n.inPlace===!0){let c=Xm(r,"@crtr_node"),u=Ghe(e);n.keepOtherViewers!==!0&&u!==void 0&&u!==r&&yE(u)&&q0(u);try{Bg(r,"@crtr_node","")}catch{}let l=y0e(r),d={...own(),...c!==void 0&&c!==""?{CRTR_ATTACH_ROSTER:c}:{},...n.openTicket!==void 0?{CRTR_ATTACH_OPEN_TICKET:n.openTicket}:{}},p=xV({pane:r,cwd:n.cwd,env:d,command:`crtr surface attach to ${e}`});return p&&l!==null&&g0e(l,n.name),{focused:p,session:s,inPlace:!0,revived:o}}if(n.newPane===!0){let c=Ghe(e);return c!==void 0&&yE(c)&&q0(c),iwn(r,e,n.cwd,s,o)}let a=Ghe(e);if(a!==void 0){let c=AE(a);if(c!==null)return I0e(c.session),wB(c.session,c.window),iU(a),{focused:!0,session:c.session,inPlace:!0,revived:o}}return iwn(r,e,n.cwd,s,o)}async function jhe(t,e,n){let r=e.node_id;if(e.kind==="human")throw new Zp({error:"not_focusable",message:`node ${r} is a human-ask (kind:human), not a conversation \u2014 it has no pi session to focus.`,next:`The pending question is queued for the user; see it with \`crtr human list\`, or retract it with \`crtr human cancel ${r}\`.`});return!nwn(e.status)&&rwn({lifecycle:e.lifecycle,finalized:e.final_report!=null})?{focused:await A0e(n.pane,e.cwd,`crtr node inspect transcript ${cn(r)}`),session:null,revived:!1,inPlace:!1}:qhe(t,r,{cwd:e.cwd,name:e.name,pane:n.pane,...n.newPane===!0?{newPane:!0}:{},...n.inPlace===!0?{inPlace:!0}:{},...n.keepOtherViewers===!0?{keepOtherViewers:!0}:{},...n.openTicket!==void 0?{openTicket:n.openTicket}:{}})}var Nhi=99,Lhi=40,Qhi=12,Ohi=.42,Fhi=.4,Uhi=52;function swn(t){let{companionNodeId:e,cwd:n,callerPane:r}=t;if(!js())return{ok:!1,reason:"no_tmux"};let o=b0e().filter(l=>l.nodeId===e&&wV(l.pane)).sort((l,d)=>d.stampMs-l.stampMs);if(o.length>0)return{ok:!0,paneId:o[0].pane,origin:"adopted"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let s=EV(r);if(s===null)return{ok:!1,reason:"split_refused"};let a,c;s.cols>=Nhi?(a=!1,c=Math.max(Lhi,Math.round(s.cols*Ohi))):(a=!0,c=Math.max(Qhi,Math.round(s.rows*Fhi)));let u=cv(r,{cwd:n,env:wz(),command:`crtr surface attach to ${e}`,vertical:a,size:c});return u===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:u,origin:"opened"}}function awn(t){let{nodeId:e,cwd:n,splitFrom:r}=t;if(!js())return{ok:!1,reason:"no_tmux"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let i=EV(r);if(i===null)return{ok:!1,reason:"split_refused"};if(Math.floor(i.cols/2)<Uhi)return{ok:!1,reason:"no_room"};let o=cv(r,{cwd:n,env:wz(),command:`crtr surface attach to ${e}`,vertical:!1,size:Math.floor(i.cols/2)});return o===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:o}}function zhe(t){return yE(t)&&wV(t)}function M7e(t,e){!yE(t)||Xm(t,"@crtr_node")!==e||q0(t)}function uwn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function $hi(t){return t!==null&&typeof t=="object"?t:{}}function Vhe(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Whi(t){return Array.isArray(t)?t.filter(e=>e!==null&&typeof e=="object"&&"anchor"in e&&"text"in e):[]}function P7e(t,e){let n=new Map(e.map(r=>[r.id,r.label]));return t.map(r=>({id:r,label:n.get(r)??r}))}function lwn(t,e){let n=t.rows?.find(i=>i.id===e),r=t.columns[0];return n===void 0||r===void 0||!uwn(n.cells,r.id)?e:String(n.cells[r.id])}function Hhi(t){let e=t.config.label;return typeof e=="string"&&e!==""?e:t.id??t.kind}function N7e(t,e){return e.kind==="whole"?Hhi(t):e.kind==="option"?t.config.options.find(n=>n.id===e.optionId)?.label??e.optionId:lwn(t.config,e.rowId)}function cwn(t,e){return Whi(e.comments).map(n=>({anchor:n.anchor,anchorLabel:N7e(t,n.anchor),text:n.text}))}function Ghi(t,e){let n=e===void 0?"unanswered":"answered",r=$hi(e),i=t.config.label,o={id:t.id,kind:t.kind,...typeof i=="string"&&i!==""?{label:i}:{},state:n};if(t.unvalidated===!0)return{...o,blank:e===void 0,groups:[],comments:[],...e===void 0?{}:{raw:r}};if(t.kind==="options"){let s=t.config,a=typeof r.freetext=="string"&&r.freetext!==""?r.freetext:void 0,c={group:"option",mode:s.mode,total:s.options.length,picked:P7e(Vhe(r.selectedOptionIds),s.options)};return{...o,blank:c.picked.length===0&&a===void 0,groups:[c],...a===void 0?{}:{freetext:a},comments:cwn(t,r)}}if(t.kind==="text"){let s=r,a=typeof s.text=="string"?s.text:"",c=t.config.singleLine===!0;return{...o,blank:c&&a==="",groups:[],text:{value:a,edited:s.edited===!0,...c?{singleLine:!0}:{}},comments:[]}}if(t.kind==="table"){let s=t.config,a=[];return(s.rowSelect==="single"||s.rowSelect==="multi")&&a.push({group:"row",mode:s.rowSelect,total:s.rows?.length??0,picked:Vhe(r.selectedRowIds).map(c=>({id:c,label:lwn(s,c)}))}),(s.columnSelect==="single"||s.columnSelect==="multi")&&a.push({group:"column",mode:s.columnSelect,total:s.columns.length,picked:P7e(Vhe(r.selectedColumnIds),s.columns)}),{...o,blank:a.every(c=>c.picked.length===0),groups:a,comments:cwn(t,r)}}if(t.kind==="cards"){let s=t.config,a=(s.cards??[]).map(u=>({id:u.id,label:u.title})),c={group:"card",mode:s.mode,total:a.length,picked:P7e(Vhe(r.selectedCardIds),a)};return{...o,blank:c.picked.length===0,groups:[c],comments:[]}}throw new Error(`slot "${t.id}" kind "${t.kind}" does not accept a response`)}function dwn(t,e,n){let r=gR(t),i=r.slots.filter(Oc).map(s=>Ghi(s,uwn(e,s.id)?e[s.id]:void 0)),o=i.filter(s=>s.state==="answered");return{title:r.title,...r.subtitle===void 0?{}:{subtitle:r.subtitle},completedAt:n.completedAt,kind:i.length===0?"acknowledgement":"answer",digest:jhi(o),slots:i}}function qhi(t){return t.picked.length===0?"no selection":t.group==="option"||t.group==="card"?t.picked.map(e=>e.label).join(", "):t.total>0?`${t.picked.length} of ${t.total} ${t.group}s`:`${t.picked.length} ${t.group}${t.picked.length===1?"":"s"}`}function jhi(t){return t.map(e=>{if(e.raw!==void 0)return`${e.kind} response`;if(e.text!==void 0)return e.text.singleLine===!0?e.text.value===""?"empty":e.text.value:e.text.edited?"edited":"unchanged";let n=e.groups.map(qhi);return e.freetext!==void 0&&n.push(e.freetext),n.join(", ")||"no selection"}).join(" \xB7 ")}var zhi=8,Khe=(t,e,n)=>Rle(Mle(t),e,n);function hwn(t){return dwn(t.manifest,Object.fromEntries(t.responses),{completedAt:""})}function Vhi(t,e){return e.id===void 0?void 0:t.slots.find(n=>n.id===e.id)}function mwn(t){if(t===void 0||t.state==="unanswered")return"unanswered";if(t.raw!==void 0)return"custom response";let e=t.text!==void 0?[t.text.edited?"edited":"accepted"]:t.groups.map(n=>n.picked.length===0?"none":n.picked.map(r=>r.label).join(", "));return t.freetext!==void 0&&e.push(t.freetext),t.comments.length>0&&e.push(`${t.comments.length} comment${t.comments.length===1?"":"s"}`),e.join("; ")||"answered"}function pwn(t,e){return N7e(t,e)}function fwn(t,e,n){let r=Math.min(Math.max(20,e-4),120),i=Math.max(20,e-4),o=["",...Yhe(Ll(t.manifest.title),r,"",0,`${bs}${Cs}`)];if(t.manifest.subtitle)for(let p of cu(ti(t.manifest.subtitle),r))o.push(` ${ut}${p}${Qe}`);if(t.displayMarkdown!==""){o.push("");for(let p of Khe(t.displayMarkdown,r,i))o.push(` ${p}`)}else t.manifest.dialect==="html"&&o.push("",` ${ut}HTML page \u2014 open in Northlight to read this${Qe}`);let s=t.slots.length>0;s&&o.push(` ${ut}${zw(r)}${Qe}`,"");let a=hwn(t),c=-1,u;for(let p=0;p<t.slots.length;p++){let h=t.slots[p];t.manifest.steps>1&&h.step!==c&&(c!==-1&&o.push(""),o.push(` ${bs}Step ${h.step+1}/${t.manifest.steps}${Qe}`),c=h.step);let m=h.id===void 0?void 0:t.responses.get(h.id),f=Oc(h)?jw(t,h)?`${wI}\u2713${Qe}`:`${ut}\u25CB${Qe}`:`${ut}\xB7${Qe}`,g=p===t.currentIndex?`${Cs}\u25B8${Qe} `:" ";p===t.currentIndex&&(u=o.length),o.push(` ${g}${f} ${nh(Ll(OO(h)),Math.max(10,e-16))}`),m!==void 0&&o.push(` ${ut}${nh(Ll(mwn(Vhi(a,h))),Math.max(10,e-10))}${Qe}`)}if(t.manifest.slots.some(p=>Oc(p)&&!eh(p))){o.push("");for(let p of cu("This page must be answered in Northlight. Leaving it here keeps it in your inbox; x on the list cancels it.",r-2))o.push(` ${aa}${p}${Qe}`)}s&&o.push(""),o.push(` ${ut}${zw(r)}${Qe}`);let d=!t.manifest.slots.some(Oc)?` ${ut}u/d${Qe} scroll ${ut}q${Qe} dismiss`:` ${ut}enter${Qe} review ${ut}\u2191\u2193/jk${Qe} navigate ${ut}u/d${Qe} scroll ${ut}q${Qe} close`;return Iwn(o,d,t,e,n,r+2,t.followSelection?u:void 0)}function KO(t,e,n){let r=[...t],i=Math.max(0,Math.min(e,r.length)),o=gwn(t,n),s=0;for(let u=0;u<o.length;u++)o[u].start<=i&&(s=u);let a=o.map((u,l)=>{if(l!==s)return r.slice(u.start,u.end).join("");let d=r.slice(u.start,i).join(""),p=i<u.end?r[i]:" ",h=i<u.end?r.slice(i+1,u.end).join(""):"";return`${d}${nz}${p}${Qe}${h}`}),c=o[s];return i===c.end&&sa(r.slice(c.start,c.end).join(""))>=n&&(a[s]=r.slice(c.start,c.end).join(""),a.splice(s+1,0,`${nz} ${Qe}`)),a}function Ez(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r>0&&/\s/.test(n[r-1]);)r--;for(;r>0&&!/\s/.test(n[r-1]);)r--;return r}function Jhe(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r<n.length&&/\s/.test(n[r]);)r++;for(;r<n.length&&!/\s/.test(n[r]);)r++;return r}function gwn(t,e){let n=[...t],r=Math.max(1,e),i=[],o=0,s=0;for(let a=0;a<n.length;a++){let c=n[a];if(c===`
1656
+ `}function _hi(t,e){let n=e+2,r=o=>Math.max(1,Math.min(o-1,e)),i=t.spans.map(o=>o!==null&&(o[0]<=1||o[1]>=n));return{lines:t.lines,rows:t.rows.map((o,s)=>i[s]===!0?null:o),spans:t.spans.map((o,s)=>o===null||i[s]===!0?null:[r(o[0]),r(o[1])]),blocks:t.blocks.map(o=>({type:o.type,start:r(o.start),end:r(o.end)}))}}function Xyn(t,e,n){let r=Kw(t).length;return _hi(Sle(Shi(t,e),n),r)}function Whe(t){let e=[],n=new Array(t.lines.length).fill(null);for(let r=0;r<t.lines.length;r++){let i=t.spans[r]??null;if(i===null){let s=t.rows[r]??null,a=s!==null?t.blocks[s]:void 0;if(a===void 0)continue;i=[a.start,a.end]}let o=e[e.length-1];o!==void 0&&o.lastRow===r-1&&o.start===i[0]&&o.end===i[1]?o.lastRow=r:e.push({start:i[0],end:i[1],firstRow:r,lastRow:r}),n[r]=e.length-1}if(e.length===0){e.push({start:t.blocks[0]?.start??1,end:t.blocks[t.blocks.length-1]?.end??1,firstRow:0,lastRow:Math.max(0,t.lines.length-1)});for(let r=0;r<n.length;r++)n[r]=0}return{units:e,rowUnits:n}}function kR(t,e){let n=-1;for(let r=0;r<t.length;r++){let i=t[r];i.start<=e&&i.end>=e&&(n===-1||i.end-i.start<t[n].end-t[n].start)&&(n=r)}if(n!==-1)return n;for(let r=0;r<t.length;r++)if(t[r].start>e)return r;return Math.max(0,t.length-1)}function R7e(t,e){for(let n=0;n<t.length;n++)if(t[n].start===e.start&&t[n].end===e.end)return n;return kR(t,e.start)}function Az(t,e,n){let r=-1,i=-1;if(t.forEach((o,s)=>{o.start<=n&&o.end>=e&&(r===-1&&(r=s),i=s)}),r===-1){let o=kR(t,e);return{lo:o,hi:o}}return{lo:r,hi:i}}_g();Hl();import{basename as khi,dirname as Zyn,join as Thi}from"node:path";import{mkdirSync as Rhi,watch as Bhi,writeFileSync as q3s}from"node:fs";function B7e(t){return Thi(oc(),"signals",t)}function Hhe(t,e){let n=B7e(t);try{Rhi(Zyn(n),{recursive:!0,mode:448});let r=Bhi(Zyn(n),(i,o)=>{String(o)===khi(n)&&e()});return()=>r.close()}catch(r){return console.error(`activity-signal: failed to watch "${t}": ${r instanceof Error?r.message:String(r)}`),()=>{}}}function ewn(t){return Hhe("review-activity",t)}var yz=class extends Error{code;details;constructor(e,n,r){super(n),this.name="ReviewDocumentError",this.code=e,this.details=r}};function twn(t,e){return{async anchorBase(){let n=await e(()=>Ft().getReviewDocumentBase(t));return{file:n.file,text:n.anchor_base_text,docHash:n.anchor_base_sha256}},async list(){return(await e(()=>Ft().listReviewComments(t,{status:"all"}))).comments.map(Mhi)},async create(n){return(await VO(()=>e(()=>Ft().createReviewComment(t,{text:n.text,anchor:{line:n.line,end_line:n.endLine},doc_hash:n.docHash,actor_node_id:null})))).comment.comment_id},async edit(n){await VO(()=>e(()=>Ft().editReviewComment(n.id,{text:n.text,if_revision:n.ifRevision,actor_node_id:null})))},async resolve(n){await VO(()=>e(()=>Ft().resolveReviewComment(n,{actor_node_id:null})))},async reopen(n){await VO(()=>e(()=>Ft().reopenReviewComment(n,{actor_node_id:null})))},async remove(n){await VO(()=>e(()=>Ft().deleteReviewComment(n,{actor_node_id:null})))},async remapRanges(n){await VO(()=>e(()=>Ft().updateReviewCommentRanges(t,{from_doc_hash:n.fromDocHash,to_doc_hash:n.toDocHash,entries:n.entries.map(r=>"detached"in r?{comment_id:r.id,detached:!0}:{comment_id:r.id,anchor:{line:r.anchor.line,end_line:r.anchor.endLine}})})))},async fork(n){let r=await e(()=>Ft().forkReviewComment(n));return{nodeId:r.node_id,cwd:r.cwd}},onChanged(n){return ewn(n)}}}function Mhi(t){let e={line:t.anchor.line,endLine:t.anchor.end_line};return{id:t.comment_id,revision:t.revision,...e,lineText:t.anchor_line_text,comment:t.text,status:t.status,authorKind:t.author.kind,createdAt:t.created_at,anchorStatus:t.anchor_state==="detached"?"detached":"live",...t.anchor_state==="detached"?{originalRange:e}:{}}}async function VO(t){try{return await t()}catch(e){throw e instanceof Xt&&Phi(e.code)?new yz(e.code,e.message,e.details):e}}function Phi(t){return t==="stale_document"||t==="stale_comment"||t==="range_batch_incomplete"||t==="range_batch_stale"}du();function D7e(t){switch(t){case"active":return 0;case"idle":return 1;case"done":return 2;case"canceled":return 3;case"dead":return 4;default:return 5}}function nwn(t){return t==="active"||t==="idle"}function rwn(t){return t.lifecycle!=="resident"||t.finalized}function wz(){let t=Q0();return t!==void 0?{CRTR_HOME:t}:{}}function own(){return{...wz(),CRTR_ATTACH_WAKE_PARKED:"0"}}function Ghe(t){let e=w0e();if(e!==null){for(let n of e)if(Xm(n,"@crtr_node")===t)return n}}function iwn(t,e,n,r,i){let o=cv(t,{cwd:n,env:own(),command:`crtr surface attach to ${e}`});if(o===null)return{focused:!1,session:null,inPlace:!1,revived:i};let s=AE(o);return s!==null&&bV(s.window,"even-horizontal"),iU(o),{focused:!0,session:s?.session??r,inPlace:!1,revived:i}}async function qhe(t,e,n){let r=n.pane??process.env.TMUX_PANE??Rg()?.pane;if(r===void 0||r==="")return{focused:!1,session:null,inPlace:!1,revived:!1};let o=(await t.ensureAttach(e,{resume:!0,revive:!0,wakeParked:!1})).revived,s=AE(r)?.session??null;if(n.inPlace===!0){let c=Xm(r,"@crtr_node"),u=Ghe(e);n.keepOtherViewers!==!0&&u!==void 0&&u!==r&&yE(u)&&q0(u);try{Bg(r,"@crtr_node","")}catch{}let l=y0e(r),d={...own(),...c!==void 0&&c!==""?{CRTR_ATTACH_ROSTER:c}:{},...n.openTicket!==void 0?{CRTR_ATTACH_OPEN_TICKET:n.openTicket}:{}},p=xV({pane:r,cwd:n.cwd,env:d,command:`crtr surface attach to ${e}`});return p&&l!==null&&g0e(l,n.name),{focused:p,session:s,inPlace:!0,revived:o}}if(n.newPane===!0){let c=Ghe(e);return c!==void 0&&yE(c)&&q0(c),iwn(r,e,n.cwd,s,o)}let a=Ghe(e);if(a!==void 0){let c=AE(a);if(c!==null)return I0e(c.session),wB(c.session,c.window),iU(a),{focused:!0,session:c.session,inPlace:!0,revived:o}}return iwn(r,e,n.cwd,s,o)}async function jhe(t,e,n){let r=e.node_id;if(e.kind==="human")throw new Zp({error:"not_focusable",message:`node ${r} is a human-ask (kind:human), not a conversation \u2014 it has no pi session to focus.`,next:`The pending question is queued for the user; see it with \`crtr human list\`, or retract it with \`crtr human cancel ${r}\`.`});return!nwn(e.status)&&rwn({lifecycle:e.lifecycle,finalized:e.final_report!=null})?{focused:await A0e(n.pane,e.cwd,`crtr node inspect transcript ${cn(r)}`),session:null,revived:!1,inPlace:!1}:qhe(t,r,{cwd:e.cwd,name:e.name,pane:n.pane,...n.newPane===!0?{newPane:!0}:{},...n.inPlace===!0?{inPlace:!0}:{},...n.keepOtherViewers===!0?{keepOtherViewers:!0}:{},...n.openTicket!==void 0?{openTicket:n.openTicket}:{}})}var Nhi=99,Lhi=40,Qhi=12,Ohi=.42,Fhi=.4,Uhi=52;function swn(t){let{companionNodeId:e,cwd:n,callerPane:r}=t;if(!js())return{ok:!1,reason:"no_tmux"};let o=b0e().filter(l=>l.nodeId===e&&wV(l.pane)).sort((l,d)=>d.stampMs-l.stampMs);if(o.length>0)return{ok:!0,paneId:o[0].pane,origin:"adopted"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let s=EV(r);if(s===null)return{ok:!1,reason:"split_refused"};let a,c;s.cols>=Nhi?(a=!1,c=Math.max(Lhi,Math.round(s.cols*Ohi))):(a=!0,c=Math.max(Qhi,Math.round(s.rows*Fhi)));let u=cv(r,{cwd:n,env:wz(),command:`crtr surface attach to ${e}`,vertical:a,size:c});return u===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:u,origin:"opened"}}function awn(t){let{nodeId:e,cwd:n,splitFrom:r}=t;if(!js())return{ok:!1,reason:"no_tmux"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let i=EV(r);if(i===null)return{ok:!1,reason:"split_refused"};if(Math.floor(i.cols/2)<Uhi)return{ok:!1,reason:"no_room"};let o=cv(r,{cwd:n,env:wz(),command:`crtr surface attach to ${e}`,vertical:!1,size:Math.floor(i.cols/2)});return o===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:o}}function zhe(t){return yE(t)&&wV(t)}function M7e(t,e){!yE(t)||Xm(t,"@crtr_node")!==e||q0(t)}function uwn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function $hi(t){return t!==null&&typeof t=="object"?t:{}}function Vhe(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Whi(t){return Array.isArray(t)?t.filter(e=>e!==null&&typeof e=="object"&&"anchor"in e&&"text"in e):[]}function P7e(t,e){let n=new Map(e.map(r=>[r.id,r.label]));return t.map(r=>({id:r,label:n.get(r)??r}))}function lwn(t,e){let n=t.rows?.find(i=>i.id===e),r=t.columns[0];return n===void 0||r===void 0||!uwn(n.cells,r.id)?e:String(n.cells[r.id])}function Hhi(t){let e=t.config.label;return typeof e=="string"&&e!==""?e:t.id??t.kind}function N7e(t,e){return e.kind==="whole"?Hhi(t):e.kind==="option"?t.config.options.find(n=>n.id===e.optionId)?.label??e.optionId:lwn(t.config,e.rowId)}function cwn(t,e){return Whi(e.comments).map(n=>({anchor:n.anchor,anchorLabel:N7e(t,n.anchor),text:n.text}))}function Ghi(t,e){let n=e===void 0?"unanswered":"answered",r=$hi(e),i=t.config.label,o={id:t.id,kind:t.kind,...typeof i=="string"&&i!==""?{label:i}:{},state:n};if(t.unvalidated===!0)return{...o,blank:e===void 0,groups:[],comments:[],...e===void 0?{}:{raw:r}};if(t.kind==="options"){let s=t.config,a=typeof r.freetext=="string"&&r.freetext!==""?r.freetext:void 0,c={group:"option",mode:s.mode,total:s.options.length,picked:P7e(Vhe(r.selectedOptionIds),s.options)};return{...o,blank:c.picked.length===0&&a===void 0,groups:[c],...a===void 0?{}:{freetext:a},comments:cwn(t,r)}}if(t.kind==="text"){let s=r,a=typeof s.text=="string"?s.text:"",c=t.config.singleLine===!0;return{...o,blank:c&&a==="",groups:[],text:{value:a,edited:s.edited===!0,...c?{singleLine:!0}:{}},comments:[]}}if(t.kind==="table"){let s=t.config,a=[];return(s.rowSelect==="single"||s.rowSelect==="multi")&&a.push({group:"row",mode:s.rowSelect,total:s.rows?.length??0,picked:Vhe(r.selectedRowIds).map(c=>({id:c,label:lwn(s,c)}))}),(s.columnSelect==="single"||s.columnSelect==="multi")&&a.push({group:"column",mode:s.columnSelect,total:s.columns.length,picked:P7e(Vhe(r.selectedColumnIds),s.columns)}),{...o,blank:a.every(c=>c.picked.length===0),groups:a,comments:cwn(t,r)}}if(t.kind==="cards"){let s=t.config,a=(s.cards??[]).map(u=>({id:u.id,label:u.title})),c={group:"card",mode:s.mode,total:a.length,picked:P7e(Vhe(r.selectedCardIds),a)};return{...o,blank:c.picked.length===0,groups:[c],comments:[]}}throw new Error(`slot "${t.id}" kind "${t.kind}" does not accept a response`)}function dwn(t,e,n){let r=gR(t),i=r.slots.filter(Oc).map(s=>Ghi(s,uwn(e,s.id)?e[s.id]:void 0)),o=i.filter(s=>s.state==="answered");return{title:r.title,...r.subtitle===void 0?{}:{subtitle:r.subtitle},completedAt:n.completedAt,kind:i.length===0?"acknowledgement":"answer",digest:jhi(o),slots:i}}function qhi(t){return t.picked.length===0?"no selection":t.group==="option"||t.group==="card"?t.picked.map(e=>e.label).join(", "):t.total>0?`${t.picked.length} of ${t.total} ${t.group}s`:`${t.picked.length} ${t.group}${t.picked.length===1?"":"s"}`}function jhi(t){return t.map(e=>{if(e.raw!==void 0)return`${e.kind} response`;if(e.text!==void 0)return e.text.singleLine===!0?e.text.value===""?"empty":e.text.value:e.text.edited?"edited":"unchanged";let n=e.groups.map(qhi);return e.freetext!==void 0&&n.push(e.freetext),n.join(", ")||"no selection"}).join(" \xB7 ")}var zhi=8,Khe=(t,e,n)=>Rle(Mle(t),e,n);function hwn(t){return dwn(t.manifest,Object.fromEntries(t.responses),{completedAt:""})}function Vhi(t,e){return e.id===void 0?void 0:t.slots.find(n=>n.id===e.id)}function mwn(t){if(t===void 0||t.state==="unanswered")return"unanswered";if(t.raw!==void 0)return"custom response";let e=t.text!==void 0?[t.text.edited?"edited":"accepted"]:t.groups.map(n=>n.picked.length===0?"none":n.picked.map(r=>r.label).join(", "));return t.freetext!==void 0&&e.push(t.freetext),t.comments.length>0&&e.push(`${t.comments.length} comment${t.comments.length===1?"":"s"}`),e.join("; ")||"answered"}function pwn(t,e){return N7e(t,e)}function fwn(t,e,n){let r=Math.min(Math.max(20,e-4),120),i=Math.max(20,e-4),o=["",...Yhe(Ll(t.manifest.title),r,"",0,`${bs}${Cs}`)];if(t.manifest.subtitle)for(let p of cu(ti(t.manifest.subtitle),r))o.push(` ${ut}${p}${Qe}`);if(t.displayMarkdown!==""){o.push("");for(let p of Khe(t.displayMarkdown,r,i))o.push(` ${p}`)}else t.manifest.dialect==="html"&&o.push("",` ${ut}HTML page \u2014 open in Northlight to read this${Qe}`);let s=t.slots.length>0;s&&o.push(` ${ut}${zw(r)}${Qe}`,"");let a=hwn(t),c=-1,u;for(let p=0;p<t.slots.length;p++){let h=t.slots[p];t.manifest.steps>1&&h.step!==c&&(c!==-1&&o.push(""),o.push(` ${bs}Step ${h.step+1}/${t.manifest.steps}${Qe}`),c=h.step);let m=h.id===void 0?void 0:t.responses.get(h.id),f=Oc(h)?jw(t,h)?`${wI}\u2713${Qe}`:`${ut}\u25CB${Qe}`:`${ut}\xB7${Qe}`,g=p===t.currentIndex?`${Cs}\u25B8${Qe} `:" ";p===t.currentIndex&&(u=o.length),o.push(` ${g}${f} ${nh(Ll(OO(h)),Math.max(10,e-16))}`),m!==void 0&&o.push(` ${ut}${nh(Ll(mwn(Vhi(a,h))),Math.max(10,e-10))}${Qe}`)}if(t.manifest.slots.some(p=>Oc(p)&&!eh(p))){o.push("");for(let p of cu("This page must be answered in Northlight. Leaving it here keeps it in your inbox; x on the list cancels it.",r-2))o.push(` ${aa}${p}${Qe}`)}s&&o.push(""),o.push(` ${ut}${zw(r)}${Qe}`);let d=!t.manifest.slots.some(Oc)?` ${ut}u/d${Qe} scroll ${ut}q${Qe} dismiss`:` ${ut}enter${Qe} review ${ut}\u2191\u2193/jk${Qe} navigate ${ut}u/d${Qe} scroll ${ut}q${Qe} close`;return Iwn(o,d,t,e,n,r+2,t.followSelection?u:void 0)}function KO(t,e,n){let r=[...t],i=Math.max(0,Math.min(e,r.length)),o=gwn(t,n),s=0;for(let u=0;u<o.length;u++)o[u].start<=i&&(s=u);let a=o.map((u,l)=>{if(l!==s)return r.slice(u.start,u.end).join("");let d=r.slice(u.start,i).join(""),p=i<u.end?r[i]:" ",h=i<u.end?r.slice(i+1,u.end).join(""):"";return`${d}${nz}${p}${Qe}${h}`}),c=o[s];return i===c.end&&sa(r.slice(c.start,c.end).join(""))>=n&&(a[s]=r.slice(c.start,c.end).join(""),a.splice(s+1,0,`${nz} ${Qe}`)),a}function Ez(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r>0&&/\s/.test(n[r-1]);)r--;for(;r>0&&!/\s/.test(n[r-1]);)r--;return r}function Jhe(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r<n.length&&/\s/.test(n[r]);)r++;for(;r<n.length&&!/\s/.test(n[r]);)r++;return r}function gwn(t,e){let n=[...t],r=Math.max(1,e),i=[],o=0,s=0;for(let a=0;a<n.length;a++){let c=n[a];if(c===`
1657
1657
  `){i.push({start:o,end:a}),o=a+1,s=0;continue}let u=sa(c);s+u>r?(i.push({start:o,end:a}),o=a,s=u):s+=u}return i.push({start:o,end:n.length}),i}function xz(t,e,n,r){let i=gwn(t,r),o=Math.max(0,Math.min(e,[...t].length)),s=0;for(let c=0;c<i.length;c++)i[c].start<=o&&(s=c);let a=i[s+n];return a===void 0?o:Math.min(a.start+(o-i[s].start),a.end)}function Khi(t,e){return e.id===void 0?[]:t.responses.get(e.id)?.comments??[]}function Yhe(t,e,n,r,i){return cu(t,Math.max(10,e-r)).map((o,s)=>` ${s===0?n:" ".repeat(r)}${i}${o}${Qe}`)}function Yhi(t,e,n,r){if(e.id===void 0)return!1;let i=t.responses.get(e.id);return n==="option"?i?.selectedOptionIds?.includes(r)===!0:n==="card"?i?.selectedCardIds?.includes(r)===!0:n==="row"?i?.selectedRowIds?.includes(r)===!0:i?.selectedColumnIds?.includes(r)===!0}function Awn(t,e){let n=t.slots[t.currentIndex],r=Math.min(Math.max(20,e-4),120),i=Math.max(20,e-4),o=`[${t.currentIndex+1}/${t.slots.length}]`,s=["",...Yhe(Ll(t.manifest.title),r,`${bs}${Cs}${o}${Qe} `,sa(o)+2,ut),` ${ut}${zw(r)}${Qe}`,"",...Yhe(Ll(OO(n)),r,"",0,bs)],a=n.config.body;if(typeof a=="string"&&a.length>0){s.push("");for(let l of Khe(a,r,i))s.push(` ${l}`)}if(eh(n)){if(n.kind==="chart"){let l=n.config,d=l.title??`${l.x} vs ${(l.y??[]).map(p=>p.label??p.field).join(", ")}`;s.push("",` ${ut}chart \u2014 ${ti(l.kind)}: ${ti(d)}${Qe}`)}else if(n.kind==="table"){s.push("");for(let d of Khe(she(n.config),r,i))s.push(` ${d}`);let l=n.config.label;l&&s.push(` ${ut}${ti(l)}${Qe}`)}else if(n.kind==="text"){let d=(n.id===void 0?void 0:t.responses.get(n.id))?.text??n.config.initialText;s.push("");for(let p of Khe(d,r,i))s.push(` ${p}`)}}else{s.push("");for(let l of cu(`${ti(n.kind)} \u2014 must be answered in Northlight; the terminal cannot submit this page`,Math.max(10,r-2)))s.push(` ${aa}${l}${Qe}`);s.push(` ${ut}q leaves it in your inbox; x on the list cancels it${Qe}`)}s.push("",` ${ut}${zw(r)}${Qe}`);let c;if(t.inputMode!==null){let l=t.inputMode.kind==="comment"?`Comment on ${pwn(n,t.inputMode.anchor)}`:t.inputMode.kind==="text"?"Edit text":"Other response";s.push(` ${bs}${l}${Qe}`);for(let d of KO(t.inputMode.buffer,t.inputMode.cursor,Math.max(10,r-4)))s.push(` ${d}`);c=` ${ut}enter save esc cancel${t.editorAvailable?" ^o editor":""}${Qe}`}else{FO(n).forEach((d,p)=>{let h=p===t.selectedAction?`${Cs}\u25B8${Qe}`:" ";if(d.kind==="select"){let m=Yhi(t,n,d.group,d.id),f;d.mode==="multi"?f=`[${m?`${wI}\u2713${Qe}`:" "}] ${d.shortcut?`[${d.shortcut}] `:""}`:f=`[${m?`${wI}\u2713${Qe}`:d.shortcut??" "}] `;let g=Go(f);if(cu(ti(d.label),Math.max(10,r-2-g)).forEach((A,x)=>s.push(x===0?` ${h} ${f}${A}`:`${" ".repeat(4+g)}${A}`)),d.description)for(let A of cu(ti(d.description),Math.max(10,r-6)))s.push(` ${ut}${A}${Qe}`)}else{let m=d.kind==="freetext"?"r":d.kind==="edit"?"e":"a";cu(ti(d.label),Math.max(10,r-6)).forEach((f,g)=>s.push(g===0?` ${h} [${m}] ${f}`:` ${f}`))}});for(let d of Khi(t,n))for(let p of cu(`attached: ${pwn(n,d.anchor)} \u2014 ${ti(d.text)}`,Math.max(10,r-2)))s.push(` ${ut}${p}${Qe}`);t.hint&&s.push(` ${aa}${ti(t.hint)}${Qe}`),c=` ${ut}n/p next/previous \u2191\u2193/jk actions${$O(n).length>0?" c comment":""} u/d scroll \u2190\u2192/hl pan q close${Qe}`}let u=Math.max(0,...s.map(Go));return{lines:s,footer:c,maxW:r,maxH:Math.max(0,u-Math.max(1,e))}}function ywn(t,e,n){if(t.slots[t.currentIndex]===void 0){t.scrollOffset=0,t.hscrollOffset=0,t.hscrollMax=0;return}let r=Awn(t,e);t.hscrollMax=r.maxH,t.hscrollOffset=Math.max(0,Math.min(t.hscrollOffset,t.hscrollMax)),t.scrollOffset=Math.max(0,Math.min(t.scrollOffset,Math.max(0,r.lines.length-L7e(n))))}function wwn(t,e){t.hscrollOffset=Math.max(0,Math.min(t.hscrollMax,t.hscrollOffset+e*zhi))}function Ewn(t,e,n){let r=Awn(t,e),i=L7e(n),o=t.scrollOffset,s=r.lines.slice(o,o+i);for(;s.length<i;)s.push("");let a=t.hscrollOffset>0?s.map(u=>uhe(u,t.hscrollOffset,e)):s,c=Math.min(e,r.maxW+2);return i<n&&a.push(Cwn(r.footer,bwn(o,i,r.lines.length),r.maxW+2)),T0(a.map(u=>Na(u,e)),e,c)}function xwn(t,e,n){let r=Math.min(Math.max(20,e-4),120),i=["",...Yhe(`${Ll(t.manifest.title)} \u2014 Summary`,r,"",0,`${bs}${Cs}`),` ${ut}${zw(r)}${Qe}`,""],o=hwn(t);for(let c of o.slots){let u=t.manifest.slots.find(p=>p.id===c.id),d=u!==void 0&&jw(t,u)?`${wI}\u2713${Qe}`:`${aa}\u25CB${Qe}`;i.push(` ${d} ${bs}${ti(u===void 0?c.kind:OO(u))}${Qe} ${ut}${ti(mwn(c))}${Qe}`)}let s=yI(t);if(!s){i.push("",` ${aa}Cannot submit yet.${Qe}`);for(let c of t.slots.filter(Oc))jw(t,c)||(i.push(` ${ut}${c.id??c.kind} is unanswered${Qe}`),eh(c)||i.push(` ${ut}${c.id} must be answered in Northlight${Qe}`))}i.push("",` ${ut}${zw(r)}${Qe}`);let a=s?` ${ut}enter${Qe} submit ${ut}u/d${Qe} scroll ${ut}q${Qe} back`:` ${ut}u/d${Qe} scroll ${ut}q${Qe} back`;return Iwn(i,a,t,e,n,r+2)}function L7e(t){return t>=2?t-1:t}function bwn(t,e,n){if(e<=0||n<=e)return{marks:"",full:""};let r=Math.min(n,t+e),i=`${t>0?"\u25B4":" "}${r<n?"\u25BE":" "}`;return{marks:`${ut}${i}${Qe}`,full:`${ut}${i} ${t+1}\u2013${r}/${n}${Qe}`}}function Cwn(t,e,n){if(e.full==="")return t;let r=i=>n-Go(t)-Go(i)-2;for(let i of[e.full,e.marks])if(r(i)>=2)return`${t}${" ".repeat(r(i))}${i}`;return` ${e.marks} ${t.trimStart()}`}function Iwn(t,e,n,r,i,o,s){let a=L7e(i),c=Math.max(0,t.length-a);n.scrollOffset=Math.max(0,Math.min(n.scrollOffset,c)),s!==void 0&&a>0&&(s<n.scrollOffset?n.scrollOffset=s:s>=n.scrollOffset+a&&(n.scrollOffset=Math.min(c,s-a+1)));let u=t.slice(n.scrollOffset,n.scrollOffset+a);for(;u.length<a;)u.push("");return a<i&&u.push(Cwn(e,bwn(n.scrollOffset,a,t.length),o)),T0(u.map(l=>Na(l,r)),r,Math.min(r,o))}function vwn(t,e,n,r){let i=e.units.length>0?e:{units:[{start:1,end:Math.max(1,t.length),firstRow:0,lastRow:0}],rowUnits:e.rowUnits};return{sourceLines:t,units:i.units,rowUnits:i.rowUnits,comments:[...n],sourceRevision:r,detached:Object.fromEntries(n.flatMap(o=>o.anchorStatus==="detached"?[[o.id,o.originalRange??{line:o.line,endLine:o.endLine}]]:[])),activeUnit:n.length>0?kR(i.units,n[0].line):0,selectionAnchor:null,scroll:0,hscroll:0,mode:"view",compose:null,listIndex:0}}function Q7e(t){let e=t.selectionAnchor??t.activeUnit;return{lo:Math.min(t.activeUnit,e),hi:Math.max(t.activeUnit,e)}}function Jhi(t){let{lo:e,hi:n}=Q7e(t),r=Number.POSITIVE_INFINITY,i=0;for(let o=e;o<=n;o++){let s=t.units[o];s!==void 0&&(r=Math.min(r,s.start),i=Math.max(i,s.end))}return Number.isFinite(r)?{line:r,endLine:Math.max(r,i)}:{line:1,endLine:Math.max(1,t.sourceLines.length)}}function O7e(t,e,n){let r=Math.max(0,t.units.length-1),i=Math.max(0,Math.min(r,t.activeUnit+e));return n?{...t,activeUnit:i,selectionAnchor:t.selectionAnchor??t.activeUnit}:{...t,activeUnit:i,selectionAnchor:null}}function Swn(t){let e=new Set;for(let n of t.comments){if(n.status==="deleted"||n.anchorStatus==="detached")continue;let r=!1;t.units.forEach((i,o)=>{i.start<=n.endLine&&i.end>=n.line&&(e.add(o),r=!0)}),r||e.add(kR(t.units,n.line))}return e}function Xhi(t,e,n){let r=t[e],i=t[n];return r===void 0||i===void 0?null:{first:r.firstRow,last:i.lastRow}}function Zhi(t,e,n,r,i,o=2){let s=Math.max(0,i-r),a=Math.max(0,Math.min(t,s));return n-e+1>=r?Math.max(0,Math.min(Math.max(0,e-1),s)):(e-o<a?a=Math.max(e-o,n-(r-1)):n+o>a+r-1&&(a=Math.min(n+o-(r-1),e)),Math.max(0,Math.min(a,s)))}function vI(t,e,n){let r=Xhi(t.units,t.activeUnit,t.activeUnit);if(r===null)return t;let i=Zhi(t.scroll,r.first,r.last,n,e.lines.length);return i===t.scroll?t:{...t,scroll:i}}function _wn(t,e,n,r){let i=Math.max(0,r-n);return{...t,scroll:Math.max(0,Math.min(t.scroll+e,i))}}function kwn(t){return Math.max(1,Math.floor(t/2))}function Twn(t,e,n,r){if(e===0)return t;let i=e>0?1:-1,o=Math.max(0,r-n),s=Math.max(0,Math.min(t.scroll+e,o)),a=s+(s>0?1:0),c=Math.max(a,s+n-1-(s+n<r?1:0)),u=t.units[t.activeUnit]?.firstRow??t.scroll,l=Math.max(a,Math.min(u+e,c)),d=emi(t,l,a,c,i)??t.activeUnit;return s===t.scroll&&d===t.activeUnit?t:{...t,scroll:s,activeUnit:d,selectionAnchor:null}}function emi(t,e,n,r,i){let o=Math.max(0,t.units.length-1);for(let s=0;s<=r-n;s++)for(let a of[e+s*i,e-s*i]){if(a<n||a>r)continue;let c=t.rowUnits[a];if(c!=null)return Math.max(0,Math.min(o,c))}return null}function Rwn(t){return{...t,mode:"compose",compose:{buffer:"",cursor:0,editingId:null,returnMode:"view",anchor:Jhi(t)}}}function Bwn(t,e){let n=t.comments[e];if(n===void 0)return t;let r=n.comment,{lo:i,hi:o}=Az(t.units,n.line,n.endLine);return{...t,activeUnit:o,selectionAnchor:i===o?null:i,mode:"compose",compose:{buffer:r,cursor:[...r].length,editingId:n.id,returnMode:"list",anchor:{line:n.line,endLine:n.endLine}}}}function Xhe(t){let e=t.compose?.returnMode??"view";return{...t,mode:e,compose:null}}function Dwn(t){let e=t.compose;if(e==null)return{state:t,commit:null};let n=e.buffer.trim();return n.length===0?{state:Xhe(t),commit:null}:{state:Xhe(t),commit:{editingId:e.editingId,anchor:e.anchor,text:n}}}function Mwn(t){return{...t,mode:"list",listIndex:Math.max(0,Math.min(t.listIndex,t.comments.length-1))}}function F7e(t){return{...t,mode:"view"}}function U7e(t,e){if(t.comments.length===0)return t;let n=Math.max(0,Math.min(t.comments.length-1,t.listIndex+e));return{...t,listIndex:n}}function Pwn(t){let e=t.comments[t.listIndex];return{state:t,id:e?.id??null}}function Nwn(t){return{state:t,id:t.comments.at(-1)?.id??null}}function Lwn(t){return{...t,mode:"help"}}function $7e(t){return{...t,mode:"view"}}function II(t){return[...t]}function Qwn(t){return t.replace(/\x1b\[20[01]~/g,"").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\r\n?/g,`
1658
1658
  `).replace(/[\x00-\x09\x0B-\x1F\x7F]/g,"")}function Zhe(t,e,n){let r=II(t),i=Math.max(0,Math.min(e,r.length));return{buffer:[...r.slice(0,i),...II(n),...r.slice(i)].join(""),cursor:i+II(n).length}}function Own(t,e){if(e<=0)return{buffer:t,cursor:e};let n=II(t);return{buffer:[...n.slice(0,e-1),...n.slice(e)].join(""),cursor:e-1}}function Fwn(t,e){let n=II(t);return e>=n.length?{buffer:t,cursor:e}:{buffer:[...n.slice(0,e),...n.slice(e+1)].join(""),cursor:e}}function Uwn(t,e){let n=e;for(;n>0&&t[n-1]!==`
1659
1659
  `;)n--;let r=e;for(;r<t.length&&t[r]!==`
@@ -1668,7 +1668,7 @@ Press Enter to open ${ime(t.command)}\u2026 `),n(),e(`
1668
1668
 
1669
1669
  `)),this.tui.requestRender(),this.notify(`Restored ${i.length} queued message${i.length>1?"s":""} to editor`)}emitDrive(e){try{let n=Buffer.byteLength(OV(e));if(n>cfi)return this.notify(`Message too large to send (${Math.round(n/(1024*1024))} MiB) \u2014 shorten the text or remove an attached image`),!1}catch{return this.notify("Message could not be encoded"),!1}return this.emitCommand(e)}async handlePaste(){try{let e=await Nyn();if(!e){this.notify("No image in the clipboard");return}if(!e.image){this.notify(e.note??"Image not pasted");return}this.attachImage(Pyn(e.image),e.note)}catch{this.notify("Could not read the clipboard image")}}attachImage(e,n){let r=++this.pasteSeq;this.pastedImages.set(r,e);let i=this.editor.getText();this.editor.insertTextAtCursor(`${i&&!/\s$/.test(i)?" ":""}[Image #${r}] `),this.notify(n?`Image #${r} attached (${n})`:`Image #${r} attached`),this.tui.requestRender()}expandImagePlaceholders(e){return e.replace(/\[Image #(\d+)\]/g,(n,r)=>this.pastedImages.get(Number(r))??n)}clearPastedImages(){this.pastedImages.clear(),this.pasteSeq=0}async openExternalEditor(){let e=XO();if(e===null){this.notify(JO);return}let n=e.command,r=this.editor,i=sfi(ofi(),`crtr-attach-editor-${Date.now()}.pi.md`);try{ifi(i,r.getExpandedText?.()??this.editor.getText(),"utf-8"),this.tui.stop();let[o,...s]=n.split(" ");process.stdout.write(`Launching external editor: ${n}
1670
1670
  The viewer resumes when it exits.
1671
- `),ZO(e);let a=await new Promise(c=>{let u=tfi(o,[...s,i],{stdio:"inherit",shell:process.platform==="win32"});u.on("error",()=>c(null)),u.on("close",l=>c(l))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${n} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(nfi(i,"utf-8").replace(/\n$/,""))}catch(o){this.notify(`External editor failed: ${o instanceof Error?o.message:String(o)}`)}finally{try{rfi(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}};XAe();pu();Pa();import{join as _En}from"node:path";import{execFile as Afi}from"node:child_process";var ufi="anthropic",lfi="openai-codex",pme="openai",J6s=600*1e3,X6s=720*60*60*1e3;function hme(t){return t===ufi||t===lfi||t===pme}var mme=class{constructor(e){this.client=e}client;async read(e){let n=(await this.client().listModelAuth()).providers.find(r=>r.provider===e);if(!(n===void 0||!n.configured))return n.managed?{type:"oauth",access:"",refresh:"",expires:Math.max(...n.accounts.map(i=>Date.parse(i.expires_at)))}:n.kind==="api_key"?{type:"api_key",key:""}:{type:"oauth",access:"",refresh:"",expires:Number.MAX_SAFE_INTEGER}}async list(){return(await this.client().listModelAuth()).providers.filter(e=>e.configured).map(e=>({providerId:e.provider,type:e.managed?"oauth":e.kind}))}async modify(e,n){if(hme(e))throw new Error(`${e} signs in through the daemon (model_auth.start), not through the credential store`);let r=await n(await this.read(e));if(r!==void 0){if(r.type==="api_key")await this.client().installCredential(e,{kind:"api_key",api_key:r.key??""});else{let{type:i,access:o,refresh:s,expires:a,...c}=r;await this.client().installCredential(e,{kind:"oauth",access_token:o,refresh_token:s,expires_at:new Date(a).toISOString(),...Object.keys(c).length?{extra:c}:{}})}return r}}async delete(e){await this.client().removeCredential(e)}};W0();async function dfi(t,e){let n=e.filter(o=>o!==void 0);if(n.length===0)return t;let r=[],i=new Promise((o,s)=>{for(let a of n){let c=()=>s(new Error("Login cancelled"));a.addEventListener("abort",c,{once:!0}),r.push(()=>a.removeEventListener("abort",c))}});try{return await Promise.race([t,i])}finally{for(let o of r)o()}}function CEn(t,e={}){let{openBrowser:n,onChange:r,isActive:i}=e,o=()=>i?i():!t.signal.aborted,s=()=>r?.();return{signal:t.signal,notify(a){if(o()){switch(a.type){case"auth_url":t.showAuth(a.url,a.instructions),n?.(a.url);break;case"device_code":t.showDeviceCode(a),t.showWaiting("Waiting for authentication..."),n?.(a.verificationUri);break;case"info":t.showInfo(a.message,a.links);break;case"progress":t.showProgress(a.message);break}s()}},async prompt(a){if(t.signal.aborted||a.signal?.aborted===!0)throw new Error("Login cancelled");let c;if(a.type==="select"){let u=a.options.map((l,d)=>`${d+1}. ${l.label}`).join(`
1671
+ `),ZO(e);let a=await new Promise(c=>{let u=tfi(o,[...s,i],{stdio:"inherit",shell:process.platform==="win32"});u.on("error",()=>c(null)),u.on("close",l=>c(l))});a===null&&e.source==="fallback"&&this.notify(`Could not launch ${n} \u2014 set $EDITOR to an editor you have installed`),a===0&&this.editor.setText(nfi(i,"utf-8").replace(/\n$/,""))}catch(o){this.notify(`External editor failed: ${o instanceof Error?o.message:String(o)}`)}finally{try{rfi(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}};XAe();pu();Pa();import{join as _En}from"node:path";import{execFile as Afi}from"node:child_process";var ufi="anthropic",lfi="openai-codex",pme="openai",X6s=600*1e3,Z6s=720*60*60*1e3;function hme(t){return t===ufi||t===lfi||t===pme}var mme=class{constructor(e,n=!1){this.client=e;this.snapshotOnce=n}client;snapshotOnce;snapshot;listAuth(){return this.snapshotOnce?this.snapshot??=this.client().listModelAuth():this.client().listModelAuth()}async read(e){let n=(await this.listAuth()).providers.find(r=>r.provider===e);if(!(n===void 0||!n.configured))return n.managed?{type:"oauth",access:"",refresh:"",expires:Math.max(...n.accounts.map(i=>Date.parse(i.expires_at)))}:n.kind==="api_key"?{type:"api_key",key:""}:{type:"oauth",access:"",refresh:"",expires:Number.MAX_SAFE_INTEGER}}async list(){return(await this.listAuth()).providers.filter(e=>e.configured).map(e=>({providerId:e.provider,type:e.managed?"oauth":e.kind}))}async modify(e,n){if(hme(e))throw new Error(`${e} signs in through the daemon (model_auth.start), not through the credential store`);let r=await n(await this.read(e));if(r!==void 0){if(r.type==="api_key")await this.client().installCredential(e,{kind:"api_key",api_key:r.key??""});else{let{type:i,access:o,refresh:s,expires:a,...c}=r;await this.client().installCredential(e,{kind:"oauth",access_token:o,refresh_token:s,expires_at:new Date(a).toISOString(),...Object.keys(c).length?{extra:c}:{}})}return r}}async delete(e){await this.client().removeCredential(e)}};W0();async function dfi(t,e){let n=e.filter(o=>o!==void 0);if(n.length===0)return t;let r=[],i=new Promise((o,s)=>{for(let a of n){let c=()=>s(new Error("Login cancelled"));a.addEventListener("abort",c,{once:!0}),r.push(()=>a.removeEventListener("abort",c))}});try{return await Promise.race([t,i])}finally{for(let o of r)o()}}function CEn(t,e={}){let{openBrowser:n,onChange:r,isActive:i}=e,o=()=>i?i():!t.signal.aborted,s=()=>r?.();return{signal:t.signal,notify(a){if(o()){switch(a.type){case"auth_url":t.showAuth(a.url,a.instructions),n?.(a.url);break;case"device_code":t.showDeviceCode(a),t.showWaiting("Waiting for authentication..."),n?.(a.verificationUri);break;case"info":t.showInfo(a.message,a.links);break;case"progress":t.showProgress(a.message);break}s()}},async prompt(a){if(t.signal.aborted||a.signal?.aborted===!0)throw new Error("Login cancelled");let c;if(a.type==="select"){let u=a.options.map((l,d)=>`${d+1}. ${l.label}`).join(`
1672
1672
  `);c=t.showPrompt(`${a.message}
1673
1673
  ${u}`,"1").then(l=>{let d=a.options[Number.parseInt(l,10)-1]?.id;if(d===void 0)throw new Error("Login cancelled");return d})}else a.type==="manual_code"?c=t.showManualInput(a.message):c=t.showPrompt(a.message,a.placeholder);return s(),dfi(c,[t.signal,a.signal])}}}_g();function pfi(t=process.env){return t.SSH_CONNECTION||t.SSH_TTY?!1:process.platform==="darwin"||process.platform==="win32"?!0:!!(t.DISPLAY||t.WAYLAND_DISPLAY)}function vEn(t){return t.aborted}function hfi(t,e){return e.aborted?Promise.reject(new Error("Login cancelled")):new Promise((n,r)=>{let i=()=>r(new Error("Login cancelled"));e.addEventListener("abort",i,{once:!0}),t.then(n,r).finally(()=>e.removeEventListener("abort",i))})}function mfi(t){if(!(!(t instanceof Xt)||t.status!==404||!/no route for/.test(t.message)))return new Error("The running crtr daemon predates daemon-run sign-in. Run `crtr sys daemon restart`, then sign in again.")}async function X7e(t,e){try{return await t.startModelAuth(e)}catch(n){throw mfi(n)??n}}async function ffi(t,e,n,r){let i={provider:e===pme?"openai-chatgpt":e,...n?{label:n}:{}};if(!r)return{flow:await X7e(t,i),loopback:!1};try{return{flow:await X7e(t,{...i,redirect:"loopback"}),loopback:!0}}catch(o){if(o instanceof Xt&&o.status===409&&o.param==="redirect")return{flow:await X7e(t,i),loopback:!1};throw o}}async function Z7e(t,e,n){for(;!vEn(n);){let r=await hfi(t.getModelAuthFlow(e,25),n);if(r.status==="connected")return;if(r.status!=="pending")throw new Error(r.message??`sign-in ${r.status}`)}throw new Error("Login cancelled")}async function SEn(t,e,n,r={}){let{flow:i,loopback:o}=await ffi(t,e,r.label,r.loopback??pfi()),s=()=>{t.cancelModelAuth(i.flow_id).catch(()=>{})};if(vEn(n.signal))throw s(),new Error("Login cancelled");n.signal.addEventListener("abort",s,{once:!0});try{await gfi(t,i,o,n)}finally{n.signal.removeEventListener("abort",s)}}async function gfi(t,e,n,r){if(e.user_code!==void 0){r.notify({type:"device_code",userCode:e.user_code,verificationUri:e.url,expiresInSeconds:900}),await Z7e(t,e.flow_id,r.signal);return}r.notify({type:"auth_url",url:e.url,instructions:e.instructions});let i=e.provider===pme;if(n&&!i){await Z7e(t,e.flow_id,r.signal);return}if(n){let o=new AbortController,s=AbortSignal.any([r.signal,o.signal]),a=IEn(t,e,r,s);a.catch(()=>{});try{await Promise.race([Z7e(t,e.flow_id,r.signal),a])}finally{o.abort()}return}if(i){await IEn(t,e,r,r.signal);return}for(;;){let o=await r.prompt({type:"manual_code",message:"Paste the code Claude shows"});try{await t.completeModelAuth(e.flow_id,{input:o});return}catch(s){if(s instanceof Xt&&s.status===400&&(s.param==="input"||s.param==="state")){r.notify({type:"info",message:`${s.message} \u2014 paste it again.`});continue}throw s}}}async function IEn(t,e,n,r){for(;;){let i=await n.prompt({type:"manual_code",message:"Paste the final redirect URL from your browser",placeholder:"http://127.0.0.1:1455/auth/callback?...",signal:r});try{await t.completeModelAuth(e.flow_id,{input:i});return}catch(o){if(o instanceof Xt&&o.status===400&&(o.param==="input"||o.param==="state")){n.notify({type:"info",message:`${o.message} \u2014 paste it again.`});continue}throw o}}}async function kEn(t){let e=_En($0(),"auth.json"),n=_En(t,"models.json"),r=new mme(()=>Ft()),i,o={read:a=>r.read(a),list:()=>r.list(),modify:(a,c)=>{let u=i;return i=void 0,u!==void 0&&!u()?Promise.reject(new Error("Login cancelled")):r.modify(a,c)},delete:a=>r.delete(a)};return{runtime:await y0.create({credentials:o,modelsPath:n}),authPath:e,beforeNextCredentialMutation:a=>{i=a}}}async function TEn(t){let e=t.getProviders(),n=[...e.filter(r=>r.auth.oauth!==void 0),...e.filter(r=>r.auth.oauth===void 0)];return Promise.all(n.map(async r=>({id:r.id,name:r.name,authType:r.auth.oauth!==void 0?"oauth":"api_key",status:await t.checkAuth(r.id)})))}function yfi(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Afi(e,[t],{timeout:5e3},()=>{})}async function REn(t,e,n,r){let{runtime:i,authPath:o,beforeNextCredentialMutation:s}=await kEn(e),a=await TEn(i);return({close:c,replace:u})=>{let l=p=>{let h=a.find(_=>_.id===p);if(h===void 0){r(`Unknown provider: ${p}`),c();return}let m=!1,f=!1,g=()=>{m||(m=!0,c())},A=new FT(t,p,(_,T)=>{m||(_?(r(`Logged in to ${h.name}`),n()):r(T?`Login failed: ${T}`:`Login to ${h.name} was cancelled`),g())},h.name);u(A,A);let x=A.handleInput.bind(A);A.handleInput=_=>{f||x(_)};let b=()=>m||A.signal.aborted?!1:(f=!0,A.showDetails(["Saving credentials\u2026"]),!0),v=CEn(A,{openBrowser:yfi,isActive:()=>!m&&!A.signal.aborted}),S=_=>{if(_ instanceof Dw){r(`Logged in to ${h.name}; provider refresh failed: ${_.message}`),n(),g();return}let T=_;T?.name!=="AbortError"&&T?.message!=="Login cancelled"&&r(`Login error: ${String(T?.message??_)}`),g()};if(hme(p)){SEn(Ft(),p,v).then(()=>{m||(r(`Logged in to ${h.name}`),n(),g())}).catch(S);return}if(h.authType==="oauth"){if(i.getProvider(p)?.auth.oauth===void 0){A.showInfo([`Provider "${h.name}" is extension-registered and cannot be logged in`,"from the viewer (the extension runs in the broker, not here).","Run /login directly in the node's terminal, or log in via the pi CLI."].join(`
1674
1674
  `));return}s(b),i.login(p,"oauth",v).then(()=>{m||(r(`Logged in to ${h.name}`),n(),g())}).catch(S).finally(()=>s(void 0))}else A.showPrompt(`Enter API key for ${h.name}:`,"sk-...").then(async _=>{if(!m){if(_.trim()){if(!b())return;await Ft().installCredential(p,{kind:"api_key",api_key:_.trim()}),r(`API key saved for ${h.name}`),n()}else r("No key entered \u2014 login cancelled");g()}}).catch(()=>g())},d=new rI("login",a,l,()=>c());return{component:d,focus:d}}}async function BEn(t,e,n){let{runtime:r,authPath:i}=await kEn(t),o=await TEn(r);return({close:s})=>{let a=u=>{let l=o.find(d=>d.id===u);(async()=>{try{await Ft().removeCredential(u),s(),n(`Logged out of ${l?.name??u}`),e()}catch(d){s(),n(`Logout error: ${d instanceof Error?d.message:String(d)}`)}})()},c=new rI("logout",o,a,()=>s());return{component:c,focus:c}}}function DEn(t,e){return gyn({nodeId:t.nodeId,profileId:t.meta.profile_id??void 0,remote:t.remote,role:t.role,isBrokerOffline:e})}function fme({level:t}){return`Verbosity: ${hV[t]} (${Ki.indexOf(t)+1}/${Ki.length})`}function wfi(t){return t.atEnd?`${fme(t)} \u2014 Ctrl+O again goes back to ${hV[Ki[0]]}`:`${fme(t)} \u2014 Ctrl+O shows more`}function eYe(t){return t.atEnd?`${fme(t)}, the most collapsed level \u2014 Ctrl+O shows more`:`${fme(t)} \u2014 Ctrl+O shows more`}function MEn(t,e,n,r){let{nodeId:i,socket:o,tui:s,editor:a,containers:c}=t,{setNotice:u}=r,l=()=>o.send({type:"reload_auth"}),d=n.permits("auth")?{openLoginPicker:()=>{let h=r.agentDir()??KT();p.openAuthPicker(()=>REn(s,h,l,m=>u(m)))},openLogoutPicker:()=>{let h=r.agentDir()??KT();p.openAuthPicker(()=>BEn(h,l,m=>u(m)))}}:{},p=new dme(s,a,e,{onCommand:h=>o.send(h),onDialogResponse:h=>o.send(h),onNotice:h=>u(h),onGraph:r.toggleGraph,onInbox:r.toggleInbox,onHelp:r.toggleHelp,onNodeMetadata:r.openNodeMetadata,onQuit:r.quit,onCopy:()=>r.copyTarget("last-assistant"),onCopyTarget:r.copyTarget,onToggleMouse:()=>{let h=r.toggleMouse();u(h?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},onColor:r.setChipColor,onPromptSent:r.onPromptSent,frecency:r.frecency,knownRefNames:()=>a.getResolvedRefNames(),onMoreDetail:()=>u(wfi(r.moreDetail())),onLessDetail:()=>u(eYe(r.lessDetail())),onToggleThinking:()=>u(r.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),onRequest:h=>{let m=n.refusal("engine-drive");return m===void 0?o.request(h):Promise.reject(new Error(m))},onMountPicker:h=>{c.pickerPanel.addChild(h),s.requestRender()},onUnmountPicker:()=>{c.pickerPanel.clear(),s.requestRender()},isDormant:r.isDormant,onDormantSubmit:n.permits("wake-dormant")?h=>{(async()=>{try{let m=await Ft().sendMessage(i,{body:h,from:"human"});u(m.revived?"\u21BB waking node\u2026":"\u2709 delivered \u2014 node reads on next wake")}catch(m){u(`Couldn't wake node: ${m instanceof Error?m.message:String(m)}`)}})()}:void 0,...d},n);return p}et();import{execFile as qEn}from"node:child_process";_g();async function Iz(t,e){await Ft().respondHumanRequest(t,{responses:e})}async function PEn(t,e){await Ft().dismissHumanRequest(t,e)}function NEn(t){if(t instanceof Xt)return t.status===503||t.code==="daemon_unavailable";let e=t?.code;return e==="ECONNREFUSED"||e==="ENOENT"}function rc(t){return NEn(t)?"could not reach crtrd \u2014 nothing was submitted":t instanceof Xt||t instanceof Error?t.message:String(t)}function vz(t){return NEn(t)?"unreachable":t instanceof Xt&&t.status===409&&t.code==="already_settled"?"already_settled":"other"}function LEn(t){return{jobId:t.job_id,command:t.command,startedAtMs:Date.parse(t.started_at)}}function Efi(t,e){let n=FAn(t);if(n.length<=e)return n;let r=n.slice(0,Math.max(1,e-1)),i=r.lastIndexOf(" ");return`${(i>=e-12?r.slice(0,i):r).trimEnd()}\u2026`}function QEn(t,e=Date.now(),n=26){if(t.length===0)return;if(t.length===1){let i=t[0];return`bash job \xB7 ${rz(e-i.startedAtMs)} \xB7 ${Efi(i.command,Math.max(12,n))}`}let r=t[0];return`${t.length} bash jobs \xB7 oldest ${rz(e-r.startedAtMs)}`}function OEn(t,e){let n=Date.parse(t)-e;if(n<=0)return"due now";let r=Math.ceil(n/6e4);if(r<60)return`in ${r}m`;let i=Math.floor(r/60),o=r%60;if(i<24)return`in ${i}h${o>0?` ${o}m`:""}`;let s=Math.floor(i/24),a=i%24;return`in ${s}d${a>0?` ${a}h`:""}`}function xfi(t){return[...t].sort((e,n)=>Date.parse(e.fire_at)-Date.parse(n.fire_at))[0]}function FEn(t,e=Date.now()){if(t.length===0)return;if(t.length>1){let i=xfi(t);return`${t.length} crons armed${i?` \xB7 next ${OEn(i.fire_at,e)}`:""}`}let n=t[0],r=OEn(n.fire_at,e);return n.cancel_on_wake?`deadline \xB7 ${r}`:n.recur!==null?`recurring cron \xB7 next ${r}`:`scheduled cron \xB7 ${r}`}import{basename as bfi}from"node:path";function Cfi(t,e){let n=bfi(t);return n.length<=e?n:`${n.slice(0,Math.max(1,e-1))}\u2026`}function UEn(t,e=28){let n=Cfi(t.file,Math.max(8,e));return t.submit_requested_at===void 0?`review open \xB7 ${n} \xB7 waiting on you`:`review submitted \xB7 ${n} \xB7 companion still editing`}function Ifi(t,e){return t.length<=e?t:`\u2026${t.slice(t.length-Math.max(1,e-1))}`}function vfi(t){let e=t.lastIndexOf(".");return e===-1?t:t.slice(e+1)}function $En(t,e=Date.now(),n=28){let r=rz(e-Date.parse(t.created));return`${vfi(t.object_type)} \xB7 ${r} \xB7 ${Ifi(t.object_name,Math.max(8,n))}`}var Sfi=34,_fi=30,kfi=40,Tfi=12,Rfi=6,WEn=22;function HEn(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t+" ".repeat(e-t.length)}function Bfi(t,e){return t.length>=e?t.slice(0,e):" ".repeat(e-t.length)+t}async function GEn(t,e,n,r,i=[],o=[],s=[]){let a=r instanceof gI,c=await r.panelRoster?.(),u=c===void 0?null:new Map(c.nodes.map(Ne=>[Ne.node_id,Ne])),l=new Map,d=new Map;if(c!==void 0)for(let Ne of c.edges){let Y=l.get(Ne.from_id)??[];Y.push(Ne.to_id),l.set(Ne.from_id,Y),d.has(Ne.to_id)||d.set(Ne.to_id,Ne.from_id)}let p=new Map,h=new Map,m=new Map,f=Ne=>{let Y=p.get(Ne);if(Y!==void 0)return Y;let Ue=u===null?r.getNode(Ne).catch(()=>null):Promise.resolve(u.get(Ne)??null);return p.set(Ne,Ue),Ue},g=Ne=>r.getNode(Ne).catch(()=>null),A=Ne=>{let Y=h.get(Ne);if(Y!==void 0)return Y;let Ue=(async()=>{let Ye=u===null?(await r.subscriptionsOf(Ne).catch(()=>[])).map(It=>It.node_id):l.get(Ne)??[],Gt=[];for(let It of Ye)(await f(It))?.kind!=="human"&&Gt.push(It);return Gt})();return h.set(Ne,Ue),Ue},x=Ne=>{let Y=m.get(Ne);if(Y!==void 0)return Y;let Ue=u===null?r.subscribersOf(Ne).then(Ye=>Ye[0]?.node_id).catch(()=>{}):Promise.resolve(d.get(Ne));return m.set(Ne,Ue),Ue},b=async Ne=>{let Y=[];for(let Ue of await A(Ne)){let Ye=(await f(Ue))?.status;(Ye==="active"||Ye==="idle")&&Y.push(Ue)}return Y},v=async Ne=>{let Y=Ne,Ue=new Set([Y]);for(;;){let Ye=await x(Y);if(Ye===void 0||Ue.has(Ye))break;Ue.add(Ye),Y=Ye}return Y},S=new Map,_=async Ne=>{let Y=new Set,Ue=async Ye=>{let Gt=(await f(Ye))?.status==="active";if(Y.has(Ye))return Gt?1:0;Y.add(Ye);let It=0;for(let on of await A(Ye))It+=await Ue(on);return S.set(Ye,It),It+(Gt?1:0)};await Ue(Ne)},T=async Ne=>{if(Ne===null||Ne.mode!=="orchestrator")return"";let Y=(await A(Ne.node_id)).length;return Y>0?` ${uu}\u2933${Y}${qr}`:""},M=Ne=>{if(Ne===null||Ne.status==="active")return"";let Y=S.get(Ne.node_id)??0;return Y>0?` ${Rhe}\u21E3${Y}${qr}`:""},R=n?.muted??(Ne=>Ne),B=n?.faint??(Ne=>Ne);await _(await v(t));let O=await x(t),W=await b(t),z=[...O!==void 0?[O]:[],...W],$=await Promise.all(z.map(async Ne=>await g(Ne)??await f(Ne))),ae=z.length>0?Math.min(WEn,Math.max(...z.map((Ne,Y)=>SR($[Y]??null,Ne).length))):WEn,X=async(Ne,Y)=>{let Ue=$[z.indexOf(Ne)]??null,Ye=HEn(SR(Ue,Ne),ae),Gt=B(HEn(Ue?.kind??"",Tfi)),It=R(Bfi(Dhe(Ue,a),Rfi)),on=`${Phe(Ue)}${await T(Ue)}${M(Ue)}${Lhe(Ne,e)}${Mhe(Ue,a)}`,U=` ${Y} ${Bhe(Ue)} ${Ye} ${Gt} ${It}${on}`;return Yw(U)},ye=[...O!==void 0?[O]:[],...W],we=[];O!==void 0&&we.push({key:`node:${O}`,kind:"node",nodeId:O,line:await X(O,"\u2191")});for(let Ne of W)we.push({key:`node:${Ne}`,kind:"node",nodeId:Ne,line:await X(Ne,"\u2193")});for(let Ne of s){let Y=n?n.info("\u270E"):"\u270E",Ue=UEn(Ne,Math.max(8,Gm()-kfi));we.push({key:`review:${Ne.review_id}`,kind:"review",companionNodeId:Ne.companion_node_id,line:` ${Y} ${R(`${Ue} \xB7 \u21B5 companion`)}${qr}`})}let We=o.length===1?" \xB7 x stop":"",bt=QEn(o,Date.now(),Gm()-(Sfi+We.length));if(bt!==void 0){let Ne=n?n.info("\u2699"):"\u2699";we.push({key:"bash",kind:"bash",line:` ${Ne} ${R(`${bt} \xB7 \u21B5 details${We}`)}${qr}`})}let Qt=FEn(i);if(Qt!==void 0){let Ne=n?n.info("\u25F7"):"\u25F7";we.push({key:"crons",kind:"crons",line:` ${Ne} ${R(`${Qt} \xB7 \u21B5 details`)}${qr}`})}for(let Ne of c?.object_waits??[]){if(Ne.node_id!==t)continue;let Y=n?n.info("\u25C7"):"\u25C7",Ue=$En(Ne,Date.now(),Math.max(8,Gm()-_fi));we.push({key:`object:${Ne.object_id}`,kind:"object-wait",objectId:Ne.object_id,line:` ${Y} ${R(`${Ue} \xB7 \u21B5 details`)}${qr}`})}return{reports:we.map(Ne=>Ne.line),reportIds:ye,items:we}}var Dfi=15e3;function jEn(t,e){let{editor:n,tui:r,pal:i,nodeId:o,remote:s,role:a,canvasSource:c}=t,u=t.containers.reports,l=[],d,p=process.env.CRTR_ATTACH_ROSTER;p!==void 0&&delete process.env.CRTR_ATTACH_ROSTER;let h,m,f=()=>{e.syncCursor(),u.clear();for(let B of l){let O=B.key===d;u.addChild(new ve(O?Jw(vR(B.line),Gm(),CI):B.line,1,0))}r.requestRender()},g=async()=>(await Ft().listBashJobs(o)).map(LEn),A=async()=>{let B=s?[]:(await Ft().listCrons({created_by:o})).filter($=>$.created_by===o),O=s?[]:await g(),W=s?[]:(await Ft().listReviews({state:"open",origin_node_id:o})).reviews;if(l=(await GEn(o,e.asks(),i,c,B,O,W)).items,p!==void 0){let $=p;p=void 0;let ae=l.find(X=>X.kind==="node"&&X.nodeId===$);ae!==void 0&&(d=ae.key)}d!==void 0&&!l.some($=>$.key===d)&&(d=void 0),h!==void 0&&!O.some($=>$.jobId===h?.jobId)&&x(!0),f()},x=B=>{m!==void 0&&(clearTimeout(m),m=void 0),h!==void 0&&(h=void 0,B&&e.setNotice(""))},b=()=>{x(!0),d!==void 0&&(d=void 0,f())},v=B=>gh(B)??(B.length===1?B:void 0),S=(B,O=40)=>{let W=(B.split(`
@@ -1698,7 +1698,7 @@ Follow the instructions below exactly as written \u2014 every part, including th
1698
1698
  ${r}`}function Cxn(t){try{let e=JSON.parse(t);return Array.isArray(e)?e.flatMap(n=>{if(typeof n!="object"||n===null||Array.isArray(n))return[];let r=n;return typeof r.name!="string"||typeof r.description!="string"||typeof r.source!="string"?[]:r.source!=="builtin"&&r.source!=="command"&&r.source!=="template"?[]:r.template!==void 0&&typeof r.template!="string"?[]:r.expansion!==void 0&&!Sme(r.expansion)?[]:[{name:r.name,description:r.description,source:r.source,...typeof r.template=="string"?{template:r.template}:{},...Sme(r.expansion)?{expansion:r.expansion}:{}}]}):[]}catch{return[]}}function Qgi(t){let e=[],n="",r=null;for(let i of t)r!==null?i===r?r=null:n+=i:i==='"'||i==="'"?r=i:/\s/.test(i)?n!==""&&(e.push(n),n=""):n+=i;return n!==""&&e.push(n),e}function Ogi(t,e){let n=e.join(" ");return t.replace(/\$\{(\d+):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(r,i,o,s,a,c)=>{if(i!==void 0)return e[Number.parseInt(i,10)-1]||o||"";if(s!==void 0){let u=Math.max(0,Number.parseInt(s,10)-1);return a!==void 0?e.slice(u,u+Number.parseInt(a,10)).join(" "):e.slice(u).join(" ")}return c==="ARGUMENTS"||c==="@"?n:e[Number.parseInt(c||"0",10)-1]??""})}function Ixn(t,e){let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(n===null)return;let r=n[1];if(e.some(c=>c.source==="builtin"&&c.name===r))return;let i=t.indexOf(" "),o=i===-1?t.slice(1):t.slice(1,i),s=e.find(c=>c.source==="command"&&c.name===o);if(s!==void 0){if(s.expansion===void 0||!Sme(s.expansion))return;let c=i===-1?"":t.slice(i+1);return{name:s.name,invocation:t,content:bxn(s.expansion,c)}}let a=e.find(c=>c.source==="template"&&c.name===r);if(typeof a?.template=="string")return{name:a.name,invocation:t,content:Ogi(a.template,Qgi(n[2]??""))}}var Fgi="CRTR_TIMING",vxn="CRTR_TIMING_T0";function Ugi(){return performance.timeOrigin+performance.now()}var Sxn=(()=>{let t=process.env[Fgi];return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"})(),$gi=(()=>{if(!Sxn)return 0;let t=Number(process.env[vxn]);if(Number.isFinite(t)&&t>0)return t;let e=performance.timeOrigin;return process.env[vxn]=String(e),e})(),Wgi=(()=>{let t=process.env.CRTR_TIMING_PROC;return t!==void 0&&t!==""?t:process.argv[2]==="surface"&&process.argv[3]==="attach"?"viewer":"cli"})(),uYe=0;function MR(t,e){if(!Sxn)return;let n=Ugi(),r=n-$gi,i=uYe===0?r:n-uYe;uYe=n;let o=performance.now(),s=e===void 0?"":" "+Object.entries(e).map(([u,l])=>`${u}=${String(l)}`).join(" "),a=process.env.CRTR_TIMING_PROC??Wgi,c=u=>u.toFixed(1).padStart(8);process.stderr.write(`[timing] +${c(r)}ms \u0394${c(i)}ms up=${c(o)}ms t=${n.toFixed(1)} ${a}/${process.pid} ${t}${s}
1699
1699
  `)}function _xn(t,e){let{socket:n}=t,r=()=>{n.send({type:"get_commands"}),e.resetMemoryRefs()},i=a=>{if(a.for==="get_commands"&&a.ok&&a.detail){try{e.setCommands(Cxn(a.detail))}catch{}return}if(a.for==="navigate_tree"&&a.ok){a.detail&&e.setEditorText(a.detail);return}if(a.for==="share"){a.ok&&a.detail?(e.setNotice(`Shared: ${a.detail}`),p7e(a.detail)):a.ok||e.setNotice(`share failed: ${a.detail??"unknown error"}`);return}if(a.for==="clone"&&!a.ok){e.setNotice(`clone failed: ${a.detail??"unknown error"}`);return}if(!a.ok){e.setNotice(`command failed: ${a.for}${a.detail?` \u2014 ${a.detail}`:""}`);return}a.for==="reload"&&(e.reloadBindings(),e.setCommands(),r(),e.setNotice("Reloaded keybindings, extensions, skills, prompts, and themes"))},o=a=>{e.chat.handleEvent(a),a.type==="session_info_changed"?e.refreshNodeIdentity():a.type==="thinking_level_changed"?e.setNotice(e.modelThinkingLabel()??`Thinking level: ${a.level}`):(a.type==="tool_execution_start"||a.type==="tool_execution_end")&&e.renderFooter()},s=!1;return a=>{switch(e.foldState(a),a.type){case"welcome":{s||(s=!0,MR("viewer.welcome")),e.chat.applySnapshot(a.snapshot),e.refreshNodeIdentity(),r(),a.pending_dialog!=null&&e.attachDialog(a.pending_dialog),e.onWelcome?.();break}case"tool_group_summary":e.chat.applyToolGroupSummary(a.key,a.summary);break;case"turn_reply":e.chat.applyTurnReply(a.key,a.reply);break;case"working_activity":e.chat.setWorkingActivity(a.activity);break;case"model_changed":{let c=e.modelThinkingLabel();c&&e.setNotice(c);break}case"error":a.code==="read_only"?e.setNotice("read-only"):e.chat.showError(a.message);break;case"node_named":break;case"ack":i(a);break;case"extension_ui_request":a.method!=="setStatus"&&a.method!=="setWidget"&&a.method!=="setTitle"&&e.attachDialog(a);break;case"extension_ui_dismiss":e.dismissDialog(a.id);break;case"bash_start":e.chat.bashStart(a.command,a.excludeFromContext);break;case"bash_output":e.chat.bashOutput(a.chunk);break;case"bash_end":e.chat.bashEnd(a);break;default:o(a);break}}}var Hgi=1e3;function kxn(t,e){let{tui:n,editor:r}=t,i=0,o={"crtr.attach.detach":e.detach,"crtr.attach.clear-or-detach":()=>{let s=Date.now();if(s-i<Hgi){i=0,e.cancelTurn();return}i=s,r.setText(""),e.setNotice(`Editor cleared \u2014 press ${e.detachHint()} again to cancel the agent`),n.requestRender()},"crtr.attach.graph.toggle":e.toggleGraph,"crtr.attach.help.toggle":e.toggleHelp,"crtr.attach.inbox.toggle":e.toggleInbox,"crtr.attach.inbox-strip":e.toggleInboxStrip,"crtr.attach.model-ladder.next":()=>e.cycleModelLadder("forward"),"crtr.attach.model-ladder.previous":()=>e.cycleModelLadder("backward"),"crtr.attach.command.inspect":e.inspectLoadedCommand,"crtr.attach.file-review":e.openFileReview,"crtr.attach.profile-files":e.openProfileFiles,"crtr.attach.search":e.openSearch,"crtr.attach.whip":e.whip};return n.addInputListener(s=>{if(s.includes("\x1B[I")||s.includes("\x1B[O")){e.setPaneFocused(s.lastIndexOf("\x1B[I")>s.lastIndexOf("\x1B[O")),n.requestRender();let c=s.replaceAll("\x1B[I","").replaceAll("\x1B[O","");return c.length>0?{data:c}:{consume:!0}}let a=u0e(s);if(a!==void 0)return u7e(a.actionId,o),a.remaining.length>0?{data:a.remaining}:{consume:!0};if(!e.hasExclusiveSurface())return e.panelHandleKey(s)?{consume:!0}:e.searchHandleKey(s)?{consume:!0}:r.focused&&ryn(e.bindings(),s,e.viewportActions())?{consume:!0}:e.stripHandleKey(s)?{consume:!0}:e.rosterHandleKey(s)?{consume:!0}:nyn(e.bindings(),s,o)?{consume:!0}:void 0})}import{spawnSync as Ggi}from"node:child_process";var qgi="\x1B[?1002h\x1B[?1006h",Txn="\x1B[?1002l\x1B[?1006l",Rxn=3;function jgi(){if(!js())return!1;let t=Ggi("tmux",["show-options","-gv","mouse"],{encoding:"utf8"});return t.status===0&&t.stdout?.trim()==="on"}function Bxn(t,e){let n=e==="on"||e==="tmux"&&jgi(),r=()=>{t(n?qgi:Txn)},i=()=>{n=!1;try{t(Txn)}catch{}};return process.once("exit",i),{enabled:()=>n,toggle:()=>(n=!n,r(),n),reassert:r,disable:i,install:(o,s)=>o.addInputListener(a=>{let c=!1,l=a.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g,(d,p,h,m,f)=>{c=!0;let g=Number(p),A=g&-29;return A===64?s.onWheel("up",Rxn,Number(h)):A===65?s.onWheel("down",Rxn,Number(h)):A===32&&f==="M"?s.onPrimaryDrag(Number(h),Number(m)):A===0&&f==="m"?s.onPrimaryRelease(Number(h),Number(m)):g===0&&f==="M"&&s.onPrimaryPress(Number(h),Number(m)),""}).replace(/\x1b\[M[\s\S]{3}/g,()=>(c=!0,""));if(c)return l.length>0?{data:l}:{consume:!0}})}}function zgi(t,e){return t.row<e.row||t.row===e.row&&t.column<=e.column}function Dxn(t,e,n){let[r,i]=zgi(t,e)?[t,e]:[e,t],o=[];for(let s=r.row;s<=i.row;s++){let a=s===r.row?r.column-1:0,c=s===i.row?i.column:n;c>a&&o.push({row:s,from:a,to:c})}return o}function Mxn(t){let e,n,r=()=>e!==void 0&&n!==void 0?{anchor:e,head:n}:void 0,i=()=>{let o=r();if(!o)return"";let s=t.frame(),a=Dxn(o.anchor,o.head,t.width()).map(c=>q0n(s[c.row-1]??"",c.from,c.to).trimEnd());for(;a.length>0&&a[a.length-1]==="";)a.pop();return a.join(`
1700
1700
  `)};return{begin(o,s){e={row:s,column:o},n=void 0},extend(o,s){return e===void 0||n!==void 0&&n.row===s&&n.column===o?!1:(n={row:s,column:o},!0)},release(){let o=e;if(o===void 0)return;if(n===void 0)return e=void 0,{kind:"click",column:o.column,row:o.row};let s=i();if(s==="")return e=void 0,n=void 0,{kind:"selection",notice:"Nothing to copy \u2014 selection is empty"};let{system:a,tmux:c}=Qhe(s),u=a&&c?"clipboard + tmux buffer":a?"clipboard":c?"tmux buffer":void 0,l=s.split(`
1701
- `).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Dxn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=j0n(c[l],u.from,u.to,a))}return c}}}import{existsSync as Vgi}from"node:fs";var Pxn="\x1B_crtr-file-open;",Nxn="\x1B\\";function Lxn(t){let e=t.indexOf(Pxn);if(e===-1)return;let n=e+Pxn.length,r=t.indexOf(Nxn,n);return r===-1?void 0:{file:Kgi(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+Nxn.length)}}function Kgi(t){let e=t.startsWith("'")?Ygi(t):Jgi(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function Ygi(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function Jgi(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function Qxn(t){if(!Vgi(t.file))return"missing";if(!eZe())return"no_nvim";let e=`crtr surface attach to ${cn(t.nodeId)}${t.observer?" --observer":""}`,n=`${YR("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),C0e({pane:t.pane,cwd:t.cwd,env:fU(),command:n})?"opened":"failed"}function Oxn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchAccess().then(a=>{i=a,Vje(),r||t.refresh()},t.onAccessError);let o=()=>{if(n)return;n=!0;let a=t.canvasSource;(a.panelRoster?a.panelRoster().then(u=>u.nodes):a.listNodes()).then(u=>{for(let l of u)e.set(l.node_id,l.name);Vje(),r||t.refresh()},()=>{n=!1})},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>{if(t.remote||i===void 0)return;let c=`/r/${a.split("/").map(encodeURIComponent).join("/")}`;return"canvas_url"in i?`${i.canvas_url}${c}`:`http://127.0.0.1:${t.port}${c}?t=${i.secret}`}};return Kje(s),{dispose(){r=!0,Kje(void 0)}}}et();import{execFile as Xgi}from"node:child_process";function pYe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function Fxn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function Uxn(t){return`${pYe(t.mode)} ${t.kind}`}var Zgi=.72,eAi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},tAi=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],nAi=[["crtr.graph.dismiss","dismiss"]],rAi=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],iAi=[...["active","idle","done","dead","canceled"].map(t=>[IR(t,{}),t]),[IR("active",{streaming:!0}),"live"],[IR("active",{frozen:!0}),"frozen"],[IR("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${rh}${t.color}m${t.glyph}${qr} ${uu}${e}${qr}`).join(" ");function oAi(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var _me=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof gI}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return av(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${da(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+Hd(s);if(o+a>n)break;i.push(s),o+=a}return i.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,eAi),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Ft().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,oAi(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async A=>{let x=i.get(A);if(x!==void 0)return x;let b;try{b=await e.subscriptions(A)}catch{b=[]}let v=b.filter(S=>n.get(S)?.kind!=="human");return i.set(A,v),v},u=async A=>{if(s.has(A))return s.get(A);let x;try{x=(await e.subscribers(A))[0]}catch{x=void 0}return s.set(A,x),x},l=async()=>{let A=this.self,x=new Set([A]);for(;;){let b=await u(A);if(b===void 0||x.has(b))break;x.add(b),A=b}return A},d=async A=>{let x=o.get(A);if(x!==void 0)return x;let b=[...await c(A)];return b.sort((v,S)=>D7e(n.get(v)?.status)-D7e(n.get(S)?.status)),o.set(A,b),b},p=new Set,h=new Set,m=async A=>{let x=n.get(A)?.status==="active";if(h.has(A))return{active:x?1:0,reveal:x||A===this.self};h.add(A);let b=0,v=!1;for(let S of await c(A)){let _=await m(S);b+=_.active,_.reveal&&(v=!0)}return a.set(A,b),v&&p.add(A),{active:b+(x?1:0),reveal:v||x||A===this.self}},f=await l();await m(f),await Promise.all([...i.keys()].map(A=>d(A)));let g={root:f,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(S,_)=>r?Jw(S,Gm(),CI):_?Jw(S,Gm(),Z0n):Yw(S);if(n.cycle){let S=`${n.branch} ${uu}\u21BA ${Nhe(n.id)}${qr}`;return o(S,!1)}let s=e.nodes.get(n.id)??null,a=Bhe(s),c=SR(s,n.id),u=n.isSelf?`${hz}${c}${qr}`:c,l=`${uu}${s?.kind??""}${qr}`,d=`${uu}${Dhe(s,this.remote)}${qr}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${uu}\u25B8${qr} `:" ",m=Phe(s),f=e.childIds.get(n.id)?.length??0,g=s!==null&&f>0?` ${uu}\u2933${f}${qr}`:"",A=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${Rhe}\u21E3${e.activeBelow.get(s.node_id)??0}${qr}`:"",x=s?.fault??null,b=x!==null?` \xB7 ${J0n(x)}`:"",v=`${n.branch}${h}${a} ${u} ${l} ${d}${m}${g}${A}${Lhe(n.id,i)}${Mhe(s,this.remote)}${b}`;return o(v,tyn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(b=>b.id===this.cursorId);i<0&&(i=r.findIndex(b=>b.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??X0n,s=Math.max(3,Math.min(Math.floor(o*Zgi),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let b=0;c>0&&b<4;b++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let v=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(v===l)break;l=Math.max(1,v)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${uu} \u2191 ${this.scrollTop} more${qr}`);for(let b=this.scrollTop;b<d;b++){let v=this.snapshot;p.push(v!==void 0?this.renderSnapshotRow(v,r[b],b===i,n):"")}for(u&&d<r.length&&p.push(`${uu} \u2193 ${r.length-d} more${qr}`),p.unshift(iAi);p.length<a;)p.push("");let h=r.length>0?`${hz}\u2317 canvas graph${qr} ${uu}(${i+1}/${r.length})${qr}`:`${hz}\u2317 canvas graph${qr} ${uu}(loading)${qr}`,m=this.pendingConfirm!==void 0?`${mz}${this.pendingConfirm.label} ${hz}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${qr}`:`${uu}${this.fitHints([...this.remote||this.role!=="controller"?nAi:tAi,...rAi],Math.max(1,e-5))}${qr}`,f=this.palette.border,g=Math.max(1,e-4),A=p.map(b=>`${f("\u2502")} ${ot(b,g,"",!0)} ${f("\u2502")}`),x=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...A,this.borderRow("\u2570","\u256F",m,e)].map(x)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-Hd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(o!==void 0&&o.collapsed&&o.hasKids)this.userExpanded.add(o.id),this.userCollapsed.delete(o.id),this.repaintFolds();else if(o!==void 0&&o.hasKids){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}let u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),this.close());return}if(this.matches("crtr.graph.focus-manager",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}let u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),this.close());return}if(this.matches("crtr.graph.close-subtree",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}let u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?Fxn(l):Nhe(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Ft(),i=await r.getNode(e);(await jhe(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(rc(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{Xgi("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};et();var sAi=.72,aAi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},kme=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*sAi),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(m=>this.boxRow(m,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,aAi)}matchesBinding(e,n){return this.bindings!==void 0&&av(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=Tg.map(({actionId:s})=>{let a=Vd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),r("mouse wheel (when reporting is on)"),i,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},i,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},i,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},i,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":da(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&ke(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-ke(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-ke(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};et();et();var Tme=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,NU(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&hYe(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>ke(a)>r?(hYe(`surface row is ${ke(a)} cells wide; expected at most ${r}`),$xn(Xi(a,0,r,!0),r)):$xn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=cAi(o);return s>1?(hYe(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(uAi)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function $xn(t,e){return ot(t,e,"",!0)}function cAi(t){return t.reduce((e,n)=>e+n.split($r).length-1,0)}function uAi(t){return t.split($r).join("")}function hYe(t){SI("surface-frame",t)}var lAi={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},dAi={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},Bme=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let r=new Tme(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,lAi),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){Rme("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new fYe(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,dAi),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=Ft(),r=await n.getNode(e),i=await qhe(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(rc(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=ume(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(pAi(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){Rme(`surface overlay hide failed: ${mYe(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>Rme(`surface cleanup failed: ${mYe(a)}`))}catch(s){Rme(`surface cleanup failed: ${mYe(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},fYe=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function pAi(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function Rme(t){SI("surface-host",t)}function mYe(t){return t instanceof Error?t.message:String(t)}et();import{watch as xAi}from"node:fs";function hAi(t,e){switch(e){case"gray":return`${ahe}${t}${Qe}`;case"cyan":return`${Cs}${t}${Qe}`;case"red":return`${TAn}${t}${Qe}`;case"yellow":return`${aa}${t}${Qe}`;default:return t}}var mAi={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},fAi={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function gAi(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function Wxn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${bs}${t.length} pending${Qe} ${ut}\xB7 ${r.label}${Qe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Qe}`),o.push(""),t.length===0)return[...o,` ${ut}${kAn}No pending interactions${Qe}`];let s=e-4,a=t.map((l,d)=>AAi(l,d,n,s)),c=yAi(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Qe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Qe}`),u}function AAi(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=mAi[i]??"\xB7",s=gAi(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${Cs}\u25B8${Qe} `:" ",c=Math.max(1,r-s.length-6),l=[`${a}${hAi(o,fAi[i]??"cyan")} ${bs}${che(t.title||`(${t.id.slice(0,8)})`,c)}${Qe} ${ut}${s}${Qe}`,` ${ut}${che(t.subtitle,r-6)}${Qe}`],d=gYe(t);return d!==void 0&&l.push(` ${ut}Recommended: ${che(d,Math.max(1,r-19))}${Qe}`),l}function gYe(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function yAi(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&wAi(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function wAi(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function Dme(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}Jd();nv();var Mme=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Xw().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(EAi(n)),!1}return!this.stopped&&ame(this.opts.host,e)}};function EAi(t){return t instanceof R0?tF(t):t instanceof Error?t.message:String(t)}var Nme=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;open;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??bAi,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.open;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=rc(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&Mgn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail()}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots())}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.open!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=Dme(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${aa}Resize terminal to at least 60\xD718 to use inbox.${Qe}`];let n=Wxn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${ahe}\u2502${Qe}`;for(let s=0;s<e.height;s++){let a=Na(n[s]??"",e.listWidth),c=Na(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-ke(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()&&!this.adapter.hasShortcut(e)){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=await this.requestOrNull(e.id);if(AYe(n)){this.status=Pme(n),await this.rescan();return}let r=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${gYe(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await Iz(e.id,e.fastAction.responses),this.status=r}catch(i){this.status=vz(i)==="already_settled"?Pme(await this.requestOrNull(e.id)):rc(i)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Xw().cancel(e.id,"Canceled from the inbox."):await PEn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=rc(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(AYe(n)){this.status=Pme(n),await this.rescan();return}let r,i;try{let o=await Ft().getHumanInboxPage(e.inboxTicketId);if(o.state==="resolved"||o.state==="canceled"){this.status=QO(o),await this.rescan();return}r=ER(o),i=o.revision}catch{this.status="page could not be read",await this.invalidate();return}this.closed||this.open!==void 0||this.adapter!==void 0||(this.open={dir:e.dir,id:e.id,ticketId:e.inboxTicketId},this.screen="detail",this.adapter=new rF({ticketId:e.inboxTicketId,page:r,productKinds:gV(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:o=>{this.complete(o)}}),this.openRevision=i,this.watchSelected(e.dir),this.markDirty())}async activateReview(e){this.reviewAdapter=new Mme({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=rc(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.open;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Ft().getHumanInboxPage(e.ticketId);if(this.closed||this.open!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(ER(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.reviewAdapter?.stop(),this.leaveDetail();for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.open;if(n===void 0)return;this.submittingDir=n.dir;try{await Iz(n.id,e)}catch(i){this.submittingDir=void 0,this.status=rc(i);let o=vz(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=Pme(await this.requestOrNull(n.id))),this.leaveDetail(),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);ql({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:AYe(await this.requestOrNull(n.id)),still_listed:r}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=Eme(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.open=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=Dme(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Qe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Qe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Qe} opens the full page ${ut}\u2191\u2193/jk${Qe} select${o} ${ut}x${Qe} cancel`,` ${ut}Page:${Qe} c comment u/d scroll${i} ${ut}q${Qe} close`]:[` ${ut}Enter${Qe} opens the full review ${ut}\u2191\u2193/jk${Qe} select ${ut}x${Qe} cancel`,` ${i} ${ut}q${Qe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>Na(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.open?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===Dle())return r.lines;let i=Hxn(r.view,n);return this.preview={...r,width:n,links:Dle(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Qe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Ft().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=ER(n),i=this.preview?.width??Dme(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:Dle(),lines:Hxn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Ft().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Qe}`];let i=[...cu(Ll(r.title),Math.max(10,e-2)).map(s=>` ${bs}${Cs}${s}${Qe}`),""];for(let s of Tle(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Qe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Qe}`)}return i.map(s=>Na(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${aa}${n}${Qe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=nF(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=xAi(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function bAi(){let{tickets:t}=await Ft().listHumanInbox();return t.map(wg).sort(AI)}function Hxn(t,e){let n=t.manifest.dialect==="html"?BO(t.document):RO(t.document,t.manifest);return lhe(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function AYe(t){return t!==void 0&&t.state!=="pending"}function Pme(t){return t?.page===void 0?"ticket was already resolved":QO(t.page)}var yYe=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),CAi(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=wme(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function CAi(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=Na(i,e);return o+" ".repeat(Math.max(0,e-Go(o)))})}async function IAi(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Ft().listHumanInbox();return e.map(wg).sort(AI)}async function Gxn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function qxn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new Nme({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new yYe(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?Gxn("inbox visibility",()=>IAi(t)):void 0,d=u===void 0?void 0:Gxn("profile membership",()=>Ft().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}dB();XR();qF();var wYe=t=>t.snapshot;async function jxn(){let t=await Ft().getSettings();kZe(t.person),Int(t.person,wYe(t)),Snt(async()=>wYe(await Ft().getSettings())),vnt(async(e,n)=>{try{return wYe(await Ft().putSettings({ops:n}))}catch(r){throw r instanceof Xt&&r.status===409?new GF:r}})}dB();import{homedir as RAi}from"node:os";import{fileURLToPath as vAi}from"node:url";import{join as zxn,dirname as SAi}from"node:path";Jd();$l();jAe();rv();pV();pV();Pge();uh();uh();var _Ai=vAi(import.meta.url),kAi=SAi(_Ai),TAi=zxn(kAi,"..",".."),oJs=zxn(TAi,"scripts","self-update.mjs");function Vxn(){return Mge()}var BAi="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function Kxn(t){let e;try{e=Vxn()}catch{}let n;try{t.profile_id&&(n=hE(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=RAi();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?BAi:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}Hl();import{createConnection as DAi}from"node:net";var MAi=15e3;async function PAi(t,e){let n=await jpe(e);return setInterval(()=>{jpe(e).then(i=>{n=i},()=>{})},MAi).unref(),{previewEndpoint:t,get relayToken(){return n}}}function Yxn(t){return t?"observer":"controller"}async function NAi(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=eB(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=DAi(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function Jxn(t,e,n=!0){let r=e!==void 0,i=r?void 0:AR(),o=e!==void 0?IAn({canvasName:e}):new LO,s,a,c,u,l;if(e!==void 0)s={cwd:process.cwd()},c=new _I(t,rhe(e));else{let m=await o.getNode(t);if(m===null)throw new Zp({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});s=m,a=m;try{if((await Ft().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let g=await Ft().getSnapshot(t);u=g.snapshot,l=g.commands}}catch(f){HKe(f,"The node may be finalized or otherwise not attachable.")}i!==void 0?c=new _I(t,await PAi(i.apiUrl,i.directoryUrl)):(u===void 0&&await NAi(t),c=new _I(t,{socketPath:zZe()}))}let d=new _z(t,{transport:c}),p=m=>m instanceof bg?new Zp({error:"no_broker",message:m.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Zp({error:"socket_error",message:`could not attach to node ${t}: ${String(m?.message??m)}`,received:t,next:"Check the node has a running headless broker."}),h;return d.on("error",m=>{h===void 0&&(h=m)}),u===void 0&&await new Promise(async(m,f)=>{let g=()=>{x(),m()},A=b=>{x(),f(b)},x=()=>{d.off("connect",g),d.off("error",A)};d.on("connect",g),d.on("error",A),d.connect()}).catch(m=>{throw p(m)}),{remote:r,canvasSource:o,meta:s,nodeIdentity:a,socket:d,...u===void 0?{}:{initialSnapshot:u,initialCommands:l},assertConnected:()=>{if(u===void 0&&h!==void 0)throw p(h)}}}import{basename as y0i}from"node:path";Pa();et();jye();import{statSync as VAi}from"node:fs";et();rv();import{mkdirSync as LAi,readFileSync as QAi,writeFileSync as OAi}from"node:fs";import{dirname as FAi,join as UAi}from"node:path";var $Ai="completion-frecency.json",WAi=336*60*60*1e3,HAi=8,GAi=1e3;function qAi(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/WAi),i=1-Math.exp(-t.n/3);return HAi*r*i}function jAi(t){let e={};try{let n=JSON.parse(QAi(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function zAi(t,e){try{LAi(FAi(t),{recursive:!0}),OAi(t,JSON.stringify(e),"utf8")}catch{}}function Xxn(t=UAi(tp(),$Ai)){let e=jAi(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,zAi(t,e)},GAi),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>qAi(e[i],o)}}function EYe(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=CE(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function xYe(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function Zxn(t){return t.replace(/:/g,"")}function kz(t,e,n){let r=t.join(`
1701
+ `).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Dxn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=j0n(c[l],u.from,u.to,a))}return c}}}import{existsSync as Vgi}from"node:fs";var Pxn="\x1B_crtr-file-open;",Nxn="\x1B\\";function Lxn(t){let e=t.indexOf(Pxn);if(e===-1)return;let n=e+Pxn.length,r=t.indexOf(Nxn,n);return r===-1?void 0:{file:Kgi(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+Nxn.length)}}function Kgi(t){let e=t.startsWith("'")?Ygi(t):Jgi(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function Ygi(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function Jgi(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function Qxn(t){if(!Vgi(t.file))return"missing";if(!eZe())return"no_nvim";let e=`crtr surface attach to ${cn(t.nodeId)}${t.observer?" --observer":""}`,n=`${YR("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),C0e({pane:t.pane,cwd:t.cwd,env:fU(),command:n})?"opened":"failed"}function Oxn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchAccess().then(a=>{i=a,Vje(),r||t.refresh()},t.onAccessError);let o=()=>{if(n)return;n=!0;let a=t.canvasSource;(a.panelRoster?a.panelRoster().then(u=>u.nodes):a.listNodes()).then(u=>{for(let l of u)e.set(l.node_id,l.name);Vje(),r||t.refresh()},()=>{n=!1})},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>{if(t.remote||i===void 0)return;let c=`/r/${a.split("/").map(encodeURIComponent).join("/")}`;return"canvas_url"in i?`${i.canvas_url}${c}`:`http://127.0.0.1:${t.port}${c}?t=${i.secret}`}};return Kje(s),{dispose(){r=!0,Kje(void 0)}}}et();import{execFile as Xgi}from"node:child_process";function pYe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function Fxn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function Uxn(t){return`${pYe(t.mode)} ${t.kind}`}var Zgi=.72,eAi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},tAi=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],nAi=[["crtr.graph.dismiss","dismiss"]],rAi=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],iAi=[...["active","idle","done","dead","canceled"].map(t=>[IR(t,{}),t]),[IR("active",{streaming:!0}),"live"],[IR("active",{frozen:!0}),"frozen"],[IR("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${rh}${t.color}m${t.glyph}${qr} ${uu}${e}${qr}`).join(" ");function oAi(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var _me=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof gI}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return av(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${da(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+Hd(s);if(o+a>n)break;i.push(s),o+=a}return i.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,eAi),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Ft().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,oAi(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async A=>{let x=i.get(A);if(x!==void 0)return x;let b;try{b=await e.subscriptions(A)}catch{b=[]}let v=b.filter(S=>n.get(S)?.kind!=="human");return i.set(A,v),v},u=async A=>{if(s.has(A))return s.get(A);let x;try{x=(await e.subscribers(A))[0]}catch{x=void 0}return s.set(A,x),x},l=async()=>{let A=this.self,x=new Set([A]);for(;;){let b=await u(A);if(b===void 0||x.has(b))break;x.add(b),A=b}return A},d=async A=>{let x=o.get(A);if(x!==void 0)return x;let b=[...await c(A)];return b.sort((v,S)=>D7e(n.get(v)?.status)-D7e(n.get(S)?.status)),o.set(A,b),b},p=new Set,h=new Set,m=async A=>{let x=n.get(A)?.status==="active";if(h.has(A))return{active:x?1:0,reveal:x||A===this.self};h.add(A);let b=0,v=!1;for(let S of await c(A)){let _=await m(S);b+=_.active,_.reveal&&(v=!0)}return a.set(A,b),v&&p.add(A),{active:b+(x?1:0),reveal:v||x||A===this.self}},f=await l();await m(f),await Promise.all([...i.keys()].map(A=>d(A)));let g={root:f,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(S,_)=>r?Jw(S,Gm(),CI):_?Jw(S,Gm(),Z0n):Yw(S);if(n.cycle){let S=`${n.branch} ${uu}\u21BA ${Nhe(n.id)}${qr}`;return o(S,!1)}let s=e.nodes.get(n.id)??null,a=Bhe(s),c=SR(s,n.id),u=n.isSelf?`${hz}${c}${qr}`:c,l=`${uu}${s?.kind??""}${qr}`,d=`${uu}${Dhe(s,this.remote)}${qr}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${uu}\u25B8${qr} `:" ",m=Phe(s),f=e.childIds.get(n.id)?.length??0,g=s!==null&&f>0?` ${uu}\u2933${f}${qr}`:"",A=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${Rhe}\u21E3${e.activeBelow.get(s.node_id)??0}${qr}`:"",x=s?.fault??null,b=x!==null?` \xB7 ${J0n(x)}`:"",v=`${n.branch}${h}${a} ${u} ${l} ${d}${m}${g}${A}${Lhe(n.id,i)}${Mhe(s,this.remote)}${b}`;return o(v,tyn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(b=>b.id===this.cursorId);i<0&&(i=r.findIndex(b=>b.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??X0n,s=Math.max(3,Math.min(Math.floor(o*Zgi),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let b=0;c>0&&b<4;b++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let v=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(v===l)break;l=Math.max(1,v)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${uu} \u2191 ${this.scrollTop} more${qr}`);for(let b=this.scrollTop;b<d;b++){let v=this.snapshot;p.push(v!==void 0?this.renderSnapshotRow(v,r[b],b===i,n):"")}for(u&&d<r.length&&p.push(`${uu} \u2193 ${r.length-d} more${qr}`),p.unshift(iAi);p.length<a;)p.push("");let h=r.length>0?`${hz}\u2317 canvas graph${qr} ${uu}(${i+1}/${r.length})${qr}`:`${hz}\u2317 canvas graph${qr} ${uu}(loading)${qr}`,m=this.pendingConfirm!==void 0?`${mz}${this.pendingConfirm.label} ${hz}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${qr}`:`${uu}${this.fitHints([...this.remote||this.role!=="controller"?nAi:tAi,...rAi],Math.max(1,e-5))}${qr}`,f=this.palette.border,g=Math.max(1,e-4),A=p.map(b=>`${f("\u2502")} ${ot(b,g,"",!0)} ${f("\u2502")}`),x=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...A,this.borderRow("\u2570","\u256F",m,e)].map(x)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-Hd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(o!==void 0&&o.collapsed&&o.hasKids)this.userExpanded.add(o.id),this.userCollapsed.delete(o.id),this.repaintFolds();else if(o!==void 0&&o.hasKids){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}let u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),this.close());return}if(this.matches("crtr.graph.focus-manager",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}let u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),this.close());return}if(this.matches("crtr.graph.close-subtree",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}let u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?Fxn(l):Nhe(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Ft(),i=await r.getNode(e);(await jhe(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(rc(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{Xgi("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};et();var sAi=.72,aAi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},kme=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*sAi),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(m=>this.boxRow(m,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,aAi)}matchesBinding(e,n){return this.bindings!==void 0&&av(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=Tg.map(({actionId:s})=>{let a=Vd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),r("mouse wheel (when reporting is on)"),i,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},i,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},i,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},i,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":da(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&ke(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-ke(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-ke(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};et();et();var Tme=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,NU(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&hYe(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>ke(a)>r?(hYe(`surface row is ${ke(a)} cells wide; expected at most ${r}`),$xn(Xi(a,0,r,!0),r)):$xn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=cAi(o);return s>1?(hYe(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(uAi)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function $xn(t,e){return ot(t,e,"",!0)}function cAi(t){return t.reduce((e,n)=>e+n.split($r).length-1,0)}function uAi(t){return t.split($r).join("")}function hYe(t){SI("surface-frame",t)}var lAi={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},dAi={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},Bme=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let r=new Tme(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,lAi),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){Rme("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new fYe(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,dAi),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=Ft(),r=await n.getNode(e),i=await qhe(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(rc(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=ume(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(pAi(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){Rme(`surface overlay hide failed: ${mYe(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>Rme(`surface cleanup failed: ${mYe(a)}`))}catch(s){Rme(`surface cleanup failed: ${mYe(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},fYe=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function pAi(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function Rme(t){SI("surface-host",t)}function mYe(t){return t instanceof Error?t.message:String(t)}et();import{watch as xAi}from"node:fs";function hAi(t,e){switch(e){case"gray":return`${ahe}${t}${Qe}`;case"cyan":return`${Cs}${t}${Qe}`;case"red":return`${TAn}${t}${Qe}`;case"yellow":return`${aa}${t}${Qe}`;default:return t}}var mAi={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},fAi={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function gAi(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function Wxn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${bs}${t.length} pending${Qe} ${ut}\xB7 ${r.label}${Qe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Qe}`),o.push(""),t.length===0)return[...o,` ${ut}${kAn}No pending interactions${Qe}`];let s=e-4,a=t.map((l,d)=>AAi(l,d,n,s)),c=yAi(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Qe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Qe}`),u}function AAi(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=mAi[i]??"\xB7",s=gAi(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${Cs}\u25B8${Qe} `:" ",c=Math.max(1,r-s.length-6),l=[`${a}${hAi(o,fAi[i]??"cyan")} ${bs}${che(t.title||`(${t.id.slice(0,8)})`,c)}${Qe} ${ut}${s}${Qe}`,` ${ut}${che(t.subtitle,r-6)}${Qe}`],d=gYe(t);return d!==void 0&&l.push(` ${ut}Recommended: ${che(d,Math.max(1,r-19))}${Qe}`),l}function gYe(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function yAi(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&wAi(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function wAi(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function Dme(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}Jd();nv();var Mme=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Xw().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(EAi(n)),!1}return!this.stopped&&ame(this.opts.host,e)}};function EAi(t){return t instanceof R0?tF(t):t instanceof Error?t.message:String(t)}var Nme=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;open;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??bAi,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.open;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=rc(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&Mgn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail()}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots())}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.open!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=Dme(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${aa}Resize terminal to at least 60\xD718 to use inbox.${Qe}`];let n=Wxn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${ahe}\u2502${Qe}`;for(let s=0;s<e.height;s++){let a=Na(n[s]??"",e.listWidth),c=Na(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-ke(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()&&!this.adapter.hasShortcut(e)){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=await this.requestOrNull(e.id);if(AYe(n)){this.status=Pme(n),await this.rescan();return}let r=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${gYe(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await Iz(e.id,e.fastAction.responses),this.status=r}catch(i){this.status=vz(i)==="already_settled"?Pme(await this.requestOrNull(e.id)):rc(i)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Xw().cancel(e.id,"Canceled from the inbox."):await PEn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=rc(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(AYe(n)){this.status=Pme(n),await this.rescan();return}let r,i;try{let o=await Ft().getHumanInboxPage(e.inboxTicketId);if(o.state==="resolved"||o.state==="canceled"){this.status=QO(o),await this.rescan();return}r=ER(o),i=o.revision}catch{this.status="page could not be read",await this.invalidate();return}this.closed||this.open!==void 0||this.adapter!==void 0||(this.open={dir:e.dir,id:e.id,ticketId:e.inboxTicketId},this.screen="detail",this.adapter=new rF({ticketId:e.inboxTicketId,page:r,productKinds:gV(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:o=>{this.complete(o)}}),this.openRevision=i,this.watchSelected(e.dir),this.markDirty())}async activateReview(e){this.reviewAdapter=new Mme({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=rc(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.open;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Ft().getHumanInboxPage(e.ticketId);if(this.closed||this.open!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(ER(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.reviewAdapter?.stop(),this.leaveDetail();for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.open;if(n===void 0)return;this.submittingDir=n.dir;try{await Iz(n.id,e)}catch(i){this.submittingDir=void 0,this.status=rc(i);let o=vz(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=Pme(await this.requestOrNull(n.id))),this.leaveDetail(),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);ql({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:AYe(await this.requestOrNull(n.id)),still_listed:r}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=Eme(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.open=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=Dme(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Qe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Qe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Qe} opens the full page ${ut}\u2191\u2193/jk${Qe} select${o} ${ut}x${Qe} cancel`,` ${ut}Page:${Qe} c comment u/d scroll${i} ${ut}q${Qe} close`]:[` ${ut}Enter${Qe} opens the full review ${ut}\u2191\u2193/jk${Qe} select ${ut}x${Qe} cancel`,` ${i} ${ut}q${Qe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>Na(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.open?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===Dle())return r.lines;let i=Hxn(r.view,n);return this.preview={...r,width:n,links:Dle(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Qe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Ft().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=ER(n),i=this.preview?.width??Dme(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:Dle(),lines:Hxn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Ft().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Qe}`];let i=[...cu(Ll(r.title),Math.max(10,e-2)).map(s=>` ${bs}${Cs}${s}${Qe}`),""];for(let s of Tle(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Qe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Qe}`)}return i.map(s=>Na(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${aa}${n}${Qe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=nF(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=xAi(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function bAi(){let{tickets:t}=await Ft().listHumanInbox();return t.map(wg).sort(AI)}function Hxn(t,e){let n=t.manifest.dialect==="html"?BO(t.document):RO(t.document,t.manifest);return lhe(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function AYe(t){return t!==void 0&&t.state!=="pending"}function Pme(t){return t?.page===void 0?"ticket was already resolved":QO(t.page)}var yYe=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),CAi(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=wme(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function CAi(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=Na(i,e);return o+" ".repeat(Math.max(0,e-Go(o)))})}async function IAi(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Ft().listHumanInbox();return e.map(wg).sort(AI)}async function Gxn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function qxn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new Nme({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new yYe(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?Gxn("inbox visibility",()=>IAi(t)):void 0,d=u===void 0?void 0:Gxn("profile membership",()=>Ft().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}dB();XR();qF();var wYe=t=>t.snapshot;async function jxn(){let t=await Ft().getSettings();kZe(t.person),Int(t.person,wYe(t)),Snt(async()=>wYe(await Ft().getSettings())),vnt(async(e,n)=>{try{return wYe(await Ft().putSettings({ops:n}))}catch(r){throw r instanceof Xt&&r.status===409?new GF:r}})}dB();import{homedir as RAi}from"node:os";import{fileURLToPath as vAi}from"node:url";import{join as zxn,dirname as SAi}from"node:path";Jd();$l();jAe();rv();pV();pV();Pge();uh();uh();var _Ai=vAi(import.meta.url),kAi=SAi(_Ai),TAi=zxn(kAi,"..",".."),sJs=zxn(TAi,"scripts","self-update.mjs");function Vxn(){return Mge()}var BAi="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function Kxn(t){let e;try{e=Vxn()}catch{}let n;try{t.profile_id&&(n=hE(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=RAi();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?BAi:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}Hl();import{createConnection as DAi}from"node:net";var MAi=15e3;async function PAi(t,e){let n=await jpe(e);return setInterval(()=>{jpe(e).then(i=>{n=i},()=>{})},MAi).unref(),{previewEndpoint:t,get relayToken(){return n}}}function Yxn(t){return t?"observer":"controller"}async function NAi(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=eB(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=DAi(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function Jxn(t,e,n=!0){let r=e!==void 0,i=r?void 0:AR(),o=e!==void 0?IAn({canvasName:e}):new LO,s,a,c,u,l;if(e!==void 0)s={cwd:process.cwd()},c=new _I(t,rhe(e));else{let m=await o.getNode(t);if(m===null)throw new Zp({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});s=m,a=m;try{if((await Ft().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let g=await Ft().getSnapshot(t);u=g.snapshot,l=g.commands}}catch(f){HKe(f,"The node may be finalized or otherwise not attachable.")}i!==void 0?c=new _I(t,await PAi(i.apiUrl,i.directoryUrl)):(u===void 0&&await NAi(t),c=new _I(t,{socketPath:zZe()}))}let d=new _z(t,{transport:c}),p=m=>m instanceof bg?new Zp({error:"no_broker",message:m.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Zp({error:"socket_error",message:`could not attach to node ${t}: ${String(m?.message??m)}`,received:t,next:"Check the node has a running headless broker."}),h;return d.on("error",m=>{h===void 0&&(h=m)}),u===void 0&&await new Promise(async(m,f)=>{let g=()=>{x(),m()},A=b=>{x(),f(b)},x=()=>{d.off("connect",g),d.off("error",A)};d.on("connect",g),d.on("error",A),d.connect()}).catch(m=>{throw p(m)}),{remote:r,canvasSource:o,meta:s,nodeIdentity:a,socket:d,...u===void 0?{}:{initialSnapshot:u,initialCommands:l},assertConnected:()=>{if(u===void 0&&h!==void 0)throw p(h)}}}import{basename as y0i}from"node:path";Pa();et();jye();import{statSync as VAi}from"node:fs";et();rv();import{mkdirSync as LAi,readFileSync as QAi,writeFileSync as OAi}from"node:fs";import{dirname as FAi,join as UAi}from"node:path";var $Ai="completion-frecency.json",WAi=336*60*60*1e3,HAi=8,GAi=1e3;function qAi(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/WAi),i=1-Math.exp(-t.n/3);return HAi*r*i}function jAi(t){let e={};try{let n=JSON.parse(QAi(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function zAi(t,e){try{LAi(FAi(t),{recursive:!0}),OAi(t,JSON.stringify(e),"utf8")}catch{}}function Xxn(t=UAi(tp(),$Ai)){let e=jAi(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,zAi(t,e)},GAi),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>qAi(e[i],o)}}function EYe(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=CE(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function xYe(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function Zxn(t){return t.replace(/:/g,"")}function kz(t,e,n){let r=t.join(`
1702
1702
  `),i=0;for(let l=0;l<e&&l<t.length;l++)i+=t[l].length+1;let o=i+n,s=fyn(r,o);if(!s)return null;let a=s.start-i,c=s.end-i;return{kind:s.start===0?"leading":"ref",startCol:a,endCol:c,prefix:s.surfacePrefix}}var Lme=class{refs;refNames;delegate;frecency;constructor(e,n,r){this.refs=e,this.refNames=new Set(e.map(i=>i.name)),this.delegate=n,this.frecency=r}get triggerCharacters(){return this.delegate.triggerCharacters}async getSuggestions(e,n,r,i){let o=kz(e,n,r);if(!o)return this.delegate.getSuggestions(e,n,r,i);if(o.kind==="leading"){if(i.force)return this.delegate.getSuggestions(e,n,r,i);let c=(e[n]??"").slice(0,r),u=await this.delegate.getSuggestions(["/"],0,1,i);if(!u)return null;let l=EYe(u.items,c.slice(1),{searchableOf:d=>xYe(d.value),idOf:d=>`command:${d.value}`,store:this.frecency});return l.length===0?null:{items:l,prefix:c}}let s=EYe(this.refs,Zxn(o.prefix.slice(1)),{searchableOf:c=>xYe(c.name),idOf:c=>`ref:${c.name}`,store:this.frecency});return s.length===0?null:{items:s.map(c=>({value:c.name,label:m7e(c.name),description:c.shortForm||void 0})),prefix:o.prefix.slice(1)}}applyCompletion(e,n,r,i,o){let s=kz(e,n,r);if(s&&s.kind==="ref"&&this.refNames.has(i.value)){let a=m7e(i.value),c=e[n]??"",u=c.slice(0,s.startCol)+a+c.slice(s.endCol),l=e.slice();return l[n]=u,{lines:l,cursorLine:n,cursorCol:s.startCol+a.length}}return this.delegate.applyCompletion(e,n,r,i,o)}shouldTriggerFileCompletion(e,n,r){let i=kz(e,n,r);return i&&i.kind==="ref"?!0:this.delegate.shouldTriggerFileCompletion?this.delegate.shouldTriggerFileCompletion(e,n,r):!1}};var bYe=8,KAi=24,YAi=8192;function JAi(t,e){let n=t.slice(0,e),r=t.length>e;return{text:n.replace(/\x1b\](?:[^\x07\x1b]*)(?:\x07|\x1b\\)?/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,""),truncated:r}}function XAi(t,e){if(e<KAi)return[];let n=Math.min(YAi,Math.max(256,e*bYe*4)),r=JAi(t,n),i=jo(r.text,e);if(!r.truncated&&i.length<=bYe)return i;let o=i.slice(0,bYe-1);return o.push(ot("\u2026 truncated \xB7 inspect for full prompt",e)),o}var Tz=[46,92,190],Rz=[166,98,24],ZAi=[0,145,170];function Bz(t,e,n){return[Math.round(t[0]+(e[0]-t[0])*n),Math.round(t[1]+(e[1]-t[1])*n),Math.round(t[2]+(e[2]-t[2])*n)]}var ebn={off:void 0,minimal:Bz(Tz,Rz,0/4),low:Bz(Tz,Rz,1/4),medium:Bz(Tz,Rz,2/4),high:Bz(Tz,Rz,3/4),xhigh:Bz(Tz,Rz,4/4),max:ZAi},e0i={black:[0,0,0],red:[205,49,49],green:[13,188,121],yellow:[229,229,16],blue:[36,114,200],magenta:[188,63,188],cyan:[17,168,205],white:[229,229,229],orange:[228,152,68],grey:[128,128,128],gray:[128,128,128],brightred:[241,76,76],brightgreen:[35,209,139],brightyellow:[245,245,67],brightblue:[59,142,234],brightmagenta:[214,112,214],brightcyan:[41,184,219]};function tbn(t){let e=t.trim().toLowerCase(),n=/^colour(\d{1,3})$/.exec(e);if(n!==null)return l=>`\x1B[48;5;${n[1]}m\x1B[97m\x1B[1m ${l} \x1B[0m`;let r,i=/^#([0-9a-f]{6})$/.exec(e);if(i!==null){let l=i[1];r=[parseInt(l.slice(0,2),16),parseInt(l.slice(2,4),16),parseInt(l.slice(4,6),16)]}else r=e0i[e];if(r===void 0)return;let[o,s,a]=r,u=.299*o+.587*s+.114*a>160?"\x1B[30m":"\x1B[97m";return l=>`\x1B[48;2;${o};${s};${a}m${u}\x1B[1m ${l} \x1B[0m`}var Qme=t=>`\x1B[7m ${t} \x1B[27m`;function nbn(t,e){let n=t===void 0?void 0:ebn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[38;2;${r};${i};${o}m${s}\x1B[39m`}function rbn(t,e){let n=t===void 0?void 0:ebn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[48;2;${r};${i};${o}m\x1B[97m\x1B[1m ${s} \x1B[0m`}function t0i(t,e,n,r,i){let o=e?r(ot(e,Math.max(1,t-4),"\u2026")):"",s=ke(o),a=t-s,c="";n&&a>4&&(c=ke(n)<=a?n:ot(n,a,"\u2026"));let u=Math.max(0,t-s-ke(c));return o+i("\u2500".repeat(u))+c}var Ome="\x1B[7m",Fme="\x1B[0m",CYe="\x1B[48;5;240m";function n0i(t){let e=t.indexOf($r);if(e===-1)return;let n=e+$r.length;if(!t.startsWith(Ome,n))return;let r=n+Ome.length,i=t.indexOf(Fme,r);if(i===-1)return;let o=t.slice(r,i),s=`${CYe}${o}\x1B[0m`;return t.slice(0,n)+s+t.slice(i+Fme.length)}var r0i=/\.(png|jpe?g|gif|webp|bmp)$/i;function i0i(t){let e=t.match(/\x1b\[200~([\s\S]*?)\x1b\[201~/),n=(e?e[1]:t).trim();if(n.length<2||/[\u0000-\u0008\u000e-\u001f]/.test(n))return null;(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))&&(n=n.slice(1,-1));let r=n.replace(/\\(.)/g,"$1");if(/\n/.test(r)||!r0i.test(r))return null;try{if(!VAi(r).isFile())return null}catch{return null}return r}function o0i(t,e,n,r){let i=[];if(t.length===0||t.length===1&&t[0]==="")return i.push({logicalLine:0,startIndex:0,endIndex:0,text:"",hasCursor:!0,cursorPos:0}),i;for(let o=0;o<t.length;o++){let s=t[o]??"",a=o===n;if(ke(s)<=e){i.push({logicalLine:o,startIndex:0,endIndex:s.length,text:s,hasCursor:a,cursorPos:a?r:0});continue}let c=LU(s,e);for(let u=0;u<c.length;u++){let l=c[u];if(!l)continue;let d=u===c.length-1,p=!1,h=0;a&&(d?(p=r>=l.startIndex,h=r-l.startIndex):(p=r>=l.startIndex&&r<l.endIndex,p&&(h=r-l.startIndex,h>l.text.length&&(h=l.text.length)))),i.push({logicalLine:o,startIndex:l.startIndex,endIndex:l.endIndex,text:l.text,hasCursor:p,cursorPos:h})}}return i}function s0i(t,e){return Fhe(t).filter(n=>e.has(n.candidate)).map(n=>({start:n.start,end:n.end}))}var a0i="\x1B[4m\x1B[2m",c0i="\x1B[24m\x1B[22m",u0i=new Intl.Segmenter(void 0,{granularity:"grapheme"});function l0i(t){for(let e of u0i.segment(t))return e.segment.length;return 0}function d0i(t){let e=t.indexOf($r),n=e===-1?0:e+$r.length,r=t.indexOf(Ome,n),i=Ome.length;if(r===-1&&(r=t.indexOf(CYe,n),i=CYe.length),r===-1)return null;let o=t.indexOf(Fme,r+i);return o===-1?null:{start:e!==-1?e:r,end:o+Fme.length}}function p0i(t,e,n,r,i){let o=[];if(e.hasCursor){let a=d0i(t);if(a===null)return t;let c=e.text.slice(e.cursorPos),u=c.length===0?0:l0i(c),l=e.cursorPos+u;for(let d of n){let p=d.start-e.startIndex,h=d.end-e.startIndex;if(h<=e.cursorPos){let m=i+p,f=i+h;f<=a.start&&t.slice(m,f)===r.slice(d.start,d.end)&&o.push({absStart:m,absEnd:f})}else if(p>=l){let m=a.end+(p-l),f=a.end+(h-l);m>=a.end&&t.slice(m,f)===r.slice(d.start,d.end)&&o.push({absStart:m,absEnd:f})}}}else for(let a of n){let c=i+(a.start-e.startIndex),u=i+(a.end-e.startIndex);t.slice(c,u)===r.slice(a.start,a.end)&&o.push({absStart:c,absEnd:u})}if(o.length===0)return t;o.sort((a,c)=>c.absStart-a.absStart);let s=t;for(let a of o)s=s.slice(0,a.absStart)+a0i+s.slice(a.absStart,a.absEnd)+c0i+s.slice(a.absEnd);return s}function h0i(t){let e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e?e[1]:null}function m0i(t,e){if(!t.startsWith("/"))return!1;let n=t.indexOf(" "),r=n===-1?t.slice(1):t.slice(1,n);if(e.has(r))return!0;if(t.startsWith("/skill:")){let i=n===-1?t.slice(7):t.slice(7,n);if(e.has(`skill:${i}`))return!0}return!1}var Ume=class t extends OT{km;pendingRawSubmitText;realOnSubmit;pendingReturn;static PASTE_BURST_MS=10;constructor(e,n,r,i){super(e,n,r,i),this.km=r;let o=this.submitValue.bind(this);this.submitValue=()=>{let s=this;this.pendingRawSubmitText=s.getExpandedText(),o()},Object.defineProperty(this,"onSubmit",{configurable:!0,get:()=>s=>{let a=this.pendingRawSubmitText??s;this.pendingRawSubmitText=void 0,this.realOnSubmit?.(a)},set:s=>{this.realOnSubmit=s}})}onPasteImagePath;settleHeldReturn(e){let n=this.pendingReturn;if(n!==void 0){if(clearTimeout(n.timer),this.pendingReturn=void 0,e==="newline"){this.insertTextAtCursor(`
1703
1703
  `);return}super.handleInput(n.data),this.tui.requestRender()}}imageTokenWidthBeforeCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(0,n).match(/\[Image #\d+\]$/);return i?i[0].length:0}imageTokenWidthAfterCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(n).match(/^\[Image #\d+\]/);return i?i[0].length:0}handleInput(e){if(this.settleHeldReturn("newline"),!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorDown")){let s=this,a=this.getCursor(),c=s.historyIndex;super.handleInput(e);let u=this.getCursor();s.historyIndex===c&&u.line===a.line&&u.col===a.col&&this.onCursorDownAtBottom?.();return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.input.newLine")){this.insertTextAtCursor(`
1704
1704
  `);return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.deleteCharBackward")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorLeft")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorRight")){let s=this.imageTokenWidthAfterCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}let n=i0i(e);if(n&&this.onPasteImagePath?.(n))return;if((e==="\r"||e===`
@@ -1709,7 +1709,7 @@ Invocation: \`${c.invocation.replaceAll("`","\\`")}\`
1709
1709
 
1710
1710
  ${c.content}
1711
1711
  `,noNvim:"nvim is required to inspect loaded commands. Install Neovim and retry."})}}}function dbn(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 D0i={readOption:Xm,writeOption:(t,e,n)=>{Bg(t,e,n)},stampAsync:x0e,currentPane:()=>process.env.TMUX_PANE??Rg()?.pane,ownerId:()=>String(process.pid)};function hbn(t,e,n=D0i){let r,i=n.ownerId(),o=()=>{if(r===void 0||r==="")return!0;let s=n.readOption(r,mbn);return s===void 0||s===""?!0:s===i};return{set:()=>{r=n.currentPane(),pbn(r,i,n.writeOption),N0i(t,r,e,n.writeOption),Q0i(r,n.writeOption),M0i(t,r,n.writeOption)},stamp:()=>{t||r===void 0||r===""||n.stampAsync(r)},clear:()=>{o()&&(L0i(t,r,n.writeOption),O0i(r,n.writeOption),P0i(t,r,n.writeOption),pbn(r,"",n.writeOption))},pane:()=>r}}var mbn="@crtr_viewer_pid";function pbn(t,e,n){if(!(t===void 0||t===""))try{n(t,mbn,e)}catch{}}function M0i(t,e,n){if(!(t||e===void 0||e===""))try{n(e,rU,String(Date.now()))}catch{}}function P0i(t,e,n=Bg){if(!(t||e===void 0||e===""))try{n(e,rU,"")}catch{}}function N0i(t,e,n,r=Bg){if(!(t||e===void 0||e===""))try{r(e,"@crtr_node",n)}catch{}}function L0i(t,e,n=Bg){if(!(t||e===void 0||e===""))try{n(e,"@crtr_node","")}catch{}}function Q0i(t,e=Bg){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","1")}catch{}}function O0i(t,e=Bg){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","")}catch{}}dB();Hl();import{constants as F0i,accessSync as U0i,existsSync as $0i,mkdtempSync as W0i,readFileSync as H0i,rmSync as Wme,statSync as G0i}from"node:fs";import{tmpdir as q0i}from"node:os";import{delimiter as j0i,join as Hme,resolve as z0i,sep as gbn}from"node:path";import{execFile as fbn,spawnSync as V0i}from"node:child_process";function K0i(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 Abn(t,e){let n=new Set(K0i(t,e));return t.filter(r=>n.has(r.node_id))}function Y0i(t){let e=[];for(let n of t)try{e.push(JZe(n.node_id,n.grantee))}catch{continue}return SYe(e)}function J0i(t){try{return G0i(t).isDirectory()}catch{return!1}}function X0i(t,e){let n=[...e==null?[]:[e],...(process.env.PATH??"").split(j0i).filter(Boolean).map(r=>Hme(r,t))];return[...new Set(n)]}function vYe(t,e){for(let n of X0i(t,e)){try{U0i(n,F0i.X_OK)}catch{continue}if(V0i(n,["--version"],{stdio:"ignore"}).status===0)return n}return null}function Z0i(t){if(t===null||t==="")return{projects:[],settings:null};try{let{profileId:e,manifest:n}=hE(t);return{projects:n.projects.map(r=>r.path),settings:cV(e)}}catch{return{projects:[],settings:null}}}function SYe(t){let e=new Set,n=[];for(let r of t){let i=z0i(r);e.has(i)||!J0i(i)||(e.add(i),n.push(i))}return n}function eyi(t){return t.filter(e=>!t.some(n=>n!==e&&e.startsWith(n+gbn)))}var tyi=20;function nyi(t){try{let e=H0i(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 ybn(t){let e=vYe("fd",t.fdPath);if(e===null){t.onNotice("fd is required for profile file search");return}let n=vYe("fzf");if(n===null){t.onNotice("fzf is required for profile file search");return}let r=vYe("nvim");if(r===null){t.onNotice("Neovim is required for profile file search");return}let i=Z0i(t.profileId),o=SYe([t.cwd,...t.nodeDirs,...i.projects]);if(o.length===0){t.onNotice("No profile file-search directories exist");return}let s=eyi(o),a=SYe([...i.settings===null?[]:[i.settings]]),c=W0i(Hme(q0i(),"crtr-profile-files-")),u=Hme(c,"selection"),l=Hme(c,"candidates"),d=Y0i(t.nodes).filter(f=>!s.some(g=>f===g||f.startsWith(g+gbn))),m=`{ ${[...s.map(f=>`${cn(e)} --type f --hidden --exclude .git . ${cn(f)}`),...d.map(f=>`${cn(e)} --type f --hidden --exclude .git --exclude ${cn("/jobs")} . ${cn(f)}`),...a.map(f=>`${cn(e)} --type f --hidden --exclude .git --no-ignore . ${cn(f)}`)].map(f=>`${f} &`).join(" ")} wait; } > ${cn(l)} && ${cn(n)} --print0 --scheme=path --hscroll-off=${tyi} --header ${cn("fuzzy path \u2022 ctrl-y yank file path")} --bind ${cn("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 ${cn("head -100 -- {}")} < ${cn(l)} > ${cn(u)}`;try{fbn("tmux",["display-popup","-E","-T"," profile files ","-w","80%","-h","60%",...rp(),m],()=>{let f=nyi(u);if(f===null||!$0i(f)){Wme(c,{recursive:!0,force:!0});return}let g=`exec ${YR("edit",[f],r)}`;try{fbn("tmux",["display-popup","-E","-T"," profile file ","-w","90%","-h","90%",...rp(),g],()=>Wme(c,{recursive:!0,force:!0}))}catch(A){Wme(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file: ${A instanceof Error?A.message:String(A)}`)}})}catch(f){Wme(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file search: ${f instanceof Error?f.message:String(f)}`)}}var Ebn={statuses:{},widgets:{},title:void 0};function xbn(t="observer"){return{role:t,agentDir:void 0,engine:void 0,contextTokens:void 0,queued:[],display:Ebn,dialog:null}}function ryi(t){let e=t.snapshot,n=e.display??Ebn,r=e.stats.contextUsage;return{role:t.role,agentDir:t.agentDir,engine:e.state,contextTokens:r?.tokens??void 0,queued:iyi(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 bbn(t,e){switch(e.type){case"welcome":return ryi(e);case"model_changed":return aF(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(syi(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:oyi(t,e.message.usage.input+e.message.usage.cacheRead+e.message.usage.cacheWrite);case"agent_start":return aF(t,{isStreaming:!0});case"agent_end":case"agent_settled":return aF(t,{isStreaming:!1});case"session_info_changed":return aF(t,{sessionName:e.name});case"thinking_level_changed":return aF(t,{thinkingLevel:e.level});case"queue_update":{let n=[...e.steering,...e.followUp].map(i=>({text:i}));return{...aF(t,{pendingMessageCount:n.length}),queued:n}}default:return t}}function iyi(t){let e=t.queued;if(typeof e!="object"||e===null)return[];let{steering:n,followUp:r}=e;return[...wbn(n),...wbn(r)].map(i=>({text:i}))}function wbn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function aF(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 oyi(t,e){return t.contextTokens===e?t:{...t,contextTokens:e}}function syi(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])}function Cbn(t,e){let n=xbn(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=bbn(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}}}et();import{spawn as ayi}from"node:child_process";import{fileURLToPath as _Ye}from"node:url";var cyi=40,Ibn=[_Ye(new URL("./assets/whip-snap.mp3",import.meta.url)),_Ye(new URL("./assets/whip-crack.mp3",import.meta.url)),_Ye(new URL("./assets/whip-06.mp3",import.meta.url))];function uyi(t){let e=process.platform==="darwin"?"afplay":process.platform==="linux"?"aplay":void 0;if(e!==void 0)try{let n=ayi(e,[t],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}var vbn=[["","","","","","","","\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",""]],_bn="Go faster",Sbn;function kbn(t){let e=t.filter(r=>r!==Sbn),n=e[Math.floor(Math.random()*e.length)];return Sbn=n,n}var Gme=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;frame=-1;nextSound=0;timer;play(){this.stop(),uyi(Ibn[this.nextSound]),this.nextSound=(this.nextSound+1)%Ibn.length,this.frame=0,this.tui.requestRender(),this.timer=setInterval(()=>{if(this.frame++,this.frame<vbn.length){this.tui.requestRender();return}this.stop()},cyi)}dispose(){this.stop()}render(e){if(this.frame<0)return[];let n=Math.max(0,e);return vbn[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()}};rv();import{execFile as lyi}from"node:child_process";import{mkdirSync as Tbn,readFileSync as dyi,renameSync as pyi,writeFileSync as Rbn}from"node:fs";import{dirname as Bbn,join as kYe}from"node:path";var hyi="whip-count.json",myi=kYe("tmp","whip-achievement.txt"),Dbn=46,fyi=4,gyi=900,Ayi=[{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."}];function yyi(t){let e={total:0,unlocked:[]};try{let n=JSON.parse(dyi(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 wyi(t,e){try{Tbn(Bbn(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;Rbn(n,JSON.stringify(e),"utf8"),pyi(n,t)}catch{}}function qme(t){let e=Math.max(0,Math.floor((Dbn-Hd(t))/2));return" ".repeat(e)+t}function Eyi(t,e,n){return["",qme(n.accent(n.bold("\u2605 ACHIEVEMENT UNLOCKED \u2605"))),"",qme(n.bold(t.title)),qme(n.muted(t.line)),"",qme(n.faint(`${e} whip${e===1?"":"s"}`))]}function xyi(t,e,n){if(process.env.TMUX===void 0||process.env.TMUX==="")return;let r=Eyi(t,e,n),i=kYe(tp(),myi);try{Tbn(Bbn(i),{recursive:!0}),Rbn(i,`\x1B[?25l${r.join(`\r
1712
- `)}`,"utf8")}catch{return}let o=`cat ${cn(i)}; sleep ${fyi}`;lyi("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(Dbn+2),"-h",String(r.length+2),...rp(),o],()=>{})}function Mbn(t,e=kYe(tp(),hyi)){let n=yyi(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=Ayi.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),wyi(e,n),i===void 0)return;let o=n.total;setTimeout(()=>xyi(i,o,t),gyi).unref?.()}function Pbn(t){return/^[A-Za-z0-9._:@/-]+$/.test(t)?t:cn(t)}async function jZs(t,e,n,r=!0){await jxn(),MR("viewer.connect_start",{node:t});let i=await Jxn(t,n,r);MR(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=Yxn(e),l=byi();lpn({cwd:a.cwd});let d=dpn(),p=opn(),h=fE(),m=h.bindings;await apn(p);let f=await upn(),g=new DE,A=new oy(g),x=new Ze,b=new Ohe,v=new khe(A,x,{cwd:a.cwd,palette:d,hideThinking:!0,banner:act(Kxn(a)),inlinePageBlocks:!o,pageOpenHint:()=>yB(m),backgroundBashHint:()=>o||!js()?null:AV(m),onActivityChange:Je=>{b.clear(),Je&&b.addChild(Je)}}),S=v.transcriptSource(),_=z0n(S),T=G0n(S,_.decorate),M=pyn(v,T,S),R,B=cxn({tui:A,pal:d},()=>R.state()),O=ayn(A,d,T,_,{bindings:()=>m,setNotice:Je=>j(Je)}),W=ubn(g,A,x,b,d,p,T,O.component),{containers:z,editor:$}=W,ae=new Gme(A,d);z.header.addChild(ae),z.header.addChild(B.component);let X={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:A,pal:d,editor:$,containers:z},ye=zEn(X,{syncCursor:()=>Nn.sync(),exitRoster:()=>Pn.exit(),openTicket:Je=>{U.open(Je)},suppressed:()=>U.active(),setNotice:Je=>j(Je),onRefreshFailure:Je=>wt.reportFailure("inbox strip refresh",Je)});z.header.addChild(ye.component);let we=Wl("user"),We=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let bt=AEn(),Qt=process.env.CRTR_ATTACH_OPEN_TICKET;Qt!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let Ne=Bxn(Je=>process.stdout.write(Je),we.mouse_mode_default),Y=Mxn({frame:()=>W.frame.lastRenderedFrame(),width:()=>A.terminal.columns});W.frame.setOverlay(Je=>Y.apply(Je));let Ue=sxn(X,{state:()=>R.state(),bashMode:()=>yt.bashMode(),asks:()=>wt.asks(),bindings:()=>m,inboxAffordance:!o&&js(),mouseEnabled:()=>Ne.enabled()}),Ye=new Bme({tui:A,mouse:Ne,rows:()=>A.terminal.rows,statusNotice:Ue.setNotice,formatNotice:Je=>d.warning(`\u26A0 ${Je}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),Gt=(()=>{let Je=a.profile_id;if(Je)try{return{id:Je,label:hE(Je).manifest.name}}catch{return{id:Je,label:Je}}})(),It=qxn({host:Ye,...Gt===void 0?{}:{profile:Gt},...o?{}:{scan:async()=>{let Je=Ft(),[pr,Li]=await Promise.all([Je.listHumanInbox(),Je.getInboxHistory(t,{state:"pending"})]),Wu=new Map;for(let la of pr.tickets){let qd=wg(la);Wu.set(qd.dir,qd)}for(let la of Li.tickets){let qd=wg(la);qd.kind!=="page"||qd.state!=="pending"||!qd.awaitsResponse||qd.inbox||Wu.has(qd.dir)||Wu.set(qd.dir,qd)}for(let la of ye.pendingTickets())Wu.has(la.dir)||Wu.set(la.dir,la);return[...Wu.values()].sort(AI)}}}),on=o?()=>{}:nF(()=>{v.refreshPageBlocks(),ye.refresh()}),U=rxn(X,{syncCursor:()=>Nn.sync(),refreshStrip:()=>{ye.refresh()},setNotice:Je=>j(Je),openInbox:Je=>It.open(Je),suspendForChild:()=>Ye.suspendForChild()});z.ticketPanel.addChild(U.component);let G={toggleInbox:()=>{let Je=U.currentDir();if(Je!==void 0){U.close(),It.open(Je);return}It.toggle()}},j=(Je,pr)=>{Ye.hasFullPaneSurface()?Ye.notice(Je,pr):Ue.setNotice(Je,pr)},Ce=Ue.render,le=Je=>{j(M.copy(Je))},be=uyn(T,()=>A.requestRender()),Pe={"crtr.attach.scroll.up":()=>{be.cancel(),T.scrollBy(-1)&&A.requestRender()},"crtr.attach.scroll.down":()=>{be.cancel(),T.scrollBy(1)&&A.requestRender()},"crtr.attach.scroll.page-up":()=>{be.page("up")},"crtr.attach.scroll.page-down":()=>{be.page("down")},"crtr.attach.scroll.live":()=>{be.cancel(),T.goLive(),A.requestRender()},"crtr.attach.mouse.toggle":()=>{let Je=Ne.toggle();!Je&&Y.clear()&&A.requestRender(),j(Je?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>le("message"),"crtr.attach.verbosity.less":()=>j(eYe(v.lessDetail()))},ce,Ee=DEn(X,()=>ce===void 0?i.initialSnapshot!==void 0:ce.isDormant()),De=Xxn(),_e=lbn(X,Ee,{setNotice:j,bindings:()=>m,fdPath:f,frecency:De}),Ve=dbn(X,i.nodeIdentity,{isTornDown:()=>ai.isTornDown(),onChanged:()=>{yt.syncContextBadge();let Je=R.state().engine;Je!==void 0&&yt.setTitle(Je.sessionName),A.requestRender()}});o&&Ve.refresh();let yt=obn(X,{nodeIdentity:Ve.current,thinkingLevel:()=>R.state().engine?.thinkingLevel,renderFooter:Ce,onTextChange:_e.syncCommandPreview});yt.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:or}=axn(X,()=>R.state());R=Cbn(u,{setEngineState:Je=>Wt.setState(Je),setEditorTitle:yt.setTitle,paintEditorFrame:yt.paintFrame,renderExtensionWidgets:()=>{B.render(),st()},renderQueued:or,renderFooter:Ce,setTerminalTitle:Je=>g.setTitle(Je),refreshChrome:()=>wt.refresh()});let Un=Je=>{if(!js()){j("Inspector requires tmux");return}j(`Opening Inspector (${Je})\u2026`);let pr=Q0(),Wu=`${pr===void 0?"":`CRTR_HOME=${cn(pr)} `}crtr surface inspect ${cn(t)} --section ${Je}`;Cyi("tmux",["display-popup","-E","-T",` inspector \xB7 ${Je} `,"-w","90%","-h","85%",...rp(),Wu],()=>{wt.refresh()})},Pn=jEn(X,{asks:()=>wt.asks(),setNotice:j,requestChromeRefresh:()=>wt.refresh(),openInspector:Un,openObject:Je=>{if(!js()){j("Object details require tmux");return}j("Opening object\u2026");let pr=Q0(),Li=pr===void 0?"":`CRTR_HOME=${cn(pr)} `;GV({name:Je,produce:Wu=>`${Li}crtr canvas read ${cn(Je)} > ${Wu} 2>&1`,title:`object \xB7 ${Je}`,noNvim:"nvim is required to view the object. Install Neovim and retry.",onClose:()=>wt.refresh()})},syncCursor:()=>Nn.sync()}),Nn=ixn($,[Pn.active,ye.active,U.active]),ni=new _me(A,t,()=>wt.asks(),d,m,s,u,Je=>wt.reportFailure("canvas graph refresh",Je),j),Oa=new kme(A,d);Oa.setBindings(m);let wt=uxn(X,{isTornDown:()=>ai.isTornDown(),setNotice:j,refreshRoster:async()=>{await Pn.refresh(),await ye.refresh()},refreshGraph:()=>ni.refresh(),refreshIdentity:()=>Ve.refresh(),renderFooter:Ce,renderExtensionWidgets:st,refreshInFlightTools:()=>v.refreshInFlightTools(),pollGit:yt.pollGit}),Wt=MEn(X,p,Ee,{setNotice:j,agentDir:()=>R.state().agentDir,openNodeMetadata:()=>Un("overview"),isDormant:()=>ce.isDormant(),copyTarget:le,moreDetail:()=>v.moreDetail(),lessDetail:()=>v.lessDetail(),toggleThinking:()=>v.toggleThinking(),toggleGraph:()=>ni.toggle(),toggleInbox:G.toggleInbox,toggleHelp:()=>Oa.toggle(),toggleMouse:()=>Ne.toggle(),quit:()=>ca("detach"),setChipColor:yt.setChipColor,onPromptSent:()=>{we.whip_mode&&ae.play()},frecency:De}),te=()=>{if(Ye.hasFullPaneSurface()){j("Close the active surface before whipping the agent");return}let Je=we.whip_message_mode==="go-faster"?_bn:kbn(we.whip_messages);Wt.sendInterrupting(Je)&&(ae.play(),Mbn(d),j(`Whipped agent \u2014 ${Je}`))},oe=Oxn({selfNodeId:t,remote:o,canvasSource:s,port:we.document_port,fetchAccess:async()=>await Ft().documents.browserAccess(),onAccessError:Je=>j(`Document links are unavailable: ${Je instanceof Error?Je.message:String(Je)}`),refresh:()=>v.refreshMarkdown()}),Ie=()=>{if(U.active()){j("Close the open request first (Esc)");return}let Je=[...v.getTranscriptDocRefsNewestFirst().map(Li=>`[[${Li}]]`),...v.getTranscriptFilePathsNewestFirst()],pr=Li=>{bEn(Ye,Li,{originNodeId:t,onNotice:j})};if(Ye.hasFullPaneSurface()){Ye.pickReviewFile({candidates:Je,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(Li=>{Li!==null&&pr(Li)});return}Wt.openFileReviewPicker(Je,a.cwd,pr)},$e=()=>{if(o){j("Profile file search is unavailable on remote canvases");return}if(!js()){j("Profile file search requires tmux");return}s.listNodes().then(Je=>{let pr=Abn(Je,t);ybn({cwd:a.cwd,nodeDirs:pr.map(Li=>Li.cwd),nodes:pr,profileId:a.profile_id??null,fdPath:f,onNotice:j})}).catch(Je=>{let pr=Je instanceof Error?Je.message:String(Je);j(`Could not load related node directories: ${pr}`)})},Be,tt=()=>{Be!==void 0&&clearTimeout(Be),Be=setTimeout(()=>{Be=void 0,l7e(()=>h,()=>{},js,HV)},1e3),Be.unref()},Et=_xn(X,{foldState:R.fold,chat:v,setNotice:j,renderFooter:Ce,setEditorText:Je=>{$.setText(Je),A.requestRender()},attachDialog:Je=>Wt.attachDialog(Je),dismissDialog:Je=>Wt.dismissDialog(Je),refreshNodeIdentity:Ve.refresh,setCommands:_e.setCommands,resetMemoryRefs:_e.resetMemoryRefs,reloadBindings:()=>{h=l7e(fE,Je=>{ni.setBindings(Je),Oa.setBindings(Je)},js,HV),m=h.bindings},modelThinkingLabel:R.modelThinkingLabel,onWelcome:()=>tt()}),Vt=Je=>{let pr=Je instanceof Error?`${Je.name}: ${Je.message}`:String(Je);SI("attach.unhandled_rejection",pr),sYe(Je)&&wt.reportFailure("background daemon call",Je)};process.on("unhandledRejection",Vt);let jr=()=>{process.off("unhandledRejection",Vt)},Nr=hbn(o,t),ai=pxn(X,{stopLocal:()=>{Be!==void 0&&clearTimeout(Be),Ye.closeAll(),be.cancel(),Ne.disable(),wt.stop(),U.close(),Ue.dispose(),ni.close(),Oa.close(),O.close(),ae.dispose(),Nr.clear(),Vme(),zme(),jme(),jr(),oe.dispose(),on();try{v.dispose()}catch{}},lastSocketError:()=>ce.lastSocketError(),reattachCommand:`crtr surface attach to ${Pbn(t)}`+(e?" --observer":"")+(n!==void 0?` --canvas ${Pbn(n)}`:""),tagPane:Nr.pane}),ca=ai.teardown;ce=xxn(X,{role:u,remote:o,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:Et,setNotice:j,isTornDown:()=>ai.isTornDown(),teardown:ca,onEnterDormancy:()=>{tt(),v.settleRun(),R.patchLocal({isStreaming:!1})}}),i.assertConnected(),Nr.set(),ce.install(),W.mount(),A.start(),i.initialSnapshot!==void 0&&(R.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),v.applySnapshot(i.initialSnapshot),_e.setCommands(i.initialCommands),o||Ft().markNodeRead(t).catch(()=>{})),we.whip_mode&&We&&ae.play(),Ne.reassert();let ua=!1,Gd=Je=>{if(ua)return;if(o){j("Opening a file is unavailable in a remote attach");return}let pr=Rg();if(pr===null)return;let Li=Qxn({file:Je,pane:pr.pane,cwd:a.cwd,nodeId:t,observer:e,beforeRespawn:Nr.clear});if(Li==="opened"){ua=!0;return}Li==="failed"&&Nr.set(),Li==="missing"&&j("File no longer exists"),Li==="no_nvim"&&j("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),Li==="failed"&&j("Could not open file in Neovim")};Ne.install(A,{onWheel:(Je,pr)=>{Y.clear()&&A.requestRender(),!Ye.handleWheel(Je,pr)&&(be.cancel(),T.scrollBy(Je==="up"?-pr:pr)&&A.requestRender())},onPrimaryPress:(Je,pr)=>{Ye.hasFullPaneSurface()||(Y.clear()&&A.requestRender(),Y.begin(Je,pr))},onPrimaryDrag:(Je,pr)=>{Ye.hasFullPaneSurface()||Y.extend(Je,pr)&&A.requestRender()},onPrimaryRelease:()=>{let Je=Y.release();Je?.kind==="selection"&&(j(Je.notice),A.requestRender())}});let jme=A.addInputListener(Je=>{let pr=Lxn(Je);if(pr===void 0)return;let Li=pr.file;return Li===void 0?j("Could not open file link"):Gd(Li),pr.remaining.length>0?{data:pr.remaining}:{consume:!0}}),zme=A.addInputListener(()=>{Y.clear()&&A.requestRender()}),Vme=kxn(X,{bindings:()=>m,detachHint:()=>iyn(m),hasExclusiveSurface:()=>Ye.hasFullPaneSurface(),setPaneFocused:Je=>{Je&&Nr.stamp(),Nn.setPaneFocused(Je),A.requestRender()},viewportActions:()=>Pe,searchHandleKey:O.handleKey,panelHandleKey:U.handleKey,stripHandleKey:ye.handleKey,rosterHandleKey:Pn.handleKey,setNotice:j,detach:()=>ca("detach"),cancelTurn:()=>{Wt.abortTurn()?j("Canceling the agent\u2026"):j(`Nothing running to cancel \u2014 press ${oyn(m)??"ctrl+d"} to detach`)},toggleGraph:()=>ni.toggle(),toggleHelp:()=>Oa.toggle(),toggleInbox:G.toggleInbox,toggleInboxStrip:()=>{if(Ye.hasFullPaneSurface()){j("Close the active surface before opening the request strip");return}U.active()&&U.close(),ye.toggle()},cycleModelLadder:Je=>Wt.cycleLadder(Je),inspectLoadedCommand:_e.inspectLoadedCommand,openFileReview:Ie,openProfileFiles:$e,openSearch:()=>{if(Ye.hasFullPaneSurface()||U.active()){j("Close the active surface before searching the transcript");return}O.open()},whip:te});ai.installSignalHandlers(),Ce(),wt.refresh(),or(),yt.pollGit(),MR("viewer.first_paint"),process.stdout.write(lxn),cpn(g.kittyProtocolActive),i.initialSnapshot!==void 0&&tt(),i.initialSnapshot===void 0?(MR("viewer.hello_sent"),ce.sendHello()):ce.startDormant(),wt.start(),bt!==void 0&&yEn(Ye,bt),Qt!==void 0&&Qt!==""&&!o&&(async()=>{let Je=Ft(),[pr,Li]=await Promise.all([Je.listHumanInbox(),Je.getInboxHistory(void 0,{state:"pending"})]),Wu=[...pr.tickets,...Li.tickets].map(wg).find(la=>la.inboxTicketId===Qt&&(la.kind!=="page"||la.state==="pending"));Wu===void 0?j("ask already answered"):U.open(Wu)})().catch(Je=>j(`could not open the ask: ${String(Je?.message??Je)}`)),await ai.done}export{jZs as runAttach};
1712
+ `)}`,"utf8")}catch{return}let o=`cat ${cn(i)}; sleep ${fyi}`;lyi("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(Dbn+2),"-h",String(r.length+2),...rp(),o],()=>{})}function Mbn(t,e=kYe(tp(),hyi)){let n=yyi(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=Ayi.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),wyi(e,n),i===void 0)return;let o=n.total;setTimeout(()=>xyi(i,o,t),gyi).unref?.()}function Pbn(t){return/^[A-Za-z0-9._:@/-]+$/.test(t)?t:cn(t)}async function zZs(t,e,n,r=!0){await jxn(),MR("viewer.connect_start",{node:t});let i=await Jxn(t,n,r);MR(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=Yxn(e),l=byi();lpn({cwd:a.cwd});let d=dpn(),p=opn(),h=fE(),m=h.bindings;await apn(p);let f=await upn(),g=new DE,A=new oy(g),x=new Ze,b=new Ohe,v=new khe(A,x,{cwd:a.cwd,palette:d,hideThinking:!0,banner:act(Kxn(a)),inlinePageBlocks:!o,pageOpenHint:()=>yB(m),backgroundBashHint:()=>o||!js()?null:AV(m),onActivityChange:Je=>{b.clear(),Je&&b.addChild(Je)}}),S=v.transcriptSource(),_=z0n(S),T=G0n(S,_.decorate),M=pyn(v,T,S),R,B=cxn({tui:A,pal:d},()=>R.state()),O=ayn(A,d,T,_,{bindings:()=>m,setNotice:Je=>j(Je)}),W=ubn(g,A,x,b,d,p,T,O.component),{containers:z,editor:$}=W,ae=new Gme(A,d);z.header.addChild(ae),z.header.addChild(B.component);let X={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:A,pal:d,editor:$,containers:z},ye=zEn(X,{syncCursor:()=>Nn.sync(),exitRoster:()=>Pn.exit(),openTicket:Je=>{U.open(Je)},suppressed:()=>U.active(),setNotice:Je=>j(Je),onRefreshFailure:Je=>wt.reportFailure("inbox strip refresh",Je)});z.header.addChild(ye.component);let we=Wl("user"),We=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let bt=AEn(),Qt=process.env.CRTR_ATTACH_OPEN_TICKET;Qt!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let Ne=Bxn(Je=>process.stdout.write(Je),we.mouse_mode_default),Y=Mxn({frame:()=>W.frame.lastRenderedFrame(),width:()=>A.terminal.columns});W.frame.setOverlay(Je=>Y.apply(Je));let Ue=sxn(X,{state:()=>R.state(),bashMode:()=>yt.bashMode(),asks:()=>wt.asks(),bindings:()=>m,inboxAffordance:!o&&js(),mouseEnabled:()=>Ne.enabled()}),Ye=new Bme({tui:A,mouse:Ne,rows:()=>A.terminal.rows,statusNotice:Ue.setNotice,formatNotice:Je=>d.warning(`\u26A0 ${Je}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),Gt=(()=>{let Je=a.profile_id;if(Je)try{return{id:Je,label:hE(Je).manifest.name}}catch{return{id:Je,label:Je}}})(),It=qxn({host:Ye,...Gt===void 0?{}:{profile:Gt},...o?{}:{scan:async()=>{let Je=Ft(),[pr,Li]=await Promise.all([Je.listHumanInbox(),Je.getInboxHistory(t,{state:"pending"})]),Wu=new Map;for(let la of pr.tickets){let qd=wg(la);Wu.set(qd.dir,qd)}for(let la of Li.tickets){let qd=wg(la);qd.kind!=="page"||qd.state!=="pending"||!qd.awaitsResponse||qd.inbox||Wu.has(qd.dir)||Wu.set(qd.dir,qd)}for(let la of ye.pendingTickets())Wu.has(la.dir)||Wu.set(la.dir,la);return[...Wu.values()].sort(AI)}}}),on=o?()=>{}:nF(()=>{v.refreshPageBlocks(),ye.refresh()}),U=rxn(X,{syncCursor:()=>Nn.sync(),refreshStrip:()=>{ye.refresh()},setNotice:Je=>j(Je),openInbox:Je=>It.open(Je),suspendForChild:()=>Ye.suspendForChild()});z.ticketPanel.addChild(U.component);let G={toggleInbox:()=>{let Je=U.currentDir();if(Je!==void 0){U.close(),It.open(Je);return}It.toggle()}},j=(Je,pr)=>{Ye.hasFullPaneSurface()?Ye.notice(Je,pr):Ue.setNotice(Je,pr)},Ce=Ue.render,le=Je=>{j(M.copy(Je))},be=uyn(T,()=>A.requestRender()),Pe={"crtr.attach.scroll.up":()=>{be.cancel(),T.scrollBy(-1)&&A.requestRender()},"crtr.attach.scroll.down":()=>{be.cancel(),T.scrollBy(1)&&A.requestRender()},"crtr.attach.scroll.page-up":()=>{be.page("up")},"crtr.attach.scroll.page-down":()=>{be.page("down")},"crtr.attach.scroll.live":()=>{be.cancel(),T.goLive(),A.requestRender()},"crtr.attach.mouse.toggle":()=>{let Je=Ne.toggle();!Je&&Y.clear()&&A.requestRender(),j(Je?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>le("message"),"crtr.attach.verbosity.less":()=>j(eYe(v.lessDetail()))},ce,Ee=DEn(X,()=>ce===void 0?i.initialSnapshot!==void 0:ce.isDormant()),De=Xxn(),_e=lbn(X,Ee,{setNotice:j,bindings:()=>m,fdPath:f,frecency:De}),Ve=dbn(X,i.nodeIdentity,{isTornDown:()=>ai.isTornDown(),onChanged:()=>{yt.syncContextBadge();let Je=R.state().engine;Je!==void 0&&yt.setTitle(Je.sessionName),A.requestRender()}});o&&Ve.refresh();let yt=obn(X,{nodeIdentity:Ve.current,thinkingLevel:()=>R.state().engine?.thinkingLevel,renderFooter:Ce,onTextChange:_e.syncCommandPreview});yt.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:or}=axn(X,()=>R.state());R=Cbn(u,{setEngineState:Je=>Wt.setState(Je),setEditorTitle:yt.setTitle,paintEditorFrame:yt.paintFrame,renderExtensionWidgets:()=>{B.render(),st()},renderQueued:or,renderFooter:Ce,setTerminalTitle:Je=>g.setTitle(Je),refreshChrome:()=>wt.refresh()});let Un=Je=>{if(!js()){j("Inspector requires tmux");return}j(`Opening Inspector (${Je})\u2026`);let pr=Q0(),Wu=`${pr===void 0?"":`CRTR_HOME=${cn(pr)} `}crtr surface inspect ${cn(t)} --section ${Je}`;Cyi("tmux",["display-popup","-E","-T",` inspector \xB7 ${Je} `,"-w","90%","-h","85%",...rp(),Wu],()=>{wt.refresh()})},Pn=jEn(X,{asks:()=>wt.asks(),setNotice:j,requestChromeRefresh:()=>wt.refresh(),openInspector:Un,openObject:Je=>{if(!js()){j("Object details require tmux");return}j("Opening object\u2026");let pr=Q0(),Li=pr===void 0?"":`CRTR_HOME=${cn(pr)} `;GV({name:Je,produce:Wu=>`${Li}crtr canvas read ${cn(Je)} > ${Wu} 2>&1`,title:`object \xB7 ${Je}`,noNvim:"nvim is required to view the object. Install Neovim and retry.",onClose:()=>wt.refresh()})},syncCursor:()=>Nn.sync()}),Nn=ixn($,[Pn.active,ye.active,U.active]),ni=new _me(A,t,()=>wt.asks(),d,m,s,u,Je=>wt.reportFailure("canvas graph refresh",Je),j),Oa=new kme(A,d);Oa.setBindings(m);let wt=uxn(X,{isTornDown:()=>ai.isTornDown(),setNotice:j,refreshRoster:async()=>{await Pn.refresh(),await ye.refresh()},refreshGraph:()=>ni.refresh(),refreshIdentity:()=>Ve.refresh(),renderFooter:Ce,renderExtensionWidgets:st,refreshInFlightTools:()=>v.refreshInFlightTools(),pollGit:yt.pollGit}),Wt=MEn(X,p,Ee,{setNotice:j,agentDir:()=>R.state().agentDir,openNodeMetadata:()=>Un("overview"),isDormant:()=>ce.isDormant(),copyTarget:le,moreDetail:()=>v.moreDetail(),lessDetail:()=>v.lessDetail(),toggleThinking:()=>v.toggleThinking(),toggleGraph:()=>ni.toggle(),toggleInbox:G.toggleInbox,toggleHelp:()=>Oa.toggle(),toggleMouse:()=>Ne.toggle(),quit:()=>ca("detach"),setChipColor:yt.setChipColor,onPromptSent:()=>{we.whip_mode&&ae.play()},frecency:De}),te=()=>{if(Ye.hasFullPaneSurface()){j("Close the active surface before whipping the agent");return}let Je=we.whip_message_mode==="go-faster"?_bn:kbn(we.whip_messages);Wt.sendInterrupting(Je)&&(ae.play(),Mbn(d),j(`Whipped agent \u2014 ${Je}`))},oe=Oxn({selfNodeId:t,remote:o,canvasSource:s,port:we.document_port,fetchAccess:async()=>await Ft().documents.browserAccess(),onAccessError:Je=>j(`Document links are unavailable: ${Je instanceof Error?Je.message:String(Je)}`),refresh:()=>v.refreshMarkdown()}),Ie=()=>{if(U.active()){j("Close the open request first (Esc)");return}let Je=[...v.getTranscriptDocRefsNewestFirst().map(Li=>`[[${Li}]]`),...v.getTranscriptFilePathsNewestFirst()],pr=Li=>{bEn(Ye,Li,{originNodeId:t,onNotice:j})};if(Ye.hasFullPaneSurface()){Ye.pickReviewFile({candidates:Je,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(Li=>{Li!==null&&pr(Li)});return}Wt.openFileReviewPicker(Je,a.cwd,pr)},$e=()=>{if(o){j("Profile file search is unavailable on remote canvases");return}if(!js()){j("Profile file search requires tmux");return}s.listNodes().then(Je=>{let pr=Abn(Je,t);ybn({cwd:a.cwd,nodeDirs:pr.map(Li=>Li.cwd),nodes:pr,profileId:a.profile_id??null,fdPath:f,onNotice:j})}).catch(Je=>{let pr=Je instanceof Error?Je.message:String(Je);j(`Could not load related node directories: ${pr}`)})},Be,tt=()=>{Be!==void 0&&clearTimeout(Be),Be=setTimeout(()=>{Be=void 0,l7e(()=>h,()=>{},js,HV)},1e3),Be.unref()},Et=_xn(X,{foldState:R.fold,chat:v,setNotice:j,renderFooter:Ce,setEditorText:Je=>{$.setText(Je),A.requestRender()},attachDialog:Je=>Wt.attachDialog(Je),dismissDialog:Je=>Wt.dismissDialog(Je),refreshNodeIdentity:Ve.refresh,setCommands:_e.setCommands,resetMemoryRefs:_e.resetMemoryRefs,reloadBindings:()=>{h=l7e(fE,Je=>{ni.setBindings(Je),Oa.setBindings(Je)},js,HV),m=h.bindings},modelThinkingLabel:R.modelThinkingLabel,onWelcome:()=>tt()}),Vt=Je=>{let pr=Je instanceof Error?`${Je.name}: ${Je.message}`:String(Je);SI("attach.unhandled_rejection",pr),sYe(Je)&&wt.reportFailure("background daemon call",Je)};process.on("unhandledRejection",Vt);let jr=()=>{process.off("unhandledRejection",Vt)},Nr=hbn(o,t),ai=pxn(X,{stopLocal:()=>{Be!==void 0&&clearTimeout(Be),Ye.closeAll(),be.cancel(),Ne.disable(),wt.stop(),U.close(),Ue.dispose(),ni.close(),Oa.close(),O.close(),ae.dispose(),Nr.clear(),Vme(),zme(),jme(),jr(),oe.dispose(),on();try{v.dispose()}catch{}},lastSocketError:()=>ce.lastSocketError(),reattachCommand:`crtr surface attach to ${Pbn(t)}`+(e?" --observer":"")+(n!==void 0?` --canvas ${Pbn(n)}`:""),tagPane:Nr.pane}),ca=ai.teardown;ce=xxn(X,{role:u,remote:o,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:Et,setNotice:j,isTornDown:()=>ai.isTornDown(),teardown:ca,onEnterDormancy:()=>{tt(),v.settleRun(),R.patchLocal({isStreaming:!1})}}),i.assertConnected(),Nr.set(),ce.install(),W.mount(),A.start(),i.initialSnapshot!==void 0&&(R.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),v.applySnapshot(i.initialSnapshot),_e.setCommands(i.initialCommands),o||Ft().markNodeRead(t).catch(()=>{})),we.whip_mode&&We&&ae.play(),Ne.reassert();let ua=!1,Gd=Je=>{if(ua)return;if(o){j("Opening a file is unavailable in a remote attach");return}let pr=Rg();if(pr===null)return;let Li=Qxn({file:Je,pane:pr.pane,cwd:a.cwd,nodeId:t,observer:e,beforeRespawn:Nr.clear});if(Li==="opened"){ua=!0;return}Li==="failed"&&Nr.set(),Li==="missing"&&j("File no longer exists"),Li==="no_nvim"&&j("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),Li==="failed"&&j("Could not open file in Neovim")};Ne.install(A,{onWheel:(Je,pr)=>{Y.clear()&&A.requestRender(),!Ye.handleWheel(Je,pr)&&(be.cancel(),T.scrollBy(Je==="up"?-pr:pr)&&A.requestRender())},onPrimaryPress:(Je,pr)=>{Ye.hasFullPaneSurface()||(Y.clear()&&A.requestRender(),Y.begin(Je,pr))},onPrimaryDrag:(Je,pr)=>{Ye.hasFullPaneSurface()||Y.extend(Je,pr)&&A.requestRender()},onPrimaryRelease:()=>{let Je=Y.release();Je?.kind==="selection"&&(j(Je.notice),A.requestRender())}});let jme=A.addInputListener(Je=>{let pr=Lxn(Je);if(pr===void 0)return;let Li=pr.file;return Li===void 0?j("Could not open file link"):Gd(Li),pr.remaining.length>0?{data:pr.remaining}:{consume:!0}}),zme=A.addInputListener(()=>{Y.clear()&&A.requestRender()}),Vme=kxn(X,{bindings:()=>m,detachHint:()=>iyn(m),hasExclusiveSurface:()=>Ye.hasFullPaneSurface(),setPaneFocused:Je=>{Je&&Nr.stamp(),Nn.setPaneFocused(Je),A.requestRender()},viewportActions:()=>Pe,searchHandleKey:O.handleKey,panelHandleKey:U.handleKey,stripHandleKey:ye.handleKey,rosterHandleKey:Pn.handleKey,setNotice:j,detach:()=>ca("detach"),cancelTurn:()=>{Wt.abortTurn()?j("Canceling the agent\u2026"):j(`Nothing running to cancel \u2014 press ${oyn(m)??"ctrl+d"} to detach`)},toggleGraph:()=>ni.toggle(),toggleHelp:()=>Oa.toggle(),toggleInbox:G.toggleInbox,toggleInboxStrip:()=>{if(Ye.hasFullPaneSurface()){j("Close the active surface before opening the request strip");return}U.active()&&U.close(),ye.toggle()},cycleModelLadder:Je=>Wt.cycleLadder(Je),inspectLoadedCommand:_e.inspectLoadedCommand,openFileReview:Ie,openProfileFiles:$e,openSearch:()=>{if(Ye.hasFullPaneSurface()||U.active()){j("Close the active surface before searching the transcript");return}O.open()},whip:te});ai.installSignalHandlers(),Ce(),wt.refresh(),or(),yt.pollGit(),MR("viewer.first_paint"),process.stdout.write(lxn),cpn(g.kittyProtocolActive),i.initialSnapshot!==void 0&&tt(),i.initialSnapshot===void 0?(MR("viewer.hello_sent"),ce.sendHello()):ce.startDormant(),wt.start(),bt!==void 0&&yEn(Ye,bt),Qt!==void 0&&Qt!==""&&!o&&(async()=>{let Je=Ft(),[pr,Li]=await Promise.all([Je.listHumanInbox(),Je.getInboxHistory(void 0,{state:"pending"})]),Wu=[...pr.tickets,...Li.tickets].map(wg).find(la=>la.inboxTicketId===Qt&&(la.kind!=="page"||la.state==="pending"));Wu===void 0?j("ask already answered"):U.open(Wu)})().catch(Je=>j(`could not open the ask: ${String(Je?.message??Je)}`)),await ai.done}export{zZs as runAttach};
1713
1713
  /*! Bundled license information:
1714
1714
 
1715
1715
  undici/lib/web/fetch/body.js: