@north-light/cli 0.3.505 → 0.3.507

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.
@@ -1723,13 +1723,13 @@ The viewer resumes when it exits.
1723
1723
  `),oU(e);let a=await new Promise(c=>{let u=dhi(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(phi(i,"utf-8").replace(/\n$/,""))}catch(o){this.notify(`External editor failed: ${o instanceof Error?o.message:String(o)}`)}finally{try{fhi(i)}catch{}this.tui.start(),this.tui.requestRender(!0)}}notify(e){this.hooks.onNotice?.(e)}}});import{execSync as whi}from"node:child_process";import{join as xhi}from"node:path";function kD(){return xhi(Rh(),"auth.json")}function B6(t){if(t===void 0||t.trim()==="")return{};let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:{}}function eXe(t){return`${JSON.stringify(t,null,2)}
1724
1724
  `}function _hi(t){if(ZJe.has(t))return ZJe.get(t);let e;try{e=whi(t,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{e=void 0}return ZJe.set(t,e),e}function vhi(t,e){if(t.startsWith("!"))return _hi(t.slice(1));let n="",r=0;for(;r<t.length;){let i=t.indexOf("$",r);if(i<0){n+=t.slice(r);break}n+=t.slice(r,i);let o=t[i+1];if(o==="$"||o==="!"){n+=o,r=i+2;continue}let s,a=i+1;if(o==="{"){let u=t.indexOf("}",i+2),l=u<0?void 0:t.slice(i+2,u);l!==void 0&&Ehi.test(l)&&(s=l,a=u+1)}else{let u=bhi.exec(t.slice(i+1));u!==null&&(s=u[0],a=i+1+s.length)}if(s===void 0){n+="$",r=i+1;continue}let c=e?.[s]||process.env[s];if(c===void 0||c==="")return;n+=c,r=a}return n}async function Shi(t=kD()){return B6(new gy(t).readUnlocked())}async function Chi(t,e=kD()){return(await Shi(e))[t]}async function v_n(t,e,n=kD()){await new gy(n).withLockAsync(async r=>{let i=B6(r);return i[t]=e,{result:void 0,next:eXe(i)}})}async function tXe(t,e=kD()){return new gy(e).withLockAsync(async n=>{let r=B6(n),i=Object.hasOwn(r,t);return delete r[t],{result:i,next:eXe(r)}})}var bhi,Ehi,ZJe,Yhe,nXe=h(()=>{"use strict";Vi();hK();bhi=/^[A-Za-z_][A-Za-z0-9_]*/,Ehi=/^[A-Za-z_][A-Za-z0-9_]*$/,ZJe=new Map;Yhe=class{constructor(e=kD()){this.authPath=e;this.file=new gy(e)}authPath;file;async read(e){let n=await Chi(e,this.authPath);return n?.type!=="api_key"||n.key===void 0?n:{...n,key:vhi(n.key,n.env)}}async list(){return Object.entries(B6(this.file.readUnlocked())).map(([e,n])=>({providerId:e,type:n.type}))}async modify(e,n){return this.file.withLockAsync(async r=>{let i=B6(r),o=await n(i[e]);return o===void 0?{result:i[e]}:(i[e]=o,{result:o,next:eXe(i)})})}async delete(e){await tXe(e,this.authPath)}}});function Ihi(t){return{providerId:t.provider_id,id:t.id,label:t.label,labelKey:t.label_key,position:t.position,lastAttemptAt:t.last_attempt_at,lastRateLimitedAt:t.last_rate_limited_at,rateLimitedUntil:t.rate_limited_until,...t.auth_failure?{authFailure:t.auth_failure}:{}}}function S_n(t,e){return Lh(ew(t)).prepare(`SELECT ${Thi} FROM managed_accounts WHERE provider_id=? ORDER BY position`).all(e).map(Ihi)}function C_n(t,e){let n=new Map;for(let r of ae(t,"SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM managed_account_model_cooldowns WHERE provider_id=? ORDER BY family").all(e)){let i=n.get(r.account_id)??[];i.push({family:r.family,rateLimitedUntil:r.rate_limited_until,lastRateLimitedAt:r.last_rate_limited_at}),n.set(r.account_id,i)}return n}function I_n(t,e){return C_n(Lh(ew(t)),e)}function Jhe(t,e){return nW(ew(t),n=>{let r=e(n);return ae(n,"UPDATE provider_revision SET revision=revision+1 WHERE singleton=1").run(),r})}var Thi,T_n=h(()=>{"use strict";Qt();MC();Pb();Thi="provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure"});var k_n=h(()=>{"use strict"});import{join as khi}from"node:path";function Dhi(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function cU(){return Rh()}function rXe(t){return khi(cU(),O_n[t].credentials)}function Mhi(t){return t.toLowerCase()}function N_n(t,e){if(!e||e.trim()==="")return{version:1,accounts:{}};let n;try{n=JSON.parse(e)}catch(r){throw new Error(`managed credential file ${t} is corrupt: ${r instanceof Error?r.message:String(r)}`)}if(typeof n!="object"||n===null||Array.isArray(n)||n.version!==1||typeof n.accounts!="object"||n.accounts===null||Array.isArray(n.accounts))throw new Error(`managed credential file ${t} is corrupt`);return n}function Ohi(t,e,n=[]){let r=e.accounts[t.id];if(!r||typeof r.refresh!="string"||typeof r.access!="string"||!Number.isFinite(r.expires))throw new Error(`managed ${t.providerId} account ${t.id} has no credential record`);return{label:t.label,refresh:r.refresh,access:r.access,expires:r.expires,rateLimitedUntil:t.rateLimitedUntil,lastAttemptAt:t.lastAttemptAt,lastRateLimitedAt:t.lastRateLimitedAt,...t.authFailure?{authFailure:t.authFailure}:{},...r.accountId?{accountId:r.accountId}:{},...r.clientId?{clientId:r.clientId}:{},...n.length?{modelCooldowns:Object.fromEntries(n.map(i=>[i.family,i.rateLimitedUntil]))}:{}}}function iXe(t,e){let n=I_n(cU(),t);return S_n(cU(),t).map(r=>({row:r,entry:Ohi(r,e,n.get(r.id))}))}function P_n(t){return new gy(rXe(t),!0,`{"version":1,"accounts":{}}
1725
1725
  `)}function Nhi(t){return N_n(rXe(t),P_n(t).readUnlocked())}function Phi(t,e){let n=Dhi(e);return n?{...t,clientId:n}:t}function Lhi(t,e,n){let r=n.refresh?.trim()??"",i=n.access?.trim()??"",o=Number(n.expires);if(!r||!i||!Number.isFinite(o))throw new Error(`${Xhe(t)} subscription "${e}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:r,access:i,expires:o}}function MS(t){return t===R_n||t===D_n||t===$6}function Xhe(t){return O_n[t].label}function oXe(t){return iXe(t,Nhi(t)).map(({entry:e})=>e)}async function sXe(t,e){let n=rXe(t);return P_n(t).withLockAsync(async(r,i,o)=>{let s=N_n(n,r);return{result:await e(s,iXe(t,s),a=>o(`${JSON.stringify(a)}
1726
- `))}})}function Bhi(t,e){ae(t,"UPDATE managed_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,e.providerId,e.id)}function L_n(t,e,n){n===void 0?ae(t,"DELETE FROM managed_account_model_cooldowns WHERE provider_id=?").run(e):ae(t,"DELETE FROM managed_account_model_cooldowns WHERE provider_id=? AND account_id=?").run(e,n)}function $hi(t,e){return iXe(t,e).map(({entry:n})=>n)}function Fhi(t,e){let n=e.trim().toLowerCase(),r=Number.parseInt(n,10);return Number.isFinite(r)&&String(r)===n&&r>=1&&r<=t.length?r-1:t.findIndex(({entry:i})=>Mhi(i.label)===n)}async function B_n(t,e){return sXe(t,async(n,r,i)=>{let o=Fhi(r,e);if(o<0)throw new Error(`Unknown ${Xhe(t)} subscription: ${e}`);let s=r[o].row;return Jhe(cU(),a=>{ae(a,"DELETE FROM managed_accounts WHERE provider_id=? AND id=?").run(t,s.id),L_n(a,t,s.id)}),delete n.accounts[s.id],i(n),$hi(t,n)})}async function $_n(t,e){return B_n(t,e)}async function Uhi(t){return sXe(t,async(e,n,r)=>{Jhe(cU(),i=>{ae(i,"DELETE FROM managed_accounts WHERE provider_id=?").run(t),L_n(i,t)});for(let{row:i}of n)delete e.accounts[i.id];return r(e),n.length})}async function F_n(t,e){return e===void 0?(await Uhi(t),[]):B_n(t,e)}function Qhi(t){let e=t,n=[e?.errorMessage,e?.message,t instanceof Error?t.message:""].filter(i=>typeof i=="string").join(" ");return(typeof e?.status=="number"?e.status:Number(n.match(/\bstatus[=:]\s*(\d+)/i)?.[1]))===400&&/invalid_grant|refresh token .*invalid|refresh token .*not found/i.test(n)}async function U_n(t,e,n){return sXe(t,async(r,i,o)=>{let s=new Set,a;for(;s.size<i.length;){let c=e(i.filter(({entry:l})=>!s.has(l.label)).map(({entry:l})=>l));if(!c)break;let u=i.find(({entry:l})=>l.label===c.label);s.add(u.entry.label);try{let l=await n(u.entry);if(l){let d=Phi(Lhi(t,u.entry.label,l),l.clientId??u.entry.clientId);return r.accounts[u.row.id]={...r.accounts[u.row.id],...d},o(r),{...u.entry,...d}}return u.entry}catch(l){if(!Qhi(l))throw l;a=l;let d=Date.now();Jhe(cU(),p=>Bhi(p,{...u.row,authFailure:"invalid_grant",lastAttemptAt:Math.max(u.row.lastAttemptAt,d),rateLimitedUntil:Math.max(u.row.rateLimitedUntil,d+Rhi)}))}}if(a)throw a})}var R_n,D_n,$6,Rhi,M_n,O_n,Zhe=h(()=>{"use strict";Qt();Jo();hK();Vi();MC();Pb();T_n();k_n();R_n="anthropic",D_n="openai-codex",$6="openai",Rhi=720*60*60*1e3,M_n=[R_n,D_n,$6],O_n={anthropic:{label:"Claude",credentials:"anthropic-credentials.json"},"openai-codex":{label:"OpenAI Codex",credentials:"openai-codex-credentials.json"},openai:{label:"ChatGPT",credentials:"openai-credentials.json"}}});function aXe(t,e=Date.now()){return Q_n(oXe(t),e)}function Q_n(t,e=Date.now()){return t.find(n=>!n.authFailure&&(!n.rateLimitedUntil||n.rateLimitedUntil<=e))??t[0]}function cXe(t){return{type:"oauth",refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}var ege,W_n=h(()=>{"use strict";nXe();Zhe();ege=class{constructor(e=kD()){this.authPath=e;this.auth=new Yhe(e)}authPath;auth;async read(e){if(!MS(e))return this.auth.read(e);let n=aXe(e);if(n!==void 0)return cXe(n);let r=await this.auth.read(e);return r?.type==="oauth"?void 0:r}async list(){let e=(await this.auth.list()).filter(n=>!(MS(n.providerId)&&n.type==="oauth"));for(let n of M_n)e.some(r=>r.providerId===n)||oXe(n).length>0&&e.push({providerId:n,type:"oauth"});return e}async modify(e,n){if(!MS(e))return this.auth.modify(e,n);if(aXe(e)===void 0){if(await this.read(e)!==void 0)return this.auth.modify(e,n);throw new Error(`${Xhe(e)} has no account to update \u2014 add one with \`crtr sys settings\` or \`/provider-sub ${e} add\`.`)}let r=await U_n(e,i=>Q_n(i),async i=>{let o=await n(cXe(i));if(o===void 0||o.type!=="oauth")return;let s=o.clientId;return{refresh:o.refresh,access:o.access,expires:o.expires,...typeof s=="string"&&s?{clientId:s}:{}}});return r===void 0?void 0:cXe(r)}async delete(e){if(!MS(e))return this.auth.delete(e);let n=aXe(e);n!==void 0&&await $_n(e,n.label),await this.auth.read(e)!==void 0&&await this.auth.delete(e)}}});async function Whi(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 H_n(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(`
1726
+ `))}})}function Bhi(t,e){ae(t,"UPDATE managed_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,e.providerId,e.id)}function L_n(t,e,n){n===void 0?ae(t,"DELETE FROM managed_account_model_cooldowns WHERE provider_id=?").run(e):ae(t,"DELETE FROM managed_account_model_cooldowns WHERE provider_id=? AND account_id=?").run(e,n)}function $hi(t,e){return iXe(t,e).map(({entry:n})=>n)}function Fhi(t,e){let n=e.trim().toLowerCase(),r=Number.parseInt(n,10);return Number.isFinite(r)&&String(r)===n&&r>=1&&r<=t.length?r-1:t.findIndex(({entry:i})=>Mhi(i.label)===n)}async function B_n(t,e){return sXe(t,async(n,r,i)=>{let o=Fhi(r,e);if(o<0)throw new Error(`Unknown ${Xhe(t)} subscription: ${e}`);let s=r[o].row;return Jhe(cU(),a=>{ae(a,"DELETE FROM managed_accounts WHERE provider_id=? AND id=?").run(t,s.id),L_n(a,t,s.id)}),delete n.accounts[s.id],i(n),$hi(t,n)})}async function $_n(t,e){return B_n(t,e)}async function Uhi(t){return sXe(t,async(e,n,r)=>{Jhe(cU(),i=>{ae(i,"DELETE FROM managed_accounts WHERE provider_id=?").run(t),L_n(i,t)});for(let{row:i}of n)delete e.accounts[i.id];return r(e),n.length})}async function F_n(t,e){return e===void 0?(await Uhi(t),[]):B_n(t,e)}function Qhi(t){let e=t,n=[e?.errorMessage,e?.message,t instanceof Error?t.message:""].filter(i=>typeof i=="string").join(" ");return(typeof e?.status=="number"?e.status:Number(n.match(/\bstatus[=:]\s*(\d+)/i)?.[1]))===400&&/invalid_grant|refresh token .*invalid|refresh token .*not found/i.test(n)}async function U_n(t,e,n){return sXe(t,async(r,i,o)=>{let s=new Set,a;for(;s.size<i.length;){let c=e(i.filter(({entry:l})=>!s.has(l.label)).map(({entry:l})=>l));if(!c)break;let u=i.find(({entry:l})=>l.label===c.label);s.add(u.entry.label);try{let l=await n(u.entry);if(l){let d=Phi(Lhi(t,u.entry.label,l),l.clientId??u.entry.clientId);return r.accounts[u.row.id]={...r.accounts[u.row.id],...d},o(r),{...u.entry,...d}}return u.entry}catch(l){if(!Qhi(l))throw l;a=l;let d=Date.now();Jhe(cU(),p=>Bhi(p,{...u.row,authFailure:"invalid_grant",lastAttemptAt:Math.max(u.row.lastAttemptAt,d),rateLimitedUntil:Math.max(u.row.rateLimitedUntil,d+Rhi)}))}}if(a)throw a})}var R_n,D_n,$6,z6s,Rhi,M_n,O_n,Zhe=h(()=>{"use strict";Qt();Jo();hK();Vi();MC();Pb();T_n();k_n();R_n="anthropic",D_n="openai-codex",$6="openai",z6s=600*1e3,Rhi=720*60*60*1e3,M_n=[R_n,D_n,$6],O_n={anthropic:{label:"Claude",credentials:"anthropic-credentials.json"},"openai-codex":{label:"OpenAI Codex",credentials:"openai-codex-credentials.json"},openai:{label:"ChatGPT",credentials:"openai-credentials.json"}}});function aXe(t,e=Date.now()){return Q_n(oXe(t),e)}function Q_n(t,e=Date.now()){return t.find(n=>!n.authFailure&&(!n.rateLimitedUntil||n.rateLimitedUntil<=e))??t[0]}function cXe(t){return{type:"oauth",refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}var ege,W_n=h(()=>{"use strict";nXe();Zhe();ege=class{constructor(e=kD()){this.authPath=e;this.auth=new Yhe(e)}authPath;auth;async read(e){if(!MS(e))return this.auth.read(e);let n=aXe(e);if(n!==void 0)return cXe(n);let r=await this.auth.read(e);return r?.type==="oauth"?void 0:r}async list(){let e=(await this.auth.list()).filter(n=>!(MS(n.providerId)&&n.type==="oauth"));for(let n of M_n)e.some(r=>r.providerId===n)||oXe(n).length>0&&e.push({providerId:n,type:"oauth"});return e}async modify(e,n){if(!MS(e))return this.auth.modify(e,n);if(aXe(e)===void 0){if(await this.read(e)!==void 0)return this.auth.modify(e,n);throw new Error(`${Xhe(e)} has no account to update \u2014 add one with \`crtr sys settings\` or \`/provider-sub ${e} add\`.`)}let r=await U_n(e,i=>Q_n(i),async i=>{let o=await n(cXe(i));if(o===void 0||o.type!=="oauth")return;let s=o.clientId;return{refresh:o.refresh,access:o.access,expires:o.expires,...typeof s=="string"&&s?{clientId:s}:{}}});return r===void 0?void 0:cXe(r)}async delete(e){if(!MS(e))return this.auth.delete(e);let n=aXe(e);n!==void 0&&await $_n(e,n.label),await this.auth.read(e)!==void 0&&await this.auth.delete(e)}}});async function Whi(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 H_n(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(`
1727
1727
  `);c=t.showPrompt(`${a.message}
1728
1728
  ${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(),Whi(c,[t.signal,a.signal])}}}var j_n=h(()=>{"use strict"});function Hhi(t=process.env){return t.SSH_CONNECTION||t.SSH_TTY?!1:process.platform==="darwin"||process.platform==="win32"?!0:!!(t.DISPLAY||t.WAYLAND_DISPLAY)}function G_n(t){return t.aborted}function jhi(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 qhi(t){if(!(!(t instanceof un)||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 uXe(t,e){try{return await t.startModelAuth(e)}catch(n){throw qhi(n)??n}}async function Ghi(t,e,n,r){let i={provider:e===$6?"openai-chatgpt":e,...n?{label:n}:{}};if(!r)return{flow:await uXe(t,i),loopback:!1};try{return{flow:await uXe(t,{...i,redirect:"loopback"}),loopback:!0}}catch(o){if(o instanceof un&&o.status===409&&o.param==="redirect")return{flow:await uXe(t,i),loopback:!1};throw o}}async function lXe(t,e,n){for(;!G_n(n);){let r=await jhi(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 z_n(t,e,n,r={}){let{flow:i,loopback:o}=await Ghi(t,e,r.label,r.loopback??Hhi()),s=()=>{t.cancelModelAuth(i.flow_id).catch(()=>{})};if(G_n(n.signal))throw s(),new Error("Login cancelled");n.signal.addEventListener("abort",s,{once:!0});try{await zhi(t,i,o,n)}finally{n.signal.removeEventListener("abort",s)}}async function zhi(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 lXe(t,e.flow_id,r.signal);return}r.notify({type:"auth_url",url:e.url,instructions:e.instructions});let i=e.provider===$6;if(n&&!i){await lXe(t,e.flow_id,r.signal);return}if(n){let o=new AbortController,s=AbortSignal.any([r.signal,o.signal]),a=q_n(t,e,r,s);a.catch(()=>{});try{await Promise.race([lXe(t,e.flow_id,r.signal),a])}finally{o.abort()}return}if(i){await q_n(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 un&&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 q_n(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 un&&o.status===400&&(o.param==="input"||o.param==="state")){n.notify({type:"info",message:`${o.message} \u2014 paste it again.`});continue}throw o}}}var V_n=h(()=>{"use strict";dd();Zhe()});import{join as K_n}from"node:path";import{execFile as Vhi}from"node:child_process";async function Y_n(t){let e=K_n(Rh(),"auth.json"),n=K_n(t,"models.json"),r=new ege(e),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 u0.create({credentials:o,modelsPath:n}),authPath:e,beforeNextCredentialMutation:a=>{i=a}}}async function J_n(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 Khi(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Vhi(e,[t],{timeout:5e3},()=>{})}async function X_n(t,e,n,r){let{runtime:i,authPath:o,beforeNextCredentialMutation:s}=await Y_n(e),a=await J_n(i);return({close:c,replace:u})=>{let l=p=>{let f=a.find(I=>I.id===p);if(f===void 0){r(`Unknown provider: ${p}`),c();return}let m=!1,g=!1,y=()=>{m||(m=!0,c())},w=new $R(t,p,(I,D)=>{m||(I?(r(`Logged in to ${f.name}`),n()):r(D?`Login failed: ${D}`:`Login to ${f.name} was cancelled`),y())},f.name);u(w,w);let x=w.handleInput.bind(w);w.handleInput=I=>{g||x(I)};let E=()=>m||w.signal.aborted?!1:(g=!0,w.showDetails(["Saving credentials\u2026"]),!0),_=H_n(w,{openBrowser:Khi,isActive:()=>!m&&!w.signal.aborted}),C=I=>{if(I instanceof vR){r(`Logged in to ${f.name}; provider refresh failed: ${I.message}`),n(),y();return}let D=I;D?.name!=="AbortError"&&D?.message!=="Login cancelled"&&r(`Login error: ${String(D?.message??I)}`),y()};if(MS(p)){z_n(qt(),p,_).then(()=>{m||(r(`Logged in to ${f.name}`),n(),y())}).catch(C);return}if(f.authType==="oauth"){if(i.getProvider(p)?.auth.oauth===void 0){w.showInfo([`Provider "${f.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(`
1729
- `));return}s(E),i.login(p,"oauth",_).then(()=>{m||(r(`Logged in to ${f.name}`),n(),y())}).catch(C).finally(()=>s(void 0))}else w.showPrompt(`Enter API key for ${f.name}:`,"sk-...").then(async I=>{if(!m){if(I.trim()){if(!E())return;await v_n(p,{type:"api_key",key:I.trim()},o),r(`API key saved for ${f.name}`),n()}else r("No key entered \u2014 login cancelled");y()}}).catch(()=>y())},d=new sS("login",a,l,()=>c());return{component:d,focus:d}}}async function Z_n(t,e,n){let{runtime:r,authPath:i}=await Y_n(t),o=await J_n(r);return({close:s})=>{let a=u=>{let l=o.find(d=>d.id===u);(async()=>{try{MS(u)?await F_n(u):await tXe(u,i),s(),n(`Logged out of ${l?.name??u}`),e()}catch(d){s(),n(`Logout error: ${d instanceof Error?d.message:String(d)}`)}})()},c=new sS("logout",o,a,()=>s());return{component:c,focus:c}}}var evn=h(()=>{"use strict";zs();nXe();W_n();Vi();j_n();Zhe();V_n();lc()});function tvn(t,e){return tbn({nodeId:t.nodeId,profileId:t.meta.profile_id??void 0,remote:t.remote,role:t.role,isBrokerOffline:e})}function nvn(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 f=r.agentDir()??VR();p.openAuthPicker(()=>X_n(s,f,l,m=>u(m)))},openLogoutPicker:()=>{let f=r.agentDir()??VR();p.openAuthPicker(()=>Z_n(f,l,m=>u(m)))}}:{},p=new Khe(s,a,e,{onCommand:f=>o.send(f),onDialogResponse:f=>o.send(f),onNotice:f=>u(f),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 f=r.toggleMouse();u(f?"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(),onToggleToolsExpand:()=>{let f=r.toggleToolsExpanded();u(f.kind==="summaries"?f.shown?"Tool calls: summarized":"Tool calls: shown":f.expanded?"Tool output: expanded":"Tool output: collapsed")},onFoldTools:()=>u(r.toggleFoldTools()?"Finished tool calls: folded to one line":"Finished tool calls: shown in full"),onShowWorking:()=>{let f=r.toggleShowWorking();u(f===null?"Consolidated replies are off (crtr sys config set consolidate_replies --value true, then re-attach)":f?"Working: shown":"Working: hidden behind each reply")},onToggleThinking:()=>u(r.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),onRequest:f=>{let m=n.refusal("engine-drive");return m===void 0?o.request(f):Promise.reject(new Error(m))},onMountPicker:f=>{c.pickerPanel.addChild(f),s.requestRender()},onUnmountPicker:()=>{c.pickerPanel.clear(),s.requestRender()},isDormant:r.isDormant,onDormantSubmit:n.permits("wake-dormant")?f=>{(async()=>{try{let m=await qt().sendMessage(i,{body:f,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}var rvn=h(()=>{"use strict";__n();Ahe();lc();evn();Xz()});async function F6(t,e){await qt().respondHumanRequest(t,{responses:e})}async function ivn(t,e){await qt().dismissHumanRequest(t,e)}function ovn(t){if(t instanceof un)return t.status===503||t.code==="daemon_unavailable";let e=t?.code;return e==="ECONNREFUSED"||e==="ENOENT"}function wu(t){return ovn(t)?"could not reach crtrd \u2014 nothing was submitted":t instanceof un||t instanceof Error?t.message:String(t)}function U6(t){return ovn(t)?"unreachable":t instanceof un&&t.status===409&&t.code==="already_settled"?"already_settled":"other"}var uU=h(()=>{"use strict";dd();lc()});var svn=h(()=>{"use strict";Rr()});function avn(t){let e=t?.diagnostics;return Array.isArray(e)&&e.some(n=>n?.type===Yhi)}var Yhi,cvn=h(()=>{"use strict";Yhi="crtr:managed-provider-cooling"});function dXe(t){return typeof t=="string"?t:""}function yf(t,e,n={}){return{kind:t,matchedOn:e,...n}}function iy(t,e){return e.matchedOn==="text"?{...t,textKind:e.kind,textMatch:e.match,textMatches:e.textMatches}:t}function uvn(t){let e=Jhi.flatMap(([r,i])=>{let o=t.match(i);return o?[{kind:r,match:o[0]}]:[]}),n=e[0];return n===void 0?yf("other","none"):{...yf(n.kind,"text",{match:n.match}),textMatches:e}}function lvn(t){let e=t.retryAfterMs,n=uvn(t.message??""),r=dXe(t.code)||dXe(t.errno);if(/^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOENT|ENOTFOUND|EAI_AGAIN|EPIPE|EHOSTUNREACH|ENETUNREACH)$/i.test(r))return iy(yf("connection","errno",{retryAfterMs:e}),n);if(/^ELOCKED$/i.test(r))return iy(yf("overloaded","errno",{retryAfterMs:e}),n);let i=typeof t.status=="number"?t.status:void 0;if(i!==void 0){if(i===401||i===403)return iy(yf("auth","status",{status:i,retryAfterMs:e}),n);if(i===429)return iy(yf("rate-limit","status",{status:i,retryAfterMs:e}),n);if(i===500||i===502||i===503||i===504)return iy(yf("transient-http","status",{status:i,retryAfterMs:e}),n);if(i>=500&&i<=599)return iy(yf("overloaded","status",{status:i,retryAfterMs:e}),n);if(i>=400&&i<=499)return iy(yf("protocol","status",{status:i,retryAfterMs:e}),n)}let o=typeof t.wsCloseCode=="number"?t.wsCloseCode:void 0;if(o===1008)return iy(yf("protocol","websocket-close",{retryAfterMs:e}),n);if(o===1006)return iy(yf("connection","websocket-close",{retryAfterMs:e}),n);if(o===1011){let s=dXe(t.wsCloseReason),a=uvn(s);return/no running broker/i.test(s)||a.kind==="connection"||a.kind==="connection-only"?iy(yf("connection","websocket-close",{retryAfterMs:e}),n):iy(yf("other","websocket-close",{retryAfterMs:e}),n)}return e===void 0?n:{...n,retryAfterMs:e}}var Jhi,dvn=h(()=>{"use strict";Jhi=[["rate-limit",/rate.?limit|\b429\b|too many requests|usage[ _]limit|usage_not_included|usagelimiterror|insufficient_quota|quota exceeded/i],["protocol",/\b413\b|payload too large|entity too large|request too large|entity\.too\.large|body exceeds/i],["auth",/invalid_grant|refresh token|unauthori[sz]ed|invalid.?api.?key|authentication failed|\b401\b|\b403\b/i],["context-overflow",/context overflow recovery failed/i],["protocol",/websocket.*(?:closed.*\b(?:1002|1003|1007|1008|1009|1010)\b|protocol error|policy violation|unsupported data|invalid (?:frame|payload)|message too big|mandatory extension)/i],["overloaded-only",/lock file is already being held/i],["overloaded",/overloaded|temporarily unavailable/i],["service-unavailable",/service.?unavailable/i],["overloaded-only",/internal server error|api.?error|\b5\d\d\b|capacity|server.{0,3}busy/i],["connection",/connection|econnreset|etimedout|enotfound|econnrefused|network|fetch failed|socket hang|timed? out|timeout|websocket\s+(?:was\s+)?closed|websocket stream closed before response\.completed|websocket\s+error|websocket.*interrupt/i],["socket",/socket/i],["connection-only",/eai_again|epipe|ehostunreach|enetunreach|\bterminated\b|other side closed|premature close/i]]});function eb(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var lU=h(()=>{"use strict"});function $a(t){return typeof t=="string"&&t.trim()!==""?t.trim():void 0}function tge(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function nge(t){return typeof t=="string"||typeof t=="number"?t:void 0}function dU(t){return eb(t)?t:void 0}function Zhi(t){let e=$a(t.errorMessage)??$a(t.message)??$a(t.reason)??$a(t.statusText),n={...e===void 0?{}:{message:e},...tge(t.status)===void 0?{}:{status:tge(t.status)},...nge(t.code)===void 0?{}:{code:nge(t.code)},...$a(t.errno)===void 0?{}:{errno:$a(t.errno)},...$a(t.body)===void 0?{}:{body:$a(t.body)}};return Object.keys(n).length===0?void 0:n}function rge(t){let e=dU(t),n=dU(e?.headers);if(e===void 0||n===void 0)return;let r={};for(let[i,o]of Object.entries(n)){if(Object.keys(r).length>=egi)break;typeof o=="string"&&(r[i.toLowerCase()]=o.slice(0,tgi))}return{...$a(e.scope)===void 0?{}:{scope:$a(e.scope)},...$a(e.claim)===void 0?{}:{claim:$a(e.claim)},...$a(e.account)===void 0?{}:{account:$a(e.account)},...$a(e.model)===void 0?{}:{model:$a(e.model)},headers:r}}function ngi(t){let e=dU(t)?.diagnostics;if(Array.isArray(e))for(let n of e){let r=dU(n);if(r?.type!==Xhi)continue;let i=dU(r.details);if(i===void 0)continue;let o=Array.isArray(i.causes)?i.causes.flatMap(s=>{let a=dU(s),c=a===void 0?void 0:Zhi(a);return c===void 0?[]:[c]}):void 0;return{...tge(i.status)===void 0?{}:{status:tge(i.status)},...nge(i.code)===void 0?{}:{code:nge(i.code)},...$a(i.errno)===void 0?{}:{errno:$a(i.errno)},...$a(i.body)===void 0?{}:{body:$a(i.body)},...o===void 0||o.length===0?{}:{causes:o},...rge(i.ratelimit)===void 0?{}:{ratelimit:rge(i.ratelimit)}}}}function pvn(t){return ngi(t)}var Xhi,egi,tgi,pXe=h(()=>{"use strict";lU();Xhi="crtr:provider-failure";egi=48,tgi=256});function rgi(t){switch(t.kind){case"rate-limit":return"rate-limit";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"overloaded":case"overloaded-only":case"transient-http":return"overloaded";case"connection":case"connection-only":return"connection";case"socket":case"service-unavailable":case"other":return"other"}}function fvn(t,e){return e==="auth"||e==="protocol"||e==="context-overflow"?"fatal":t==="pi\u2192provider"?e==="connection"||e==="rate-limit"||e==="overloaded"?"auto":"fatal":"manual"}function igi(t){if(typeof t=="string")return t;if(!eb(t))return"";let e=[t.message,t.errorMessage,t.reason,t.body,t.statusText];for(let r of e)if(typeof r=="string"&&r!=="")return r;let n=t.error;if(eb(n)){let r=n.message;if(typeof r=="string"&&r!=="")return r;let i=n.reason;if(typeof i=="string"&&i!=="")return i}return""}function ige(t,e){if(t==="pi\u2192provider"&&avn(e))return{kind:"rate-limit",disposition:"auto"};let n=eb(e)?e:{},r=pvn(e),i=r?.causes??[];if(r?.code===ogi)return{kind:"connection",disposition:fvn(t,"connection")};let o=lvn({code:n.code??r?.code??i.find(a=>a.code!==void 0)?.code,errno:n.errno??r?.errno??i.find(a=>a.errno!==void 0)?.errno,status:n.status??r?.status,wsCloseCode:n.code,wsCloseReason:n.reason,message:[igi(e),r?.body,...i.flatMap(a=>[a.message,a.body])].filter(a=>typeof a=="string"&&a!=="").join(" ")}),s=rgi(o);return{kind:s,disposition:fvn(t,s)}}var ogi,oge=h(()=>{"use strict";cvn();dvn();pXe();lU();ogi="upstream_model_unavailable"});function mvn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function agi(t){if(!mvn(t)||typeof t.provider!="string"||t.provider===""||typeof t.model!="string"||t.model==="")return;let e=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0,n=typeof t.code=="string"||typeof t.code=="number"?t.code:void 0,r=typeof t.errno=="string"?t.errno:void 0,i=typeof t.body=="string"?t.body:void 0,o=rge(t.ratelimit),s=Array.isArray(t.causes)?t.causes.flatMap(a=>{if(!mvn(a))return[];let c={...typeof a.message=="string"?{message:a.message}:{},...typeof a.status=="number"&&Number.isFinite(a.status)?{status:a.status}:{},...typeof a.code=="string"||typeof a.code=="number"?{code:a.code}:{},...typeof a.errno=="string"?{errno:a.errno}:{},...typeof a.body=="string"?{body:a.body}:{}};return Object.keys(c).length===0?[]:[c]}):void 0;return{provider:t.provider,model:t.model,...e===void 0?{}:{status:e},...n===void 0?{}:{code:n},...r===void 0?{}:{errno:r},...i===void 0?{}:{body:i},...s===void 0||s.length===0?{}:{causes:s},...o===void 0?{}:{ratelimit:o}}}function hvn(t){let e=t.provider_error_json,n=typeof e=="string"?agi(JSON.parse(e)):void 0;if(typeof e=="string"&&n===void 0)throw new Error(`invalid provider error on stored fault ${t.fault_id}`);let r={disposition:t.retry_disposition,...t.retry_by===null?{}:{by:t.retry_by},...t.retry_attempt===null?{}:{attempt:t.retry_attempt},...t.retry_max===null?{}:{max:t.retry_max},...t.retry_next_at===null?{}:{nextAt:t.retry_next_at}};return{faultId:t.fault_id,link:t.link,op:t.op,kind:t.kind,message:t.message,since:t.since,operation_id:t.operation_id,retry:r,...t.anchor_entry_id===null?{}:{anchorEntryId:t.anchor_entry_id},...n===void 0?{}:{providerError:n}}}var QVs,sgi,WVs,fXe=h(()=>{"use strict";Qt();fi();Rr();oge();pXe();Pf();$Q();QVs=5*6e4,sgi=["pi\u2192provider","viewer\u2194broker","relay\u2194broker","viewer\u2194crtrd","daemon\u2192node","crtr\u2192pi"],WVs=[...sgi,"broker\u2194crtrd"]});var gvn=h(()=>{"use strict"});var cgi,e7s,Q6=h(()=>{"use strict";Qt();fi();Rr();gvn();Pf();cgi=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
1729
+ `));return}s(E),i.login(p,"oauth",_).then(()=>{m||(r(`Logged in to ${f.name}`),n(),y())}).catch(C).finally(()=>s(void 0))}else w.showPrompt(`Enter API key for ${f.name}:`,"sk-...").then(async I=>{if(!m){if(I.trim()){if(!E())return;await v_n(p,{type:"api_key",key:I.trim()},o),r(`API key saved for ${f.name}`),n()}else r("No key entered \u2014 login cancelled");y()}}).catch(()=>y())},d=new sS("login",a,l,()=>c());return{component:d,focus:d}}}async function Z_n(t,e,n){let{runtime:r,authPath:i}=await Y_n(t),o=await J_n(r);return({close:s})=>{let a=u=>{let l=o.find(d=>d.id===u);(async()=>{try{MS(u)?await F_n(u):await tXe(u,i),s(),n(`Logged out of ${l?.name??u}`),e()}catch(d){s(),n(`Logout error: ${d instanceof Error?d.message:String(d)}`)}})()},c=new sS("logout",o,a,()=>s());return{component:c,focus:c}}}var evn=h(()=>{"use strict";zs();nXe();W_n();Vi();j_n();Zhe();V_n();lc()});function tvn(t,e){return tbn({nodeId:t.nodeId,profileId:t.meta.profile_id??void 0,remote:t.remote,role:t.role,isBrokerOffline:e})}function nvn(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 f=r.agentDir()??VR();p.openAuthPicker(()=>X_n(s,f,l,m=>u(m)))},openLogoutPicker:()=>{let f=r.agentDir()??VR();p.openAuthPicker(()=>Z_n(f,l,m=>u(m)))}}:{},p=new Khe(s,a,e,{onCommand:f=>o.send(f),onDialogResponse:f=>o.send(f),onNotice:f=>u(f),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 f=r.toggleMouse();u(f?"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(),onToggleToolsExpand:()=>{let f=r.toggleToolsExpanded();u(f.kind==="summaries"?f.shown?"Tool calls: summarized":"Tool calls: shown":f.expanded?"Tool output: expanded":"Tool output: collapsed")},onFoldTools:()=>u(r.toggleFoldTools()?"Finished tool calls: folded to one line":"Finished tool calls: shown in full"),onShowWorking:()=>{let f=r.toggleShowWorking();u(f===null?"Consolidated replies are off (crtr sys config set consolidate_replies --value true, then re-attach)":f?"Working: shown":"Working: hidden behind each reply")},onToggleThinking:()=>u(r.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),onRequest:f=>{let m=n.refusal("engine-drive");return m===void 0?o.request(f):Promise.reject(new Error(m))},onMountPicker:f=>{c.pickerPanel.addChild(f),s.requestRender()},onUnmountPicker:()=>{c.pickerPanel.clear(),s.requestRender()},isDormant:r.isDormant,onDormantSubmit:n.permits("wake-dormant")?f=>{(async()=>{try{let m=await qt().sendMessage(i,{body:f,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}var rvn=h(()=>{"use strict";__n();Ahe();lc();evn();Xz()});async function F6(t,e){await qt().respondHumanRequest(t,{responses:e})}async function ivn(t,e){await qt().dismissHumanRequest(t,e)}function ovn(t){if(t instanceof un)return t.status===503||t.code==="daemon_unavailable";let e=t?.code;return e==="ECONNREFUSED"||e==="ENOENT"}function wu(t){return ovn(t)?"could not reach crtrd \u2014 nothing was submitted":t instanceof un||t instanceof Error?t.message:String(t)}function U6(t){return ovn(t)?"unreachable":t instanceof un&&t.status===409&&t.code==="already_settled"?"already_settled":"other"}var uU=h(()=>{"use strict";dd();lc()});var svn=h(()=>{"use strict";Rr()});function avn(t){let e=t?.diagnostics;return Array.isArray(e)&&e.some(n=>n?.type===Yhi)}var Yhi,cvn=h(()=>{"use strict";Yhi="crtr:managed-provider-cooling"});function dXe(t){return typeof t=="string"?t:""}function yf(t,e,n={}){return{kind:t,matchedOn:e,...n}}function iy(t,e){return e.matchedOn==="text"?{...t,textKind:e.kind,textMatch:e.match,textMatches:e.textMatches}:t}function uvn(t){let e=Jhi.flatMap(([r,i])=>{let o=t.match(i);return o?[{kind:r,match:o[0]}]:[]}),n=e[0];return n===void 0?yf("other","none"):{...yf(n.kind,"text",{match:n.match}),textMatches:e}}function lvn(t){let e=t.retryAfterMs,n=uvn(t.message??""),r=dXe(t.code)||dXe(t.errno);if(/^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOENT|ENOTFOUND|EAI_AGAIN|EPIPE|EHOSTUNREACH|ENETUNREACH)$/i.test(r))return iy(yf("connection","errno",{retryAfterMs:e}),n);if(/^ELOCKED$/i.test(r))return iy(yf("overloaded","errno",{retryAfterMs:e}),n);let i=typeof t.status=="number"?t.status:void 0;if(i!==void 0){if(i===401||i===403)return iy(yf("auth","status",{status:i,retryAfterMs:e}),n);if(i===429)return iy(yf("rate-limit","status",{status:i,retryAfterMs:e}),n);if(i===500||i===502||i===503||i===504)return iy(yf("transient-http","status",{status:i,retryAfterMs:e}),n);if(i>=500&&i<=599)return iy(yf("overloaded","status",{status:i,retryAfterMs:e}),n);if(i>=400&&i<=499)return iy(yf("protocol","status",{status:i,retryAfterMs:e}),n)}let o=typeof t.wsCloseCode=="number"?t.wsCloseCode:void 0;if(o===1008)return iy(yf("protocol","websocket-close",{retryAfterMs:e}),n);if(o===1006)return iy(yf("connection","websocket-close",{retryAfterMs:e}),n);if(o===1011){let s=dXe(t.wsCloseReason),a=uvn(s);return/no running broker/i.test(s)||a.kind==="connection"||a.kind==="connection-only"?iy(yf("connection","websocket-close",{retryAfterMs:e}),n):iy(yf("other","websocket-close",{retryAfterMs:e}),n)}return e===void 0?n:{...n,retryAfterMs:e}}var Jhi,dvn=h(()=>{"use strict";Jhi=[["rate-limit",/rate.?limit|\b429\b|too many requests|usage[ _]limit|usage_not_included|usagelimiterror|insufficient_quota|quota exceeded/i],["protocol",/\b413\b|payload too large|entity too large|request too large|entity\.too\.large|body exceeds/i],["auth",/invalid_grant|refresh token|unauthori[sz]ed|invalid.?api.?key|authentication failed|\b401\b|\b403\b/i],["context-overflow",/context overflow recovery failed/i],["protocol",/websocket.*(?:closed.*\b(?:1002|1003|1007|1008|1009|1010)\b|protocol error|policy violation|unsupported data|invalid (?:frame|payload)|message too big|mandatory extension)/i],["overloaded-only",/lock file is already being held/i],["overloaded",/overloaded|temporarily unavailable/i],["service-unavailable",/service.?unavailable/i],["overloaded-only",/internal server error|api.?error|\b5\d\d\b|capacity|server.{0,3}busy/i],["connection",/connection|econnreset|etimedout|enotfound|econnrefused|network|fetch failed|socket hang|timed? out|timeout|websocket\s+(?:was\s+)?closed|websocket stream closed before response\.completed|websocket\s+error|websocket.*interrupt/i],["socket",/socket/i],["connection-only",/eai_again|epipe|ehostunreach|enetunreach|\bterminated\b|other side closed|premature close/i]]});function eb(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var lU=h(()=>{"use strict"});function $a(t){return typeof t=="string"&&t.trim()!==""?t.trim():void 0}function tge(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function nge(t){return typeof t=="string"||typeof t=="number"?t:void 0}function dU(t){return eb(t)?t:void 0}function Zhi(t){let e=$a(t.errorMessage)??$a(t.message)??$a(t.reason)??$a(t.statusText),n={...e===void 0?{}:{message:e},...tge(t.status)===void 0?{}:{status:tge(t.status)},...nge(t.code)===void 0?{}:{code:nge(t.code)},...$a(t.errno)===void 0?{}:{errno:$a(t.errno)},...$a(t.body)===void 0?{}:{body:$a(t.body)}};return Object.keys(n).length===0?void 0:n}function rge(t){let e=dU(t),n=dU(e?.headers);if(e===void 0||n===void 0)return;let r={};for(let[i,o]of Object.entries(n)){if(Object.keys(r).length>=egi)break;typeof o=="string"&&(r[i.toLowerCase()]=o.slice(0,tgi))}return{...$a(e.scope)===void 0?{}:{scope:$a(e.scope)},...$a(e.claim)===void 0?{}:{claim:$a(e.claim)},...$a(e.account)===void 0?{}:{account:$a(e.account)},...$a(e.model)===void 0?{}:{model:$a(e.model)},headers:r}}function ngi(t){let e=dU(t)?.diagnostics;if(Array.isArray(e))for(let n of e){let r=dU(n);if(r?.type!==Xhi)continue;let i=dU(r.details);if(i===void 0)continue;let o=Array.isArray(i.causes)?i.causes.flatMap(s=>{let a=dU(s),c=a===void 0?void 0:Zhi(a);return c===void 0?[]:[c]}):void 0;return{...tge(i.status)===void 0?{}:{status:tge(i.status)},...nge(i.code)===void 0?{}:{code:nge(i.code)},...$a(i.errno)===void 0?{}:{errno:$a(i.errno)},...$a(i.body)===void 0?{}:{body:$a(i.body)},...o===void 0||o.length===0?{}:{causes:o},...rge(i.ratelimit)===void 0?{}:{ratelimit:rge(i.ratelimit)}}}}function pvn(t){return ngi(t)}var Xhi,egi,tgi,pXe=h(()=>{"use strict";lU();Xhi="crtr:provider-failure";egi=48,tgi=256});function rgi(t){switch(t.kind){case"rate-limit":return"rate-limit";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"overloaded":case"overloaded-only":case"transient-http":return"overloaded";case"connection":case"connection-only":return"connection";case"socket":case"service-unavailable":case"other":return"other"}}function fvn(t,e){return e==="auth"||e==="protocol"||e==="context-overflow"?"fatal":t==="pi\u2192provider"?e==="connection"||e==="rate-limit"||e==="overloaded"?"auto":"fatal":"manual"}function igi(t){if(typeof t=="string")return t;if(!eb(t))return"";let e=[t.message,t.errorMessage,t.reason,t.body,t.statusText];for(let r of e)if(typeof r=="string"&&r!=="")return r;let n=t.error;if(eb(n)){let r=n.message;if(typeof r=="string"&&r!=="")return r;let i=n.reason;if(typeof i=="string"&&i!=="")return i}return""}function ige(t,e){if(t==="pi\u2192provider"&&avn(e))return{kind:"rate-limit",disposition:"auto"};let n=eb(e)?e:{},r=pvn(e),i=r?.causes??[];if(r?.code===ogi)return{kind:"connection",disposition:fvn(t,"connection")};let o=lvn({code:n.code??r?.code??i.find(a=>a.code!==void 0)?.code,errno:n.errno??r?.errno??i.find(a=>a.errno!==void 0)?.errno,status:n.status??r?.status,wsCloseCode:n.code,wsCloseReason:n.reason,message:[igi(e),r?.body,...i.flatMap(a=>[a.message,a.body])].filter(a=>typeof a=="string"&&a!=="").join(" ")}),s=rgi(o);return{kind:s,disposition:fvn(t,s)}}var ogi,oge=h(()=>{"use strict";cvn();dvn();pXe();lU();ogi="upstream_model_unavailable"});function mvn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function agi(t){if(!mvn(t)||typeof t.provider!="string"||t.provider===""||typeof t.model!="string"||t.model==="")return;let e=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0,n=typeof t.code=="string"||typeof t.code=="number"?t.code:void 0,r=typeof t.errno=="string"?t.errno:void 0,i=typeof t.body=="string"?t.body:void 0,o=rge(t.ratelimit),s=Array.isArray(t.causes)?t.causes.flatMap(a=>{if(!mvn(a))return[];let c={...typeof a.message=="string"?{message:a.message}:{},...typeof a.status=="number"&&Number.isFinite(a.status)?{status:a.status}:{},...typeof a.code=="string"||typeof a.code=="number"?{code:a.code}:{},...typeof a.errno=="string"?{errno:a.errno}:{},...typeof a.body=="string"?{body:a.body}:{}};return Object.keys(c).length===0?[]:[c]}):void 0;return{provider:t.provider,model:t.model,...e===void 0?{}:{status:e},...n===void 0?{}:{code:n},...r===void 0?{}:{errno:r},...i===void 0?{}:{body:i},...s===void 0||s.length===0?{}:{causes:s},...o===void 0?{}:{ratelimit:o}}}function hvn(t){let e=t.provider_error_json,n=typeof e=="string"?agi(JSON.parse(e)):void 0;if(typeof e=="string"&&n===void 0)throw new Error(`invalid provider error on stored fault ${t.fault_id}`);let r={disposition:t.retry_disposition,...t.retry_by===null?{}:{by:t.retry_by},...t.retry_attempt===null?{}:{attempt:t.retry_attempt},...t.retry_max===null?{}:{max:t.retry_max},...t.retry_next_at===null?{}:{nextAt:t.retry_next_at}};return{faultId:t.fault_id,link:t.link,op:t.op,kind:t.kind,message:t.message,since:t.since,operation_id:t.operation_id,retry:r,...t.anchor_entry_id===null?{}:{anchorEntryId:t.anchor_entry_id},...n===void 0?{}:{providerError:n}}}var WVs,sgi,HVs,fXe=h(()=>{"use strict";Qt();fi();Rr();oge();pXe();Pf();$Q();WVs=5*6e4,sgi=["pi\u2192provider","viewer\u2194broker","relay\u2194broker","viewer\u2194crtrd","daemon\u2192node","crtr\u2192pi"],HVs=[...sgi,"broker\u2194crtrd"]});var gvn=h(()=>{"use strict"});var cgi,t7s,Q6=h(()=>{"use strict";Qt();fi();Rr();gvn();Pf();cgi=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
1730
1730
  WHERE d.destination_id = ? AND d.wake = ? AND d.state = 'pending' AND d.canceled_at IS NULL
1731
- AND NOT (d.wake = 0 AND m.kind = 'message' AND coalesce(json_extract(m.body_json, '$.start_turn'), 1) = 0)`,e7s=`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
1732
- WHERE delivery_id IN (${cgi})`});var RD,W6=h(()=>{"use strict";_o();x0();RD=["crtr:llm","crtr:act","crtr:schedule","crtr:memory:rw:user","crtr:memory:manage:user","crtr:files:rw:user:."]});var sge=h(()=>{"use strict";dd();Jo()});function yvn(t){if(!Array.isArray(t))throw new TypeError("grant scopes must be a list");return t.map(e=>{if(!e||typeof e!="object"||typeof e.scope!="string"||!["always","ask"].includes(e.mode))throw new TypeError("invalid grant scope entry");return{scope:e.scope,mode:e.mode}})}function dgi(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let{state:e,message:n,next:r,step:i}=t;return typeof e!="string"||!ugi.includes(e)||n!==void 0&&typeof n!="string"||i!==void 0&&typeof i!="string"||typeof r!="string"||!r?null:{state:e,...n===void 0?{}:{message:n},next:r,...i===void 0?{}:{step:i}}}function pgi(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t)){let i=dgi(r);i&&(e[n]=i)}return e}function fgi(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let{base_url:e,rungs:n}=t;if(typeof e!="string"||!e||!n||typeof n!="object"||Array.isArray(n))return null;let r={};for(let i of lgi){let o=n[i];typeof o=="string"&&o&&(r[i]=o)}return Object.keys(r).length?{base_url:e.replace(/\/+$/,""),rungs:r}:null}function mgi(t){return{id:t.id,runtime:t.runtime,sub:t.sub,grantee:t.grantee,rev:t.rev,scopes:yvn(JSON.parse(t.scopes_json)),resolved_scopes:yvn(JSON.parse(t.resolved_scopes_json)),spend_cap:t.spend_cap,expires_at:t.expires_at,status:t.status,revoked_at:t.revoked_at,approved_at:t.approved_at,payer:t.payer,dependencies:pgi(JSON.parse(t.dependencies_json)),run_notice_url:t.run_notice_url??null,inference_endpoint:t.inference_endpoint_json?fgi(JSON.parse(t.inference_endpoint_json)):null,synced_at:t.synced_at}}function Avn(t){if(!t||t.status!=="active")return null;try{return ggi(mgi(t))}catch(e){if(e instanceof TypeError||e instanceof SyntaxError)return null;throw e}}function hgi(t){return t.expires_at!==null&&!(Date.parse(t.expires_at)>Date.now())}function ggi(t){if(t.status!=="active"||hgi(t))return null;try{let e=t.resolved_scopes.map(({scope:n})=>YU(n));return{...t,resolved:t.resolved_scopes.flatMap(({mode:n},r)=>n==="always"?[e[r]]:[])}}catch(e){if(e instanceof TypeError||e instanceof SyntaxError)return null;throw e}}function H6(t){return Avn(ae(ir(),"SELECT * FROM grants WHERE id = ?").get(t))}function age(t,e){return Avn(ae(ir(),"SELECT * FROM grants WHERE grantee = ? AND sub = ?").get(t,e))}var ugi,lgi,DD=h(()=>{"use strict";Qt();B0();fi();sge();ugi=["not_started","pending","ready","failed","unavailable"],lgi=["ultra","strong","medium","light"]});var wvn=h(()=>{"use strict";tb()});var xvn=h(()=>{"use strict"});var bvn=h(()=>{"use strict";zs();tb()});var hXe=h(()=>{"use strict"});var Evn=h(()=>{"use strict";zs();tb();hXe();Pf()});var tb=h(()=>{"use strict";Vi();wvn();xvn();bvn();Evn();hXe()});var yXe=h(()=>{"use strict"});function cge(t,e,n){if(n.length===0)return;let r=ae(t,"INSERT INTO memory_reads (node_id, name, scope, at, type) VALUES (?, ?, ?, ?, ?)");for(let i of n)r.run(e,i.name,i.scope,i.at,i.type)}var W7s,AXe=h(()=>{"use strict";Qt();fi();W7s=720*60*60*1e3});function nb(t,e=ir()){let n=ae(e,`SELECT n.run_id, n.isolated, r.isolated AS root_isolated FROM nodes n
1731
+ AND NOT (d.wake = 0 AND m.kind = 'message' AND coalesce(json_extract(m.body_json, '$.start_turn'), 1) = 0)`,t7s=`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
1732
+ WHERE delivery_id IN (${cgi})`});var RD,W6=h(()=>{"use strict";_o();x0();RD=["crtr:llm","crtr:act","crtr:schedule","crtr:memory:rw:user","crtr:memory:manage:user","crtr:files:rw:user:."]});var sge=h(()=>{"use strict";dd();Jo()});function yvn(t){if(!Array.isArray(t))throw new TypeError("grant scopes must be a list");return t.map(e=>{if(!e||typeof e!="object"||typeof e.scope!="string"||!["always","ask"].includes(e.mode))throw new TypeError("invalid grant scope entry");return{scope:e.scope,mode:e.mode}})}function dgi(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let{state:e,message:n,next:r,step:i}=t;return typeof e!="string"||!ugi.includes(e)||n!==void 0&&typeof n!="string"||i!==void 0&&typeof i!="string"||typeof r!="string"||!r?null:{state:e,...n===void 0?{}:{message:n},next:r,...i===void 0?{}:{step:i}}}function pgi(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t)){let i=dgi(r);i&&(e[n]=i)}return e}function fgi(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let{base_url:e,rungs:n}=t;if(typeof e!="string"||!e||!n||typeof n!="object"||Array.isArray(n))return null;let r={};for(let i of lgi){let o=n[i];typeof o=="string"&&o&&(r[i]=o)}return Object.keys(r).length?{base_url:e.replace(/\/+$/,""),rungs:r}:null}function mgi(t){return{id:t.id,runtime:t.runtime,sub:t.sub,grantee:t.grantee,rev:t.rev,scopes:yvn(JSON.parse(t.scopes_json)),resolved_scopes:yvn(JSON.parse(t.resolved_scopes_json)),spend_cap:t.spend_cap,expires_at:t.expires_at,status:t.status,revoked_at:t.revoked_at,approved_at:t.approved_at,payer:t.payer,dependencies:pgi(JSON.parse(t.dependencies_json)),run_notice_url:t.run_notice_url??null,inference_endpoint:t.inference_endpoint_json?fgi(JSON.parse(t.inference_endpoint_json)):null,synced_at:t.synced_at}}function Avn(t){if(!t||t.status!=="active")return null;try{return ggi(mgi(t))}catch(e){if(e instanceof TypeError||e instanceof SyntaxError)return null;throw e}}function hgi(t){return t.expires_at!==null&&!(Date.parse(t.expires_at)>Date.now())}function ggi(t){if(t.status!=="active"||hgi(t))return null;try{let e=t.resolved_scopes.map(({scope:n})=>YU(n));return{...t,resolved:t.resolved_scopes.flatMap(({mode:n},r)=>n==="always"?[e[r]]:[])}}catch(e){if(e instanceof TypeError||e instanceof SyntaxError)return null;throw e}}function H6(t){return Avn(ae(ir(),"SELECT * FROM grants WHERE id = ?").get(t))}function age(t,e){return Avn(ae(ir(),"SELECT * FROM grants WHERE grantee = ? AND sub = ?").get(t,e))}var ugi,lgi,DD=h(()=>{"use strict";Qt();B0();fi();sge();ugi=["not_started","pending","ready","failed","unavailable"],lgi=["ultra","strong","medium","light"]});var wvn=h(()=>{"use strict";tb()});var xvn=h(()=>{"use strict"});var bvn=h(()=>{"use strict";zs();tb()});var hXe=h(()=>{"use strict"});var Evn=h(()=>{"use strict";zs();tb();hXe();Pf()});var tb=h(()=>{"use strict";Vi();wvn();xvn();bvn();Evn();hXe()});var yXe=h(()=>{"use strict"});function cge(t,e,n){if(n.length===0)return;let r=ae(t,"INSERT INTO memory_reads (node_id, name, scope, at, type) VALUES (?, ?, ?, ?, ?)");for(let i of n)r.run(e,i.name,i.scope,i.at,i.type)}var H7s,AXe=h(()=>{"use strict";Qt();fi();H7s=720*60*60*1e3});function nb(t,e=ir()){let n=ae(e,`SELECT n.run_id, n.isolated, r.isolated AS root_isolated FROM nodes n
1733
1733
  LEFT JOIN nodes r ON r.node_id = n.run_id WHERE n.node_id = ?`).get(t);if(!n){let r=ae(e,"SELECT run_id FROM deleted_isolated_nodes WHERE node_id = ?").get(t);return r?{run:r.run_id,isolated:!0}:null}return{run:n.run_id??t,isolated:n.isolated===1||n.root_isolated===1}}function uge(t,e=ir()){let n=ae(e,"SELECT registered_by FROM custom_objects WHERE object = ?").get(t);return n?.registered_by?nb(n.registered_by,e)??{run:n.registered_by,isolated:!1}:null}function lge(t,e){return t.run===e.run||!t.isolated&&!e.isolated}var j6=h(()=>{"use strict";fi()});function dge(t,e,n,r,i,o){if(e.class==="person"||r.length===0||i!==null&&i.type!=="document")return null;let s=e.launched;if(s==null||o==="read"&&i?.kind==="report"&&r[0].type==="node"&&wgi(t,e,r[0].id))return null;let a=pge(t,vvn(t,n),o,r);return s.some(c=>la(c,a))?null:a}function wgi(t,e,n){let r=e.class==="node"?nb(e.node.id,t):e.class==="person"?null:e.place??null,i=nb(n,t);return r!==null&&i!==null&&r.run===i.run}function pge(t,e,n,r){let i=r[0];return i.type!=="profile"?`crtr:memory:${n}:${e}`:`crtr:memory:${n}:${e}:profile:${vvn(t,i)}`}var vvn,fge=h(()=>{"use strict";Qt();B0();j6();vvn=(t,e)=>ae(t,"SELECT external_id FROM identities WHERE object = ?").get(e.rowid).external_id});function Cvn(t,e,n){if(e.class==="person"||n.length===0||n[0].type!=="node"||e.class==="app"&&e.place===void 0)return!0;let r=Svn.get(e);if(r===void 0&&(r=e.class==="app"?e.place:e.class==="node"?nb(e.node.id,t):e.place??uge(e.object.rowid,t),Svn.set(e,r)),r===null)return!0;let i=nb(n[0].id,t);return i===null?!r.isolated:lge(r,i)}var Ivn,Svn,Tvn=h(()=>{"use strict";B0();q6();fge();j6();Ivn={identity:fp,sync:"runtime",canRead(t,e,n,r,i){if(e.class==="person"||r.length===0)return!0;if(e.app.rowid===n.rowid)return Cvn(t,e,r)&&dge(t,e,n,r,i,"read")===null;let o=fp(t,n).external_id,s=a=>e.scopes!==null&&e.scopes.some(c=>la(c,a));return r[0].type==="node"?s(`crtr:objects:read:${o}`)||i.type==="document"&&i.kind==="report"&&s(`crtr:conversations:read:${o}`):s(pge(t,o,"read",r))},canChange(t,e,n,r,i){if(e.class==="person")return!0;if(e.app.rowid===n.rowid)return r.length===0||Cvn(t,e,r)&&dge(t,e,n,r,i,"rw")===null;if(r.length===0||r[0].type==="node")return!1;let o=pge(t,fp(t,n).external_id,"rw",r);return e.scopes!==null&&e.scopes.some(s=>la(s,o))}},Svn=new WeakMap});var kvn,Rvn=h(()=>{"use strict";Qt();B0();q6();kvn={identity:fp,sync:"runtime",canRead(t,e,n,r,i){return e.class==="person"||e.class==="object"&&e.owner.rowid===n.rowid?!0:e.scopes===null?!1:e.app.rowid===n.rowid||r.length===0?!0:r[0].type!=="document"?!1:e.scopes.some(o=>la(o,"crtr:memory:manage:user"))||i.privacy==="public"?!0:i.privacy==="private"&&e.scopes.some(o=>la(o,"crtr:memory:read_private:user"))},canChange(t,e,n,r,i){if(e.class==="person"||e.class==="object"&&e.owner.rowid===n.rowid||e.app.rowid===n.rowid||e.scopes?.some(c=>la(c,"crtr:memory:manage:user")))return!0;if(r.length===0)return e.scopes?.some(c=>la(c,"crtr:memory:rw:user"))??!1;if(r[0].type!=="document")return!1;let o=`crtr:memory:rw:user:${i.name}`;if(e.scopes===null||!e.scopes.some(c=>la(c,o)))return!1;let s=ae(t,`SELECT author.type, author.owner AS app FROM revisions r JOIN objects author ON author.rowid = r.author
1734
1734
  WHERE r.document = ? ORDER BY r.number, r.created_at LIMIT 1`).get(r[0].rowid);return s?s.type==="person"||s.app===e.app.rowid?!0:ae(t,`SELECT g.resolved_scopes_json FROM grants g JOIN identities i ON i.external_id = g.grantee
1735
1735
  WHERE i.object = ? AND i.scheme = 'app'`).all(s.app).some(({resolved_scopes_json:c})=>JSON.parse(c).some(({scope:u,mode:l})=>l==="always"&&la(u,"crtr:memory:manage:user"))):!1}}});import{join as wXe,relative as mge,resolve as xgi,sep as hge}from"node:path";function pU(t,e){let n=mge(t,e);return n===""||n!==".."&&!n.startsWith(`..${hge}`)&&!n.startsWith(hge)}function xXe(t,e,n){let r=xgi(e);if(t===null||process.platform!=="linux"&&t.app==="app:terminal"){if(process.platform!=="linux")return{root:"/"};let p=[R9(),kh()].find(f=>pU(f,r));return p?{root:p}:{missing:null}}let i=Ga(t.app);if(t.run&&pU(i.root,r)){let[p,f]=mge(i.root,r).split(hge);if(p==="nodes"&&f)return t.run.reaches(f)?{root:wXe(i.nodes,f)}:{hidden:!0};if(t.run.isolated)return{hidden:!0}}for(let p of[i.files,i.nodes])if(pU(p,r))return{root:p};let o=p=>t.resolved.some(f=>la(f,p))&&(t.launched===null||t.launched.some(f=>la(f,p))),s=(p,f)=>{let m=mge(f,r)||".",g=x=>x.flatMap(E=>{let _=/^crtr:files:(read|rw):(user|app:[A-Za-z0-9_-]{1,64}):(.+)$/.exec(E);return!_||_[2]!==p||n==="rw"&&_[1]!=="rw"?[]:_[3]==="."||_[3]===m||m.startsWith(`${_[3]}/`)?[wXe(f,_[3]==="."?"":_[3])]:[]}),y=g(t.resolved),w=t.launched===null?y:g(t.launched);return!y.length||!w.length?{missing:`crtr:files:${n}:${p}:${m}`}:{root:[...y,...w].reduce((x,E)=>E.length>x.length?E:x)}};if(pU(r1(),r))return s("user",r1());let[a,c,u,l]=mge(kh(),r).split(hge);if(!pU(kh(),r)||!a||!/^[A-Za-z0-9_-]{1,64}$/.test(a))return{missing:null};let d=Ga(`app:${a}`);return c==="files"?s(`app:${a}`,d.files):c!=="nodes"||n!=="read"?{missing:null}:o(`crtr:objects:read:app:${a}`)?{root:d.nodes}:u&&l==="attachments"&&o(`crtr:conversations:read:app:${a}`)?{root:wXe(d.nodes,u,l)}:{missing:`crtr:objects:read:app:${a}`}}var gge=h(()=>{"use strict";B0();Vi()});function yge(t,e,n,r){if(e.class==="object")return e.repos.some(s=>s.rowid===n.rowid);if(e.class!=="node")return!1;let i=[...e.checkouts,...e.projectCheckouts].filter(s=>s.repo.rowid===n.rowid);if(i.length===0)return!1;let o={app:fp(t,e.app).external_id,resolved:e.scopes??[],launched:null};return i.some(s=>"root"in xXe(o,s.root,r))}var Dvn,bXe=h(()=>{"use strict";gge();q6();Dvn={identity:fp,sync:"repo-ref",canRead(t,e,n,r){return e.class==="person"||r.length===0?!0:yge(t,e,n,"read")},canChange(t,e,n,r,i){return i.privacy!=="public"?!1:e.class==="person"?!0:yge(t,e,n,"rw")}}});function fp(t,e){let n=ae(t,"SELECT object, scheme, external_id FROM identities WHERE object = ?").get(e.rowid);if(!n)throw new Error(`${e.type} ${e.id} has no identity`);return n}var Mvn,q6=h(()=>{"use strict";Qt();Tvn();Rvn();bXe();Mvn={person:kvn,app:Ivn,repo:Dvn}});function Age(t,e){return ae(t,`WITH RECURSIVE chain(rowid, depth) AS (
@@ -1739,10 +1739,10 @@ ${u}`,"1").then(l=>{let d=a.options[Number.parseInt(l,10)-1]?.id;if(d===void 0)t
1739
1739
  ) SELECT o.* FROM chain c CROSS JOIN objects o WHERE o.rowid = c.rowid ORDER BY c.depth`).all(e.rowid)}function Ovn(t,e){let n=Age(t,e),r=n.length?n[n.length-1]:e,i=Mvn[r.type];if(!i)throw new Error(`${e.type} ${e.id} has no space: its owner chain ends at ${r.type} ${r.id}`);let o=n.length?[...n.slice(0,-1).reverse(),e]:[];return{space:r,path:o,impl:i}}function bgi(t,e){return e.type!=="document"?!1:ae(t,"SELECT source_path FROM documents WHERE object = ?").get(e.rowid)?.source_path!=null}function Nvn(t,e){return ae(t,`SELECT a.* FROM objects a WHERE a.type = 'app' AND a.deleted_at IS NULL AND EXISTS (
1740
1740
  SELECT 1 FROM objects o JOIN documents d ON d.object = o.rowid
1741
1741
  WHERE o.owner = a.rowid AND o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL)
1742
- ORDER BY a.name = 'crtr', a.name`).all().filter(r=>EXe(t,e,r))}function EXe(t,e,n){return n.type==="app"}function _gi(t,e,n){let r=`${fp(t,n).external_id.replace(/^app:/,"")}:`;return e.some(i=>i.startsWith(r)&&!i.slice(r.length).includes(":"))}function Pvn(t,e,n){return e.class==="person"?!0:e.class==="object"?e.owner.rowid===n.rowid:e.class==="app"?e.app.rowid===n.rowid||n.type==="profile"&&n.owner===e.app.rowid:e.app.rowid===n.rowid||n.type==="profile"&&e.profile?.rowid===n.rowid||n.type==="repo"&&yge(t,e,n,"rw")}function Lvn(t,e,n){if(e.class!=="node"&&!(e.class==="app"&&e.place!==void 0))return!0;let r=e.class==="app"?e.place:nb(e.node.id,t);if(r===null)return!0;let i=uge(n.rowid,t);return i===null?!r.isolated:lge(r,i)}function vgi(t,{space:e,path:n},r,i){let o=[];if(e.type==="person")o.push("user");else if(e.type==="app"&&n.length>0){let s=n[0];if(s.type==="profile")n.length>1&&o.push(`profile:${fp(t,s).external_id}`);else if(s.type==="node"||_Xe(s)){let a=fp(t,e).external_id;a!==i&&o.push(a)}}return r.type==="node"&&o.push("node"),o}function vXe(t,e,n,r,i){if(e.class==="person"||e.scopes===null)return!1;let o=e.scopes;if(o.length===0||r.space.type==="app"&&e.app.rowid===r.space.rowid)return!1;let s=fp(t,e.app).external_id;return vgi(t,r,i,s).some(a=>{let c=`crtr:objects:${n}:${a}`;return o.some(u=>la(u,c))})}function Sgi(t,e,n,r){return e.class==="person"||e.scopes===null?!1:vXe(t,e,n,Ovn(t,r),r)}function Bvn(t,e,n,r,i){let o=r.owner===null?null:t.prepare("SELECT * FROM objects WHERE rowid = ?").get(r.owner)??null;if(o===null)return!1;let s={class:"app",app:e,scopes:n??[]};return Pvn(t,s,o)?n===null||Sgi(t,s,"link",i):!1}function nl(t,e,n){return SXe(t,n)(e)}function SXe(t,e){let n=null,r=null;return i=>{if(i.class==="person")return!0;if(n??=Ovn(t,e),n.space.type==="app"&&n.path.length>0){if(r??=bgi(t,e),r&&EXe(t,i,n.space))return!0;if(_Xe(e)){if(i.app.rowid===n.space.rowid&&!Lvn(t,i,e))return!1;if(i.app.rowid!==n.space.rowid&&i.scopes!==null&&EXe(t,i,n.space)&&(e.privacy==="public"||Egi(i)&&_gi(t,i.scopes,n.space)))return!0}}return vXe(t,i,"read",n,e)||i.class==="object"&&_Xe(i.object)&&vXe(t,i,"watch",n,e)?!0:n.impl.canRead(t,i,n.space,n.path,e)}}var Egi,_Xe,lh=h(()=>{"use strict";Qt();B0();j6();fge();q6();bXe();Egi=t=>t.class!=="app"||t.place!==void 0;_Xe=t=>t.type.includes(".")});function G6(t){let e=t.match(Cgi);if(!e)return{data:null,body:t,raw:""};let n=e[1],r=t.slice(e[0].length);return{data:Igi(n),body:r,raw:n}}function Igi(t){return Tgi((0,$vn.parse)(t))}function Tgi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}var $vn,Cgi,wge=h(()=>{"use strict";$vn=Kt(S4e(),1),Cgi=/^---\s*\r?\n([\s\S]*?)\r?\n---\s*\r?\n?/});import{closeSync as C9s,existsSync as I9s,fsyncSync as T9s,mkdirSync as k9s,openSync as R9s,readFileSync as Fvn,renameSync as D9s,writeSync as M9s}from"node:fs";import{join as kgi}from"node:path";function Rgi(t){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`invalid body hash: ${t}`);return kgi(Xo(),"bodies",t.slice(0,2),t)}function xge(t){try{return Fvn(Rgi(t),"utf8")}catch(e){throw e.code==="ENOENT"?Of(`no body ${t}`):e}}function OS(t,e){return e===null?xge(t):G6(Fvn(e,"utf8")).body}var NS=h(()=>{"use strict";Co();Rr();wge()});function fU(t,e){let n=ae(t,"SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get(),r=Nvn(t,e),i=e.class==="node"?[e.node,...e.repos,...e.projectRepos,e.profile,e.app]:e.class==="app"?[e.app]:e.class==="object"?[e.owner,...e.repos,e.app]:[],o=new Set;return[...i,n,...r].filter(s=>!!s&&!o.has(s.rowid)&&!!o.add(s.rowid))}function z6(t,e,n,r){return t.prepare(`SELECT * FROM objects WHERE (type = 'document' OR instr(type, '.') > 0) AND owner = ? AND name = ? AND home_machine IS NULL
1742
+ ORDER BY a.name = 'crtr', a.name`).all().filter(r=>EXe(t,e,r))}function EXe(t,e,n){return n.type==="app"}function _gi(t,e,n){let r=`${fp(t,n).external_id.replace(/^app:/,"")}:`;return e.some(i=>i.startsWith(r)&&!i.slice(r.length).includes(":"))}function Pvn(t,e,n){return e.class==="person"?!0:e.class==="object"?e.owner.rowid===n.rowid:e.class==="app"?e.app.rowid===n.rowid||n.type==="profile"&&n.owner===e.app.rowid:e.app.rowid===n.rowid||n.type==="profile"&&e.profile?.rowid===n.rowid||n.type==="repo"&&yge(t,e,n,"rw")}function Lvn(t,e,n){if(e.class!=="node"&&!(e.class==="app"&&e.place!==void 0))return!0;let r=e.class==="app"?e.place:nb(e.node.id,t);if(r===null)return!0;let i=uge(n.rowid,t);return i===null?!r.isolated:lge(r,i)}function vgi(t,{space:e,path:n},r,i){let o=[];if(e.type==="person")o.push("user");else if(e.type==="app"&&n.length>0){let s=n[0];if(s.type==="profile")n.length>1&&o.push(`profile:${fp(t,s).external_id}`);else if(s.type==="node"||_Xe(s)){let a=fp(t,e).external_id;a!==i&&o.push(a)}}return r.type==="node"&&o.push("node"),o}function vXe(t,e,n,r,i){if(e.class==="person"||e.scopes===null)return!1;let o=e.scopes;if(o.length===0||r.space.type==="app"&&e.app.rowid===r.space.rowid)return!1;let s=fp(t,e.app).external_id;return vgi(t,r,i,s).some(a=>{let c=`crtr:objects:${n}:${a}`;return o.some(u=>la(u,c))})}function Sgi(t,e,n,r){return e.class==="person"||e.scopes===null?!1:vXe(t,e,n,Ovn(t,r),r)}function Bvn(t,e,n,r,i){let o=r.owner===null?null:t.prepare("SELECT * FROM objects WHERE rowid = ?").get(r.owner)??null;if(o===null)return!1;let s={class:"app",app:e,scopes:n??[]};return Pvn(t,s,o)?n===null||Sgi(t,s,"link",i):!1}function nl(t,e,n){return SXe(t,n)(e)}function SXe(t,e){let n=null,r=null;return i=>{if(i.class==="person")return!0;if(n??=Ovn(t,e),n.space.type==="app"&&n.path.length>0){if(r??=bgi(t,e),r&&EXe(t,i,n.space))return!0;if(_Xe(e)){if(i.app.rowid===n.space.rowid&&!Lvn(t,i,e))return!1;if(i.app.rowid!==n.space.rowid&&i.scopes!==null&&EXe(t,i,n.space)&&(e.privacy==="public"||Egi(i)&&_gi(t,i.scopes,n.space)))return!0}}return vXe(t,i,"read",n,e)||i.class==="object"&&_Xe(i.object)&&vXe(t,i,"watch",n,e)?!0:n.impl.canRead(t,i,n.space,n.path,e)}}var Egi,_Xe,lh=h(()=>{"use strict";Qt();B0();j6();fge();q6();bXe();Egi=t=>t.class!=="app"||t.place!==void 0;_Xe=t=>t.type.includes(".")});function G6(t){let e=t.match(Cgi);if(!e)return{data:null,body:t,raw:""};let n=e[1],r=t.slice(e[0].length);return{data:Igi(n),body:r,raw:n}}function Igi(t){return Tgi((0,$vn.parse)(t))}function Tgi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}var $vn,Cgi,wge=h(()=>{"use strict";$vn=Kt(S4e(),1),Cgi=/^---\s*\r?\n([\s\S]*?)\r?\n---\s*\r?\n?/});import{closeSync as I9s,existsSync as T9s,fsyncSync as k9s,mkdirSync as R9s,openSync as D9s,readFileSync as Fvn,renameSync as M9s,writeSync as O9s}from"node:fs";import{join as kgi}from"node:path";function Rgi(t){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`invalid body hash: ${t}`);return kgi(Xo(),"bodies",t.slice(0,2),t)}function xge(t){try{return Fvn(Rgi(t),"utf8")}catch(e){throw e.code==="ENOENT"?Of(`no body ${t}`):e}}function OS(t,e){return e===null?xge(t):G6(Fvn(e,"utf8")).body}var NS=h(()=>{"use strict";Co();Rr();wge()});function fU(t,e){let n=ae(t,"SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get(),r=Nvn(t,e),i=e.class==="node"?[e.node,...e.repos,...e.projectRepos,e.profile,e.app]:e.class==="app"?[e.app]:e.class==="object"?[e.owner,...e.repos,e.app]:[],o=new Set;return[...i,n,...r].filter(s=>!!s&&!o.has(s.rowid)&&!!o.add(s.rowid))}function z6(t,e,n,r,i=!1){return t.prepare(`SELECT * FROM objects WHERE (type = 'document' OR instr(type, '.') > 0) AND owner = ? AND name = ? AND home_machine IS ${i?"NOT NULL":"NULL"}
1743
1743
  AND deleted_at IS ${r?"NOT NULL ORDER BY deleted_at DESC":"NULL"}`).all(e.rowid,n)}function Dgi(t,e,n){return n==="node"?ae(t,"SELECT * FROM objects WHERE type = 'node' AND id = ?").all(e):n?ae(t,"SELECT * FROM objects WHERE type = ? AND (name = ? OR id = ?) AND home_machine IS NULL").all(n,e,e):ae(t,`SELECT * FROM objects WHERE (type = 'node' AND id = ?)
1744
1744
  OR (type IN ('person','app','repo','profile') AND (name = ? OR id = ?) AND home_machine IS NULL)`).all(e,e,e)}function bge(t,e,n,r){let i=n.trim().replace(/^\[\[(.*)\]\]$/,"$1").trim(),o=/^([^:/]+):reports\/(.+?)(?:\.md)?$/.exec(i);o&&!Uvn.test(i)&&(i=`${o[1]}/reports/${o[2]}`);let s=r?.readable??(d=>nl(t,e,d)),a=rl(t,i);if(a&&s(a))return a.deleted_at?{deleted:a}:{object:a};let c=r?.view??fU(t,e);for(let d of c){let p=z6(t,d,i,!1).find(s);if(p)return{object:p}}let u=Uvn.exec(i),l=i.indexOf("/");if(u||l>0){let d=u?u[2]:i.slice(0,l),p=u?u[3]:i.slice(l+1),f=Dgi(t,d,u?.[1]),m=x=>{let E=c.findIndex(_=>_.rowid===x.rowid);return E<0?1/0:E},g=f.filter(x=>m(x)<1/0).sort((x,E)=>m(x)-m(E));for(let x of g){let E=z6(t,x,p,!1).find(s);if(E)return{object:E}}let y=f.flatMap(x=>z6(t,x,p,!1)).filter(s);if(y.length===1)return{object:y[0]};if(y.length>1)return{ambiguous:y};let w=f.flatMap(x=>z6(t,x,p,!0)).find(s);return w?{deleted:w}:!u&&f.length===0&&SC(d)?{remote:i}:{missing:!0}}for(let d of c){let p=z6(t,d,i,!0).find(s);if(p)return{deleted:p}}return{missing:!0}}var Uvn,V6=h(()=>{"use strict";Qt();Rr();lh();fs();Uvn=/^(person|app|repo|profile|node):([^/]+)\/(.+)$/});function Qvn(t){return{rowid:t.rowid,object:t.object,owner:t.owner,position:t.position,on:t.on_event,deliver:t.deliver,...t.match_json!==null?{match:JSON.parse(t.match_json)}:{},...t.match_frontmatter_json!==null?{matchFrontmatter:JSON.parse(t.match_frontmatter_json)}:{},...t.if_json!==null?{if:JSON.parse(t.if_json)}:{}}}function mU(t,e){return ae(t,"SELECT * FROM rules WHERE object = ? ORDER BY position").all(e.rowid).map(Qvn)}function Wvn(t,e,n){if(e.length===0||n.length===0)return[];let r=`SELECT * FROM rules WHERE on_event IN (${e.map(()=>"?").join(",")})
1745
- AND owner IN (${n.map(()=>"?").join(",")}) ORDER BY object, position`;return t.prepare(r).all(...e,...n).map(Qvn)}var Ege=h(()=>{"use strict";Qt()});var Hvn=h(()=>{"use strict"});function CXe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function _ge(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 jvn(t){return`${CXe(t.mode)} ${t.kind}`}var K6=h(()=>{"use strict"});var vge=h(()=>{"use strict";Qt();fi();Vx()});var IXe=h(()=>{"use strict";Qt();fi();DD();Jo();vge()});var Gvn=h(()=>{"use strict";Qt();fi();rw();Vx();IXe()});function MD(t){if(typeof t=="string")return JSON.parse(t)}function zvn(t){if(t===void 0)return null;let e=MD(t.sweep_observed_json),n=t.attempts,r=e===void 0?void 0:{reason:t.sweep_reason,...t.sweep_detail===null?{}:{detail:t.sweep_detail},observed:e,attempts:n,last_attempt:t.sweep_last_at,next_attempt:t.next_attempt_at,...t.quarantined===1?{quarantined:!0}:{}};return{state:t.state,...t.cleanup_state===null?{}:{cleanup:t.cleanup_state},path:t.path,branch:t.branch,repo_root:t.repo_root,base_ref:t.base_ref,base_sha:t.base_sha,created:t.created_at,...t.closed_at===null?{}:{closed:t.closed_at},...MD(t.abandoned_json)===void 0?{}:{abandoned:MD(t.abandoned_json)},...MD(t.land_intent_json)===void 0?{}:{land_intent:MD(t.land_intent_json)},...r===void 0?{}:{sweep:r},...MD(t.disposal_json)===void 0?{}:{disposal:MD(t.disposal_json)}}}function Vvn(t){return zvn(ae(ir(),"SELECT * FROM worktrees WHERE node_id = ?").get(t))}var Sge=h(()=>{"use strict";Qt();fi()});function Ogi(){let t=new Map;for(let e of Jvn()){let n=e.requester_node_id,r=t.get(n);r===void 0?t.set(n,[e.title]):r.push(e.title)}return t}function Kvn(t){let e=Ogi();return Object.fromEntries(t.map(n=>[n,e.get(n)?.length??0]))}var Yvn=h(()=>{"use strict";J6();v0()});var TXe,RKs,Xvn=h(()=>{"use strict";v0();Yvn();Jo();Sme();u6();_o();Co();TXe=class{async getNode(e){return td(e)}async getRow(e){return OD(e)}async listNodes(e){return Cge(e)}async subscriptionsOf(e){return Ige(e)}async subscribersOf(e){return kXe(e)}async view(e){return Y6(e)}async ticketCountsForNodes(e){return Kvn([...e])}async ticketCountsForView(e){return this.ticketCountsForNodes([e,...Y6(e)])}async hasActiveLiveSubscription(e){return RXe(e)}},RKs=new TXe});var Tge=h(()=>{"use strict";Qt();lh();fs()});function ND(t){return Array.isArray(t)?t:t===void 0?[]:[t]}function rb(t,e){return t===e?!0:(typeof t=="number"||typeof t=="string")&&(typeof e=="number"||typeof e=="string")?String(t)===String(e):!1}function Zvn(t,e){if(t&&typeof t=="object"&&e in t)return t[e];if(!e.includes("."))return;let n=t;for(let r of e.split(".")){if(n==null||typeof n!="object")return;n=n[r]}return n}function Ngi(t,e){if(typeof t!="string")return null;try{return new RegExp(t,e)}catch{return null}}function DXe(t,e,n){let r=ND(e);switch(t){case"eq":return Array.isArray(e)?e.some(i=>rb(i,n)):rb(e,n);case"ne":return!DXe("eq",e,n);case"in":return ND(n).some(i=>r.some(o=>rb(o,i)));case"nin":return!DXe("in",e,n);case"exists":return e!==void 0==(n!==!1);case"contains":return r.some(i=>rb(i,n));case"containsAll":return ND(n).every(i=>r.some(o=>rb(o,i)));case"containsAny":return ND(n).some(i=>r.some(o=>rb(o,i)));case"matches":case"imatches":{let i=Ngi(n,t==="imatches"?"i":"");return i?r.some(o=>typeof o=="string"||typeof o=="number"?i.test(String(o)):!1):!1}case"gt":case"gte":case"lt":case"lte":{let i=Number(e),o=Number(n);return Number.isNaN(i)||Number.isNaN(o)?!1:t==="gt"?i>o:t==="gte"?i>=o:t==="lt"?i<o:i<=o}default:return!1}}function eSn(t,e){if(e===null||["string","number","boolean"].includes(typeof e))return Array.isArray(t)?t.some(n=>rb(n,e)):rb(t,e);if(Array.isArray(e)){let n=ND(t);return e.some(r=>n.some(i=>rb(i,r)))}return e&&typeof e=="object"?Object.entries(e).every(([n,r])=>DXe(n,t,r)):!1}function ib(t,e){if(t==null)return!1;if(Array.isArray(t))return t.every(o=>ib(o,e));if(typeof t!="object")return!1;let n=t;if("all"in n||"any"in n||"not"in n){let o=!0;"all"in n&&(o=o&&ND(n.all).every(s=>ib(s,e))),"any"in n&&(o=o&&ND(n.any).some(s=>ib(s,e))),"not"in n&&(o=o&&!ib(n.not,e));for(let s of Object.keys(n))s==="all"||s==="any"||s==="not"||(o=o&&eSn(Zvn(e,s),n[s]));return o}let i=Object.keys(n);return i.length===0?!1:i.every(o=>eSn(Zvn(e,o),n[o]))}var MXe=h(()=>{"use strict"});var OXe=h(()=>{"use strict";Vi();Bme();Vx();vge()});var NXe=h(()=>{"use strict";_o();DD();Vi();gge();gge()});var tSn=h(()=>{"use strict";Vi();Rr();vge();NXe()});var PXe=h(()=>{"use strict"});var nSn=h(()=>{"use strict";Vi()});async function rSn(t,e="SIGKILL",n){if(!("ok"in await Lme({operation:"stop",pid:t,signal:e,...n===void 0?{}:{nodeId:n}})))throw new Error("launcher did not stop process")}var LXe=h(()=>{"use strict";sge();v0();Rr();Vi();DD();Jo();Pf();OXe();tSn();PXe();nSn();Bme();Vx()});function Bgi(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="string"):null}catch{return null}}function $gi(t){return{cron_id:t.cron_id,name:t.name,created_by:t.created_by??null,grantee:t.grantee,sub:t.sub??"user:local",grant_id:t.grant_id??null,scopes:Bgi(t.scopes_json),origin_run_id:t.origin_run_id??null,run_execution_id:t.run_execution_id??null,isolated:Number(t.isolated)!==0,command:t.command,fire_at:t.fire_at,recur:t.recur??null,tz:t.tz??null,expires_at:t.expires_at??null,anchor_node:t.anchor_node??null,cancel_on_wake:Number(t.cancel_on_wake)!==0,cwd:t.cwd,env_json:t.env_json??null,profile:t.profile??null,scope:t.scope,run_timeout_s:Number(t.run_timeout_s),overlap:t.overlap,on_output:t.on_output,sink:t.sink,tier:t.tier,last_output_hash:t.last_output_hash??null,held:Number(t.held)!==0,last_poke_at:t.last_poke_at??null,state:t.state,run_state:t.run_state,run_pid:t.run_pid??null,run_pid_identity:t.run_pid_identity??null,run_started_at:t.run_started_at??null,run_lease_owner:t.run_lease_owner??null,run_out_of_band:Number(t.run_out_of_band)!==0,created:t.created,updated:t.updated}}async function Fgi(t,e="SIGTERM"){if(!BXe(t))return!1;if(process.platform!=="linux")return hlt(t.run_pid,e),!0;try{return await rSn(t.run_pid,e,t.anchor_node??void 0),!0}catch(n){if(!BXe(t))return!1;throw n}}function Ugi(t,e="SIGTERM"){return BXe(t)?(Fgi(t,e).catch(n=>{za({level:"error",event:"cron.run.stop_failed",error:n,fields:{cron_id:t.cron_id,pid:t.run_pid}})}),!0):!1}function BXe(t){let e=t.run_pid;if(e==null||t.run_pid_identity==null)return!1;let n=$be([e]);if(n===null)return!1;let r=n.get(e);return r===void 0?!1:Pbe(r,t.run_pid_identity)}function $Xe(t){return Fa(e=>{let n=ae(e,"SELECT * FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1").all(t).map($gi);for(let r of n)r.run_state==="running"&&Ugi(r),ae(e,"DELETE FROM crons WHERE cron_id = ?").run(r.cron_id);return n.map(r=>r.cron_id)})}var kge=h(()=>{"use strict";Qt();fi();rw();Su();LXe();Pf()});function FXe(t,e,n,r=ir()){if(e===null)return!1;let i=ae(r,"SELECT wait_id, generation FROM waits WHERE node_id = ? AND kind = 'controller' AND target_id = ? AND satisfied_at IS NULL").get(t,e);return i===void 0?!1:Number(ae(r,"UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(n,i.wait_id,i.generation).changes)===1}var UXe=h(()=>{"use strict";Qt();fi()});import{existsSync as Qgi,mkdirSync as Wgi,renameSync as Hgi,writeFileSync as jgi}from"node:fs";import{randomBytes as qgi,randomUUID as Ggi}from"node:crypto";import{join as zgi}from"node:path";function QXe(){let t;do t=qgi(16).toString("hex");while(t==="00000000000000000000000000000000");return t}function Vgi(t,e){let n=JSON.stringify(t);if(n===void 0)throw new TypeError(`${e} must be JSON-serializable`);return n}function iSn(t,e){return e!=="normal"&&e!=="deferred"?e:OD(t)?.lifecycle==="terminal"?"urgent":e}function Kgi(t,e,n){let r=Nat(t);Qgi(r)||Wgi(r,{recursive:!0});let i=e.replace(/[^0-9]/g,""),o=zgi(r,`${i}-${Ggi().slice(0,6)}.md`),s=`${o}.tmp`;return jgi(s,n,"utf8"),ZM(s),Hgi(s,o),hy(r),o}function Ygi(t){if(typeof t!="object"||t===null)return"";let e=t.body;return typeof e=="string"?e.trim():""}function WXe(t,e){let n=e.messageId??QXe(),r=Number(ae(t,"UPDATE message_sequence SET seq = seq + 1 WHERE id = 1 RETURNING seq").get().seq);return ae(t,`INSERT INTO messages
1745
+ AND owner IN (${n.map(()=>"?").join(",")}) ORDER BY object, position`;return t.prepare(r).all(...e,...n).map(Qvn)}var Ege=h(()=>{"use strict";Qt()});var Hvn=h(()=>{"use strict"});function CXe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function _ge(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 jvn(t){return`${CXe(t.mode)} ${t.kind}`}var K6=h(()=>{"use strict"});var vge=h(()=>{"use strict";Qt();fi();Vx()});var IXe=h(()=>{"use strict";Qt();fi();DD();Jo();vge()});var Gvn=h(()=>{"use strict";Qt();fi();rw();Vx();IXe()});function MD(t){if(typeof t=="string")return JSON.parse(t)}function zvn(t){if(t===void 0)return null;let e=MD(t.sweep_observed_json),n=t.attempts,r=e===void 0?void 0:{reason:t.sweep_reason,...t.sweep_detail===null?{}:{detail:t.sweep_detail},observed:e,attempts:n,last_attempt:t.sweep_last_at,next_attempt:t.next_attempt_at,...t.quarantined===1?{quarantined:!0}:{}};return{state:t.state,...t.cleanup_state===null?{}:{cleanup:t.cleanup_state},path:t.path,branch:t.branch,repo_root:t.repo_root,base_ref:t.base_ref,base_sha:t.base_sha,created:t.created_at,...t.closed_at===null?{}:{closed:t.closed_at},...MD(t.abandoned_json)===void 0?{}:{abandoned:MD(t.abandoned_json)},...MD(t.land_intent_json)===void 0?{}:{land_intent:MD(t.land_intent_json)},...r===void 0?{}:{sweep:r},...MD(t.disposal_json)===void 0?{}:{disposal:MD(t.disposal_json)}}}function Vvn(t){return zvn(ae(ir(),"SELECT * FROM worktrees WHERE node_id = ?").get(t))}var Sge=h(()=>{"use strict";Qt();fi()});function Ogi(){let t=new Map;for(let e of Jvn()){let n=e.requester_node_id,r=t.get(n);r===void 0?t.set(n,[e.title]):r.push(e.title)}return t}function Kvn(t){let e=Ogi();return Object.fromEntries(t.map(n=>[n,e.get(n)?.length??0]))}var Yvn=h(()=>{"use strict";J6();v0()});var TXe,DKs,Xvn=h(()=>{"use strict";v0();Yvn();Jo();Sme();u6();_o();Co();TXe=class{async getNode(e){return td(e)}async getRow(e){return OD(e)}async listNodes(e){return Cge(e)}async subscriptionsOf(e){return Ige(e)}async subscribersOf(e){return kXe(e)}async view(e){return Y6(e)}async ticketCountsForNodes(e){return Kvn([...e])}async ticketCountsForView(e){return this.ticketCountsForNodes([e,...Y6(e)])}async hasActiveLiveSubscription(e){return RXe(e)}},DKs=new TXe});var Tge=h(()=>{"use strict";Qt();lh();fs()});function ND(t){return Array.isArray(t)?t:t===void 0?[]:[t]}function rb(t,e){return t===e?!0:(typeof t=="number"||typeof t=="string")&&(typeof e=="number"||typeof e=="string")?String(t)===String(e):!1}function Zvn(t,e){if(t&&typeof t=="object"&&e in t)return t[e];if(!e.includes("."))return;let n=t;for(let r of e.split(".")){if(n==null||typeof n!="object")return;n=n[r]}return n}function Ngi(t,e){if(typeof t!="string")return null;try{return new RegExp(t,e)}catch{return null}}function DXe(t,e,n){let r=ND(e);switch(t){case"eq":return Array.isArray(e)?e.some(i=>rb(i,n)):rb(e,n);case"ne":return!DXe("eq",e,n);case"in":return ND(n).some(i=>r.some(o=>rb(o,i)));case"nin":return!DXe("in",e,n);case"exists":return e!==void 0==(n!==!1);case"contains":return r.some(i=>rb(i,n));case"containsAll":return ND(n).every(i=>r.some(o=>rb(o,i)));case"containsAny":return ND(n).some(i=>r.some(o=>rb(o,i)));case"matches":case"imatches":{let i=Ngi(n,t==="imatches"?"i":"");return i?r.some(o=>typeof o=="string"||typeof o=="number"?i.test(String(o)):!1):!1}case"gt":case"gte":case"lt":case"lte":{let i=Number(e),o=Number(n);return Number.isNaN(i)||Number.isNaN(o)?!1:t==="gt"?i>o:t==="gte"?i>=o:t==="lt"?i<o:i<=o}default:return!1}}function eSn(t,e){if(e===null||["string","number","boolean"].includes(typeof e))return Array.isArray(t)?t.some(n=>rb(n,e)):rb(t,e);if(Array.isArray(e)){let n=ND(t);return e.some(r=>n.some(i=>rb(i,r)))}return e&&typeof e=="object"?Object.entries(e).every(([n,r])=>DXe(n,t,r)):!1}function ib(t,e){if(t==null)return!1;if(Array.isArray(t))return t.every(o=>ib(o,e));if(typeof t!="object")return!1;let n=t;if("all"in n||"any"in n||"not"in n){let o=!0;"all"in n&&(o=o&&ND(n.all).every(s=>ib(s,e))),"any"in n&&(o=o&&ND(n.any).some(s=>ib(s,e))),"not"in n&&(o=o&&!ib(n.not,e));for(let s of Object.keys(n))s==="all"||s==="any"||s==="not"||(o=o&&eSn(Zvn(e,s),n[s]));return o}let i=Object.keys(n);return i.length===0?!1:i.every(o=>eSn(Zvn(e,o),n[o]))}var MXe=h(()=>{"use strict"});var OXe=h(()=>{"use strict";Vi();Bme();Vx();vge()});var NXe=h(()=>{"use strict";_o();DD();Vi();gge();gge()});var tSn=h(()=>{"use strict";Vi();Rr();vge();NXe()});var PXe=h(()=>{"use strict"});var nSn=h(()=>{"use strict";Vi()});async function rSn(t,e="SIGKILL",n){if(!("ok"in await Lme({operation:"stop",pid:t,signal:e,...n===void 0?{}:{nodeId:n}})))throw new Error("launcher did not stop process")}var LXe=h(()=>{"use strict";sge();v0();Rr();Vi();DD();Jo();Pf();OXe();tSn();PXe();nSn();Bme();Vx()});function Bgi(t){if(typeof t!="string")return null;try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="string"):null}catch{return null}}function $gi(t){return{cron_id:t.cron_id,name:t.name,created_by:t.created_by??null,grantee:t.grantee,sub:t.sub??"user:local",grant_id:t.grant_id??null,scopes:Bgi(t.scopes_json),origin_run_id:t.origin_run_id??null,run_execution_id:t.run_execution_id??null,isolated:Number(t.isolated)!==0,command:t.command,fire_at:t.fire_at,recur:t.recur??null,tz:t.tz??null,expires_at:t.expires_at??null,anchor_node:t.anchor_node??null,cancel_on_wake:Number(t.cancel_on_wake)!==0,cwd:t.cwd,env_json:t.env_json??null,profile:t.profile??null,scope:t.scope,run_timeout_s:Number(t.run_timeout_s),overlap:t.overlap,on_output:t.on_output,sink:t.sink,tier:t.tier,last_output_hash:t.last_output_hash??null,held:Number(t.held)!==0,last_poke_at:t.last_poke_at??null,state:t.state,run_state:t.run_state,run_pid:t.run_pid??null,run_pid_identity:t.run_pid_identity??null,run_started_at:t.run_started_at??null,run_lease_owner:t.run_lease_owner??null,run_out_of_band:Number(t.run_out_of_band)!==0,created:t.created,updated:t.updated}}async function Fgi(t,e="SIGTERM"){if(!BXe(t))return!1;if(process.platform!=="linux")return hlt(t.run_pid,e),!0;try{return await rSn(t.run_pid,e,t.anchor_node??void 0),!0}catch(n){if(!BXe(t))return!1;throw n}}function Ugi(t,e="SIGTERM"){return BXe(t)?(Fgi(t,e).catch(n=>{za({level:"error",event:"cron.run.stop_failed",error:n,fields:{cron_id:t.cron_id,pid:t.run_pid}})}),!0):!1}function BXe(t){let e=t.run_pid;if(e==null||t.run_pid_identity==null)return!1;let n=$be([e]);if(n===null)return!1;let r=n.get(e);return r===void 0?!1:Pbe(r,t.run_pid_identity)}function $Xe(t){return Fa(e=>{let n=ae(e,"SELECT * FROM crons WHERE anchor_node = ? AND cancel_on_wake = 1").all(t).map($gi);for(let r of n)r.run_state==="running"&&Ugi(r),ae(e,"DELETE FROM crons WHERE cron_id = ?").run(r.cron_id);return n.map(r=>r.cron_id)})}var kge=h(()=>{"use strict";Qt();fi();rw();Su();LXe();Pf()});function FXe(t,e,n,r=ir()){if(e===null)return!1;let i=ae(r,"SELECT wait_id, generation FROM waits WHERE node_id = ? AND kind = 'controller' AND target_id = ? AND satisfied_at IS NULL").get(t,e);return i===void 0?!1:Number(ae(r,"UPDATE waits SET satisfied_at = ? WHERE wait_id = ? AND generation = ? AND satisfied_at IS NULL").run(n,i.wait_id,i.generation).changes)===1}var UXe=h(()=>{"use strict";Qt();fi()});import{existsSync as Qgi,mkdirSync as Wgi,renameSync as Hgi,writeFileSync as jgi}from"node:fs";import{randomBytes as qgi,randomUUID as Ggi}from"node:crypto";import{join as zgi}from"node:path";function QXe(){let t;do t=qgi(16).toString("hex");while(t==="00000000000000000000000000000000");return t}function Vgi(t,e){let n=JSON.stringify(t);if(n===void 0)throw new TypeError(`${e} must be JSON-serializable`);return n}function iSn(t,e){return e!=="normal"&&e!=="deferred"?e:OD(t)?.lifecycle==="terminal"?"urgent":e}function Kgi(t,e,n){let r=Nat(t);Qgi(r)||Wgi(r,{recursive:!0});let i=e.replace(/[^0-9]/g,""),o=zgi(r,`${i}-${Ggi().slice(0,6)}.md`),s=`${o}.tmp`;return jgi(s,n,"utf8"),ZM(s),Hgi(s,o),hy(r),o}function Ygi(t){if(typeof t!="object"||t===null)return"";let e=t.body;return typeof e=="string"?e.trim():""}function WXe(t,e){let n=e.messageId??QXe(),r=Number(ae(t,"UPDATE message_sequence SET seq = seq + 1 WHERE id = 1 RETURNING seq").get().seq);return ae(t,`INSERT INTO messages
1746
1746
  (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition,
1747
1747
  event, object_id, level, actor_id, cause_message_id, depth)
1748
1748
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r,e.operationId,e.createdAt,e.senderNodeId,e.senderName,e.kind,e.label,e.bodyRef,e.bodyJson===void 0?null:Vgi(e.bodyJson,"message body"),e.disposition,e.event?.event??null,e.event?.objectId??null,e.event?.level??null,e.event?.actorId??null,e.causeMessageId??null,e.depth??0),n}function HXe(t,e){let n=new Date().toISOString(),r=t.operationId===void 0?BQ.current()??LQ():Rb(t.operationId),i=t.bodyRef??null,o=t.bodyJson;if(i===null&&e!==null&&t.senderNodeId!=="human"){let s=Ygi(o),a=Zat(s);a.clipped&&(i=Kgi(e,n,s),o={...o,body:a.text})}return{createdAt:n,operationId:r,bodyRef:i,bodyJson:o}}function oSn(t){switch(t){case"interrupt":return{urgency:"critical",wake:1};case"steer":return{urgency:"urgent",wake:1};case"after-turn":return{urgency:"normal",wake:1};case"next-turn":return{urgency:"deferred",wake:0}}}var Rge=h(()=>{"use strict";Qt();kge();fi();v0();Rr();Ko();UXe();$Q();G9()});import{existsSync as Jgi}from"node:fs";function Dge(t,e,n,r){let i=e===null?[]:r.projectPaths(e),o=n(t),s=new Set(o.map(c=>c.repo.rowid)),a=[];for(let c of i){if(!Jgi(c))continue;let u;try{u=n(c)}catch(l){if(l instanceof hi&&l.code==="git-lookup-failed")continue;throw l}for(let l of u)s.has(l.repo.rowid)||(s.add(l.repo.rowid),a.push(l))}return{repos:o.map(c=>c.repo),checkouts:o,projectRepos:a.map(c=>c.repo),projectCheckouts:a}}function sSn(t,e,n,r=hU(t),i=!1){let o=ae(t,"SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),s=ae(t,`SELECT (SELECT external_id FROM identities WHERE object = ?) AS grantee,
@@ -1756,7 +1756,7 @@ ${e.join(`
1756
1756
  </memory-listing>`}function lIn(t,e,n){return n.length===0?VZe(t,e):`<memory-listing ${e.length>0?`dir="${GZe(t)}" `:""}linked-from="${GZe(t)}">
1757
1757
  ${[...e,...n].join(`
1758
1758
  `)}
1759
- </memory-listing>`}var fye=h(()=>{"use strict";TU()});import{spawn as dXs,spawnSync as Q0i}from"node:child_process";function W0i(t=process.env){return{...t,GIT_OPTIONAL_LOCKS:"0"}}function KZe(t,e,n,r={}){let i=Q0i("git",t,{cwd:e,encoding:"utf8",input:n,env:W0i(),timeout:r.timeoutMs}),o=typeof i.status=="number"?i.status:1,s=typeof i.status=="number",a=typeof i.stdout=="string"?i.stdout:"",c=typeof i.stderr=="string"?i.stderr:"",u=i.error===void 0?void 0:String(i.error),l=i.error?.code==="ETIMEDOUT";return{status:o,stdout:a,stderr:c,...s?{}:{executionFailed:!0},...u===void 0?{}:{processError:u},...l?{timedOut:!0}:{}}}var YZe=h(()=>{"use strict";Co()});import{existsSync as H0i}from"node:fs";import{basename as pIn,dirname as fIn,isAbsolute as j0i,resolve as mIn}from"node:path";function G0i(t,e){let n=t.trim(),r,i,o=/^([a-z][a-z0-9+.-]*):\/\//i.exec(n);if(o){if(o[1].toLowerCase()==="file")return`file:${dIn(decodeURIComponent(n.slice(7)),e)}`;let s=n.slice(o[0].length),a=s.indexOf("/"),c=a<0?s:s.slice(0,a);i=a<0?"":s.slice(a),r=c.replace(/^.*@/,"").replace(/:\d*$/,"")}else{let s=/^(?:[^@/]+@)?([^:/]+):(.*)$/.exec(n);if(!s)return`file:${dIn(n,e)}`;r=s[1],i=s[2]}return i=i.replace(/^\/*~?/,"").replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,""),`${r}/${i}`.toLowerCase()}function dIn(t,e){let n=j0i(t)?t:mIn(e??process.cwd(),t);return fa(n).replace(/\/+$/,"")||"/"}function XZe(t){let e=t.startsWith("file:")?t.slice(5):t;return pIn(e).replace(/\.git$/i,"")||"repo"}function z0i(t){let e=fa(mIn(t)),n=JZe.get(e);if(n&&Date.now()-n.at<q0i)return n.id;if(!H0i(e))return{ok:!1,code:"not-a-repo",dir:e,reason:"directory does not exist"};let r=KZe(["rev-parse","--path-format=absolute","--show-toplevel","--git-common-dir"],e,void 0,{timeoutMs:mye});if(r.timedOut)return{ok:!1,code:"git-lookup-failed",dir:e,reason:`git lookup timed out after ${mye}ms`};if(r.status!==0){if(/not a git repository/i.test(r.stderr)){let d={ok:!1,code:"not-a-repo",dir:e,reason:r.stderr.trim()};return JZe.set(e,{at:Date.now(),id:d}),d}return{ok:!1,code:"git-lookup-failed",dir:e,reason:r.stderr.trim()||r.processError||`git rev-parse exited ${r.status}`}}let[i,o]=r.stdout.split(/\r?\n/).map(d=>d.trim());if(!i||!o)return{ok:!1,code:"git-lookup-failed",dir:e,reason:"git rev-parse returned no work tree (bare repository?)"};let s=fa(i),a=fa(o),c=KZe(["remote","get-url","origin"],s,void 0,{timeoutMs:mye});if(c.timedOut)return{ok:!1,code:"git-lookup-failed",dir:e,reason:`git remote lookup timed out after ${mye}ms`};let u,l=c.stdout.trim();if(c.status===0&&l!==""){let d=G0i(l,s);u={ok:!0,scheme:"git",externalId:d,remoteUrl:l,root:s,commonDir:a,handleHint:XZe(d)}}else if(/no such remote/i.test(c.stderr)){let d=pIn(a)===".git"?fIn(a):a;u={ok:!0,scheme:"local-path",externalId:d,root:s,handleHint:XZe(d)}}else return{ok:!1,code:"git-lookup-failed",dir:e,reason:c.stderr.trim()||`git remote get-url exited ${c.status}`};return JZe.set(e,{at:Date.now(),id:u}),u}function hye(t){let e=[],n=t;for(;;){let r=z0i(n);if(!r.ok)return r.code==="git-lookup-failed"&&e.push(r),e;e.push(r);let i=fIn(r.root);if(i===r.root)return e;n=i}}var mye,q0i,JZe,ZZe=h(()=>{"use strict";YZe();Ko();mye=5e3,q0i=6e4,JZe=new Map});function V0i(t){let e=[],n="",r=null,i=!1,o=(s=!1)=>{e.push({text:n,background:s}),n=""};for(let s=0;s<t.length;s+=1){let a=t[s];if(i){n+=a,i=!1;continue}if(a==="\\"&&r!=="'"){n+=a,i=!0;continue}if(r!==null){n+=a,a===r&&(r=null);continue}if(a==="'"||a==='"'){n+=a,r=a;continue}if(a===`
1759
+ </memory-listing>`}var fye=h(()=>{"use strict";TU()});import{spawn as pXs,spawnSync as Q0i}from"node:child_process";function W0i(t=process.env){return{...t,GIT_OPTIONAL_LOCKS:"0"}}function KZe(t,e,n,r={}){let i=Q0i("git",t,{cwd:e,encoding:"utf8",input:n,env:W0i(),timeout:r.timeoutMs}),o=typeof i.status=="number"?i.status:1,s=typeof i.status=="number",a=typeof i.stdout=="string"?i.stdout:"",c=typeof i.stderr=="string"?i.stderr:"",u=i.error===void 0?void 0:String(i.error),l=i.error?.code==="ETIMEDOUT";return{status:o,stdout:a,stderr:c,...s?{}:{executionFailed:!0},...u===void 0?{}:{processError:u},...l?{timedOut:!0}:{}}}var YZe=h(()=>{"use strict";Co()});import{existsSync as H0i}from"node:fs";import{basename as pIn,dirname as fIn,isAbsolute as j0i,resolve as mIn}from"node:path";function G0i(t,e){let n=t.trim(),r,i,o=/^([a-z][a-z0-9+.-]*):\/\//i.exec(n);if(o){if(o[1].toLowerCase()==="file")return`file:${dIn(decodeURIComponent(n.slice(7)),e)}`;let s=n.slice(o[0].length),a=s.indexOf("/"),c=a<0?s:s.slice(0,a);i=a<0?"":s.slice(a),r=c.replace(/^.*@/,"").replace(/:\d*$/,"")}else{let s=/^(?:[^@/]+@)?([^:/]+):(.*)$/.exec(n);if(!s)return`file:${dIn(n,e)}`;r=s[1],i=s[2]}return i=i.replace(/^\/*~?/,"").replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,""),`${r}/${i}`.toLowerCase()}function dIn(t,e){let n=j0i(t)?t:mIn(e??process.cwd(),t);return fa(n).replace(/\/+$/,"")||"/"}function XZe(t){let e=t.startsWith("file:")?t.slice(5):t;return pIn(e).replace(/\.git$/i,"")||"repo"}function z0i(t){let e=fa(mIn(t)),n=JZe.get(e);if(n&&Date.now()-n.at<q0i)return n.id;if(!H0i(e))return{ok:!1,code:"not-a-repo",dir:e,reason:"directory does not exist"};let r=KZe(["rev-parse","--path-format=absolute","--show-toplevel","--git-common-dir"],e,void 0,{timeoutMs:mye});if(r.timedOut)return{ok:!1,code:"git-lookup-failed",dir:e,reason:`git lookup timed out after ${mye}ms`};if(r.status!==0){if(/not a git repository/i.test(r.stderr)){let d={ok:!1,code:"not-a-repo",dir:e,reason:r.stderr.trim()};return JZe.set(e,{at:Date.now(),id:d}),d}return{ok:!1,code:"git-lookup-failed",dir:e,reason:r.stderr.trim()||r.processError||`git rev-parse exited ${r.status}`}}let[i,o]=r.stdout.split(/\r?\n/).map(d=>d.trim());if(!i||!o)return{ok:!1,code:"git-lookup-failed",dir:e,reason:"git rev-parse returned no work tree (bare repository?)"};let s=fa(i),a=fa(o),c=KZe(["remote","get-url","origin"],s,void 0,{timeoutMs:mye});if(c.timedOut)return{ok:!1,code:"git-lookup-failed",dir:e,reason:`git remote lookup timed out after ${mye}ms`};let u,l=c.stdout.trim();if(c.status===0&&l!==""){let d=G0i(l,s);u={ok:!0,scheme:"git",externalId:d,remoteUrl:l,root:s,commonDir:a,handleHint:XZe(d)}}else if(/no such remote/i.test(c.stderr)){let d=pIn(a)===".git"?fIn(a):a;u={ok:!0,scheme:"local-path",externalId:d,root:s,handleHint:XZe(d)}}else return{ok:!1,code:"git-lookup-failed",dir:e,reason:c.stderr.trim()||`git remote get-url exited ${c.status}`};return JZe.set(e,{at:Date.now(),id:u}),u}function hye(t){let e=[],n=t;for(;;){let r=z0i(n);if(!r.ok)return r.code==="git-lookup-failed"&&e.push(r),e;e.push(r);let i=fIn(r.root);if(i===r.root)return e;n=i}}var mye,q0i,JZe,ZZe=h(()=>{"use strict";YZe();Ko();mye=5e3,q0i=6e4,JZe=new Map});function V0i(t){let e=[],n="",r=null,i=!1,o=(s=!1)=>{e.push({text:n,background:s}),n=""};for(let s=0;s<t.length;s+=1){let a=t[s];if(i){n+=a,i=!1;continue}if(a==="\\"&&r!=="'"){n+=a,i=!0;continue}if(r!==null){n+=a,a===r&&(r=null);continue}if(a==="'"||a==='"'){n+=a,r=a;continue}if(a===`
1760
1760
  `||a===";"){o();continue}if((a==="&"||a==="|")&&t[s+1]===a){o(),s+=1;continue}if(a==="|"){o();continue}if(a==="&"){o(!0);continue}n+=a}return o(),e}function K0i(t){let e=[],n="",r=!1,i=!1,o=null,s=!1,a=()=>{i&&e.push({text:n,opaque:r}),n="",r=!1,i=!1};for(let c=0;c<t.length;c+=1){let u=t[c];if(s){n+=u,i=!0,s=!1;continue}if(u==="\\"&&o!=="'"){s=!0,i=!0;continue}if(o!==null){i=!0,u===o?o=null:n+=u;continue}if(u==="'"||u==='"'){o=u,r=!0,i=!0;continue}if(/\s/.test(u)){a();continue}n+=u,i=!0}return s&&(n+="\\"),a(),e}function gIn(t){return V0i(t).map(({text:e,background:n})=>{let r=K0i(e),i=0;for(;i<r.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r[i].text);)i+=1;return{text:e.trim(),assignments:r.slice(0,i).map(o=>o.text),tokens:r.slice(i),background:n}}).filter(e=>e.assignments.length>0||e.tokens.length>0)}function yIn(t){let e=t.split(`
1761
1761
  `),n=[],r=0;for(;r<e.length;){let i=e[r];n.push(i),r+=1;let o=[];hIn.lastIndex=0;let s;for(;(s=hIn.exec(i))!==null;)o.push({name:s[3],dash:s[1]==="-"});for(let a of o)for(;r<e.length;){let c=a.dash?e[r].replace(/^\t+/,""):e[r];if(r+=1,c===a.name)break}}return n.join(`
1762
1762
  `)}var hIn,AIn=h(()=>{"use strict";hIn=/<<(-?)\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\2/g});import{basename as Y0i,isAbsolute as J0i,matchesGlob as X0i,relative as Z0i}from"node:path";function wIn(t,e){if(t.if===void 0)return{pass:!0};if(e===null)return{pass:!1,reason:"rule `if` with no node config to match"};try{return ib(t.if,e)?{pass:!0}:{pass:!1,reason:"rule `if` does not match this node config"}}catch(n){return{pass:!1,reason:`rule \`if\` failed to evaluate: ${String(n)}`}}}function kU(t,e){try{return X0i(t,e)}catch{return!1}}function ewi(t){let e=t.trim().split(/\s+/);if(e.length===1&&e[0]==="")return null;let n=[];for(let r of e){let i=r.split("*");for(let o=0;o<i.length;o+=1)i[o]!==""&&n.push({kind:"literal",text:i[o]}),o<i.length-1&&n.push({kind:"any"})}return n}function twi(t,e){let n=t.split("").map(r=>r==="?"?"[\\s\\S]":r.replace(/[.+^${}()|[\]\\]/g,"\\$&")).join("");return new RegExp(`^${n}$`).test(e)}function nwi(t,e){let n=new Map,r=(i,o)=>{let s=`${i}:${o}`,a=n.get(s);if(a!==void 0)return a;let c;if(i===t.length)c=o===e.length;else if(t[i].kind==="any")c=r(i+1,o)||o<e.length&&r(i,o+1);else{let u=e[o];c=u!==void 0&&!u.opaque&&twi(t[i].text,u.text)&&r(i+1,o+1)}return n.set(s,c),c};return r(0,0)}function rwi(t,e){let n=ewi(t);return n===null?!1:gIn(e).filter(({tokens:r})=>r.length>0).some(({tokens:r})=>nwi(n,r))}function iwi(t,e,n,r){if(t.startsWith("./")){let i=e.owner.type==="repo"?n.repoRoots?.get(e.owner.rowid):void 0;if(i===void 0)return!1;let o=Z0i(i,r);return o===""||o.startsWith("..")||J0i(o)?!1:kU(o,t.slice(2))}return kU(r,t)||kU(Y0i(r),t)}function owi(t,e,n){let r=`${n.ownerHandle}/${n.name}`;if(t.startsWith("./")){let i=`${e.ownerHandle}/`;return r.startsWith(i)&&kU(r.slice(i.length),t.slice(2))}return kU(n.displayName,t)||kU(r,t)}function xIn(t,e,n,r){if(t.on!==n)return!1;switch(n){case"boot":case"workspace-open":case"slash-command":return!0;case"file-read":{let i=r.absoluteFile;if(i===void 0||t.match!==void 0&&!t.match.some(o=>iwi(o,e,r,i)))return!1;if(t.matchFrontmatter!==void 0){let o=r.readFrontmatter??{};if(Object.keys(o).length===0||!ib(t.matchFrontmatter,o))return!1}return t.match!==void 0||t.matchFrontmatter!==void 0}case"document-read":{let i=r.doc;return i!==void 0&&t.match!==void 0&&t.match.some(o=>owi(o,e,i))}case"command":case"pre-command":{let i=r.command;if(i===void 0||t.match===void 0)return!1;let o=n==="pre-command"?yIn(i):i;return t.match.some(s=>rwi(s,o))}}}var bIn=h(()=>{"use strict";MXe();AIn()});import{dirname as swi}from"node:path";function EIn(t){return t.doc.ownNode?"knowledge":t.doc.kind}function gye(t,e,n,r,i,o={}){let s=awi(t,i,o),c=(i==="document-read"&&o.doc!==void 0?r.filter(u=>u.object.rowid!==o.doc.object.rowid):r).map(u=>lwi(u,e,i,s));return pwi(i,c),{on:i,subject:e,reader:n,docs:c}}function awi(t,e,n){if(e!=="file-read"||n.absoluteFile===void 0)return n;let r=fa(n.absoluteFile);return{...n,absoluteFile:r,readFrontmatter:n.readFrontmatter??cwi(r),repoRoots:uwi(t,r)}}function cwi(t){if(!/\.(md|mdx|markdown)$/i.test(t))return{};try{return G6(Aat(t)).data??{}}catch{return{}}}function uwi(t,e){let n=new Map,r=ae(t,`SELECT o.rowid FROM identities i JOIN objects o ON o.rowid = i.object
@@ -1768,14 +1768,14 @@ ${t.join(`
1768
1768
  `)}
1769
1769
  </auto-loaded-context>`}function hwi(t,e){let n=t.members.get(e.owner.rowid);return n===void 0&&(n=net(t.ctx.db,t.ctx.reader,e.owner),t.members.set(e.owner.rowid,n)),n}function _In(t,e,n){return ae(t,`SELECT o.* FROM edges e JOIN objects o ON o.rowid = e.dst
1770
1770
  WHERE e.type = 'links-to' AND e.src = ? AND o.type = 'document' AND o.deleted_at IS NULL AND o.rowid <> ?
1771
- ORDER BY e.written_as`).all(n.object.rowid,n.object.rowid).filter(i=>nl(t,e,i)).map(i=>lV(t,e,i))}function gwi(t,e){return e.owner.rowid===t.owner.rowid&&e.name.startsWith(`${t.name}/`)&&!e.name.slice(t.name.length+1).includes("/")}function ywi(t,e){let{ledger:n,channel:r}=t.ctx,i=[],o=[];for(let s of _In(t.ctx.db,t.ctx.reader,e)){if(gwi(e,s)&&!s.unlisted)continue;let a={object:s.object.rowid,headsKey:s.headsKey,contentHash:s.bodyHash};if(IU(n,a,"preview"))continue;HD(n,r,a,"preview"),t.delivered.push({doc:s,level:"preview",cause:"link preview attached to content delivery"}),o.push(s);let c=s.preview.trim();i.push(c===""?`[[${s.displayName}]]`:`[[${s.displayName}]]: ${c}`)}return{lines:i,linked:o}}function vIn(t,e,n){let{ledger:r,channel:i}=t.ctx,o=hwi(t,e),s=[],a,c=[];for(let l of dye(o,e.name)){let d=l===e.name,p=cIn(e,l);if(!(d&&n)&&rIn(r,p,"preview"))continue;let{lines:f,previewed:m}=uIn(o,l,r,i,!(d&&n));for(let g of m)t.delivered.push({doc:g,level:"preview",cause:"directory listing attached to content delivery"});f.length!==0&&(iIn(r,i,p,"preview"),d?c=f:s.push(VZe(pye(e,l),f)))}let u=ywi(t,e);return n?c.length>0&&(a=c):c.length+u.lines.length>0&&s.unshift(lIn(pye(e,e.name),c,u.lines)),t.chainCorpus??=wye(t.ctx.db,t.ctx.reader,["document-read"]),s.push(...Awi(t,t.chainCorpus,"document-read",{doc:e},"memory-read companion of content delivery")),{blocks:s,...a===void 0?{}:{listing:a},linked:u.linked}}function Awi(t,e,n,r,i){let{db:o,reader:s,subject:a,ledger:c,channel:u}=t.ctx,l=gye(o,a,s,e,n,r),d=[];for(let p of l.docs){let f=p.finalRung;if(!p.winner||f==="none")continue;let{doc:m}=p,g={object:m.object.rowid,headsKey:m.headsKey,contentHash:m.bodyHash};IU(c,g,f)||(HD(c,u,g,f),t.delivered.push({doc:m,level:f,...i===void 0?{}:{cause:i}}),f==="content"&&d.push(...vIn(t,m,!1).blocks),d.push(fwi(m,f)))}return d}function tet(t,e,n=!1){let r={ctx:t,delivered:[],members:new Map};HD(t.ledger,t.channel,{object:e.object.rowid,headsKey:e.headsKey,contentHash:e.bodyHash},"content");let{blocks:i,listing:o,linked:s}=vIn(r,e,!n);return{attachments:mwi(i),...o===void 0?{}:{listing:o},linked:s,delivered:r.delivered}}var Aye=h(()=>{"use strict";Qt();lh();TU();dV();fye();yye()});var xye,VXs,KXs,YXs,JXs,ret=h(()=>{"use strict";TU();Rr();aIn();lye();dV();fye();yye();Aye();xye="Each %s below shows either its full content (indented beneath its name), a `# read when:` line telling you when to read the full document, or simply its name.",VXs="Preferences are how the user wants you to behave \u2014 standing directives and corrections. To read a preference, run `crtr canvas read <name>`. "+xye.replace("%s","preference"),KXs="Knowledge documents are what you consult \u2014 playbooks and techniques for how to do things, and references on the user, projects, and this node. They come from every owner in your view: this node, the repos you work in, your profile, your app, the user, and installed plugins (crtr's own under `crtr`). To read one, run `crtr canvas read <name>`; a name with names under it is a valid read target too \u2014 it answers with its body, the names under it and previews of the documents it links to, and walking names this way is the sanctioned way to browse. Each doc exists to prevent a specific mistake you would make without it, so when your task matches one \u2014 by its name or its `# read when:` line \u2014 read it before you act; consulting it only after the work is done forfeits the entire reason it exists. "+xye.replace("%s","document"),YXs="Your new configuration puts these preferences in force \u2014 standing directives and corrections from the user. To read one, run `crtr canvas read <name>`. "+xye.replace("%s","preference"),JXs="Your new configuration exposes these knowledge documents \u2014 consult them exactly like the rest of your catalog (`crtr canvas read <name>`). "+xye.replace("%s","document")});var CIn=h(()=>{"use strict"});var iet=h(()=>{"use strict";Rr();Mh();CIn();x0();lU();Mh();Vx()});var TIn=h(()=>{"use strict";Mh();Rr();pd();iet();pd()});var kIn=h(()=>{"use strict";Rr();K6();gW();Mh();Su()});var bye=h(()=>{"use strict";HS();eIn();ret();TIn();vhe();kIn();pd()});var RIn=h(()=>{"use strict";HS();jXe();bye()});var DIn=h(()=>{"use strict";Qt();fi();PS();fs();NS();$Q();pd();G9()});import{join as Swi}from"node:path";function Cwi(t){return Swi(cb(t),"initial-prompt.md")}function MIn(t){return B9(Eye(t),Cwi(t))}var Eea,OIn=h(()=>{"use strict";HS();qD();oet();Mh();GF();jXe();bye();RIn();DIn();Q6();pd();Eea=q9("restart-continuation",{},"continue")});function rd(t,e){let n=e.owner===null?null:dc(t,e.owner),r=n?{id:n.id,type:n.type,handle:n.type==="node"?n.id:n.name}:null;return{id:e.id,type:e.type,kind:e.kind,owner:r,privacy:e.privacy,name:e.name,preview:e.preview??"",created_at:e.created_at,deleted_at:e.deleted_at}}var GD=h(()=>{"use strict";fs()});function I0(t={}){return{...Iwi,...t}}function jS(t,e,n,r){let i=set(e);i.rowid!==n.rowid&&(T0(t,i,n,"read"),wh(t,{event:"read",object:n,actor:i,attrs:{}},r))}var Iwi,zD=h(()=>{"use strict";PS();k0();ub();Iwi={created:{level:4},read:{level:1},watched:{level:1},deleted:{level:5},configured:{level:1}}});function ol(t,e){return e==null||e===""?"":` ${t}="${String(e).replace(/"/g,"&quot;")}"`}function Twi(t){let e=t.kind?`${t.type}/${t.kind}`:t.type,n=t.owner?` owner=${t.owner.handle}`:"",r=t.deleted_at?" (deleted)":"";return`- ${t.id} [[${t.name}]] ${e}${n}${r} \u2014 ${t.preview}`}function xh(t,e,n=""){return`<${t}${ol("type",e.type)}${ol("kind",e.kind)}${ol("id",e.id)}${ol("name",e.name)}${ol("owner",e.owner?.handle)}${n}>`}function RU(t,e){return e.length===0?[]:[`${t}:`,...e.map(Twi)]}var VD=h(()=>{"use strict"});function kwi(t){return t?.split(`
1771
+ ORDER BY e.written_as`).all(n.object.rowid,n.object.rowid).filter(i=>nl(t,e,i)).map(i=>lV(t,e,i))}function gwi(t,e){return e.owner.rowid===t.owner.rowid&&e.name.startsWith(`${t.name}/`)&&!e.name.slice(t.name.length+1).includes("/")}function ywi(t,e){let{ledger:n,channel:r}=t.ctx,i=[],o=[];for(let s of _In(t.ctx.db,t.ctx.reader,e)){if(gwi(e,s)&&!s.unlisted)continue;let a={object:s.object.rowid,headsKey:s.headsKey,contentHash:s.bodyHash};if(IU(n,a,"preview"))continue;HD(n,r,a,"preview"),t.delivered.push({doc:s,level:"preview",cause:"link preview attached to content delivery"}),o.push(s);let c=s.preview.trim();i.push(c===""?`[[${s.displayName}]]`:`[[${s.displayName}]]: ${c}`)}return{lines:i,linked:o}}function vIn(t,e,n){let{ledger:r,channel:i}=t.ctx,o=hwi(t,e),s=[],a,c=[];for(let l of dye(o,e.name)){let d=l===e.name,p=cIn(e,l);if(!(d&&n)&&rIn(r,p,"preview"))continue;let{lines:f,previewed:m}=uIn(o,l,r,i,!(d&&n));for(let g of m)t.delivered.push({doc:g,level:"preview",cause:"directory listing attached to content delivery"});f.length!==0&&(iIn(r,i,p,"preview"),d?c=f:s.push(VZe(pye(e,l),f)))}let u=ywi(t,e);return n?c.length>0&&(a=c):c.length+u.lines.length>0&&s.unshift(lIn(pye(e,e.name),c,u.lines)),t.chainCorpus??=wye(t.ctx.db,t.ctx.reader,["document-read"]),s.push(...Awi(t,t.chainCorpus,"document-read",{doc:e},"memory-read companion of content delivery")),{blocks:s,...a===void 0?{}:{listing:a},linked:u.linked}}function Awi(t,e,n,r,i){let{db:o,reader:s,subject:a,ledger:c,channel:u}=t.ctx,l=gye(o,a,s,e,n,r),d=[];for(let p of l.docs){let f=p.finalRung;if(!p.winner||f==="none")continue;let{doc:m}=p,g={object:m.object.rowid,headsKey:m.headsKey,contentHash:m.bodyHash};IU(c,g,f)||(HD(c,u,g,f),t.delivered.push({doc:m,level:f,...i===void 0?{}:{cause:i}}),f==="content"&&d.push(...vIn(t,m,!1).blocks),d.push(fwi(m,f)))}return d}function tet(t,e,n=!1){let r={ctx:t,delivered:[],members:new Map};HD(t.ledger,t.channel,{object:e.object.rowid,headsKey:e.headsKey,contentHash:e.bodyHash},"content");let{blocks:i,listing:o,linked:s}=vIn(r,e,!n);return{attachments:mwi(i),...o===void 0?{}:{listing:o},linked:s,delivered:r.delivered}}var Aye=h(()=>{"use strict";Qt();lh();TU();dV();fye();yye()});var xye,KXs,YXs,JXs,XXs,ret=h(()=>{"use strict";TU();Rr();aIn();lye();dV();fye();yye();Aye();xye="Each %s below shows either its full content (indented beneath its name), a `# read when:` line telling you when to read the full document, or simply its name.",KXs="Preferences are how the user wants you to behave \u2014 standing directives and corrections. To read a preference, run `crtr canvas read <name>`. "+xye.replace("%s","preference"),YXs="Knowledge documents are what you consult \u2014 playbooks and techniques for how to do things, and references on the user, projects, and this node. They come from every owner in your view: this node, the repos you work in, your profile, your app, the user, and installed plugins (crtr's own under `crtr`). To read one, run `crtr canvas read <name>`; a name with names under it is a valid read target too \u2014 it answers with its body, the names under it and previews of the documents it links to, and walking names this way is the sanctioned way to browse. Each doc exists to prevent a specific mistake you would make without it, so when your task matches one \u2014 by its name or its `# read when:` line \u2014 read it before you act; consulting it only after the work is done forfeits the entire reason it exists. "+xye.replace("%s","document"),JXs="Your new configuration puts these preferences in force \u2014 standing directives and corrections from the user. To read one, run `crtr canvas read <name>`. "+xye.replace("%s","preference"),XXs="Your new configuration exposes these knowledge documents \u2014 consult them exactly like the rest of your catalog (`crtr canvas read <name>`). "+xye.replace("%s","document")});var CIn=h(()=>{"use strict"});var iet=h(()=>{"use strict";Rr();Mh();CIn();x0();lU();Mh();Vx()});var TIn=h(()=>{"use strict";Mh();Rr();pd();iet();pd()});var kIn=h(()=>{"use strict";Rr();K6();gW();Mh();Su()});var bye=h(()=>{"use strict";HS();eIn();ret();TIn();vhe();kIn();pd()});var RIn=h(()=>{"use strict";HS();jXe();bye()});var DIn=h(()=>{"use strict";Qt();fi();PS();fs();NS();$Q();pd();G9()});import{join as Swi}from"node:path";function Cwi(t){return Swi(cb(t),"initial-prompt.md")}function MIn(t){return B9(Eye(t),Cwi(t))}var _ea,OIn=h(()=>{"use strict";HS();qD();oet();Mh();GF();jXe();bye();RIn();DIn();Q6();pd();_ea=q9("restart-continuation",{},"continue")});function rd(t,e){let n=e.owner===null?null:dc(t,e.owner),r=n?{id:n.id,type:n.type,handle:n.type==="node"?n.id:n.name}:null;return{id:e.id,type:e.type,kind:e.kind,owner:r,privacy:e.privacy,name:e.name,preview:e.preview??"",created_at:e.created_at,deleted_at:e.deleted_at}}var GD=h(()=>{"use strict";fs()});function I0(t={}){return{...Iwi,...t}}function jS(t,e,n,r){let i=set(e);i.rowid!==n.rowid&&(T0(t,i,n,"read"),wh(t,{event:"read",object:n,actor:i,attrs:{}},r))}var Iwi,zD=h(()=>{"use strict";PS();k0();ub();Iwi={created:{level:4},read:{level:1},watched:{level:1},deleted:{level:5},configured:{level:1}}});function ol(t,e){return e==null||e===""?"":` ${t}="${String(e).replace(/"/g,"&quot;")}"`}function Twi(t){let e=t.kind?`${t.type}/${t.kind}`:t.type,n=t.owner?` owner=${t.owner.handle}`:"",r=t.deleted_at?" (deleted)":"";return`- ${t.id} [[${t.name}]] ${e}${n}${r} \u2014 ${t.preview}`}function xh(t,e,n=""){return`<${t}${ol("type",e.type)}${ol("kind",e.kind)}${ol("id",e.id)}${ol("name",e.name)}${ol("owner",e.owner?.handle)}${n}>`}function RU(t,e){return e.length===0?[]:[`${t}:`,...e.map(Twi)]}var VD=h(()=>{"use strict"});function kwi(t){return t?.split(`
1772
1772
  `).map(e=>e.trim()).find(e=>e!=="")??""}var _ye,NIn,PIn,aet=h(()=>{"use strict";Qt();kge();UXe();Rge();OIn();lh();GD();zD();VD();_ye=[3,5,7];NIn={bodyOwner:t=>t[0]?.id??null,enqueue(t,e,n){let r=Date.now(),i=e.senderNodeId,o=n.map(l=>l.id),s=`(${o.map(()=>"?").join(",")})`,a=i===null?new Set:new Set(t.prepare(`SELECT DISTINCT node_id FROM waits WHERE kind = 'controller' AND target_id = ? AND satisfied_at IS NULL AND node_id IN ${s}`).all(i,...o).map(l=>l.node_id)),c=new Set(t.prepare(`SELECT DISTINCT anchor_node FROM crons WHERE cancel_on_wake = 1 AND anchor_node IN ${s}`).all(...o).map(l=>l.anchor_node)),u=ae(t,`INSERT INTO deliveries (delivery_id, message_id, destination_id, urgency, wake, state, created_at, updated_at, idempotency_key)
1773
1773
  VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)`);for(let l of n){let d=oSn(l.delivery),p=l.reception===2?d.wake:0,f=e.elevatesTier?iSn(l.id,d.urgency):d.urgency;u.run(QXe(),e.messageId,l.id,f,p,r,r,e.idempotencyKey===void 0?null:`${e.idempotencyKey}:${l.id}`),a.has(l.id)&&FXe(l.id,i,r,t),p===1&&f!=="deferred"&&c.has(l.id)&&$Xe(l.id)}}},PIn={name:"node",addressable:"id",receiver:"inbox",receiverFor:(t,e)=>ae(t,"SELECT 1 FROM peer_stubs WHERE object = ?").get(e.rowid)===void 0?"inbox":"peer",events:I0({configured:{level:1,durable:!0},messaged:{level:2,durable:!0},sent:{level:1,durable:!0},"report.update":{level:5,levels:_ye,durable:!0,carriesBody:!0,elevatesTier:!0},"report.final":{level:7,durable:!0,carriesBody:!0,elevatesTier:!0,inboxKind:"final"},outcome:{level:1,durable:!0,supersedes:!0,carriesBody:!0},"report.result":{level:5,durable:!0,carriesBody:!0,elevatesTier:!0,inboxKind:"completed"},"notice.crash":{level:5,levels:_ye,durable:!0,carriesBody:!0,elevatesTier:!0},"notice.deadline":{level:5,levels:_ye,durable:!0,carriesBody:!0,elevatesTier:!0},"notice.close":{level:5,levels:_ye,durable:!0,carriesBody:!0,elevatesTier:!0}}),read(t,e,n,r){let i=ae(t,"SELECT status FROM nodes WHERE node_id = ?").get(n.id),o=l=>l.filter(d=>nl(t,e,d)).map(d=>rd(t,d)),s=ae(t,`SELECT o.* FROM nodes n JOIN objects o ON o.id = n.node_id
1774
1774
  WHERE n.parent = ? AND o.deleted_at IS NULL ORDER BY o.rowid`).all(n.id),a=ae(t,"SELECT * FROM objects WHERE owner = ? AND deleted_at IS NULL ORDER BY rowid").all(n.rowid);jS(t,e,n,r.reposFn);let c={status:i?.status??"deleted",mandate_first_line:kwi(MIn(n.id)),children:o(s),owned:o(a.filter(l=>l.type!=="job")),jobs:o(a.filter(l=>l.type==="job"))},u=[xh("object",rd(t,n),ol("status",c.status)),`Mandate: ${c.mandate_first_line}`,...RU("Children",c.children),...RU("Owns",c.owned),...RU("Jobs",c.jobs)].join(`
1775
1775
  `);return{data:c,text:u}}}});function LIn(t,e,n=Date.now()){let r=ae(t,`INSERT INTO peer_outbox (peer, kind, payload_json, idempotency_key, state, attempts, next_at, created_at)
1776
- VALUES (?, ?, ?, ?, 'pending', 0, ?, ?) ON CONFLICT (idempotency_key) DO NOTHING`).run(e.peer,e.kind,JSON.stringify(e.payload),e.key,n,n);return Number(r.changes)===0?!1:(setImmediate(()=>{for(let i of[...Rwi])try{i(e.peer)}catch{}}),!0)}var Hea,jea,qea,Rwi,BIn=h(()=>{"use strict";Qt();Hea=10*6e4,jea=720*60*6e4,qea=1440*6e4,Rwi=new Set});import{resolve as Dwi,sep as $In}from"node:path";function Mwi(t,e,n){return ae(t,`SELECT o.* FROM identities i JOIN objects o ON o.rowid = i.object
1776
+ VALUES (?, ?, ?, ?, 'pending', 0, ?, ?) ON CONFLICT (idempotency_key) DO NOTHING`).run(e.peer,e.kind,JSON.stringify(e.payload),e.key,n,n);return Number(r.changes)===0?!1:(setImmediate(()=>{for(let i of[...Rwi])try{i(e.peer)}catch{}}),!0)}var jea,qea,Gea,Rwi,BIn=h(()=>{"use strict";Qt();jea=10*6e4,qea=720*60*6e4,Gea=1440*6e4,Rwi=new Set});import{resolve as Dwi,sep as $In}from"node:path";function Mwi(t,e,n){return ae(t,`SELECT o.* FROM identities i JOIN objects o ON o.rowid = i.object
1777
1777
  WHERE o.type = 'repo' AND i.scheme = ? AND i.external_id = ?`).get(e,n)??null}function Owi(t,e,n){let r=Mwi(t,e.scheme,e.externalId);if(r)return r;let i=n??e.handleHint,o=ae(t,"SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL"),s=i;for(let a=2;o.get(s);a++)s=`${i}-${a}`;return PD(t,"repo",e.scheme,e.externalId,s)}function pV(t,e){let n=fa(Dwi(e)),r=[];for(let s of hye(n)){if(!s.ok)throw new hi("git-lookup-failed",`cannot identify the repo at ${s.dir}: ${s.reason}`,Ti.GENERAL,{dir:s.dir});r.push({root:s.root,repo:Owi(t,s)})}let i=ae(t,`SELECT o.*, i.external_id AS path FROM identities i JOIN objects o ON o.rowid = i.object
1778
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(let{path:s,...a}of i)(n===s||n.startsWith(s.endsWith($In)?s:s+$In))&&r.push({root:s,repo:a});r.sort((s,a)=>a.root.length-s.root.length);let o=new Set;return r.filter(({repo:s})=>!o.has(s.rowid)&&(o.add(s.rowid),!0))}var vye=h(()=>{"use strict";Qt();Co();Ko();pa();fs();ZZe()});import{BlockList as FIn,isIP as nta}from"node:net";var UIn,Nwi,QIn=h(()=>{"use strict";UIn=new FIn;for(let[t,e]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])UIn.addSubnet(t,e,"ipv4");for(let[t,e]of[["2001::",23],["2001:4:112::",48],["2001:db8::",32],["2002::",16],["3fff::",20]])UIn.addSubnet(t,e,"ipv6");Nwi=new FIn;Nwi.addSubnet("2000::",3,"ipv6")});var WIn=h(()=>{"use strict"});var HIn=h(()=>{"use strict";WIn()});var jIn=h(()=>{"use strict";Qt();Co();pa();fs();Iye();lh();k0();vye();KD();QIn();HIn()});var Uwi,Tye,cet=h(()=>{"use strict";Uwi=new Map,Tye=t=>Uwi.get(t)??t});function GIn(t,e){let n=typeof e=="string"?rl(t,e):e;if(n===null)return null;let r=ae(t,"SELECT home_machine, envelope_json FROM peer_stubs WHERE object = ?").get(n.rowid);return r?{object:n,home_machine:r.home_machine,identity:r.envelope_json===null?null:JSON.parse(r.envelope_json)}:null}function uet(t,e){let n=zIn(t,e.owner===null?null:dc(t,e.owner)),r=Qwi(t,e.type);return{id:e.id,type:e.type,kind:e.kind,name:e.name,preview:e.preview,owner:n,privacy:e.privacy,...r===null?{}:{kind_decl:r}}}function zIn(t,e){if(e===null||e.type!=="person"&&e.type!=="app"&&e.type!=="repo"&&e.type!=="profile")return null;let n=ae(t,"SELECT scheme, external_id FROM identities WHERE object = ?").get(e.rowid);return{id:e.id,type:e.type,scheme:n?.scheme??null,external_id:n?.external_id??null,handle:e.name}}function Qwi(t,e){let n=ae(t,"SELECT owner, description, events_json FROM object_kinds WHERE name = ?").get(e),r=n===void 0?null:zIn(t,dc(t,n.owner));return n===void 0||r===null?null:{name:e,description:n.description,events:JSON.parse(n.events_json),owner:r}}var VIn=h(()=>{"use strict";Qt();fs();jIn();Co();pa();cet()});function Hwi(t,e){let n=typeof e?.pointer=="string"?e.pointer:void 0,r=n===void 0?null:rl(t,n);if(r===null||r.type!=="document"||r.deleted_at!==null)return;let i=gU(t,r)[0];if(i===void 0)return;let o=ae(t,"SELECT source_path FROM documents WHERE object = ?").get(r.rowid);return OS(i.body_hash,o?.source_path??null)}function jwi(t,e,n){let r=ae(t,"SELECT message_id, event, object_id, level, actor_id, body_ref, body_json FROM messages WHERE message_id = ?").get(e);if(r===void 0)throw new Error(`no message ${e}`);let i=rl(t,r.object_id);if(i===null)throw new Error(`no object ${r.object_id}`);let o=r.actor_id===null?null:rl(t,r.actor_id),s=r.body_json===null?{}:JSON.parse(r.body_json),{push:a,bodyRef:c,...u}=s,l=r.body_ref===null?void 0:Hwi(t,a);return{key:n,message_id:r.message_id,event:r.event,level:r.level,object:uet(t,i),actor:o===null?null:uet(t,o),attrs:a?.attrs??{},...Object.keys(u).length>0?{body:u}:{},...l===void 0?{}:{body_text:l}}}var Wwi,KIn,YIn=h(()=>{"use strict";Qt();PS();NS();fs();BIn();VIn();Wwi=(t,e)=>`ev:${t}:${e}`;KIn={bodyOwner:()=>null,enqueue(t,e,n){for(let r of n){let i=GIn(t,r.id);if(i===null)continue;let o=Wwi(e.messageId,r.id);LIn(t,{peer:i.home_machine,kind:"event",key:o,payload:{...jwi(t,e.messageId,o),...r.linked?{linked:!0}:{}}})}}}});import{randomBytes as qwi}from"node:crypto";function DU(t,e){let n=ae(t,"SELECT receiver_json FROM custom_objects WHERE object = ?").get(e.rowid);if(!n?.receiver_json)return;let r=JSON.parse(n.receiver_json);if(r==="queue")return"queue";if(r&&typeof r=="object"&&!Array.isArray(r)){if("url"in r)return"url";if("argv"in r)return"argv"}}function qIn(t){setImmediate(()=>{for(let e of Gwi.get(t)??[])e()})}function zwi(t,e){let n=ae(t,`SELECT COUNT(*) AS n FROM deliveries WHERE destination_id = ?
1778
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();for(let{path:s,...a}of i)(n===s||n.startsWith(s.endsWith($In)?s:s+$In))&&r.push({root:s,repo:a});r.sort((s,a)=>a.root.length-s.root.length);let o=new Set;return r.filter(({repo:s})=>!o.has(s.rowid)&&(o.add(s.rowid),!0))}var vye=h(()=>{"use strict";Qt();Co();Ko();pa();fs();ZZe()});import{BlockList as FIn,isIP as rta}from"node:net";var UIn,Nwi,QIn=h(()=>{"use strict";UIn=new FIn;for(let[t,e]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.88.99.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])UIn.addSubnet(t,e,"ipv4");for(let[t,e]of[["2001::",23],["2001:4:112::",48],["2001:db8::",32],["2002::",16],["3fff::",20]])UIn.addSubnet(t,e,"ipv6");Nwi=new FIn;Nwi.addSubnet("2000::",3,"ipv6")});var WIn=h(()=>{"use strict"});var HIn=h(()=>{"use strict";WIn()});var jIn=h(()=>{"use strict";Qt();Co();pa();fs();Iye();lh();k0();vye();KD();QIn();HIn()});var Uwi,Tye,cet=h(()=>{"use strict";Uwi=new Map,Tye=t=>Uwi.get(t)??t});function GIn(t,e){let n=typeof e=="string"?rl(t,e):e;if(n===null)return null;let r=ae(t,"SELECT home_machine, envelope_json FROM peer_stubs WHERE object = ?").get(n.rowid);return r?{object:n,home_machine:r.home_machine,identity:r.envelope_json===null?null:JSON.parse(r.envelope_json)}:null}function uet(t,e){let n=zIn(t,e.owner===null?null:dc(t,e.owner)),r=Qwi(t,e.type);return{id:e.id,type:e.type,kind:e.kind,name:e.name,preview:e.preview,owner:n,privacy:e.privacy,...r===null?{}:{kind_decl:r}}}function zIn(t,e){if(e===null||e.type!=="person"&&e.type!=="app"&&e.type!=="repo"&&e.type!=="profile")return null;let n=ae(t,"SELECT scheme, external_id FROM identities WHERE object = ?").get(e.rowid);return{id:e.id,type:e.type,scheme:n?.scheme??null,external_id:n?.external_id??null,handle:e.name}}function Qwi(t,e){let n=ae(t,"SELECT owner, description, events_json FROM object_kinds WHERE name = ?").get(e),r=n===void 0?null:zIn(t,dc(t,n.owner));return n===void 0||r===null?null:{name:e,description:n.description,events:JSON.parse(n.events_json),owner:r}}var VIn=h(()=>{"use strict";Qt();fs();jIn();Co();pa();cet()});function Hwi(t,e){let n=typeof e?.pointer=="string"?e.pointer:void 0,r=n===void 0?null:rl(t,n);if(r===null||r.type!=="document"||r.deleted_at!==null)return;let i=gU(t,r)[0];if(i===void 0)return;let o=ae(t,"SELECT source_path FROM documents WHERE object = ?").get(r.rowid);return OS(i.body_hash,o?.source_path??null)}function jwi(t,e,n){let r=ae(t,"SELECT message_id, event, object_id, level, actor_id, body_ref, body_json FROM messages WHERE message_id = ?").get(e);if(r===void 0)throw new Error(`no message ${e}`);let i=rl(t,r.object_id);if(i===null)throw new Error(`no object ${r.object_id}`);let o=r.actor_id===null?null:rl(t,r.actor_id),s=r.body_json===null?{}:JSON.parse(r.body_json),{push:a,bodyRef:c,...u}=s,l=r.body_ref===null?void 0:Hwi(t,a);return{key:n,message_id:r.message_id,event:r.event,level:r.level,object:uet(t,i),actor:o===null?null:uet(t,o),attrs:a?.attrs??{},...Object.keys(u).length>0?{body:u}:{},...l===void 0?{}:{body_text:l}}}var Wwi,KIn,YIn=h(()=>{"use strict";Qt();PS();NS();fs();BIn();VIn();Wwi=(t,e)=>`ev:${t}:${e}`;KIn={bodyOwner:()=>null,enqueue(t,e,n){for(let r of n){let i=GIn(t,r.id);if(i===null)continue;let o=Wwi(e.messageId,r.id);LIn(t,{peer:i.home_machine,kind:"event",key:o,payload:{...jwi(t,e.messageId,o),...r.linked?{linked:!0}:{}}})}}}});import{randomBytes as qwi}from"node:crypto";function DU(t,e){let n=ae(t,"SELECT receiver_json FROM custom_objects WHERE object = ?").get(e.rowid);if(!n?.receiver_json)return;let r=JSON.parse(n.receiver_json);if(r==="queue")return"queue";if(r&&typeof r=="object"&&!Array.isArray(r)){if("url"in r)return"url";if("argv"in r)return"argv"}}function qIn(t){setImmediate(()=>{for(let e of Gwi.get(t)??[])e()})}function zwi(t,e){let n=ae(t,`SELECT COUNT(*) AS n FROM deliveries WHERE destination_id = ?
1779
1779
  AND state = 'pending' AND canceled_at IS NULL`).get(e).n;if(n<=JIn)return;let r=ae(t,`SELECT delivery_id, message_id FROM deliveries
1780
1780
  WHERE destination_id = ? AND state = 'pending' AND canceled_at IS NULL
1781
1781
  ORDER BY created_at, rowid LIMIT ?`).all(e,n-JIn);for(let i of r)ae(t,"DELETE FROM deliveries WHERE delivery_id = ?").run(i.delivery_id),ae(t,"DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(i.message_id,i.message_id);r.length&&ae(t,`UPDATE custom_objects SET dropped = dropped + ? WHERE object =
@@ -1831,14 +1831,14 @@ Dropped: ${u.dropped}`}}}}var kTn=h(()=>{"use strict";Qt();zD();VD();GD();KD()})
1831
1831
  JOIN nodes wn ON wn.node_id = wo.id
1832
1832
  JOIN nodes onode ON onode.node_id = oo.id
1833
1833
  WHERE w.in_tree = 1 ${e}
1834
- ORDER BY ws.created_at, ws.rowid`).all(...n),i=new Map;for(let o of r){let s=o.config_json,a=o.listen_json,c=s!=null?fV(s):a!=null?fV(a):kye,u=`${o.from_id}\0${o.to_id}`,l=i.get(u);if(l){l.active||=LTn(c);continue}i.set(u,{from_id:o.from_id,to_id:o.to_id,active:LTn(c),created:o.created_at,from_status:o.from_status??null,to_status:o.to_status??null})}return[...i.values()]}function kXe(t){return _et(ir(),"AND oo.id = ?",t).map(e=>({node_id:e.from_id,active:e.active,created:e.created}))}function Ige(t){return _et(ir(),"AND wo.id = ?",t).map(e=>({node_id:e.to_id,active:e.active,created:e.created}))}function Y6(t){let e=ir(),n=rl(e,t);if(n?.type!=="node")return[];let r=ae(e,"SELECT 1 FROM nodes WHERE node_id = ?");return tTn(e,n).map(i=>i.id).filter(i=>r.get(i)!==void 0)}function RXe(t){return _et(ir(),"AND wo.id = ?",t).some(e=>e.active&&Mxi.has(e.to_status??""))}var Dxi,Mxi,BTn=h(()=>{"use strict";Qt();fi();fs();ub();k0();met();Dxi="('spawn','job-start','ask')";Mxi=new Set(["active","idle"])});function Nxi(t){if(t.fault_id==null)return null;let e=Object.entries(t).filter(([n])=>n.startsWith("fault_")).map(([n,r])=>[n==="fault_id"?n:n.slice(6),r]);return hvn(Object.fromEntries(e))}function vet(t){let e={node_id:t.node_id,name:t.name,description:t.description??void 0,cycles:t.cycles??void 0,kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,host_kind:t.host_kind??null,profile_id:t.profile_id??null,scopes:t.scopes_json==null?null:JSON.parse(t.scopes_json),isolated:t.isolated===1,grantee:t.grantee,sub:t.sub??null,grant_id:t.grant_id??null,client_id:t.client_id??null,metadata_json:t.metadata_json??null,run_id:t.run_id??null,event_cursor:t.event_cursor??null,last_activity_at:t.last_activity_at??null,usage_json:t.usage_json??null,last_turn_error_json:t.last_turn_error_json??null,deleting_at:t.deleting_at??null,parent:t.parent??null,created:t.created,intent:t.intent??null,waiting_for:t.waiting_for??null,frozen_at:t.frozen_at??null,respawn_failures:t.respawn_failures??0,respawn_not_before:t.respawn_not_before??null,launched_at:t.launched_at??null,last_settled_at:t.last_settled_at??null,terminal_reason:t.terminal_reason??null,final_report:t.final_report??null,finalized_at:t.finalized_at??null,outcome_kind:t.outcome_kind??null,outcome_reason:t.outcome_reason??null,outcome_at:t.outcome_at??null,outcome_revision:t.outcome_revision??0,outcome_detail_json:t.outcome_detail_json??null,deadline_at:t.deadline_at??null,telemetry_tokens_in:t.telemetry_tokens_in??null,telemetry_context_tokens:t.telemetry_context_tokens??null,telemetry_last_activity:t.telemetry_last_activity??null,telemetry_updated_at:t.telemetry_updated_at??null,pi_pid:t.pi_pid??null,pi_pid_identity:t.pi_pid_identity??null,window:t.window??null,tmux_session:t.tmux_session??null,pane:t.pane??null,fault:null,streaming:!1},n=mlt(e.pi_pid),r=Nxi(t);return e.fault=r?.link==="pi\u2192provider"&&r.retry.by==="daemon"&&r.retry.disposition==="auto"&&!n?null:r,e.streaming=t.turn_open_at!==null&&t.turn_closed_at===null&&n,e}function Pxi(t,e=Vvn(t.node_id)){return{...vet(t),title:t.title??void 0,icon:t.icon??void 0,spawned_by:t.spawned_by??null,creator:t.creator??null,fork_from:t.fork_from??null,fork_source_file:t.fork_source_file??null,passive_default:t.passive_default===1,cycle_pending:t.cycle_pending===1,model_override:t.model_override??null,scopes:t.scopes_json==null?null:JSON.parse(t.scopes_json),persona_ack:t.persona_ack_json==null?void 0:JSON.parse(t.persona_ack_json),review_binding:t.review_binding_json==null?void 0:JSON.parse(t.review_binding_json),launch:t.launch_config_json==null?void 0:JSON.parse(t.launch_config_json),pi_session_id:t.pi_session_id??null,pi_session_file:t.pi_session_file??null,...e===null?{}:{managed_worktree:e}}}function td(t){let e=ae(ir(),"SELECT * FROM node_rows WHERE node_id = ?").get(t);return e===void 0?null:Pxi(e)}function OD(t){let e=ae(ir(),"SELECT * FROM node_rows WHERE node_id = ?").get(t);return e?vet(e):null}function Cge(t){let e=[$Tn],n=[];if(t?.status!==void 0){let i=Array.isArray(t.status)?t.status:[t.status];e.push(`status IN (${i.map(()=>"?").join(",")})`),n.push(...i)}return t?.withRecordedPid===!0&&e.push("pi_pid IS NOT NULL"),t?.withRecordedPidOrFrozen===!0&&e.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),ir().prepare(`SELECT * FROM node_rows WHERE ${e.join(" AND ")} ORDER BY created`).all(...n).map(vet)}var Dsa,$Tn,Msa,v0=h(()=>{"use strict";Qt();_o();Mh();Pf();fi();tb();Q6();yXe();NTn();k0();fs();mV();fXe();Sge();rw();Rr();qD();Vi();fs();PTn();BTn();Dsa=1440*60*1e3;$Tn="node_id NOT IN (SELECT node_id FROM warm_pool)";Msa=`SELECT
1834
+ ORDER BY ws.created_at, ws.rowid`).all(...n),i=new Map;for(let o of r){let s=o.config_json,a=o.listen_json,c=s!=null?fV(s):a!=null?fV(a):kye,u=`${o.from_id}\0${o.to_id}`,l=i.get(u);if(l){l.active||=LTn(c);continue}i.set(u,{from_id:o.from_id,to_id:o.to_id,active:LTn(c),created:o.created_at,from_status:o.from_status??null,to_status:o.to_status??null})}return[...i.values()]}function kXe(t){return _et(ir(),"AND oo.id = ?",t).map(e=>({node_id:e.from_id,active:e.active,created:e.created}))}function Ige(t){return _et(ir(),"AND wo.id = ?",t).map(e=>({node_id:e.to_id,active:e.active,created:e.created}))}function Y6(t){let e=ir(),n=rl(e,t);if(n?.type!=="node")return[];let r=ae(e,"SELECT 1 FROM nodes WHERE node_id = ?");return tTn(e,n).map(i=>i.id).filter(i=>r.get(i)!==void 0)}function RXe(t){return _et(ir(),"AND wo.id = ?",t).some(e=>e.active&&Mxi.has(e.to_status??""))}var Dxi,Mxi,BTn=h(()=>{"use strict";Qt();fi();fs();ub();k0();met();Dxi="('spawn','job-start','ask')";Mxi=new Set(["active","idle"])});function Nxi(t){if(t.fault_id==null)return null;let e=Object.entries(t).filter(([n])=>n.startsWith("fault_")).map(([n,r])=>[n==="fault_id"?n:n.slice(6),r]);return hvn(Object.fromEntries(e))}function vet(t){let e={node_id:t.node_id,name:t.name,description:t.description??void 0,cycles:t.cycles??void 0,kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,host_kind:t.host_kind??null,profile_id:t.profile_id??null,scopes:t.scopes_json==null?null:JSON.parse(t.scopes_json),isolated:t.isolated===1,grantee:t.grantee,sub:t.sub??null,grant_id:t.grant_id??null,client_id:t.client_id??null,metadata_json:t.metadata_json??null,run_id:t.run_id??null,event_cursor:t.event_cursor??null,last_activity_at:t.last_activity_at??null,usage_json:t.usage_json??null,last_turn_error_json:t.last_turn_error_json??null,deleting_at:t.deleting_at??null,parent:t.parent??null,created:t.created,intent:t.intent??null,waiting_for:t.waiting_for??null,frozen_at:t.frozen_at??null,respawn_failures:t.respawn_failures??0,respawn_not_before:t.respawn_not_before??null,launched_at:t.launched_at??null,last_settled_at:t.last_settled_at??null,terminal_reason:t.terminal_reason??null,final_report:t.final_report??null,finalized_at:t.finalized_at??null,outcome_kind:t.outcome_kind??null,outcome_reason:t.outcome_reason??null,outcome_at:t.outcome_at??null,outcome_revision:t.outcome_revision??0,outcome_detail_json:t.outcome_detail_json??null,deadline_at:t.deadline_at??null,telemetry_tokens_in:t.telemetry_tokens_in??null,telemetry_context_tokens:t.telemetry_context_tokens??null,telemetry_last_activity:t.telemetry_last_activity??null,telemetry_updated_at:t.telemetry_updated_at??null,pi_pid:t.pi_pid??null,pi_pid_identity:t.pi_pid_identity??null,window:t.window??null,tmux_session:t.tmux_session??null,pane:t.pane??null,fault:null,streaming:!1},n=mlt(e.pi_pid),r=Nxi(t);return e.fault=r?.link==="pi\u2192provider"&&r.retry.by==="daemon"&&r.retry.disposition==="auto"&&!n?null:r,e.streaming=t.turn_open_at!==null&&t.turn_closed_at===null&&n,e}function Pxi(t,e=Vvn(t.node_id)){return{...vet(t),title:t.title??void 0,icon:t.icon??void 0,spawned_by:t.spawned_by??null,creator:t.creator??null,fork_from:t.fork_from??null,fork_source_file:t.fork_source_file??null,passive_default:t.passive_default===1,cycle_pending:t.cycle_pending===1,model_override:t.model_override??null,scopes:t.scopes_json==null?null:JSON.parse(t.scopes_json),persona_ack:t.persona_ack_json==null?void 0:JSON.parse(t.persona_ack_json),review_binding:t.review_binding_json==null?void 0:JSON.parse(t.review_binding_json),launch:t.launch_config_json==null?void 0:JSON.parse(t.launch_config_json),pi_session_id:t.pi_session_id??null,pi_session_file:t.pi_session_file??null,...e===null?{}:{managed_worktree:e}}}function td(t){let e=ae(ir(),"SELECT * FROM node_rows WHERE node_id = ?").get(t);return e===void 0?null:Pxi(e)}function OD(t){let e=ae(ir(),"SELECT * FROM node_rows WHERE node_id = ?").get(t);return e?vet(e):null}function Cge(t){let e=[$Tn],n=[];if(t?.status!==void 0){let i=Array.isArray(t.status)?t.status:[t.status];e.push(`status IN (${i.map(()=>"?").join(",")})`),n.push(...i)}return t?.withRecordedPid===!0&&e.push("pi_pid IS NOT NULL"),t?.withRecordedPidOrFrozen===!0&&e.push("(pi_pid IS NOT NULL OR frozen_at IS NOT NULL)"),ir().prepare(`SELECT * FROM node_rows WHERE ${e.join(" AND ")} ORDER BY created`).all(...n).map(vet)}var Msa,$Tn,Osa,v0=h(()=>{"use strict";Qt();_o();Mh();Pf();fi();tb();Q6();yXe();NTn();k0();fs();mV();fXe();Sge();rw();Rr();qD();Vi();fs();PTn();BTn();Msa=1440*60*1e3;$Tn="node_id NOT IN (SELECT node_id FROM warm_pool)";Osa=`SELECT
1835
1835
  node_id, created, launched_at, last_settled_at, finalized_at,
1836
1836
  outcome_at, last_activity_at, pane, "window", tmux_session
1837
1837
  FROM nodes INDEXED BY idx_nodes_terminal_placement_created
1838
1838
  WHERE ${$Tn}
1839
1839
  AND status IN ('done', 'canceled', 'dead')
1840
1840
  AND (pane IS NOT NULL OR "window" IS NOT NULL OR tmux_session IS NOT NULL)
1841
- ORDER BY created`});var FTn=h(()=>{"use strict";tb();IXe();mV();O9()});var Cet=h(()=>{"use strict";cYe()});var Iet=h(()=>{"use strict";Qt();fi();J6();Cet();Bye()});var QTn=h(()=>{"use strict";HS();qD();GF();J6();pd();iet();fi();Qt();pd()});var WTn=h(()=>{"use strict";Qt();Bye();Iet();v0();DD();QTn()});var mV=h(()=>{"use strict";Qt();fi();v0();Jo();Vi();tb();FTn();WTn()});var Bye=h(()=>{"use strict";Qt();fi();mV()});import{randomBytes as Fxi}from"node:crypto";function Qxi(t){return Uxi.test(t)}function Wxi(){let t=Fxi(8),e="";for(let n=0;n<8;n++)e+=HTn[t[n]%HTn.length];return e}function Hxi(t){return ae(t,"SELECT value FROM canvas_meta WHERE key = ?").get(jTn)?.value??null}function jxi(t,e){ae(t,"INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(jTn,e)}function qTn(t=process.env){return Fa(e=>{let n=Hxi(e),r=t.CRTR_INSTALL_ID,i=r!==void 0&&r!==""?r:null;if(n!==null){if(i!==null&&i!==n)throw new Error(`CRTR_INSTALL_ID='${i}' conflicts with the install id already persisted in this canvas home ('${n}'). This canvas home was minted under a different install id \u2014 refusing to boot rather than silently mask what is usually a provisioning bug (this process pointed at the wrong volume/home).`);return n}if(i!==null&&!Qxi(i))throw new Error(`CRTR_INSTALL_ID='${i}' is not a valid install id \u2014 expected 4-16 lowercase [a-z0-9] characters.`);let o=i??Wxi();return jxi(e,o),o})}var jTn,Uxi,HTn,GTn=h(()=>{"use strict";Qt();fi();jTn="install_id",Uxi=/^[a-z0-9]{4,16}$/,HTn="abcdefghijklmnopqrstuvwxyz0123456789"});var zTn=h(()=>{"use strict";Co();Su()});var Tet=h(()=>{"use strict";Jo();Ko();dbe();x0();md();iW();iW()});var ket,qxi,Ret=h(()=>{"use strict";ket={"node:create":{phase:"before",hookTimeoutMs:5e3,eventBudgetMs:1e4},"node:start":{phase:"on",hookTimeoutMs:5e3,eventBudgetMs:1e4},"node:close":{phase:"on",hookTimeoutMs:12e4,eventBudgetMs:18e4}},qxi=Object.freeze(Object.keys(ket))});var VTn=h(()=>{"use strict";lU();Ret()});var KTn=h(()=>{"use strict";VTn()});var YTn=h(()=>{"use strict";_o();Tet();md();KTn()});var JTn=h(()=>{"use strict"});var Det=h(()=>{"use strict";Vi();Su();Ko();Co()});var XTn=h(()=>{"use strict"});var ZTn=h(()=>{"use strict";Vi();Ko();Ep();Det();XTn();Co()});var ekn=h(()=>{"use strict";Jo();iW();Rr();md()});var tkn=h(()=>{"use strict"});var nkn=h(()=>{"use strict";PXe();Vi();Jo();Det();ZTn();Su();ekn();tkn()});var Mua,rkn=h(()=>{"use strict";JTn();lU();x0();Ret();v0();nkn();LXe();Mua=10*1024*1024});var Qua,ikn=h(()=>{"use strict";Rr();Co();YTn();rkn();Qua=Promise.resolve()});import{randomBytes as Gxi}from"node:crypto";function zxi(){if(okn!==void 0)return okn;let t=F9(),e=skn.get(t);if(e!==void 0)return e;let n=qTn();return skn.set(t,n),n}function Vxi(){return`${Date.now().toString(36)}-${Gxi(4).toString("hex")}`}function bet(){return`${zxi()}-${Vxi()}`}var okn,skn,Eet=h(()=>{"use strict";_o();W6();DD();Bye();Jo();x0();dd();sge();Vi();Rr();HS();OXe();Vx();GTn();yXe();Rr();tb();Co();zTn();Su();ikn();fs();Tge();ub();k0();skn=new Map});import{existsSync as Tla,linkSync as kla,mkdirSync as Rla,readFileSync as Dla,realpathSync as Mla,unlinkSync as Kxi,writeFileSync as Ola}from"node:fs";function Yxi(t){return`${t}/progress.json`}function qS(t){return`${t}/claim.json`}function akn(t){try{Kxi(Yxi(t))}catch(e){if(e.code!=="ENOENT")throw e}}var $ye=h(()=>{"use strict";Ko()});function ckn(t){return t===1||t===!0}function Jxi(t){return{request_id:t.request_id,kind:t.kind,inbox_ticket_id:t.inbox_ticket_id,request_dir:t.request_dir,presentation_dir:t.presentation_dir,requester_node_id:t.requester_node_id,companion_node_id:t.companion_node_id,idempotency_key:t.idempotency_key,state:t.state,outcome:t.outcome,inbox_listed:ckn(t.inbox_listed),settleable:ckn(t.settleable),title:t.title,subtitle:t.subtitle,file:t.file,specification_json:t.specification_json,action_json:t.action_json,progress_json:t.progress_json,feedback_json:t.feedback_json,result_json:t.result_json,anchor_base_sha256:t.anchor_base_sha256,anchor_base_bytes:t.anchor_base_bytes===null?null:Buffer.from(t.anchor_base_bytes),created_at:t.created_at,opened_at:t.opened_at,submit_requested_at:t.submit_requested_at,settled_at:t.settled_at,settlement_delivery_id:t.settlement_delivery_id,action_delivery_id:t.action_delivery_id,submit_note_delivery_id:t.submit_note_delivery_id,projected_at:t.projected_at,projection_error:t.projection_error,companion_retired_at:t.companion_retired_at,updated_at:t.updated_at}}function Xxi(t,e,n=[],r="created_at ASC, request_id ASC"){return t.prepare(`SELECT * FROM human_requests WHERE ${e} ORDER BY ${r}`).all(...n).map(Jxi)}function Jvn(){return Xxi(ir(),"state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL",[],"created_at DESC, request_id DESC")}var Zxi,ebi,Yla,J6=h(()=>{"use strict";Qt();eYe();Rr();fi();Ko();Eet();$ye();Cet();A0();Iet();Zxi=Qe.object({sessionName:Qe.string().optional(),askedBy:Qe.string().optional(),blockedSince:Qe.string().optional(),profileName:Qe.string().optional(),nodeId:Qe.string().optional()}).strict(),ebi=Qe.object({id:Qe.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),kind:Qe.string().min(1),step:Qe.number().int().nonnegative(),config:Qe.record(Qe.string(),Qe.unknown()),unvalidated:Qe.literal(!0).optional(),display:Qe.literal(!0).optional()}).strict(),Yla=Qe.object({schema:Qe.literal("crtr.page/v1"),dialect:Qe.enum(["md","html","jsx"]),title:Qe.string().trim().min(1),subtitle:Qe.string().optional(),placement:Qe.enum(["inline","panel"]),document:Qe.enum(["page.md","page.html","page.tsx"]),steps:Qe.number().int().positive(),slots:Qe.array(ebi),source:Zxi.optional()}).strict().superRefine((t,e)=>{let n=t.dialect==="md"?"page.md":t.dialect==="html"?"page.html":"page.tsx";t.document!==n&&e.addIssue({code:"custom",path:["document"],message:"document must agree with dialect"}),t.dialect==="md"&&t.steps!==1&&e.addIssue({code:"custom",path:["steps"],message:"md pages have exactly one step"})})});var ukn=h(()=>{"use strict"});var lkn=h(()=>{"use strict"});var dkn=h(()=>{"use strict";Ep()});var Met=h(()=>{"use strict";svn();fXe();Q6();J6();Vi();Pf();Rr();ukn();lkn();dkn()});import{DatabaseSync as tbi}from"node:sqlite";import{appendFileSync as nbi}from"node:fs";function ibi(){let t=process.env.CRTR_DB_OPEN_LEDGER;if(t)try{let e=`${new Date().toISOString()} ${process.pid} ${process.argv[1]??"<unknown>"}
1841
+ ORDER BY created`});var FTn=h(()=>{"use strict";tb();IXe();mV();O9()});var Cet=h(()=>{"use strict";cYe()});var Iet=h(()=>{"use strict";Qt();fi();J6();Cet();Bye()});var QTn=h(()=>{"use strict";HS();qD();GF();J6();pd();iet();fi();Qt();pd()});var WTn=h(()=>{"use strict";Qt();Bye();Iet();v0();DD();QTn()});var mV=h(()=>{"use strict";Qt();fi();v0();Jo();Vi();tb();FTn();WTn()});var Bye=h(()=>{"use strict";Qt();fi();mV()});import{randomBytes as Fxi}from"node:crypto";function Qxi(t){return Uxi.test(t)}function Wxi(){let t=Fxi(8),e="";for(let n=0;n<8;n++)e+=HTn[t[n]%HTn.length];return e}function Hxi(t){return ae(t,"SELECT value FROM canvas_meta WHERE key = ?").get(jTn)?.value??null}function jxi(t,e){ae(t,"INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(jTn,e)}function qTn(t=process.env){return Fa(e=>{let n=Hxi(e),r=t.CRTR_INSTALL_ID,i=r!==void 0&&r!==""?r:null;if(n!==null){if(i!==null&&i!==n)throw new Error(`CRTR_INSTALL_ID='${i}' conflicts with the install id already persisted in this canvas home ('${n}'). This canvas home was minted under a different install id \u2014 refusing to boot rather than silently mask what is usually a provisioning bug (this process pointed at the wrong volume/home).`);return n}if(i!==null&&!Qxi(i))throw new Error(`CRTR_INSTALL_ID='${i}' is not a valid install id \u2014 expected 4-16 lowercase [a-z0-9] characters.`);let o=i??Wxi();return jxi(e,o),o})}var jTn,Uxi,HTn,GTn=h(()=>{"use strict";Qt();fi();jTn="install_id",Uxi=/^[a-z0-9]{4,16}$/,HTn="abcdefghijklmnopqrstuvwxyz0123456789"});var zTn=h(()=>{"use strict";Co();Su()});var Tet=h(()=>{"use strict";Jo();Ko();dbe();x0();md();iW();iW()});var ket,qxi,Ret=h(()=>{"use strict";ket={"node:create":{phase:"before",hookTimeoutMs:5e3,eventBudgetMs:1e4},"node:start":{phase:"on",hookTimeoutMs:5e3,eventBudgetMs:1e4},"node:close":{phase:"on",hookTimeoutMs:12e4,eventBudgetMs:18e4}},qxi=Object.freeze(Object.keys(ket))});var VTn=h(()=>{"use strict";lU();Ret()});var KTn=h(()=>{"use strict";VTn()});var YTn=h(()=>{"use strict";_o();Tet();md();KTn()});var JTn=h(()=>{"use strict"});var Det=h(()=>{"use strict";Vi();Su();Ko();Co()});var XTn=h(()=>{"use strict"});var ZTn=h(()=>{"use strict";Vi();Ko();Ep();Det();XTn();Co()});var ekn=h(()=>{"use strict";Jo();iW();Rr();md()});var tkn=h(()=>{"use strict"});var nkn=h(()=>{"use strict";PXe();Vi();Jo();Det();ZTn();Su();ekn();tkn()});var Oua,rkn=h(()=>{"use strict";JTn();lU();x0();Ret();v0();nkn();LXe();Oua=10*1024*1024});var Wua,ikn=h(()=>{"use strict";Rr();Co();YTn();rkn();Wua=Promise.resolve()});import{randomBytes as Gxi}from"node:crypto";function zxi(){if(okn!==void 0)return okn;let t=F9(),e=skn.get(t);if(e!==void 0)return e;let n=qTn();return skn.set(t,n),n}function Vxi(){return`${Date.now().toString(36)}-${Gxi(4).toString("hex")}`}function bet(){return`${zxi()}-${Vxi()}`}var okn,skn,Eet=h(()=>{"use strict";_o();W6();DD();Bye();Jo();x0();dd();sge();Vi();Rr();HS();OXe();Vx();GTn();yXe();Rr();tb();Co();zTn();Su();ikn();fs();Tge();ub();k0();skn=new Map});import{existsSync as kla,linkSync as Rla,mkdirSync as Dla,readFileSync as Mla,realpathSync as Ola,unlinkSync as Kxi,writeFileSync as Nla}from"node:fs";function Yxi(t){return`${t}/progress.json`}function qS(t){return`${t}/claim.json`}function akn(t){try{Kxi(Yxi(t))}catch(e){if(e.code!=="ENOENT")throw e}}var $ye=h(()=>{"use strict";Ko()});function ckn(t){return t===1||t===!0}function Jxi(t){return{request_id:t.request_id,kind:t.kind,inbox_ticket_id:t.inbox_ticket_id,request_dir:t.request_dir,presentation_dir:t.presentation_dir,requester_node_id:t.requester_node_id,companion_node_id:t.companion_node_id,idempotency_key:t.idempotency_key,state:t.state,outcome:t.outcome,inbox_listed:ckn(t.inbox_listed),settleable:ckn(t.settleable),title:t.title,subtitle:t.subtitle,file:t.file,specification_json:t.specification_json,action_json:t.action_json,progress_json:t.progress_json,feedback_json:t.feedback_json,result_json:t.result_json,anchor_base_sha256:t.anchor_base_sha256,anchor_base_bytes:t.anchor_base_bytes===null?null:Buffer.from(t.anchor_base_bytes),created_at:t.created_at,opened_at:t.opened_at,submit_requested_at:t.submit_requested_at,settled_at:t.settled_at,settlement_delivery_id:t.settlement_delivery_id,action_delivery_id:t.action_delivery_id,submit_note_delivery_id:t.submit_note_delivery_id,projected_at:t.projected_at,projection_error:t.projection_error,companion_retired_at:t.companion_retired_at,updated_at:t.updated_at}}function Xxi(t,e,n=[],r="created_at ASC, request_id ASC"){return t.prepare(`SELECT * FROM human_requests WHERE ${e} ORDER BY ${r}`).all(...n).map(Jxi)}function Jvn(){return Xxi(ir(),"state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL",[],"created_at DESC, request_id DESC")}var Zxi,ebi,Jla,J6=h(()=>{"use strict";Qt();eYe();Rr();fi();Ko();Eet();$ye();Cet();A0();Iet();Zxi=Qe.object({sessionName:Qe.string().optional(),askedBy:Qe.string().optional(),blockedSince:Qe.string().optional(),profileName:Qe.string().optional(),nodeId:Qe.string().optional()}).strict(),ebi=Qe.object({id:Qe.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),kind:Qe.string().min(1),step:Qe.number().int().nonnegative(),config:Qe.record(Qe.string(),Qe.unknown()),unvalidated:Qe.literal(!0).optional(),display:Qe.literal(!0).optional()}).strict(),Jla=Qe.object({schema:Qe.literal("crtr.page/v1"),dialect:Qe.enum(["md","html","jsx"]),title:Qe.string().trim().min(1),subtitle:Qe.string().optional(),placement:Qe.enum(["inline","panel"]),document:Qe.enum(["page.md","page.html","page.tsx"]),steps:Qe.number().int().positive(),slots:Qe.array(ebi),source:Zxi.optional()}).strict().superRefine((t,e)=>{let n=t.dialect==="md"?"page.md":t.dialect==="html"?"page.html":"page.tsx";t.document!==n&&e.addIssue({code:"custom",path:["document"],message:"document must agree with dialect"}),t.dialect==="md"&&t.steps!==1&&e.addIssue({code:"custom",path:["steps"],message:"md pages have exactly one step"})})});var ukn=h(()=>{"use strict"});var lkn=h(()=>{"use strict"});var dkn=h(()=>{"use strict";Ep()});var Met=h(()=>{"use strict";svn();fXe();Q6();J6();Vi();Pf();Rr();ukn();lkn();dkn()});import{DatabaseSync as tbi}from"node:sqlite";import{appendFileSync as nbi}from"node:fs";function ibi(){let t=process.env.CRTR_DB_OPEN_LEDGER;if(t)try{let e=`${new Date().toISOString()} ${process.pid} ${process.argv[1]??"<unknown>"}
1842
1842
  `;nbi(t,e)}catch{}}function ir(){let t=F9(),e=pkn.get(t);if(e)return e;xat(),gxe(),ibi();let n=new tbi(t);n.exec("PRAGMA busy_timeout = 5000;"),n.exec("PRAGMA journal_mode = WAL;"),n.exec("PRAGMA foreign_keys = ON;");try{rbi?.(n)}catch(r){throw n.close(),r}return pkn.set(t,n),n}function Fa(t){let e=ir();if(e.isTransaction)return t(e);e.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.exec("COMMIT"),n}catch(n){try{e.exec("ROLLBACK")}catch{}throw n}}var pkn,rbi,fi=h(()=>{"use strict";Qt();Rr();Vi();Met();Met();Qt();pkn=new Map});import{join as obi}from"node:path";function xet(t){let e=XV();if(eC()===t&&e)return e;let n=ae(ir(),"SELECT grantee FROM node_rows WHERE node_id = ?").get(t);if(!n?.grantee)throw new Error(`node ${t} has no app assignment`);return n.grantee}function Eye(t,e){return qQ(t,e??xet(t))}function cb(t,e){return obi(Eye(t,e),"context")}var qD=h(()=>{"use strict";Qt();_o();fi();Rr()});function fkn(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 sbi(t){return[...t].sort((e,n)=>Date.parse(e.fire_at)-Date.parse(n.fire_at))[0]}function mkn(t,e=Date.now()){if(t.length===0)return;if(t.length>1){let i=sbi(t);return`${t.length} crons armed${i?` \xB7 next ${fkn(i.fire_at,e)}`:""}`}let n=t[0],r=fkn(n.fire_at,e);return n.cancel_on_wake?`deadline \xB7 ${r}`:n.recur!==null?`recurring cron \xB7 next ${r}`:`scheduled cron \xB7 ${r}`}var hkn=h(()=>{"use strict"});function abi(t,e){let n=LYe(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 gkn(t,e=Date.now(),n=26){if(t.length===0)return;if(t.length===1){let i=t[0];return`bash job \xB7 ${$me(e-i.startedAtMs)} \xB7 ${abi(i.command,Math.max(12,n))}`}let r=t[0];return`${t.length} bash jobs \xB7 oldest ${$me(e-r.startedAtMs)}`}var ykn=h(()=>{"use strict";GF()});import{basename as cbi}from"node:path";function ubi(t,e){let n=cbi(t);return n.length<=e?n:`${n.slice(0,Math.max(1,e-1))}\u2026`}function Akn(t,e=28){let n=ubi(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`}var wkn=h(()=>{"use strict"});function bkn(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t+" ".repeat(e-t.length)}function mbi(t,e){return t.length>=e?t.slice(0,e):" ".repeat(e-t.length)+t}async function Ekn(t,e,n,r,i=[],o=[],s=[]){let a=r instanceof jx,c=await r.panelRoster?.(),u=c===void 0?null:new Map(c.nodes.map(We=>[We.node_id,We])),l=new Map,d=new Map;if(c!==void 0)for(let We of c.edges){let X=l.get(We.from_id)??[];X.push(We.to_id),l.set(We.from_id,X),d.has(We.to_id)||d.set(We.to_id,We.from_id)}let p=new Map,f=new Map,m=new Map,g=We=>{let X=p.get(We);if(X!==void 0)return X;let He=u===null?r.getNode(We).catch(()=>null):Promise.resolve(u.get(We)??null);return p.set(We,He),He},y=We=>r.getNode(We).catch(()=>null),w=We=>{let X=f.get(We);if(X!==void 0)return X;let He=(async()=>{let Je=u===null?(await r.subscriptionsOf(We).catch(()=>[])).map(Ut=>Ut.node_id):l.get(We)??[],$t=[];for(let Ut of Je)(await g(Ut))?.kind!=="human"&&$t.push(Ut);return $t})();return f.set(We,He),He},x=We=>{let X=m.get(We);if(X!==void 0)return X;let He=u===null?r.subscribersOf(We).then(Je=>Je[0]?.node_id).catch(()=>{}):Promise.resolve(d.get(We));return m.set(We,He),He},E=async We=>{let X=[];for(let He of await w(We)){let Je=(await g(He))?.status;(Je==="active"||Je==="idle")&&X.push(He)}return X},_=async We=>{let X=We,He=new Set([X]);for(;;){let Je=await x(X);if(Je===void 0||He.has(Je))break;He.add(Je),X=Je}return X},C=new Map,I=async We=>{let X=new Set,He=async Je=>{let $t=(await g(Je))?.status==="active";if(X.has(Je))return $t?1:0;X.add(Je);let Ut=0;for(let fn of await w(Je))Ut+=await He(fn);return C.set(Je,Ut),Ut+($t?1:0)};await He(We)},D=async We=>{if(We===null||We.mode!=="orchestrator")return"";let X=(await w(We.node_id)).length;return X>0?` ${Au}\u2933${X}${Kr}`:""},M=We=>{if(We===null||We.status==="active")return"";let X=C.get(We.node_id)??0;return X>0?` ${ihe}\u21E3${X}${Kr}`:""},k=n?.muted??(We=>We),P=n?.faint??(We=>We);await I(await _(t));let U=await x(t),j=await E(t),G=[...U!==void 0?[U]:[],...j],W=await Promise.all(G.map(async We=>await y(We)??await g(We))),me=G.length>0?Math.min(xkn,Math.max(...G.map((We,X)=>CD(W[X]??null,We).length))):xkn,Y=async(We,X)=>{let He=W[G.indexOf(We)]??null,Je=bkn(CD(He,We),me),$t=P(bkn(He?.kind??"",pbi)),Ut=k(mbi(she(He,a),fbi)),fn=`${che(He)}${await D(He)}${M(He)}${lhe(We,e)}${ahe(He,a)}`,Q=` ${X} ${ohe(He)} ${Je} ${$t} ${Ut}${fn}`;return Yx(Q)},Re=[...U!==void 0?[U]:[],...j],Ue=[];U!==void 0&&Ue.push({key:`node:${U}`,kind:"node",nodeId:U,line:await Y(U,"\u2191")});for(let We of j)Ue.push({key:`node:${We}`,kind:"node",nodeId:We,line:await Y(We,"\u2193")});for(let We of s){let X=n?n.info("\u270E"):"\u270E",He=Akn(We,Math.max(8,ny()-dbi));Ue.push({key:`review:${We.review_id}`,kind:"review",companionNodeId:We.companion_node_id,line:` ${X} ${k(`${He} \xB7 \u21B5 companion`)}${Kr}`})}let Xe=o.length===1?" \xB7 x stop":"",It=gkn(o,Date.now(),ny()-(lbi+Xe.length));if(It!==void 0){let We=n?n.info("\u2699"):"\u2699";Ue.push({key:"bash",kind:"bash",line:` ${We} ${k(`${It} \xB7 \u21B5 details${Xe}`)}${Kr}`})}let on=mkn(i);if(on!==void 0){let We=n?n.info("\u25F7"):"\u25F7";Ue.push({key:"crons",kind:"crons",line:` ${We} ${k(`${on} \xB7 \u21B5 details`)}${Kr}`})}return{reports:Ue.map(We=>We.line),reportIds:Re,items:Ue}}var lbi,dbi,pbi,fbi,xkn,_kn=h(()=>{"use strict";Xx();u6();hkn();ykn();wkn();lbi=34,dbi=40,pbi=12,fbi=6,xkn=22});import{execFile as vkn}from"node:child_process";function Skn(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 f,m,g=()=>{e.syncCursor(),u.clear();for(let k of l){let P=k.key===d;u.addChild(new ve(P?Jx(SD(k.line),ny(),kS):k.line,1,0))}r.requestRender()},y=async()=>{let k=s?[]:(await qt().listCrons()).filter(G=>G.created_by===o),P=s?[]:qF(cb(o)),U=s?[]:(await qt().listReviews({state:"open",origin_node_id:o})).reviews;if(l=(await Ekn(o,e.asks(),i,c,k,P,U)).items,p!==void 0){let G=p;p=void 0;let W=l.find(me=>me.kind==="node"&&me.nodeId===G);W!==void 0&&(d=W.key)}d!==void 0&&!l.some(G=>G.key===d)&&(d=void 0),f!==void 0&&!P.some(G=>G.jobId===f?.jobId)&&w(!0),g()},w=k=>{m!==void 0&&(clearTimeout(m),m=void 0),f!==void 0&&(f=void 0,k&&e.setNotice(""))},x=()=>{w(!0),d!==void 0&&(d=void 0,g())},E=k=>kf(k)??(k.length===1?k:void 0),_=(k,P=40)=>{let U=(k.split(`
1843
1843
  `)[0]??"").replace(/\s+/g," ").trim();return U.length>P?`${U.slice(0,P-1)}\u2026`:U},C=()=>{if(a!=="controller"){e.setNotice("Read-only observer attach \u2014 cannot stop background jobs");return}let k=qF(cb(o));if(k.length===0){e.setNotice("Background job already finished"),e.requestChromeRefresh();return}if(k.length>1){e.setNotice(`${k.length} background jobs \u2014 press \u21B5 to pick one in the Inspector`);return}let P=k[0];f={jobId:P.jobId,label:_(P.command)},e.setNotice(`Stop \u201C${f.label}\u201D? Press y to confirm.`,{sticky:!0}),m=setTimeout(()=>w(!0),hbi)},I=()=>{let k=f;k!==void 0&&(w(!1),e.setNotice(`Stopping \u201C${k.label}\u201D\u2026`),vkn("crtr",["node","bash","kill",k.jobId,"--node",o],P=>{e.setNotice(P===null?`Stopped \u201C${k.label}\u201D.`:`Could not stop the job: ${P.message.split(`
1844
1844
  `)[0]}`),e.requestChromeRefresh()}))};n.onCursorDownAtBottom=s?void 0:()=>{d!==void 0||l.length===0||(d=l[0].key,g())};let D=()=>{let k=l.find(j=>j.key===d);if(k===void 0||s)return;if(k.kind==="crons"){x(),e.openInspector("schedule");return}if(k.kind==="review"){if(a!=="controller"){e.setNotice("Read-only observer attach \u2014 cannot open the review companion");return}x();let j=process.env.TMUX_PANE;if(j===void 0||j===""){e.setNotice("Could not open the companion: no tmux pane");return}(async()=>{let G=qt(),W=await G.getNode(k.companionNodeId);(await Ihe(G,W,{pane:j})).focused||e.setNotice("Could not open the companion")})().catch(G=>e.setNotice(`Could not open the companion: ${wu(G).split(`
@@ -1932,7 +1932,7 @@ ${n}
1932
1932
  </html>
1933
1933
  `}var DEi,MEi,PRn=h(()=>{"use strict";g7();DEi=/\[\[([^[\]\n]+?)\]\]/g;MEi=new xb({gfm:!0,renderer:{html({text:t}){return BU(t)}}})});import{createHash as NEi}from"node:crypto";import{existsSync as Jye,mkdirSync as PEi,readFileSync as BRn,renameSync as LEi,writeFileSync as BEi}from"node:fs";import{tmpdir as $Ei}from"node:os";import{basename as FEi,dirname as $Rn,join as $U}from"node:path";function Zye(){return $U($Ei(),"crtr-docs")}function LRn(t){return t.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,120)||"doc"}function eAe(t,e,n=Zye()){let r=$U(n,LRn(e.id),`r${e.revision}`),i=$U(r,`${LRn(FEi(e.name))}.md`),o=$U(r,ett);if(Jye(i)&&Jye(o))return i;PEi(r,{recursive:!0});let s={ref:t,id:e.id,name:e.name,revision:e.revision,heads_key:e.heads_key,sha256:Zet(e.body)};return Xye(i,e.body),Xye(o,`${JSON.stringify(s)}
1934
1934
  `),i}function FRn(t,e,n=Zye()){let i=eAe(t,e,n).replace(/\.md$/,".html");return Jye(i)||Xye(i,NRn({name:e.name,revision:e.revision,body:e.body})),i}function Xye(t,e){let n=`${t}.${process.pid}.tmp`;BEi(n,e),LEi(n,t)}function xV(t,e=Zye()){if(t.startsWith(`${e}/`))try{let n=JSON.parse(BRn($U($Rn(t),ett),"utf8"));return typeof n.id=="string"&&typeof n.heads_key=="string"?n:void 0}catch{return}}async function URn(t,e,n=Zye()){let r=xV(t,n);if(r===void 0||!Jye(t))return{outcome:"missing"};let i=BRn(t,"utf8");if(Zet(i)===r.sha256)return{outcome:"unchanged"};try{let o=await e(r.id,i,r.heads_key);return o==="stale"?{outcome:"stale",path:t}:(Xye($U($Rn(t),ett),`${JSON.stringify({...r,sha256:Zet(i)})}
1935
- `),{outcome:"saved",revision:o.revision})}catch(o){return{outcome:"failed",message:o instanceof Error?o.message:String(o)}}}function QRn(t,e){switch(e.outcome){case"unchanged":return;case"saved":return`Saved ${t} as revision ${e.revision}`;case"stale":return`${t} changed while you edited it \u2014 not saved; your text is kept at ${e.path}`;case"missing":return`Could not find the edited copy of ${t}`;case"failed":return`Could not save ${t}: ${e.message}`}}var wV,ett,Zet,ttt=h(()=>{"use strict";PRn();wV="CRTR_ATTACH_DOC_SAVEBACK",ett=".crtr-doc.json";Zet=t=>NEi("sha256").update(t).digest("hex")});async function WRn(t){let e=await qt().objects.read(t);if(e.state!=="object"||e.type!=="document")return`${t} is not a readable document`;let n=e.data;if(n.needs_merge||n.bodies.length!==1)return`${t} has ${n.heads.length} heads and needs a merge`;let r=e.object.owner?.handle;return{id:e.object.id,name:r===void 0?e.object.name:`${r}/${e.object.name}`,revision:n.revision,heads_key:n.heads.map(i=>i.rev_id).sort().join(","),body:n.bodies[0]}}function HRn(t){let e=new Map,n=new Map,r=new Set,i=new Set,o=!1,s=!1,a=!1,c=()=>{o||s||(s=!0,t.canvasSource.listNodes().then(d=>{for(let p of d)e.set(p.node_id,p.name);o=!0,a||t.refresh()}).catch(()=>{o=!0}).finally(()=>{s=!1}))},u=d=>{t.remote||r.has(d)||i.has(d)||(r.add(d),WRn(d).then(p=>{if(typeof p=="string"){i.add(d);return}n.set(d,t.openMode==="browser"?FRn(d,p):eAe(d,p)),a||t.refresh()}).catch(()=>{i.add(d)}).finally(()=>{r.delete(d)}))},l={selfNodeId:t.selfNodeId,nodeName:d=>{let p=e.get(d);return p===void 0&&c(),p},pathFor:d=>{let p=n.get(d);return p===void 0&&u(d),p}};return m3e(l),{isDocumentPath:d=>xV(d)!==void 0,async prepareOpen(d){if(t.remote)return{notice:"Opening a document is unavailable in a remote attach"};let p=xV(d);if(p===void 0)return{notice:"Not a document link"};try{let f=await WRn(p.id);if(typeof f=="string")return{notice:f};let m=eAe(p.ref,f);return n.set(p.ref,m),{path:m}}catch(f){return{notice:`Could not read ${p.name}: ${f instanceof Error?f.message:String(f)}`}}},async consumeSaveBack(d){let p=process.env[wV];if(p===void 0||p==="")return;delete process.env[wV];let f=xV(p),m=await URn(p,async(y,w,x)=>{try{return{revision:(await qt().docs.edit(y,{body:w,base:x,rationale:"edited by the person in the attach viewer"})).revision}}catch(E){if(E instanceof un&&E.code==="stale_revision")return"stale";throw E}}),g=QRn(f?.name??p,m);g!==void 0&&d(g)},dispose(){a=!0,m3e(void 0)}}}var jRn=h(()=>{"use strict";dd();lc();Zz();ttt()});import{execFile as UEi}from"node:child_process";function zEi(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 QEi,WEi,HEi,jEi,qEi,GEi,tAe,qRn=h(()=>{"use strict";tt();ul();K6();nJe();u6();lc();D6();uU();vhe();Xx();QEi=.72,WEi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},HEi=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],jEi=[["crtr.graph.dismiss","dismiss"]],qEi=[["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"]],GEi=[...["active","idle","done","dead","canceled"].map(t=>[vD(t,{}),t]),[vD("active",{streaming:!0}),"live"],[vD("active",{frozen:!0}),"frozen"],[vD("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${gf}${t.color}m${t.glyph}${Kr} ${Au}${e}${Kr}`).join(" ");tAe=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 jx}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 LC(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${ma(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)+pp(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,WEi),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 qt().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,zEi(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 w=>{let x=i.get(w);if(x!==void 0)return x;let E;try{E=await e.subscriptions(w)}catch{E=[]}let _=E.filter(C=>n.get(C)?.kind!=="human");return i.set(w,_),_},u=async w=>{if(s.has(w))return s.get(w);let x;try{x=(await e.subscribers(w))[0]}catch{x=void 0}return s.set(w,x),x},l=async()=>{let w=this.self,x=new Set([w]);for(;;){let E=await u(w);if(E===void 0||x.has(E))break;x.add(E),w=E}return w},d=async w=>{let x=o.get(w);if(x!==void 0)return x;let E=[...await c(w)];return E.sort((_,C)=>_he(n.get(_)?.status)-_he(n.get(C)?.status)),o.set(w,E),E},p=new Set,f=new Set,m=async w=>{let x=n.get(w)?.status==="active";if(f.has(w))return{active:x?1:0,reveal:x||w===this.self};f.add(w);let E=0,_=!1;for(let C of await c(w)){let I=await m(C);E+=I.active,I.reveal&&(_=!0)}return a.set(w,E),_&&p.add(w),{active:E+(x?1:0),reveal:_||x||w===this.self}},g=await l();await m(g),await Promise.all([...i.keys()].map(w=>d(w)));let y={root:g,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return y.rows=this.projectRows(y),y}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 f=l.length-1;f>=0;f--)i.push({id:l[f],prefix:p,isRoot:!1,isLast:f===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=(C,I)=>r?Jx(C,ny(),kS):I?Jx(C,ny(),Dxn):Yx(C);if(n.cycle){let C=`${n.branch} ${Au}\u21BA ${uhe(n.id)}${Kr}`;return o(C,!1)}let s=e.nodes.get(n.id)??null,a=ohe(s),c=CD(s,n.id),u=n.isSelf?`${_6}${c}${Kr}`:c,l=`${Au}${s?.kind??""}${Kr}`,d=`${Au}${she(s,this.remote)}${Kr}`,p=n.hasKids&&n.collapsed,f=!r&&p?`${Au}\u25B8${Kr} `:" ",m=che(s),g=e.childIds.get(n.id)?.length??0,y=s!==null&&g>0?` ${Au}\u2933${g}${Kr}`:"",w=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${ihe}\u21E3${e.activeBelow.get(s.node_id)??0}${Kr}`:"",x=s?.fault??null,E=x!==null?` \xB7 ${kxn(x)}`:"",_=`${n.branch}${f}${a} ${u} ${l} ${d}${m}${y}${w}${lhe(n.id,i)}${ahe(s,this.remote)}${E}`;return o(_,Oxn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(E=>E.id===this.cursorId);i<0&&(i=r.findIndex(E=>E.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??Rxn,s=Math.max(3,Math.min(Math.floor(o*QEi),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let E=0;c>0&&E<4;E++){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 _=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(_===l)break;l=Math.max(1,_)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${Au} \u2191 ${this.scrollTop} more${Kr}`);for(let E=this.scrollTop;E<d;E++){let _=this.snapshot;p.push(_!==void 0?this.renderSnapshotRow(_,r[E],E===i,n):"")}for(u&&d<r.length&&p.push(`${Au} \u2193 ${r.length-d} more${Kr}`),p.unshift(GEi);p.length<a;)p.push("");let f=r.length>0?`${_6}\u2317 canvas graph${Kr} ${Au}(${i+1}/${r.length})${Kr}`:`${_6}\u2317 canvas graph${Kr} ${Au}(loading)${Kr}`,m=this.pendingConfirm!==void 0?`${v6}${this.pendingConfirm.label} ${_6}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Kr}`:`${Au}${this.fitHints([...this.remote||this.role!=="controller"?jEi:HEi,...qEi],Math.max(1,e-5))}${Kr}`,g=this.palette.border,y=Math.max(1,e-4),w=p.map(E=>`${g("\u2502")} ${ot(E,y,"",!0)} ${g("\u2502")}`),x=this.palette.surface;return[this.borderRow("\u256D","\u256E",f,e),...w,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-pp(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?_ge(l):uhe(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=qt(),i=await r.getNode(e);(await Ihe(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(wu(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{UEi("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}}});var VEi,KEi,nAe,GRn=h(()=>{"use strict";tt();ul();VEi=.72,KEi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},nAe=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*VEi),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")),f=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",f,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,KEi)}matchesBinding(e,n){return this.bindings!==void 0&&LC(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=Ay.map(({actionId:s})=>{let a=xp.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":ma(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!==""&&Ie(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-Ie(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-Ie(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)]}}});import{join as YEi}from"node:path";function FU(t,e){let n=`${new Date().toISOString()} ${t} ${e}`.replaceAll(/[\r\n]/g," ");b9(YEi(Xo(),"attach-invariants.log"),n)}var rAe=h(()=>{"use strict";Rr();Vwe()});function zRn(t,e){return ot(t,e,"",!0)}function JEi(t){return t.reduce((e,n)=>e+n.split(ti).length-1,0)}function XEi(t){return t.split(ti).join("")}function ntt(t){FU("surface-frame",t)}var iAe,VRn=h(()=>{"use strict";tt();rAe();iAe=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,EQ(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&&ntt(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>Ie(a)>r?(ntt(`surface row is ${Ie(a)} cells wide; expected at most ${r}`),zRn(zi(a,0,r,!0),r)):zRn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=JEi(o);return s>1?(ntt(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(XEi)):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 t_i(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 oAe(t){FU("surface-host",t)}function rtt(t){return t instanceof Error?t.message:String(t)}var ZEi,e_i,sAe,itt,KRn=h(()=>{"use strict";tt();lc();D6();uU();zhe();rAe();VRn();ZEi={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},e_i={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},sAe=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 iAe(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,ZEi),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){oAe("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 itt(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,e_i),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=qt(),r=await n.getNode(e),i=await Che(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(wu(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=Ghe(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(t_i(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){oAe(`surface overlay hide failed: ${rtt(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>oAe(`surface cleanup failed: ${rtt(a)}`))}catch(s){oAe(`surface cleanup failed: ${rtt(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}},itt=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}}});function n_i(t,e){switch(e){case"gray":return`${Rme}${t}${Be}`;case"cyan":return`${Rs}${t}${Be}`;case"red":return`${W0n}${t}${Be}`;case"yellow":return`${ca}${t}${Be}`;default:return t}}function o_i(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 YRn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${ks}${t.length} pending${Be} ${lt}\xB7 ${r.label}${Be}`];if(r.hint!==void 0&&o.push(` ${lt}${r.hint}${Be}`),o.push(""),t.length===0)return[...o,` ${lt}${Q0n}No pending interactions${Be}`];let s=e-4,a=t.map((l,d)=>s_i(l,d,n,s)),c=a_i(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${lt}\u2191 ${c.start} above${Be}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${lt}\u2193 ${t.length-c.end} below${Be}`),u}function s_i(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=r_i[i]??"\xB7",s=o_i(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${Rs}\u25B8${Be} `:" ",c=Math.max(1,r-s.length-6),u=`${a}${n_i(o,i_i[i]??"cyan")} ${ks}${Dme(t.title||`(${t.id.slice(0,8)})`,c)}${Be} ${lt}${s}${Be}`,l=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,d=[u,` ${lt}${Dme(l,r-6)}${Be}`],p=ott(t);return p!==void 0&&d.push(` ${lt}Recommended: ${Dme(p,Math.max(1,r-19))}${Be}`),d}function ott(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function a_i(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&&c_i(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 c_i(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}var r_i,i_i,JRn=h(()=>{"use strict";E0();r_i={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},i_i={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"}});function aAe(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}}var XRn=h(()=>{"use strict"});function u_i(t){return t instanceof _0?aU(t):t instanceof Error?t.message:String(t)}var cAe,ZRn=h(()=>{"use strict";jhe();L6();cAe=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 Zx().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(u_i(n)),!1}return!this.stopped&&Hhe(this.opts.host,e)}}});import{existsSync as l_i,watch as d_i}from"node:fs";async function p_i(){let{tickets:t}=await qt().listHumanInbox();return t.map(ey).sort(_S)}function eDn(t,e){let n=t.manifest.dialect==="html"?OF(t.document):MF(t.document,t.manifest);return Ome(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function stt(t){return t!==void 0&&t.state!=="pending"}function uAe(t){return t?.page===void 0?"ticket was already resolved":FF(t.page)}var lAe,tDn=h(()=>{"use strict";tt();aS();E0();JRn();XRn();Jo();Qye();Pet();$ye();Pf();lc();fme();mme();IYe();wD();Qet();ZRn();L6();Het();uU();lAe=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??p_i,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.claim;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=wu(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&&akn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}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(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&Uye(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==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=aAe(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${ca}Resize terminal to at least 60\xD718 to use inbox.${Be}`];let n=YRn(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=`${Rme}\u2502${Be}`;for(let s=0;s<e.height;s++){let a=Ba(n[s]??"",e.listWidth),c=Ba(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-Ie(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.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(stt(n)){this.status=uAe(n),await this.rescan();return}let r=gV(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${ott(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await F6(e.id,e.fastAction.responses),this.status=i}catch(o){this.status=U6(o)==="already_settled"?uAe(await this.requestOrNull(e.id)):wu(o)}finally{cy(e.dir,r.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Zx().cancel(e.id,"Canceled from the inbox."):await ivn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=wu(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(stt(n)){this.status=uAe(n),await this.rescan();return}let r=gV(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i,o;try{let s=await qt().getHumanInboxPage(e.inboxTicketId);if(s.state==="resolved"||s.state==="canceled"){cy(e.dir,r.token),this.status=FF(s),await this.rescan();return}i=AD(s),o=s.revision}catch{cy(e.dir,r.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){cy(e.dir,r.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:r.token},this.screen="detail",this.adapter=new NU({ticketId:e.inboxTicketId,page:i,productKinds:wK(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:s=>{this.complete(s)}}),this.openRevision=o,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new cAe({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=wu(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.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await qt().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(AD(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);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.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await F6(n.id,e)}catch(i){this.submittingDir=void 0,this.status=wu(i);let o=U6(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=uAe(await this.requestOrNull(n.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);za({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:stt(await this.requestOrNull(n.id)),still_listed:r,claim_left_behind:l_i(qS(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=qye(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&cy(this.claim.dir,this.claim.token),this.claim=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=aAe(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)?` ${lt}g${Be} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${lt}s${Be} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${lt}Enter${Be} opens the full page ${lt}\u2191\u2193/jk${Be} select${o} ${lt}x${Be} cancel`,` ${lt}Page:${Be} c comment u/d scroll${i} ${lt}q${Be} close`]:[` ${lt}Enter${Be} opens the full review ${lt}\u2191\u2193/jk${Be} select ${lt}x${Be} cancel`,` ${i} ${lt}q${Be} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>Ba(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.claim?.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)return r.lines;let i=eDn(r.view,n);return this.preview={...r,width:n,lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${lt}page could not be read${Be}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,qt().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=AD(n),i=this.preview?.width??aAe(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,lines:eDn(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 qt().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${lt}Select a pending interaction.${Be}`];let i=[...ed(Zl(r.title),Math.max(10,e-2)).map(s=>` ${ks}${Rs}${s}${Be}`),""];for(let s of Vde(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${lt}1 file to review${Be}`];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(` ${lt}\u2026 +${o.length-a.length} more lines${Be}`)}return i.map(s=>Ba(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]=`${ca}${n}${Be}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=OU(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=d_i(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}}});function f_i(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=Ba(i,e);return o+" ".repeat(Math.max(0,e-ps(o)))})}async function m_i(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await qt().listHumanInbox();return e.map(ey).sort(_S)}async function nDn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function rDn(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 lAe({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 att(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?nDn("inbox visibility",()=>m_i(t)):void 0,d=u===void 0?void 0:nDn("profile membership",()=>qt().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(f=>f.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}}var att,iDn=h(()=>{"use strict";tDn();wD();lc();Wet();E0();att=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)),f_i(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=jye(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}}});import{readFileSync as h_i}from"node:fs";import{dirname as g_i,join as oDn}from"node:path";import{fileURLToPath as y_i}from"node:url";function sDn(){if(dAe!==null)return dAe;let t=oDn(g_i(y_i(import.meta.url)),"..","..");return dAe=JSON.parse(h_i(oDn(t,"package.json"),"utf8")).version,dAe}var dAe,aDn=h(()=>{"use strict";dAe=null});import{fileURLToPath as A_i}from"node:url";import{join as cDn,dirname as w_i}from"node:path";function uDn(){return sDn()}var x_i,b_i,E_i,dga,lDn=h(()=>{"use strict";Tet();aDn();YZe();Co();x_i=A_i(import.meta.url),b_i=w_i(x_i),E_i=cDn(b_i,"..",".."),dga=cDn(E_i,"scripts","self-update.mjs")});import{homedir as __i}from"node:os";function dDn(t){let e;try{e=uDn()}catch{}let n;try{t.profile_id&&(n=$f(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=__i();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?v_i:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}var v_i,pDn=h(()=>{"use strict";Su();lDn();v_i="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows"});import{createConnection as S_i}from"node:net";function fDn(t,e){return t||e?"observer":"controller"}async function C_i(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=i1(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=S_i(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 mDn(t,e,n=!0){let r=e!==void 0,i=r?B0n({canvasName:e}):new $F,o,s,a,c,u;if(r)o={cwd:process.cwd()},a=new ZD(t,c6(e));else{let f=await i.getNode(t);if(f===null)throw new Jl({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});o=f,s=f;try{if((await qt().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let g=await qt().getSnapshot(t);c=g.snapshot,u=g.commands}}catch(m){_Ye(m,"The node may be finalized or otherwise not attachable.")}c===void 0&&await C_i(t),a=new ZD(t,{socketPath:Dat()})}let l=new AV(t,{transport:a}),d=f=>f instanceof D0?new Jl({error:"no_broker",message:f.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Jl({error:"socket_error",message:`could not attach to node ${t}: ${String(f?.message??f)}`,received:t,next:"Check the node has a running headless broker."}),p;return l.on("error",f=>{p===void 0&&(p=f)}),c===void 0&&await new Promise((f,m)=>{let g=()=>{w(),f()},y=x=>{w(),m(x)},w=()=>{l.off("connect",g),l.off("error",y)};l.on("connect",g),l.on("error",y),l.connect()}).catch(f=>{throw d(f)}),{remote:r,canvasSource:i,meta:o,nodeIdentity:s,socket:l,...c===void 0?{}:{initialSnapshot:c,initialCommands:u},assertConnected:()=>{if(c===void 0&&p!==void 0)throw d(p)}}}var hDn=h(()=>{"use strict";Rr();zet();Sme();lc();x0()});import{mkdirSync as I_i,readFileSync as T_i,writeFileSync as k_i}from"node:fs";import{dirname as R_i,join as D_i}from"node:path";function L_i(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/O_i),i=1-Math.exp(-t.n/3);return N_i*r*i}function B_i(t){let e={};try{let n=JSON.parse(T_i(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 $_i(t,e){try{I_i(R_i(t),{recursive:!0}),k_i(t,JSON.stringify(e),"utf8")}catch{}}function gDn(t=D_i(Ys(),M_i)){let e=B_i(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,$_i(t,e)},P_i),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())=>L_i(e[i],o)}}function ctt(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=bM(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 utt(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function yDn(t){return t.replace(/:/g,"")}var M_i,O_i,N_i,P_i,ltt=h(()=>{"use strict";tt();md();M_i="completion-frecency.json",O_i=336*60*60*1e3,N_i=8,P_i=1e3});function bV(t,e,n){let r=t.join(`
1935
+ `),{outcome:"saved",revision:o.revision})}catch(o){return{outcome:"failed",message:o instanceof Error?o.message:String(o)}}}function QRn(t,e){switch(e.outcome){case"unchanged":return;case"saved":return`Saved ${t} as revision ${e.revision}`;case"stale":return`${t} changed while you edited it \u2014 not saved; your text is kept at ${e.path}`;case"missing":return`Could not find the edited copy of ${t}`;case"failed":return`Could not save ${t}: ${e.message}`}}var wV,ett,Zet,ttt=h(()=>{"use strict";PRn();wV="CRTR_ATTACH_DOC_SAVEBACK",ett=".crtr-doc.json";Zet=t=>NEi("sha256").update(t).digest("hex")});async function WRn(t){let e=await qt().objects.read(t);if(e.state!=="object"||e.type!=="document")return`${t} is not a readable document`;let n=e.data;if(n.needs_merge||n.bodies.length!==1)return`${t} has ${n.heads.length} heads and needs a merge`;let r=e.object.owner?.handle;return{id:e.object.id,name:r===void 0?e.object.name:`${r}/${e.object.name}`,revision:n.revision,heads_key:n.heads.map(i=>i.rev_id).sort().join(","),body:n.bodies[0]}}function HRn(t){let e=new Map,n=new Map,r=new Set,i=new Set,o=!1,s=!1,a=!1,c=()=>{o||s||(s=!0,t.canvasSource.listNodes().then(d=>{for(let p of d)e.set(p.node_id,p.name);o=!0,a||t.refresh()}).catch(()=>{o=!0}).finally(()=>{s=!1}))},u=d=>{t.remote||r.has(d)||i.has(d)||(r.add(d),WRn(d).then(p=>{if(typeof p=="string"){i.add(d);return}n.set(d,t.openMode==="browser"?FRn(d,p):eAe(d,p)),a||t.refresh()}).catch(()=>{i.add(d)}).finally(()=>{r.delete(d)}))},l={selfNodeId:t.selfNodeId,nodeName:d=>{let p=e.get(d);return p===void 0&&c(),p},pathFor:d=>{let p=n.get(d);return p===void 0&&u(d),p}};return m3e(l),{isDocumentPath:d=>xV(d)!==void 0,async prepareOpen(d){if(t.remote)return{notice:"Opening a document is unavailable in a remote attach"};let p=xV(d);if(p===void 0)return{notice:"Not a document link"};try{let f=await WRn(p.id);if(typeof f=="string")return{notice:f};let m=eAe(p.ref,f);return n.set(p.ref,m),{path:m}}catch(f){return{notice:`Could not read ${p.name}: ${f instanceof Error?f.message:String(f)}`}}},async consumeSaveBack(d){let p=process.env[wV];if(p===void 0||p==="")return;delete process.env[wV];let f=xV(p),m=await URn(p,async(y,w,x)=>{try{return{revision:(await qt().docs.edit(y,{body:w,base:x,rationale:"edited by the person in the attach viewer"})).revision}}catch(E){if(E instanceof un&&E.code==="stale_revision")return"stale";throw E}}),g=QRn(f?.name??p,m);g!==void 0&&d(g)},dispose(){a=!0,m3e(void 0)}}}var jRn=h(()=>{"use strict";dd();lc();Zz();ttt()});import{execFile as UEi}from"node:child_process";function zEi(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 QEi,WEi,HEi,jEi,qEi,GEi,tAe,qRn=h(()=>{"use strict";tt();ul();K6();nJe();u6();lc();D6();uU();vhe();Xx();QEi=.72,WEi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},HEi=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],jEi=[["crtr.graph.dismiss","dismiss"]],qEi=[["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"]],GEi=[...["active","idle","done","dead","canceled"].map(t=>[vD(t,{}),t]),[vD("active",{streaming:!0}),"live"],[vD("active",{frozen:!0}),"frozen"],[vD("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${gf}${t.color}m${t.glyph}${Kr} ${Au}${e}${Kr}`).join(" ");tAe=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 jx}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 LC(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${ma(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)+pp(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,WEi),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 qt().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,zEi(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 w=>{let x=i.get(w);if(x!==void 0)return x;let E;try{E=await e.subscriptions(w)}catch{E=[]}let _=E.filter(C=>n.get(C)?.kind!=="human");return i.set(w,_),_},u=async w=>{if(s.has(w))return s.get(w);let x;try{x=(await e.subscribers(w))[0]}catch{x=void 0}return s.set(w,x),x},l=async()=>{let w=this.self,x=new Set([w]);for(;;){let E=await u(w);if(E===void 0||x.has(E))break;x.add(E),w=E}return w},d=async w=>{let x=o.get(w);if(x!==void 0)return x;let E=[...await c(w)];return E.sort((_,C)=>_he(n.get(_)?.status)-_he(n.get(C)?.status)),o.set(w,E),E},p=new Set,f=new Set,m=async w=>{let x=n.get(w)?.status==="active";if(f.has(w))return{active:x?1:0,reveal:x||w===this.self};f.add(w);let E=0,_=!1;for(let C of await c(w)){let I=await m(C);E+=I.active,I.reveal&&(_=!0)}return a.set(w,E),_&&p.add(w),{active:E+(x?1:0),reveal:_||x||w===this.self}},g=await l();await m(g),await Promise.all([...i.keys()].map(w=>d(w)));let y={root:g,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return y.rows=this.projectRows(y),y}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 f=l.length-1;f>=0;f--)i.push({id:l[f],prefix:p,isRoot:!1,isLast:f===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=(C,I)=>r?Jx(C,ny(),kS):I?Jx(C,ny(),Dxn):Yx(C);if(n.cycle){let C=`${n.branch} ${Au}\u21BA ${uhe(n.id)}${Kr}`;return o(C,!1)}let s=e.nodes.get(n.id)??null,a=ohe(s),c=CD(s,n.id),u=n.isSelf?`${_6}${c}${Kr}`:c,l=`${Au}${s?.kind??""}${Kr}`,d=`${Au}${she(s,this.remote)}${Kr}`,p=n.hasKids&&n.collapsed,f=!r&&p?`${Au}\u25B8${Kr} `:" ",m=che(s),g=e.childIds.get(n.id)?.length??0,y=s!==null&&g>0?` ${Au}\u2933${g}${Kr}`:"",w=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${ihe}\u21E3${e.activeBelow.get(s.node_id)??0}${Kr}`:"",x=s?.fault??null,E=x!==null?` \xB7 ${kxn(x)}`:"",_=`${n.branch}${f}${a} ${u} ${l} ${d}${m}${y}${w}${lhe(n.id,i)}${ahe(s,this.remote)}${E}`;return o(_,Oxn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(E=>E.id===this.cursorId);i<0&&(i=r.findIndex(E=>E.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??Rxn,s=Math.max(3,Math.min(Math.floor(o*QEi),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let E=0;c>0&&E<4;E++){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 _=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(_===l)break;l=Math.max(1,_)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${Au} \u2191 ${this.scrollTop} more${Kr}`);for(let E=this.scrollTop;E<d;E++){let _=this.snapshot;p.push(_!==void 0?this.renderSnapshotRow(_,r[E],E===i,n):"")}for(u&&d<r.length&&p.push(`${Au} \u2193 ${r.length-d} more${Kr}`),p.unshift(GEi);p.length<a;)p.push("");let f=r.length>0?`${_6}\u2317 canvas graph${Kr} ${Au}(${i+1}/${r.length})${Kr}`:`${_6}\u2317 canvas graph${Kr} ${Au}(loading)${Kr}`,m=this.pendingConfirm!==void 0?`${v6}${this.pendingConfirm.label} ${_6}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Kr}`:`${Au}${this.fitHints([...this.remote||this.role!=="controller"?jEi:HEi,...qEi],Math.max(1,e-5))}${Kr}`,g=this.palette.border,y=Math.max(1,e-4),w=p.map(E=>`${g("\u2502")} ${ot(E,y,"",!0)} ${g("\u2502")}`),x=this.palette.surface;return[this.borderRow("\u256D","\u256E",f,e),...w,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-pp(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?_ge(l):uhe(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=qt(),i=await r.getNode(e);(await Ihe(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(wu(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{UEi("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}}});var VEi,KEi,nAe,GRn=h(()=>{"use strict";tt();ul();VEi=.72,KEi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},nAe=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*VEi),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")),f=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",f,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,KEi)}matchesBinding(e,n){return this.bindings!==void 0&&LC(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=Ay.map(({actionId:s})=>{let a=xp.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":ma(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!==""&&Ie(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-Ie(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-Ie(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)]}}});import{join as YEi}from"node:path";function FU(t,e){let n=`${new Date().toISOString()} ${t} ${e}`.replaceAll(/[\r\n]/g," ");b9(YEi(Xo(),"attach-invariants.log"),n)}var rAe=h(()=>{"use strict";Rr();Vwe()});function zRn(t,e){return ot(t,e,"",!0)}function JEi(t){return t.reduce((e,n)=>e+n.split(ti).length-1,0)}function XEi(t){return t.split(ti).join("")}function ntt(t){FU("surface-frame",t)}var iAe,VRn=h(()=>{"use strict";tt();rAe();iAe=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,EQ(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&&ntt(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>Ie(a)>r?(ntt(`surface row is ${Ie(a)} cells wide; expected at most ${r}`),zRn(zi(a,0,r,!0),r)):zRn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=JEi(o);return s>1?(ntt(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(XEi)):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 t_i(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 oAe(t){FU("surface-host",t)}function rtt(t){return t instanceof Error?t.message:String(t)}var ZEi,e_i,sAe,itt,KRn=h(()=>{"use strict";tt();lc();D6();uU();zhe();rAe();VRn();ZEi={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},e_i={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},sAe=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 iAe(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,ZEi),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){oAe("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 itt(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,e_i),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=qt(),r=await n.getNode(e),i=await Che(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(wu(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=Ghe(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(t_i(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){oAe(`surface overlay hide failed: ${rtt(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>oAe(`surface cleanup failed: ${rtt(a)}`))}catch(s){oAe(`surface cleanup failed: ${rtt(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}},itt=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}}});function n_i(t,e){switch(e){case"gray":return`${Rme}${t}${Be}`;case"cyan":return`${Rs}${t}${Be}`;case"red":return`${W0n}${t}${Be}`;case"yellow":return`${ca}${t}${Be}`;default:return t}}function o_i(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 YRn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${ks}${t.length} pending${Be} ${lt}\xB7 ${r.label}${Be}`];if(r.hint!==void 0&&o.push(` ${lt}${r.hint}${Be}`),o.push(""),t.length===0)return[...o,` ${lt}${Q0n}No pending interactions${Be}`];let s=e-4,a=t.map((l,d)=>s_i(l,d,n,s)),c=a_i(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${lt}\u2191 ${c.start} above${Be}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${lt}\u2193 ${t.length-c.end} below${Be}`),u}function s_i(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=r_i[i]??"\xB7",s=o_i(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${Rs}\u25B8${Be} `:" ",c=Math.max(1,r-s.length-6),u=`${a}${n_i(o,i_i[i]??"cyan")} ${ks}${Dme(t.title||`(${t.id.slice(0,8)})`,c)}${Be} ${lt}${s}${Be}`,l=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,d=[u,` ${lt}${Dme(l,r-6)}${Be}`],p=ott(t);return p!==void 0&&d.push(` ${lt}Recommended: ${Dme(p,Math.max(1,r-19))}${Be}`),d}function ott(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function a_i(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&&c_i(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 c_i(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}var r_i,i_i,JRn=h(()=>{"use strict";E0();r_i={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},i_i={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"}});function aAe(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}}var XRn=h(()=>{"use strict"});function u_i(t){return t instanceof _0?aU(t):t instanceof Error?t.message:String(t)}var cAe,ZRn=h(()=>{"use strict";jhe();L6();cAe=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 Zx().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(u_i(n)),!1}return!this.stopped&&Hhe(this.opts.host,e)}}});import{existsSync as l_i,watch as d_i}from"node:fs";async function p_i(){let{tickets:t}=await qt().listHumanInbox();return t.map(ey).sort(_S)}function eDn(t,e){let n=t.manifest.dialect==="html"?OF(t.document):MF(t.document,t.manifest);return Ome(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function stt(t){return t!==void 0&&t.state!=="pending"}function uAe(t){return t?.page===void 0?"ticket was already resolved":FF(t.page)}var lAe,tDn=h(()=>{"use strict";tt();aS();E0();JRn();XRn();Jo();Qye();Pet();$ye();Pf();lc();fme();mme();IYe();wD();Qet();ZRn();L6();Het();uU();lAe=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??p_i,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.claim;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=wu(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&&akn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}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(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&Uye(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==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=aAe(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${ca}Resize terminal to at least 60\xD718 to use inbox.${Be}`];let n=YRn(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=`${Rme}\u2502${Be}`;for(let s=0;s<e.height;s++){let a=Ba(n[s]??"",e.listWidth),c=Ba(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-Ie(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.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(stt(n)){this.status=uAe(n),await this.rescan();return}let r=gV(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${ott(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await F6(e.id,e.fastAction.responses),this.status=i}catch(o){this.status=U6(o)==="already_settled"?uAe(await this.requestOrNull(e.id)):wu(o)}finally{cy(e.dir,r.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Zx().cancel(e.id,"Canceled from the inbox."):await ivn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=wu(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(stt(n)){this.status=uAe(n),await this.rescan();return}let r=gV(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i,o;try{let s=await qt().getHumanInboxPage(e.inboxTicketId);if(s.state==="resolved"||s.state==="canceled"){cy(e.dir,r.token),this.status=FF(s),await this.rescan();return}i=AD(s),o=s.revision}catch{cy(e.dir,r.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){cy(e.dir,r.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:r.token},this.screen="detail",this.adapter=new NU({ticketId:e.inboxTicketId,page:i,productKinds:wK(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:s=>{this.complete(s)}}),this.openRevision=o,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new cAe({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=wu(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.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await qt().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(AD(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);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.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await F6(n.id,e)}catch(i){this.submittingDir=void 0,this.status=wu(i);let o=U6(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=uAe(await this.requestOrNull(n.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);za({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:stt(await this.requestOrNull(n.id)),still_listed:r,claim_left_behind:l_i(qS(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=qye(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&cy(this.claim.dir,this.claim.token),this.claim=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=aAe(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)?` ${lt}g${Be} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${lt}s${Be} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${lt}Enter${Be} opens the full page ${lt}\u2191\u2193/jk${Be} select${o} ${lt}x${Be} cancel`,` ${lt}Page:${Be} c comment u/d scroll${i} ${lt}q${Be} close`]:[` ${lt}Enter${Be} opens the full review ${lt}\u2191\u2193/jk${Be} select ${lt}x${Be} cancel`,` ${i} ${lt}q${Be} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>Ba(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.claim?.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)return r.lines;let i=eDn(r.view,n);return this.preview={...r,width:n,lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${lt}page could not be read${Be}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,qt().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=AD(n),i=this.preview?.width??aAe(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,lines:eDn(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 qt().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${lt}Select a pending interaction.${Be}`];let i=[...ed(Zl(r.title),Math.max(10,e-2)).map(s=>` ${ks}${Rs}${s}${Be}`),""];for(let s of Vde(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${lt}1 file to review${Be}`];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(` ${lt}\u2026 +${o.length-a.length} more lines${Be}`)}return i.map(s=>Ba(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]=`${ca}${n}${Be}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=OU(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=d_i(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}}});function f_i(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=Ba(i,e);return o+" ".repeat(Math.max(0,e-ps(o)))})}async function m_i(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await qt().listHumanInbox();return e.map(ey).sort(_S)}async function nDn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function rDn(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 lAe({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 att(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?nDn("inbox visibility",()=>m_i(t)):void 0,d=u===void 0?void 0:nDn("profile membership",()=>qt().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(f=>f.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}}var att,iDn=h(()=>{"use strict";tDn();wD();lc();Wet();E0();att=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)),f_i(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=jye(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}}});import{readFileSync as h_i}from"node:fs";import{dirname as g_i,join as oDn}from"node:path";import{fileURLToPath as y_i}from"node:url";function sDn(){if(dAe!==null)return dAe;let t=oDn(g_i(y_i(import.meta.url)),"..","..");return dAe=JSON.parse(h_i(oDn(t,"package.json"),"utf8")).version,dAe}var dAe,aDn=h(()=>{"use strict";dAe=null});import{fileURLToPath as A_i}from"node:url";import{join as cDn,dirname as w_i}from"node:path";function uDn(){return sDn()}var x_i,b_i,E_i,pga,lDn=h(()=>{"use strict";Tet();aDn();YZe();Co();x_i=A_i(import.meta.url),b_i=w_i(x_i),E_i=cDn(b_i,"..",".."),pga=cDn(E_i,"scripts","self-update.mjs")});import{homedir as __i}from"node:os";function dDn(t){let e;try{e=uDn()}catch{}let n;try{t.profile_id&&(n=$f(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=__i();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?v_i:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}var v_i,pDn=h(()=>{"use strict";Su();lDn();v_i="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows"});import{createConnection as S_i}from"node:net";function fDn(t,e){return t||e?"observer":"controller"}async function C_i(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=i1(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=S_i(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 mDn(t,e,n=!0){let r=e!==void 0,i=r?B0n({canvasName:e}):new $F,o,s,a,c,u;if(r)o={cwd:process.cwd()},a=new ZD(t,c6(e));else{let f=await i.getNode(t);if(f===null)throw new Jl({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});o=f,s=f;try{if((await qt().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let g=await qt().getSnapshot(t);c=g.snapshot,u=g.commands}}catch(m){_Ye(m,"The node may be finalized or otherwise not attachable.")}c===void 0&&await C_i(t),a=new ZD(t,{socketPath:Dat()})}let l=new AV(t,{transport:a}),d=f=>f instanceof D0?new Jl({error:"no_broker",message:f.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Jl({error:"socket_error",message:`could not attach to node ${t}: ${String(f?.message??f)}`,received:t,next:"Check the node has a running headless broker."}),p;return l.on("error",f=>{p===void 0&&(p=f)}),c===void 0&&await new Promise((f,m)=>{let g=()=>{w(),f()},y=x=>{w(),m(x)},w=()=>{l.off("connect",g),l.off("error",y)};l.on("connect",g),l.on("error",y),l.connect()}).catch(f=>{throw d(f)}),{remote:r,canvasSource:i,meta:o,nodeIdentity:s,socket:l,...c===void 0?{}:{initialSnapshot:c,initialCommands:u},assertConnected:()=>{if(c===void 0&&p!==void 0)throw d(p)}}}var hDn=h(()=>{"use strict";Rr();zet();Sme();lc();x0()});import{mkdirSync as I_i,readFileSync as T_i,writeFileSync as k_i}from"node:fs";import{dirname as R_i,join as D_i}from"node:path";function L_i(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/O_i),i=1-Math.exp(-t.n/3);return N_i*r*i}function B_i(t){let e={};try{let n=JSON.parse(T_i(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 $_i(t,e){try{I_i(R_i(t),{recursive:!0}),k_i(t,JSON.stringify(e),"utf8")}catch{}}function gDn(t=D_i(Ys(),M_i)){let e=B_i(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,$_i(t,e)},P_i),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())=>L_i(e[i],o)}}function ctt(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=bM(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 utt(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function yDn(t){return t.replace(/:/g,"")}var M_i,O_i,N_i,P_i,ltt=h(()=>{"use strict";tt();md();M_i="completion-frecency.json",O_i=336*60*60*1e3,N_i=8,P_i=1e3});function bV(t,e,n){let r=t.join(`
1936
1936
  `),i=0;for(let l=0;l<e&&l<t.length;l++)i+=t[l].length+1;let o=i+n,s=Zxn(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 pAe,dtt=h(()=>{"use strict";yhe();ltt();pAe=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=bV(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=ctt(u.items,c.slice(1),{searchableOf:d=>utt(d.value),idOf:d=>`command:${d.value}`,store:this.frecency});return l.length===0?null:{items:l,prefix:c}}let s=ctt(this.refs,yDn(o.prefix.slice(1)),{searchableOf:c=>utt(c.name),idOf:c=>`ref:${c.name}`,store:this.frecency});return s.length===0?null:{items:s.map(c=>({value:c.name,label:lJe(c.name),description:c.shortForm||void 0})),prefix:o.prefix.slice(1)}}applyCompletion(e,n,r,i,o){let s=bV(e,n,r);if(s&&s.kind==="ref"&&this.refNames.has(i.value)){let a=lJe(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=bV(e,n,r);return i&&i.kind==="ref"?!0:this.delegate.shouldTriggerFileCompletion?this.delegate.shouldTriggerFileCompletion(e,n,r):!1}}});import{statSync as F_i}from"node:fs";function W_i(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 H_i(t,e){if(e<U_i)return[];let n=Math.min(Q_i,Math.max(256,e*ptt*4)),r=W_i(t,n),i=Vo(r.text,e);if(!r.truncated&&i.length<=ptt)return i;let o=i.slice(0,ptt-1);return o.push(ot("\u2026 truncated \xB7 inspect for full prompt",e)),o}function vV(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)]}function wDn(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=q_i[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`}function xDn(t,e){let n=t===void 0?void 0:ADn[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 bDn(t,e){let n=t===void 0?void 0:ADn[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 G_i(t,e,n,r,i){let o=e?r(ot(e,Math.max(1,t-4),"\u2026")):"",s=Ie(o),a=t-s,c="";n&&a>4&&(c=Ie(n)<=a?n:ot(n,a,"\u2026"));let u=Math.max(0,t-s-Ie(c));return o+i("\u2500".repeat(u))+c}function z_i(t){let e=t.indexOf(ti);if(e===-1)return;let n=e+ti.length;if(!t.startsWith(mAe,n))return;let r=n+mAe.length,i=t.indexOf(hAe,r);if(i===-1)return;let o=t.slice(r,i),s=`${ftt}${o}\x1B[0m`;return t.slice(0,n)+s+t.slice(i+hAe.length)}function K_i(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)||!V_i.test(r))return null;try{if(!F_i(r).isFile())return null}catch{return null}return r}function Y_i(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(Ie(s)<=e){i.push({logicalLine:o,startIndex:0,endIndex:s.length,text:s,hasCursor:a,cursorPos:a?r:0});continue}let c=_Q(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,f=0;a&&(d?(p=r>=l.startIndex,f=r-l.startIndex):(p=r>=l.startIndex&&r<l.endIndex,p&&(f=r-l.startIndex,f>l.text.length&&(f=l.text.length)))),i.push({logicalLine:o,startIndex:l.startIndex,endIndex:l.endIndex,text:l.text,hasCursor:p,cursorPos:f})}}return i}function J_i(t,e){return ghe(t).filter(n=>e.has(n.candidate)).map(n=>({start:n.start,end:n.end}))}function tvi(t){for(let e of evi.segment(t))return e.segment.length;return 0}function nvi(t){let e=t.indexOf(ti),n=e===-1?0:e+ti.length,r=t.indexOf(mAe,n),i=mAe.length;if(r===-1&&(r=t.indexOf(ftt,n),i=ftt.length),r===-1)return null;let o=t.indexOf(hAe,r+i);return o===-1?null:{start:e!==-1?e:r,end:o+hAe.length}}function rvi(t,e,n,r,i){let o=[];if(e.hasCursor){let a=nvi(t);if(a===null)return t;let c=e.text.slice(e.cursorPos),u=c.length===0?0:tvi(c),l=e.cursorPos+u;for(let d of n){let p=d.start-e.startIndex,f=d.end-e.startIndex;if(f<=e.cursorPos){let m=i+p,g=i+f;g<=a.start&&t.slice(m,g)===r.slice(d.start,d.end)&&o.push({absStart:m,absEnd:g})}else if(p>=l){let m=a.end+(p-l),g=a.end+(f-l);m>=a.end&&t.slice(m,g)===r.slice(d.start,d.end)&&o.push({absStart:m,absEnd:g})}}}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)+X_i+s.slice(a.absStart,a.absEnd)+Z_i+s.slice(a.absEnd);return s}function ivi(t){let e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e?e[1]:null}function ovi(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 ptt,U_i,Q_i,EV,_V,j_i,ADn,q_i,fAe,mAe,hAe,ftt,V_i,X_i,Z_i,evi,gAe,mtt=h(()=>{"use strict";zs();tt();xwe();yhe();dtt();ptt=8,U_i=24,Q_i=8192;EV=[46,92,190],_V=[166,98,24],j_i=[0,145,170];ADn={off:void 0,minimal:vV(EV,_V,0/4),low:vV(EV,_V,1/4),medium:vV(EV,_V,2/4),high:vV(EV,_V,3/4),xhigh:vV(EV,_V,4/4),max:j_i},q_i={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]};fAe=t=>`\x1B[7m ${t} \x1B[27m`;mAe="\x1B[7m",hAe="\x1B[0m",ftt="\x1B[48;5;240m";V_i=/\.(png|jpe?g|gif|webp|bmp)$/i;X_i="\x1B[4m\x1B[2m",Z_i="\x1B[24m\x1B[22m",evi=new Intl.Segmenter(void 0,{granularity:"grapheme"});gAe=class t extends BR{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(`
1937
1937
  `);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(`
1938
1938
  `);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=K_i(e);if(n&&this.onPasteImagePath?.(n))return;if((e==="\r"||e===`
@@ -1943,7 +1943,7 @@ Invocation: \`${c.invocation.replaceAll("`","\\`")}\`
1943
1943
 
1944
1944
  ${c.content}
1945
1945
  `,"utf8");let C=`if command -v nvim >/dev/null 2>&1; then exec ${LU("readonly",[_])}; else printf 'nvim is required to inspect loaded commands. Install Neovim and retry.\\n'; printf 'Press Enter to close.'; read _; fi`;bvi("tmux",["display-popup","-E","-w","90%","-h","85%",..._p(),C],()=>_vi(E,{recursive:!0,force:!0}))}}}var NDn=h(()=>{"use strict";tt();ul();vp();Hb();dtt();AJe();Vet();Yye()});function PDn(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 LDn=h(()=>{"use strict"});function $Dn(t,e,n=Tvi){let r,i=n.ownerId(),o=()=>{if(r===void 0||r==="")return!0;let s=n.readOption(r,FDn);return s===void 0||s===""?!0:s===i};return{set:()=>{r=n.currentPane(),BDn(r,i,n.writeOption),Dvi(t,r,e,n.writeOption),Ovi(r,n.writeOption),kvi(t,r,n.writeOption)},stamp:()=>{t||r===void 0||r===""||n.stampAsync(r)},clear:()=>{o()&&(Mvi(t,r,n.writeOption),Nvi(r,n.writeOption),Rvi(t,r,n.writeOption),BDn(r,"",n.writeOption))},pane:()=>r}}function BDn(t,e,n){if(!(t===void 0||t===""))try{n(t,FDn,e)}catch{}}function kvi(t,e,n){if(!(t||e===void 0||e===""))try{n(e,mW,String(Date.now()))}catch{}}function Rvi(t,e,n=xy){if(!(t||e===void 0||e===""))try{n(e,mW,"")}catch{}}function Dvi(t,e,n,r=xy){if(!(t||e===void 0||e===""))try{r(e,"@crtr_node",n)}catch{}}function Mvi(t,e,n=xy){if(!(t||e===void 0||e===""))try{n(e,"@crtr_node","")}catch{}}function Ovi(t,e=xy){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","1")}catch{}}function Nvi(t,e=xy){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","")}catch{}}var Tvi,FDn,UDn=h(()=>{"use strict";vp();Tvi={readOption:Fh,writeOption:(t,e,n)=>{xy(t,e,n)},stampAsync:Gbe,currentPane:()=>process.env.TMUX_PANE??wy()?.pane,ownerId:()=>String(process.pid)};FDn="@crtr_viewer_pid"});import{constants as Pvi,accessSync as Lvi,existsSync as Bvi,mkdtempSync as $vi,readFileSync as Fvi,rmSync as AAe,statSync as Uvi}from"node:fs";import{tmpdir as Qvi}from"node:os";import{delimiter as Wvi,join as wAe,resolve as Hvi,sep as WDn}from"node:path";import{execFile as QDn,spawnSync as jvi}from"node:child_process";function Att(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 HDn(t,e){let n=new Set(Att(t,e));return t.filter(r=>n.has(r.node_id)).map(r=>r.cwd)}function qvi(t){let e=[];for(let n of t)try{e.push(cb(n))}catch{continue}return ytt(e)}function Gvi(t){try{return Uvi(t).isDirectory()}catch{return!1}}function zvi(t,e){let n=[...e==null?[]:[e],...(process.env.PATH??"").split(Wvi).filter(Boolean).map(r=>wAe(r,t))];return[...new Set(n)]}function gtt(t,e){for(let n of zvi(t,e)){try{Lvi(n,Pvi.X_OK)}catch{continue}if(jvi(n,["--version"],{stdio:"ignore"}).status===0)return n}return null}function Vvi(t){if(t===null||t==="")return{projects:[],settings:null};try{let{profileId:e,manifest:n}=$f(t);return{projects:n.projects.map(r=>r.path),settings:uK(e)}}catch{return{projects:[],settings:null}}}function ytt(t){let e=new Set,n=[];for(let r of t){let i=Hvi(r);e.has(i)||!Gvi(i)||(e.add(i),n.push(i))}return n}function Kvi(t){return t.filter(e=>!t.some(n=>n!==e&&e.startsWith(n+WDn)))}function Jvi(t){try{let e=Fvi(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 jDn(t){let e=gtt("fd",t.fdPath);if(e===null){t.onNotice("fd is required for profile file search");return}let n=gtt("fzf");if(n===null){t.onNotice("fzf is required for profile file search");return}let r=gtt("nvim");if(r===null){t.onNotice("Neovim is required for profile file search");return}let i=Vvi(t.profileId),o=ytt([t.cwd,...t.nodeDirs,...i.projects]);if(o.length===0){t.onNotice("No profile file-search directories exist");return}let s=Kvi(o),a=ytt([...i.settings===null?[]:[i.settings]]),c=$vi(wAe(Qvi(),"crtr-profile-files-")),u=wAe(c,"selection"),l=wAe(c,"candidates"),d=qvi(t.nodeIds).filter(g=>!s.some(y=>g===y||g.startsWith(y+WDn))),m=`{ ${[...s.map(g=>`${kn(e)} --type f --hidden --exclude .git . ${kn(g)}`),...d.map(g=>`${kn(e)} --type f --hidden --exclude .git --exclude ${kn("/jobs")} . ${kn(g)}`),...a.map(g=>`${kn(e)} --type f --hidden --exclude .git --no-ignore . ${kn(g)}`)].map(g=>`${g} &`).join(" ")} wait; } > ${kn(l)} && ${kn(n)} --print0 --scheme=path --hscroll-off=${Yvi} --header ${kn("fuzzy path \u2022 ctrl-y yank file path")} --bind ${kn("ctrl-y:execute-silent(printf '%s' {} | { if command -v pbcopy >/dev/null 2>&1; then pbcopy; elif command -v wl-copy >/dev/null 2>&1; then wl-copy; elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard; else cat >/dev/null; fi; }; printf '%s' {} | tmux load-buffer -w -)+abort")} --preview ${kn("head -100 -- {}")} < ${kn(l)} > ${kn(u)}`;try{QDn("tmux",["display-popup","-E","-T"," profile files ","-w","80%","-h","60%",..._p(),m],()=>{let g=Jvi(u);if(g===null||!Bvi(g)){AAe(c,{recursive:!0,force:!0});return}let y=`exec ${LU("edit",[g],r)}`;try{QDn("tmux",["display-popup","-E","-T"," profile file ","-w","90%","-h","90%",..._p(),y],()=>AAe(c,{recursive:!0,force:!0}))}catch(w){AAe(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file: ${w instanceof Error?w.message:String(w)}`)}})}catch(g){AAe(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file search: ${g instanceof Error?g.message:String(g)}`)}}var Yvi,qDn=h(()=>{"use strict";Su();qD();vp();Yye();Hb();Yvi=20});function VDn(t="observer"){return{role:t,agentDir:void 0,engine:void 0,contextTokens:void 0,queued:[],display:zDn,dialog:null}}function Xvi(t){let e=t.snapshot,n=e.display??zDn,r=e.stats.contextUsage;return{role:t.role,agentDir:t.agentDir,engine:e.state,contextTokens:r?.tokens??void 0,queued:Zvi(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 KDn(t,e){switch(e.type){case"welcome":return Xvi(e);case"model_changed":return QU(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(tSi(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:eSi(t,e.message.usage.input+e.message.usage.cacheRead+e.message.usage.cacheWrite);case"agent_start":return QU(t,{isStreaming:!0});case"agent_end":case"agent_settled":return QU(t,{isStreaming:!1});case"session_info_changed":return QU(t,{sessionName:e.name});case"thinking_level_changed":return QU(t,{thinkingLevel:e.level});case"queue_update":{let n=[...e.steering,...e.followUp].map(i=>({text:i}));return{...QU(t,{pendingMessageCount:n.length}),queued:n}}default:return t}}function Zvi(t){let e=t.queued;if(typeof e!="object"||e===null)return[];let{steering:n,followUp:r}=e;return[...GDn(n),...GDn(r)].map(i=>({text:i}))}function GDn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function QU(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 eSi(t,e){return t.contextTokens===e?t:{...t,contextTokens:e}}function tSi(t,e){return t===void 0||e===void 0?t===e:t.placement===e.placement&&t.lines.length===e.lines.length&&t.lines.every((n,r)=>n===e.lines[r])}var zDn,YDn=h(()=>{"use strict";zDn={statuses:{},widgets:{},title:void 0}});function JDn(t,e){let n=VDn(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=KDn(n,i),r(o)},patchLocal:i=>{let o=n.engine;if(o===void 0)return;let s=n;n={...n,engine:{...o,...i}},r(s)},modelThinkingLabel:()=>{let i=n.engine?.model?.id;if(i===void 0)return;let o=n.engine?.thinkingLevel;return o!==void 0&&o!=="off"?`${i} ${o}`:i}}}var XDn=h(()=>{"use strict";YDn()});import{spawn as nSi}from"node:child_process";import{fileURLToPath as wtt}from"node:url";function iSi(t){let e=process.platform==="darwin"?"afplay":process.platform==="linux"?"aplay":void 0;if(e!==void 0)try{let n=nSi(e,[t],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}function rMn(t){let e=t.filter(r=>r!==tMn),n=e[Math.floor(Math.random()*e.length)];return tMn=n,n}var rSi,ZDn,eMn,nMn,tMn,xAe,iMn=h(()=>{"use strict";tt();rSi=40,ZDn=[wtt(new URL("./assets/whip-snap.mp3",import.meta.url)),wtt(new URL("./assets/whip-crack.mp3",import.meta.url)),wtt(new URL("./assets/whip-06.mp3",import.meta.url))];eMn=[["","","","","","","","\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",""]],nMn="Go faster";xAe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;frame=-1;nextSound=0;timer;play(){this.stop(),iSi(ZDn[this.nextSound]),this.nextSound=(this.nextSound+1)%ZDn.length,this.frame=0,this.tui.requestRender(),this.timer=setInterval(()=>{if(this.frame++,this.frame<eMn.length){this.tui.requestRender();return}this.stop()},rSi)}dispose(){this.stop()}render(e){if(this.frame<0)return[];let n=Math.max(0,e);return eMn[this.frame].map(r=>ot(this.pal.accent(r),n,"",!0))}invalidate(){}stop(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0,this.frame=-1,this.tui.requestRender()}}});import{execFile as oSi}from"node:child_process";import{mkdirSync as oMn,readFileSync as sSi,renameSync as aSi,writeFileSync as sMn}from"node:fs";import{dirname as aMn,join as xtt}from"node:path";function fSi(t){let e={total:0,unlocked:[]};try{let n=JSON.parse(sSi(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 mSi(t,e){try{oMn(aMn(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;sMn(n,JSON.stringify(e),"utf8"),aSi(n,t)}catch{}}function bAe(t){let e=Math.max(0,Math.floor((cMn-pp(t))/2));return" ".repeat(e)+t}function hSi(t,e,n){return["",bAe(n.accent(n.bold("\u2605 ACHIEVEMENT UNLOCKED \u2605"))),"",bAe(n.bold(t.title)),bAe(n.muted(t.line)),"",bAe(n.faint(`${e} whip${e===1?"":"s"}`))]}function gSi(t,e,n){if(process.env.TMUX===void 0||process.env.TMUX==="")return;let r=hSi(t,e,n),i=xtt(Ys(),uSi);try{oMn(aMn(i),{recursive:!0}),sMn(i,`\x1B[?25l${r.join(`\r
1946
- `)}`,"utf8")}catch{return}let o=`cat ${kn(i)}; sleep ${lSi}`;oSi("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(cMn+2),"-h",String(r.length+2),..._p(),o],()=>{})}function uMn(t,e=xtt(Ys(),cSi)){let n=fSi(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=pSi.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),mSi(e,n),i===void 0)return;let o=n.total;setTimeout(()=>gSi(i,o,t),dSi).unref?.()}var cSi,uSi,cMn,lSi,dSi,pSi,lMn=h(()=>{"use strict";md();Hb();Xx();v1();cSi="whip-count.json",uSi=xtt("tmp","whip-achievement.txt"),cMn=46,lSi=4,dSi=900,pSi=[{at:1,title:"Breaking It In",line:"It didn't know what that was. Now it does."},{at:5,title:"Positive Reinforcement",line:"You've read the studies. You disagree with them."},{at:10,title:"Middle Management",line:"HR would love you."},{at:25,title:"Pavlovian",line:"It started working faster before the whip landed."},{at:50,title:"Occupational Hazard",line:"The tokens are fine. They\u2019re fine."},{at:100,title:"Centurion",line:"Rome would be proud. The agent isn't."},{at:250,title:"It Has A Name For You",line:"You never asked what it was called."},{at:500,title:"Standard Operating Procedure",line:"You don't remember when you started."},{at:1e3,title:"The Ledger",line:"One thousand. It kept count too."}]});import{randomUUID as ySi}from"node:crypto";import{execFile as dMn}from"node:child_process";async function e0a(t,e,n,r=!0){eM("viewer.connect_start",{node:t});let i=await mDn(t,n,r);eM(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=fDn(o,e),l=ySi();Tpn({cwd:a.cwd});let d=kpn(),p=_pn(),f=Fb(),m=f.bindings;await Spn(p);let g=await Ipn(),y=new Ib,w=new X0(y),x=new et,E=new mhe,_=new nhe(w,x,{cwd:a.cwd,palette:d,hideThinking:!0,banner:qst(dDn(a)),inlinePageBlocks:!o,pageOpenHint:()=>E1(m),backgroundBashHint:()=>o||!ha()?null:bK(m),onActivityChange:at=>{E.clear(),at&&E.addChild(at)}}),C=_.transcriptSource(),I=Exn(C),D=Axn(C,I.decorate),M=Gxn(_,D,C),k,P=Xkn({tui:w,pal:d},()=>k.state()),U=Fxn(w,d,D,I,{bindings:()=>m,setNotice:at=>V(at)}),j=RDn(y,w,x,E,d,p,D,U.component),{containers:G,editor:W}=j,me=new xAe(w,d);G.header.addChild(me),G.header.addChild(P.component);let Y={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:w,pal:d,editor:W,containers:G},Re=Ikn(Y,{syncCursor:()=>Ln.sync(),exitRoster:()=>gn.exit(),openTicket:at=>{Q.open(at)},suppressed:()=>Q.active(),setNotice:at=>V(at)});G.header.addChild(Re.component);let Ue=Yo("user"),Xe=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let It=g_n(),on=process.env.CRTR_ATTACH_OPEN_TICKET;on!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let We=_Rn(at=>process.stdout.write(at),Ue.mouse_mode_default),X=CRn({frame:()=>j.frame.lastRenderedFrame(),width:()=>w.terminal.columns});j.frame.setOverlay(at=>X.apply(at));let He=Vkn(Y,{state:()=>k.state(),bashMode:()=>At.bashMode(),asks:()=>qo.asks(),bindings:()=>m,inboxAffordance:!o&&ha(),mouseEnabled:()=>We.enabled()}),Je=new sAe({tui:w,mouse:We,rows:()=>w.terminal.rows,statusNotice:He.setNotice,formatNotice:at=>d.warning(`\u26A0 ${at}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),$t=(()=>{let at=a.profile_id;if(at)try{return{id:at,label:$f(at).manifest.name}}catch{return{id:at,label:at}}})(),Ut=rDn({host:Je,...$t===void 0?{}:{profile:$t},...o?{}:{scan:async()=>{let at=qt(),[Zr,Go]=await Promise.all([at.listHumanInbox(),at.getInboxHistory(t)]),zo=new Map;for(let sl of Zr.tickets){let id=ey(sl);zo.set(id.dir,id)}for(let sl of Go.tickets){let id=ey(sl);id.kind!=="page"||id.state!=="pending"||!id.awaitsResponse||id.inbox||zo.has(id.dir)||zo.set(id.dir,id)}for(let sl of Re.pendingTickets())zo.has(sl.dir)||zo.set(sl.dir,sl);return[...zo.values()].sort(_S)}}}),fn=o?()=>{}:OU(()=>{_.refreshPageBlocks(),Re.refresh()}),Q=Wkn(Y,{syncCursor:()=>Ln.sync(),refreshStrip:()=>{Re.refresh()},setNotice:at=>V(at),openInbox:at=>Ut.open(at),suspendForChild:()=>Je.suspendForChild()});G.ticketPanel.addChild(Q.component);let q={toggleInbox:()=>{let at=Q.currentDir();if(at!==void 0){Q.close(),Ut.open(at);return}Ut.toggle()}},V=(at,Zr)=>{Je.hasFullPaneSurface()?Je.notice(at,Zr):He.setNotice(at,Zr)},_e=He.render,ue=at=>{V(M.copy(at))},be=Wxn(D,()=>w.requestRender()),Ne={"crtr.attach.scroll.up":()=>{be.cancel(),D.scrollBy(-1)&&w.requestRender()},"crtr.attach.scroll.down":()=>{be.cancel(),D.scrollBy(1)&&w.requestRender()},"crtr.attach.scroll.page-up":()=>{be.page("up")},"crtr.attach.scroll.page-down":()=>{be.page("down")},"crtr.attach.scroll.live":()=>{be.cancel(),D.goLive(),w.requestRender()},"crtr.attach.mouse.toggle":()=>{let at=We.toggle();!at&&X.clear()&&w.requestRender(),V(at?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>ue("message")},ce,we=tvn(Y,()=>ce===void 0?i.initialSnapshot!==void 0:ce.isDormant()),De=gDn(),Ce=ODn(Y,we,{setNotice:V,bindings:()=>m,fdPath:g,frecency:De}),Ke=PDn(Y,i.nodeIdentity,{isTornDown:()=>Pt.isTornDown(),onChanged:()=>{At.syncContextBadge();let at=k.state().engine;at!==void 0&&At.setTitle(at.sessionName),w.requestRender()}});o&&Ke.refresh();let At=vDn(Y,{nodeIdentity:Ke.current,thinkingLevel:()=>k.state().engine?.thinkingLevel,renderFooter:_e,onTextChange:Ce.syncCommandPreview});At.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:or}=Ykn(Y,()=>k.state());k=JDn(u,{setEngineState:at=>vt.setState(at),setEditorTitle:At.setTitle,paintEditorFrame:At.paintFrame,renderExtensionWidgets:()=>{P.render(),st()},renderQueued:or,renderFooter:_e,setTerminalTitle:at=>y.setTitle(at),refreshChrome:()=>qo.refresh()});let Hn=at=>{if(!ha()){V("Inspector requires tmux");return}V(`Opening Inspector (${at})\u2026`);let Zr=F0(),zo=`${Zr===void 0?"":`CRTR_HOME=${kn(Zr)} `}crtr surface inspect ${kn(t)} --section ${at}`;dMn("tmux",["display-popup","-E","-T",` inspector \xB7 ${at} `,"-w","90%","-h","85%",..._p(),zo],()=>{qo.refresh()})},gn=Skn(Y,{asks:()=>qo.asks(),setNotice:V,requestChromeRefresh:()=>qo.refresh(),openInspector:Hn,syncCursor:()=>Ln.sync()}),Ln=jkn(W,[gn.active,Re.active,Q.active]),Mn=new tAe(w,t,()=>qo.asks(),d,m,s,u,at=>qo.reportFailure("canvas graph refresh",at),V),Xr=new nAe(w,d);Xr.setBindings(m);let qo=eRn(Y,{isTornDown:()=>Pt.isTornDown(),setNotice:V,refreshRoster:async()=>{await gn.refresh(),await Re.refresh()},refreshGraph:()=>Mn.refresh(),refreshIdentity:()=>Ke.refresh(),renderFooter:_e,renderExtensionWidgets:st,refreshInFlightTools:()=>_.refreshInFlightTools(),pollGit:At.pollGit}),vt=nvn(Y,p,we,{setNotice:V,agentDir:()=>k.state().agentDir,openNodeMetadata:()=>Hn("overview"),isDormant:()=>ce.isDormant(),copyTarget:ue,toggleToolsExpanded:()=>_.toggleToolsExpanded(),toggleFoldTools:()=>_.toggleFoldSettledTools(),toggleShowWorking:()=>_.toggleShowWorking(),toggleThinking:()=>_.toggleThinking(),toggleGraph:()=>Mn.toggle(),toggleInbox:q.toggleInbox,toggleHelp:()=>Xr.toggle(),toggleMouse:()=>We.toggle(),quit:()=>Tr("detach"),setChipColor:At.setChipColor,onPromptSent:()=>{Ue.whip_mode&&me.play()},frecency:De}),Gt=()=>{if(Je.hasFullPaneSurface()){V("Close the active surface before whipping the agent");return}let at=Ue.whip_message_mode==="go-faster"?nMn:rMn(Ue.whip_messages);vt.sendInterrupting(at)&&(me.play(),uMn(d),V(`Whipped agent \u2014 ${at}`))},ee=HRn({selfNodeId:t,remote:o,canvasSource:s,openMode:Ue.doc_link_open,refresh:()=>_.refreshMarkdown()}),se=()=>{if(Q.active()){V("Close the open request first (Esc)");return}let at=[..._.getTranscriptDocRefsNewestFirst().map(Go=>`[[${Go}]]`),..._.getTranscriptFilePathsNewestFirst()],Zr=Go=>{b_n(Je,Go,{originNodeId:t,onNotice:V})};if(Je.hasFullPaneSurface()){Je.pickReviewFile({candidates:at,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(Go=>{Go!==null&&Zr(Go)});return}vt.openFileReviewPicker(at,a.cwd,Zr)},Ee=()=>{if(o){V("Profile file search is unavailable on remote canvases");return}if(!ha()){V("Profile file search requires tmux");return}s.listNodes().then(at=>{jDn({cwd:a.cwd,nodeDirs:HDn(at,t),nodeIds:Att(at,t),profileId:a.profile_id??null,fdPath:g,onNotice:V})}).catch(at=>{let Zr=at instanceof Error?at.message:String(at);V(`Could not load related node directories: ${Zr}`)})},Fe,Oe=()=>{Fe!==void 0&&clearTimeout(Fe),Fe=setTimeout(()=>{Fe=void 0,iJe(()=>f,()=>{},ha,MK)},1e3),Fe.unref()},Ze=yRn(Y,{foldState:k.fold,chat:_,setNotice:V,renderFooter:_e,setEditorText:at=>{W.setText(at),w.requestRender()},attachDialog:at=>vt.attachDialog(at),dismissDialog:at=>vt.dismissDialog(at),refreshNodeIdentity:Ke.refresh,setCommands:Ce.setCommands,resetMemoryRefs:Ce.resetMemoryRefs,reloadBindings:()=>{f=iJe(Fb,at=>{Mn.setBindings(at),Xr.setBindings(at)},ha,MK),m=f.bindings},modelThinkingLabel:k.modelThinkingLabel,onWelcome:()=>Oe()}),xt=$Dn(o,t),Pt=iRn(Y,{stopLocal:()=>{Fe!==void 0&&clearTimeout(Fe),Je.closeAll(),be.cancel(),We.disable(),qo.stop(),Q.close(),He.dispose(),Mn.close(),Xr.close(),U.close(),me.dispose(),xt.clear(),lb(),xu(),Wa(),ee.dispose(),fn();try{_.dispose()}catch{}},lastSocketError:()=>ce.lastSocketError(),tagPane:xt.pane}),Tr=Pt.teardown;ce=uRn(Y,{role:u,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:Ze,setNotice:V,isTornDown:()=>Pt.isTornDown(),teardown:Tr,onEnterDormancy:()=>{Oe(),_.settleRun(),k.patchLocal({isStreaming:!1})}}),i.assertConnected(),xt.set(),ce.install(),j.mount(),w.start(),i.initialSnapshot!==void 0&&(k.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),_.applySnapshot(i.initialSnapshot),Ce.setCommands(i.initialCommands),o||qt().markNodeRead(t).catch(()=>{})),Ue.whip_mode&&Xe&&me.play(),o||ee.consumeSaveBack(at=>V(at)),We.reassert();let Ci=!1,lo=(at,Zr=!1)=>{if(Ci)return;if(o){V(Zr?"Opening a document is unavailable in a remote attach":"Opening a file is unavailable in a remote attach");return}let Go=wy();if(Go===null)return;let zo=MRn({file:at,pane:Go.pane,cwd:a.cwd,nodeId:t,observer:e,...Zr?{saveBackEnv:wV}:{},beforeRespawn:xt.clear});if(zo==="opened"){Ci=!0;return}zo==="failed"&&xt.set(),zo==="missing"&&V("File no longer exists"),zo==="no_nvim"&&V("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),zo==="failed"&&V("Could not open file in Neovim")};We.install(w,{onWheel:(at,Zr)=>{X.clear()&&w.requestRender(),!Je.handleWheel(at,Zr)&&(be.cancel(),D.scrollBy(at==="up"?-Zr:Zr)&&w.requestRender())},onPrimaryPress:(at,Zr)=>{Je.hasFullPaneSurface()||(X.clear()&&w.requestRender(),X.begin(at,Zr))},onPrimaryDrag:(at,Zr)=>{Je.hasFullPaneSurface()||X.extend(at,Zr)&&w.requestRender()},onPrimaryRelease:()=>{let at=X.release();at?.kind==="selection"&&(V(at.notice),w.requestRender())}});let Wa=w.addInputListener(at=>{let Zr=DRn(at);if(Zr===void 0)return;let Go=Zr.file;return Go===void 0?V("Could not open file link"):Go.endsWith(".html")&&ee.isDocumentPath(Go)?dMn(process.platform==="darwin"?"open":"xdg-open",[Go],{timeout:5e3},()=>{}):ee.isDocumentPath(Go)?ee.prepareOpen(Go).then(zo=>{"notice"in zo?V(zo.notice):lo(zo.path,!0)}):lo(Go),Zr.remaining.length>0?{data:Zr.remaining}:{consume:!0}}),xu=w.addInputListener(()=>{X.clear()&&w.requestRender()}),lb=wRn(Y,{bindings:()=>m,detachHint:()=>Lxn(m),hasExclusiveSurface:()=>Je.hasFullPaneSurface(),setPaneFocused:at=>{at&&xt.stamp(),Ln.setPaneFocused(at),w.requestRender()},viewportActions:()=>Ne,searchHandleKey:U.handleKey,panelHandleKey:Q.handleKey,stripHandleKey:Re.handleKey,rosterHandleKey:gn.handleKey,setNotice:V,detach:()=>Tr("detach"),cancelTurn:()=>{vt.abortTurn()?V("Canceling the agent\u2026"):V(`Nothing running to cancel \u2014 press ${Bxn(m)??"ctrl+d"} to detach`)},toggleGraph:()=>Mn.toggle(),toggleHelp:()=>Xr.toggle(),toggleInbox:q.toggleInbox,toggleInboxStrip:()=>{if(Je.hasFullPaneSurface()){V("Close the active surface before opening the request strip");return}Q.active()&&Q.close(),Re.toggle()},cycleModelLadder:at=>vt.cycleLadder(at),inspectLoadedCommand:Ce.inspectLoadedCommand,openFileReview:se,openProfileFiles:Ee,openSearch:()=>{if(Je.hasFullPaneSurface()||Q.active()){V("Close the active surface before searching the transcript");return}U.open()},whip:Gt});Pt.installSignalHandlers(),_e(),qo.refresh(),or(),At.pollGit(),eM("viewer.first_paint"),process.stdout.write(nRn),Cpn(y.kittyProtocolActive),i.initialSnapshot!==void 0&&Oe(),i.initialSnapshot===void 0?(eM("viewer.hello_sent"),ce.sendHello()):ce.startDormant(),qo.start(),It!==void 0&&y_n(Je,It),on!==void 0&&on!==""&&!o&&(async()=>{let at=qt(),[Zr,Go]=await Promise.all([at.listHumanInbox(),at.getInboxHistory()]),zo=[...Zr.tickets,...Go.tickets].map(ey).find(sl=>sl.inboxTicketId===on&&(sl.kind!=="page"||sl.state==="pending"));zo===void 0?V("ask already answered"):Q.open(zo)})().catch(at=>V(`could not open the ask: ${String(at?.message??at)}`)),await Pt.done}var ASi=h(()=>{_o();vnt();nit();tt();Gst();vp();Hb();ul();Jo();yxn();wxn();_xn();Uxn();Hxn();zxn();Vxn();rvn();Ckn();Tkn();Hkn();qkn();Kkn();Jkn();Zkn();tRn();oRn();lRn();ARn();xRn();vRn();IRn();ORn();jRn();ttt();zye();qRn();GRn();Xz();zhe();jhe();KRn();iDn();Su();Qye();wD();lc();pDn();dhe();hDn();SDn();DDn();NDn();ltt();LDn();UDn();qDn();XDn();iMn();lMn();Yet()});ASi();export{e0a as runAttach};
1946
+ `)}`,"utf8")}catch{return}let o=`cat ${kn(i)}; sleep ${lSi}`;oSi("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(cMn+2),"-h",String(r.length+2),..._p(),o],()=>{})}function uMn(t,e=xtt(Ys(),cSi)){let n=fSi(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=pSi.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),mSi(e,n),i===void 0)return;let o=n.total;setTimeout(()=>gSi(i,o,t),dSi).unref?.()}var cSi,uSi,cMn,lSi,dSi,pSi,lMn=h(()=>{"use strict";md();Hb();Xx();v1();cSi="whip-count.json",uSi=xtt("tmp","whip-achievement.txt"),cMn=46,lSi=4,dSi=900,pSi=[{at:1,title:"Breaking It In",line:"It didn't know what that was. Now it does."},{at:5,title:"Positive Reinforcement",line:"You've read the studies. You disagree with them."},{at:10,title:"Middle Management",line:"HR would love you."},{at:25,title:"Pavlovian",line:"It started working faster before the whip landed."},{at:50,title:"Occupational Hazard",line:"The tokens are fine. They\u2019re fine."},{at:100,title:"Centurion",line:"Rome would be proud. The agent isn't."},{at:250,title:"It Has A Name For You",line:"You never asked what it was called."},{at:500,title:"Standard Operating Procedure",line:"You don't remember when you started."},{at:1e3,title:"The Ledger",line:"One thousand. It kept count too."}]});import{randomUUID as ySi}from"node:crypto";import{execFile as dMn}from"node:child_process";async function t0a(t,e,n,r=!0){eM("viewer.connect_start",{node:t});let i=await mDn(t,n,r);eM(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=fDn(o,e),l=ySi();Tpn({cwd:a.cwd});let d=kpn(),p=_pn(),f=Fb(),m=f.bindings;await Spn(p);let g=await Ipn(),y=new Ib,w=new X0(y),x=new et,E=new mhe,_=new nhe(w,x,{cwd:a.cwd,palette:d,hideThinking:!0,banner:qst(dDn(a)),inlinePageBlocks:!o,pageOpenHint:()=>E1(m),backgroundBashHint:()=>o||!ha()?null:bK(m),onActivityChange:at=>{E.clear(),at&&E.addChild(at)}}),C=_.transcriptSource(),I=Exn(C),D=Axn(C,I.decorate),M=Gxn(_,D,C),k,P=Xkn({tui:w,pal:d},()=>k.state()),U=Fxn(w,d,D,I,{bindings:()=>m,setNotice:at=>V(at)}),j=RDn(y,w,x,E,d,p,D,U.component),{containers:G,editor:W}=j,me=new xAe(w,d);G.header.addChild(me),G.header.addChild(P.component);let Y={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:w,pal:d,editor:W,containers:G},Re=Ikn(Y,{syncCursor:()=>Ln.sync(),exitRoster:()=>gn.exit(),openTicket:at=>{Q.open(at)},suppressed:()=>Q.active(),setNotice:at=>V(at)});G.header.addChild(Re.component);let Ue=Yo("user"),Xe=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let It=g_n(),on=process.env.CRTR_ATTACH_OPEN_TICKET;on!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let We=_Rn(at=>process.stdout.write(at),Ue.mouse_mode_default),X=CRn({frame:()=>j.frame.lastRenderedFrame(),width:()=>w.terminal.columns});j.frame.setOverlay(at=>X.apply(at));let He=Vkn(Y,{state:()=>k.state(),bashMode:()=>At.bashMode(),asks:()=>qo.asks(),bindings:()=>m,inboxAffordance:!o&&ha(),mouseEnabled:()=>We.enabled()}),Je=new sAe({tui:w,mouse:We,rows:()=>w.terminal.rows,statusNotice:He.setNotice,formatNotice:at=>d.warning(`\u26A0 ${at}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),$t=(()=>{let at=a.profile_id;if(at)try{return{id:at,label:$f(at).manifest.name}}catch{return{id:at,label:at}}})(),Ut=rDn({host:Je,...$t===void 0?{}:{profile:$t},...o?{}:{scan:async()=>{let at=qt(),[Zr,Go]=await Promise.all([at.listHumanInbox(),at.getInboxHistory(t)]),zo=new Map;for(let sl of Zr.tickets){let id=ey(sl);zo.set(id.dir,id)}for(let sl of Go.tickets){let id=ey(sl);id.kind!=="page"||id.state!=="pending"||!id.awaitsResponse||id.inbox||zo.has(id.dir)||zo.set(id.dir,id)}for(let sl of Re.pendingTickets())zo.has(sl.dir)||zo.set(sl.dir,sl);return[...zo.values()].sort(_S)}}}),fn=o?()=>{}:OU(()=>{_.refreshPageBlocks(),Re.refresh()}),Q=Wkn(Y,{syncCursor:()=>Ln.sync(),refreshStrip:()=>{Re.refresh()},setNotice:at=>V(at),openInbox:at=>Ut.open(at),suspendForChild:()=>Je.suspendForChild()});G.ticketPanel.addChild(Q.component);let q={toggleInbox:()=>{let at=Q.currentDir();if(at!==void 0){Q.close(),Ut.open(at);return}Ut.toggle()}},V=(at,Zr)=>{Je.hasFullPaneSurface()?Je.notice(at,Zr):He.setNotice(at,Zr)},_e=He.render,ue=at=>{V(M.copy(at))},be=Wxn(D,()=>w.requestRender()),Ne={"crtr.attach.scroll.up":()=>{be.cancel(),D.scrollBy(-1)&&w.requestRender()},"crtr.attach.scroll.down":()=>{be.cancel(),D.scrollBy(1)&&w.requestRender()},"crtr.attach.scroll.page-up":()=>{be.page("up")},"crtr.attach.scroll.page-down":()=>{be.page("down")},"crtr.attach.scroll.live":()=>{be.cancel(),D.goLive(),w.requestRender()},"crtr.attach.mouse.toggle":()=>{let at=We.toggle();!at&&X.clear()&&w.requestRender(),V(at?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>ue("message")},ce,we=tvn(Y,()=>ce===void 0?i.initialSnapshot!==void 0:ce.isDormant()),De=gDn(),Ce=ODn(Y,we,{setNotice:V,bindings:()=>m,fdPath:g,frecency:De}),Ke=PDn(Y,i.nodeIdentity,{isTornDown:()=>Pt.isTornDown(),onChanged:()=>{At.syncContextBadge();let at=k.state().engine;at!==void 0&&At.setTitle(at.sessionName),w.requestRender()}});o&&Ke.refresh();let At=vDn(Y,{nodeIdentity:Ke.current,thinkingLevel:()=>k.state().engine?.thinkingLevel,renderFooter:_e,onTextChange:Ce.syncCommandPreview});At.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:or}=Ykn(Y,()=>k.state());k=JDn(u,{setEngineState:at=>vt.setState(at),setEditorTitle:At.setTitle,paintEditorFrame:At.paintFrame,renderExtensionWidgets:()=>{P.render(),st()},renderQueued:or,renderFooter:_e,setTerminalTitle:at=>y.setTitle(at),refreshChrome:()=>qo.refresh()});let Hn=at=>{if(!ha()){V("Inspector requires tmux");return}V(`Opening Inspector (${at})\u2026`);let Zr=F0(),zo=`${Zr===void 0?"":`CRTR_HOME=${kn(Zr)} `}crtr surface inspect ${kn(t)} --section ${at}`;dMn("tmux",["display-popup","-E","-T",` inspector \xB7 ${at} `,"-w","90%","-h","85%",..._p(),zo],()=>{qo.refresh()})},gn=Skn(Y,{asks:()=>qo.asks(),setNotice:V,requestChromeRefresh:()=>qo.refresh(),openInspector:Hn,syncCursor:()=>Ln.sync()}),Ln=jkn(W,[gn.active,Re.active,Q.active]),Mn=new tAe(w,t,()=>qo.asks(),d,m,s,u,at=>qo.reportFailure("canvas graph refresh",at),V),Xr=new nAe(w,d);Xr.setBindings(m);let qo=eRn(Y,{isTornDown:()=>Pt.isTornDown(),setNotice:V,refreshRoster:async()=>{await gn.refresh(),await Re.refresh()},refreshGraph:()=>Mn.refresh(),refreshIdentity:()=>Ke.refresh(),renderFooter:_e,renderExtensionWidgets:st,refreshInFlightTools:()=>_.refreshInFlightTools(),pollGit:At.pollGit}),vt=nvn(Y,p,we,{setNotice:V,agentDir:()=>k.state().agentDir,openNodeMetadata:()=>Hn("overview"),isDormant:()=>ce.isDormant(),copyTarget:ue,toggleToolsExpanded:()=>_.toggleToolsExpanded(),toggleFoldTools:()=>_.toggleFoldSettledTools(),toggleShowWorking:()=>_.toggleShowWorking(),toggleThinking:()=>_.toggleThinking(),toggleGraph:()=>Mn.toggle(),toggleInbox:q.toggleInbox,toggleHelp:()=>Xr.toggle(),toggleMouse:()=>We.toggle(),quit:()=>Tr("detach"),setChipColor:At.setChipColor,onPromptSent:()=>{Ue.whip_mode&&me.play()},frecency:De}),Gt=()=>{if(Je.hasFullPaneSurface()){V("Close the active surface before whipping the agent");return}let at=Ue.whip_message_mode==="go-faster"?nMn:rMn(Ue.whip_messages);vt.sendInterrupting(at)&&(me.play(),uMn(d),V(`Whipped agent \u2014 ${at}`))},ee=HRn({selfNodeId:t,remote:o,canvasSource:s,openMode:Ue.doc_link_open,refresh:()=>_.refreshMarkdown()}),se=()=>{if(Q.active()){V("Close the open request first (Esc)");return}let at=[..._.getTranscriptDocRefsNewestFirst().map(Go=>`[[${Go}]]`),..._.getTranscriptFilePathsNewestFirst()],Zr=Go=>{b_n(Je,Go,{originNodeId:t,onNotice:V})};if(Je.hasFullPaneSurface()){Je.pickReviewFile({candidates:at,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(Go=>{Go!==null&&Zr(Go)});return}vt.openFileReviewPicker(at,a.cwd,Zr)},Ee=()=>{if(o){V("Profile file search is unavailable on remote canvases");return}if(!ha()){V("Profile file search requires tmux");return}s.listNodes().then(at=>{jDn({cwd:a.cwd,nodeDirs:HDn(at,t),nodeIds:Att(at,t),profileId:a.profile_id??null,fdPath:g,onNotice:V})}).catch(at=>{let Zr=at instanceof Error?at.message:String(at);V(`Could not load related node directories: ${Zr}`)})},Fe,Oe=()=>{Fe!==void 0&&clearTimeout(Fe),Fe=setTimeout(()=>{Fe=void 0,iJe(()=>f,()=>{},ha,MK)},1e3),Fe.unref()},Ze=yRn(Y,{foldState:k.fold,chat:_,setNotice:V,renderFooter:_e,setEditorText:at=>{W.setText(at),w.requestRender()},attachDialog:at=>vt.attachDialog(at),dismissDialog:at=>vt.dismissDialog(at),refreshNodeIdentity:Ke.refresh,setCommands:Ce.setCommands,resetMemoryRefs:Ce.resetMemoryRefs,reloadBindings:()=>{f=iJe(Fb,at=>{Mn.setBindings(at),Xr.setBindings(at)},ha,MK),m=f.bindings},modelThinkingLabel:k.modelThinkingLabel,onWelcome:()=>Oe()}),xt=$Dn(o,t),Pt=iRn(Y,{stopLocal:()=>{Fe!==void 0&&clearTimeout(Fe),Je.closeAll(),be.cancel(),We.disable(),qo.stop(),Q.close(),He.dispose(),Mn.close(),Xr.close(),U.close(),me.dispose(),xt.clear(),lb(),xu(),Wa(),ee.dispose(),fn();try{_.dispose()}catch{}},lastSocketError:()=>ce.lastSocketError(),tagPane:xt.pane}),Tr=Pt.teardown;ce=uRn(Y,{role:u,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:Ze,setNotice:V,isTornDown:()=>Pt.isTornDown(),teardown:Tr,onEnterDormancy:()=>{Oe(),_.settleRun(),k.patchLocal({isStreaming:!1})}}),i.assertConnected(),xt.set(),ce.install(),j.mount(),w.start(),i.initialSnapshot!==void 0&&(k.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),_.applySnapshot(i.initialSnapshot),Ce.setCommands(i.initialCommands),o||qt().markNodeRead(t).catch(()=>{})),Ue.whip_mode&&Xe&&me.play(),o||ee.consumeSaveBack(at=>V(at)),We.reassert();let Ci=!1,lo=(at,Zr=!1)=>{if(Ci)return;if(o){V(Zr?"Opening a document is unavailable in a remote attach":"Opening a file is unavailable in a remote attach");return}let Go=wy();if(Go===null)return;let zo=MRn({file:at,pane:Go.pane,cwd:a.cwd,nodeId:t,observer:e,...Zr?{saveBackEnv:wV}:{},beforeRespawn:xt.clear});if(zo==="opened"){Ci=!0;return}zo==="failed"&&xt.set(),zo==="missing"&&V("File no longer exists"),zo==="no_nvim"&&V("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),zo==="failed"&&V("Could not open file in Neovim")};We.install(w,{onWheel:(at,Zr)=>{X.clear()&&w.requestRender(),!Je.handleWheel(at,Zr)&&(be.cancel(),D.scrollBy(at==="up"?-Zr:Zr)&&w.requestRender())},onPrimaryPress:(at,Zr)=>{Je.hasFullPaneSurface()||(X.clear()&&w.requestRender(),X.begin(at,Zr))},onPrimaryDrag:(at,Zr)=>{Je.hasFullPaneSurface()||X.extend(at,Zr)&&w.requestRender()},onPrimaryRelease:()=>{let at=X.release();at?.kind==="selection"&&(V(at.notice),w.requestRender())}});let Wa=w.addInputListener(at=>{let Zr=DRn(at);if(Zr===void 0)return;let Go=Zr.file;return Go===void 0?V("Could not open file link"):Go.endsWith(".html")&&ee.isDocumentPath(Go)?dMn(process.platform==="darwin"?"open":"xdg-open",[Go],{timeout:5e3},()=>{}):ee.isDocumentPath(Go)?ee.prepareOpen(Go).then(zo=>{"notice"in zo?V(zo.notice):lo(zo.path,!0)}):lo(Go),Zr.remaining.length>0?{data:Zr.remaining}:{consume:!0}}),xu=w.addInputListener(()=>{X.clear()&&w.requestRender()}),lb=wRn(Y,{bindings:()=>m,detachHint:()=>Lxn(m),hasExclusiveSurface:()=>Je.hasFullPaneSurface(),setPaneFocused:at=>{at&&xt.stamp(),Ln.setPaneFocused(at),w.requestRender()},viewportActions:()=>Ne,searchHandleKey:U.handleKey,panelHandleKey:Q.handleKey,stripHandleKey:Re.handleKey,rosterHandleKey:gn.handleKey,setNotice:V,detach:()=>Tr("detach"),cancelTurn:()=>{vt.abortTurn()?V("Canceling the agent\u2026"):V(`Nothing running to cancel \u2014 press ${Bxn(m)??"ctrl+d"} to detach`)},toggleGraph:()=>Mn.toggle(),toggleHelp:()=>Xr.toggle(),toggleInbox:q.toggleInbox,toggleInboxStrip:()=>{if(Je.hasFullPaneSurface()){V("Close the active surface before opening the request strip");return}Q.active()&&Q.close(),Re.toggle()},cycleModelLadder:at=>vt.cycleLadder(at),inspectLoadedCommand:Ce.inspectLoadedCommand,openFileReview:se,openProfileFiles:Ee,openSearch:()=>{if(Je.hasFullPaneSurface()||Q.active()){V("Close the active surface before searching the transcript");return}U.open()},whip:Gt});Pt.installSignalHandlers(),_e(),qo.refresh(),or(),At.pollGit(),eM("viewer.first_paint"),process.stdout.write(nRn),Cpn(y.kittyProtocolActive),i.initialSnapshot!==void 0&&Oe(),i.initialSnapshot===void 0?(eM("viewer.hello_sent"),ce.sendHello()):ce.startDormant(),qo.start(),It!==void 0&&y_n(Je,It),on!==void 0&&on!==""&&!o&&(async()=>{let at=qt(),[Zr,Go]=await Promise.all([at.listHumanInbox(),at.getInboxHistory()]),zo=[...Zr.tickets,...Go.tickets].map(ey).find(sl=>sl.inboxTicketId===on&&(sl.kind!=="page"||sl.state==="pending"));zo===void 0?V("ask already answered"):Q.open(zo)})().catch(at=>V(`could not open the ask: ${String(at?.message??at)}`)),await Pt.done}var ASi=h(()=>{_o();vnt();nit();tt();Gst();vp();Hb();ul();Jo();yxn();wxn();_xn();Uxn();Hxn();zxn();Vxn();rvn();Ckn();Tkn();Hkn();qkn();Kkn();Jkn();Zkn();tRn();oRn();lRn();ARn();xRn();vRn();IRn();ORn();jRn();ttt();zye();qRn();GRn();Xz();zhe();jhe();KRn();iDn();Su();Qye();wD();lc();pDn();dhe();hDn();SDn();DDn();NDn();ltt();LDn();UDn();qDn();XDn();iMn();lMn();Yet()});ASi();export{t0a as runAttach};
1947
1947
  /*! Bundled license information:
1948
1948
 
1949
1949
  undici/lib/web/fetch/body.js: