pi-cowboy 0.36.4 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{Ha as x}from"./chunk-UEMXTMQN.js";import{a as s,q as f,y as C}from"./chunk-AOUEQXPY.js";import{Container as y,fuzzyFilter as M,getKeybindings as N,Input as k,Spacer as v,Text as b}from"@earendil-works/pi-tui";import{DynamicBorder as w}from"@earendil-works/pi-coding-agent";var h=10,g=class extends y{static{s(this,"SearchableSelectDialog")}searchInput;listContainer;items;filteredItems;selectedIndex;currentValue;callbacks;theme;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}constructor(e,n,r,l){super(),this.items=e,this.currentValue=n,this.callbacks=r,this.theme=l,this.filteredItems=[...e];let a=e.findIndex(o=>o.value===n);this.selectedIndex=a>=0?a:0,this.addChild(new w),this.addChild(new v(1)),this.searchInput=new k,this.searchInput.onSubmit=()=>{this.filteredItems[this.selectedIndex]&&this.callbacks.onSelect(this.filteredItems[this.selectedIndex].value)},this.addChild(this.searchInput),this.addChild(new v(1)),this.listContainer=new y,this.addChild(this.listContainer),this.addChild(new v(1)),this.addChild(new w),this.updateList()}handleInput(e){let n=N();if(!(this.filteredItems.length===0&&(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")||n.matches(e,"tui.select.pageUp")||n.matches(e,"tui.select.pageDown")))){if(n.matches(e,"tui.select.up")){this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(n.matches(e,"tui.select.down")){this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}if(n.matches(e,"tui.select.pageUp")){this.selectedIndex=Math.max(0,this.selectedIndex-h),this.updateList();return}if(n.matches(e,"tui.select.pageDown")){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+h),this.updateList();return}if(n.matches(e,"tui.select.confirm")){let r=this.filteredItems.at(this.selectedIndex);r&&this.callbacks.onSelect(r.value);return}if(n.matches(e,"tui.select.cancel")){this.callbacks.onCancel();return}this.searchInput.handleInput(e),this.filterItems()}}invalidate(){}filterItems(){let e=this.searchInput.getValue();e?this.filteredItems=M(this.items,e,n=>`${n.label} ${n.provider} ${n.value??""}`):this.filteredItems=[...this.items],this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList()}updateList(){this.listContainer.clear();let{filteredItems:e}=this;if(e.length===0){this.listContainer.addChild(new b(this.theme.fg("muted"," No matching items"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(h/2),e.length-h)),r=Math.min(n+h,e.length);for(let l=n;l<r;l++){let a=e.at(l);if(!a)continue;let o=l===this.selectedIndex,d=a.value===this.currentValue,c=o?this.theme.fg("accent","\u2192 ")+this.theme.fg("accent",a.label):` ${a.label}`,i=a.provider?this.theme.fg("muted",`[${a.provider}]`):"",u=d?this.theme.fg("success"," \u2713"):"",m=`${c} ${i}${u}`;this.listContainer.addChild(new b(m,0,0))}if(n>0||r<e.length){let l=this.theme.fg("muted",` (${this.selectedIndex+1}/${e.length})`);this.listContainer.addChild(new b(l,0,0))}}};import{isFocusable as L}from"@earendil-works/pi-tui";var O=class{constructor(e){this.ctx=e}ctx;static{s(this,"ScreenHost")}async open(e){return await this.show(e,!1)}async openOverlay(e){return await this.show(e,!0)}async show(e,n){if(x(this.ctx))return await new Promise(r=>{this.ctx.ui.custom((l,a,o,d)=>e({tui:l,theme:a,keybindings:o,close:s(c=>{x(this.ctx)&&d(c),r(c)},"close")}),n?{overlay:!0}:void 0).then(r)})}},j=void 0;function K(t){return Object.assign(t,{focused:!0})}s(K,"asSubmenuComponent");var I=class{static{s(this,"SwappableView")}active;constructor(e){this.active=e}activate(e){this.active=e}invalidate(){this.active.invalidate()}render(e){return this.active.render(e)}handleInput(e){this.active.handleInput?.(e)}get focused(){return L(this.active)?this.active.focused:!1}set focused(e){L(this.active)&&(this.active.focused=e)}};var F="group-header";function q(t,e){return{id:T,kind:F,label:t.bold(t.fg("accent",e)),currentValue:""}}s(q,"headerItem");var T="__sep__",p=new WeakMap;function X(t){if(!Array.isArray(t.items))return;let e=s(o=>o?.value===T||o?.id===T,"isSep"),n=s((o,d,c)=>{let i=d+c;for(;i>=0&&i<o.length&&e(o[i]);)i+=c;return i},"firstNonSepFrom"),r=s((o,d)=>d>=0&&d<o.length,"inBounds"),l=s((o,d)=>{let c=Math.max(0,Math.min(d,o.length-1));for(let i=c;i<o.length;i+=1)if(!e(o[i]))return i;for(let i=c-1;i>=0;i-=1)if(!e(o[i]))return i;return 0},"seedIndex"),a=t.selectedIndex??0;Object.defineProperty(t,"selectedIndex",{get(){return p.get(t)},set(o){let d=t.items,c=p.get(t)??0,i=Math.max(0,Math.min(o,d.length-1));if(!e(d[i])){p.set(t,i);return}let u=o>c?1:-1,m=n(d,i,u),S=n(d,i,-u);r(d,m)?p.set(t,m):r(d,S)?p.set(t,S):p.set(t,i)},configurable:!0}),p.set(t,l(t.items,a))}s(X,"installSeparatorSkip");function J(t,e,n){let r=[{value:null,label:"(none)",provider:""}],l=[];for(let i of t){let u=f(i);u&&l.push({value:i,label:u.modelId,provider:u.provider})}if(e===null&&n.length===0)return r.push(...l),r;let a=[],o=[],d=[],c=new Set;if(e){let i=f(e);i&&(a.push({value:e,label:i.modelId,provider:i.provider}),c.add(e))}for(let i of n){if(c.has(i))continue;let u=f(i);u&&(o.push({value:i,label:u.modelId,provider:u.provider}),c.add(i))}for(let i of l)i.value!=null&&!c.has(i.value)&&d.push(i);return r.push(...a,...o,...d),r}s(J,"buildModelOptions");function Q(t){let e=[];t.default&&typeof t.default=="string"&&e.push(t.default);for(let[n,r]of Object.entries(t))n!=="default"&&typeof r=="string"&&r.includes("/")&&e.push(r);return[...new Set(e)]}s(Q,"extractConfiguredModels");function Y(t,e){return C(t)?e:[]}s(Y,"mergedModelsForHarness");function Z(t){return{label:s((e,n)=>n?t.fg("accent",e):e,"label"),value:s((e,n)=>n?t.fg("accent",e):t.fg("muted",e),"value"),description:s(e=>t.fg("dim",e),"description"),cursor:t.fg("accent","\u2192 "),hint:s(e=>t.fg("dim",e),"hint")}}s(Z,"buildSettingsListTheme");function ee(t,e){let n=t.trim();if(!/^\d*\.?\d+$/.test(n))return;let r=parseFloat(n);if(!(r<e))return r}s(ee,"validateNumeric");var _=new Map([["k","\x1B[A"],["j","\x1B[B"]]);function te(t){let e=t,n=e.handleInput?.bind(e);return n&&(e.handleInput=r=>{let l=e.submenuComponent?void 0:_.get(r);n(l??r)}),t}s(te,"withVimKeys");function ne(t){return{selectedPrefix:s(()=>t.fg("accent","\u2192 "),"selectedPrefix"),selectedText:s(e=>t.fg("accent",e),"selectedText"),description:s(e=>t.fg("muted",e),"description"),scrollInfo:s(e=>t.fg("dim",e),"scrollInfo"),noMatch:s(e=>t.fg("dim",e),"noMatch")}}s(ne,"buildSelectListTheme");function ie(t,e,n){let r,l=new g(t,null,{onSelect:s(a=>{let o=e.onSelect(a);o&&r.activate(o)},"onSelect"),onCancel:e.onCancel},n);return r=new I(l),r}s(ie,"createSearchableSelect");function se(t){return t.length===1?`agent ${t[0]}`:`${t.length} agent(s)`}s(se,"agentSubject");export{g as a,O as b,j as c,K as d,I as e,q as f,T as g,X as h,J as i,Q as j,Y as k,Z as l,ee as m,te as n,ne as o,ie as p,se as q};
2
- //# sourceMappingURL=chunk-WP65L6WI.js.map
1
+ import{Ha as x}from"./chunk-Y6XBNRLR.js";import{a as s,q as f,y as C}from"./chunk-AOUEQXPY.js";import{Container as y,fuzzyFilter as M,getKeybindings as N,Input as k,Spacer as v,Text as b}from"@earendil-works/pi-tui";import{DynamicBorder as w}from"@earendil-works/pi-coding-agent";var h=10,g=class extends y{static{s(this,"SearchableSelectDialog")}searchInput;listContainer;items;filteredItems;selectedIndex;currentValue;callbacks;theme;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}constructor(e,n,r,l){super(),this.items=e,this.currentValue=n,this.callbacks=r,this.theme=l,this.filteredItems=[...e];let a=e.findIndex(o=>o.value===n);this.selectedIndex=a>=0?a:0,this.addChild(new w),this.addChild(new v(1)),this.searchInput=new k,this.searchInput.onSubmit=()=>{this.filteredItems[this.selectedIndex]&&this.callbacks.onSelect(this.filteredItems[this.selectedIndex].value)},this.addChild(this.searchInput),this.addChild(new v(1)),this.listContainer=new y,this.addChild(this.listContainer),this.addChild(new v(1)),this.addChild(new w),this.updateList()}handleInput(e){let n=N();if(!(this.filteredItems.length===0&&(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")||n.matches(e,"tui.select.pageUp")||n.matches(e,"tui.select.pageDown")))){if(n.matches(e,"tui.select.up")){this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(n.matches(e,"tui.select.down")){this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}if(n.matches(e,"tui.select.pageUp")){this.selectedIndex=Math.max(0,this.selectedIndex-h),this.updateList();return}if(n.matches(e,"tui.select.pageDown")){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+h),this.updateList();return}if(n.matches(e,"tui.select.confirm")){let r=this.filteredItems.at(this.selectedIndex);r&&this.callbacks.onSelect(r.value);return}if(n.matches(e,"tui.select.cancel")){this.callbacks.onCancel();return}this.searchInput.handleInput(e),this.filterItems()}}invalidate(){}filterItems(){let e=this.searchInput.getValue();e?this.filteredItems=M(this.items,e,n=>`${n.label} ${n.provider} ${n.value??""}`):this.filteredItems=[...this.items],this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList()}updateList(){this.listContainer.clear();let{filteredItems:e}=this;if(e.length===0){this.listContainer.addChild(new b(this.theme.fg("muted"," No matching items"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(h/2),e.length-h)),r=Math.min(n+h,e.length);for(let l=n;l<r;l++){let a=e.at(l);if(!a)continue;let o=l===this.selectedIndex,d=a.value===this.currentValue,c=o?this.theme.fg("accent","\u2192 ")+this.theme.fg("accent",a.label):` ${a.label}`,i=a.provider?this.theme.fg("muted",`[${a.provider}]`):"",u=d?this.theme.fg("success"," \u2713"):"",m=`${c} ${i}${u}`;this.listContainer.addChild(new b(m,0,0))}if(n>0||r<e.length){let l=this.theme.fg("muted",` (${this.selectedIndex+1}/${e.length})`);this.listContainer.addChild(new b(l,0,0))}}};import{isFocusable as L}from"@earendil-works/pi-tui";var O=class{constructor(e){this.ctx=e}ctx;static{s(this,"ScreenHost")}async open(e){return await this.show(e,!1)}async openOverlay(e){return await this.show(e,!0)}async show(e,n){if(x(this.ctx))return await new Promise(r=>{this.ctx.ui.custom((l,a,o,d)=>e({tui:l,theme:a,keybindings:o,close:s(c=>{x(this.ctx)&&d(c),r(c)},"close")}),n?{overlay:!0}:void 0).then(r)})}},j=void 0;function K(t){return Object.assign(t,{focused:!0})}s(K,"asSubmenuComponent");var I=class{static{s(this,"SwappableView")}active;constructor(e){this.active=e}activate(e){this.active=e}invalidate(){this.active.invalidate()}render(e){return this.active.render(e)}handleInput(e){this.active.handleInput?.(e)}get focused(){return L(this.active)?this.active.focused:!1}set focused(e){L(this.active)&&(this.active.focused=e)}};var F="group-header";function q(t,e){return{id:T,kind:F,label:t.bold(t.fg("accent",e)),currentValue:""}}s(q,"headerItem");var T="__sep__",p=new WeakMap;function X(t){if(!Array.isArray(t.items))return;let e=s(o=>o?.value===T||o?.id===T,"isSep"),n=s((o,d,c)=>{let i=d+c;for(;i>=0&&i<o.length&&e(o[i]);)i+=c;return i},"firstNonSepFrom"),r=s((o,d)=>d>=0&&d<o.length,"inBounds"),l=s((o,d)=>{let c=Math.max(0,Math.min(d,o.length-1));for(let i=c;i<o.length;i+=1)if(!e(o[i]))return i;for(let i=c-1;i>=0;i-=1)if(!e(o[i]))return i;return 0},"seedIndex"),a=t.selectedIndex??0;Object.defineProperty(t,"selectedIndex",{get(){return p.get(t)},set(o){let d=t.items,c=p.get(t)??0,i=Math.max(0,Math.min(o,d.length-1));if(!e(d[i])){p.set(t,i);return}let u=o>c?1:-1,m=n(d,i,u),S=n(d,i,-u);r(d,m)?p.set(t,m):r(d,S)?p.set(t,S):p.set(t,i)},configurable:!0}),p.set(t,l(t.items,a))}s(X,"installSeparatorSkip");function J(t,e,n){let r=[{value:null,label:"(none)",provider:""}],l=[];for(let i of t){let u=f(i);u&&l.push({value:i,label:u.modelId,provider:u.provider})}if(e===null&&n.length===0)return r.push(...l),r;let a=[],o=[],d=[],c=new Set;if(e){let i=f(e);i&&(a.push({value:e,label:i.modelId,provider:i.provider}),c.add(e))}for(let i of n){if(c.has(i))continue;let u=f(i);u&&(o.push({value:i,label:u.modelId,provider:u.provider}),c.add(i))}for(let i of l)i.value!=null&&!c.has(i.value)&&d.push(i);return r.push(...a,...o,...d),r}s(J,"buildModelOptions");function Q(t){let e=[];t.default&&typeof t.default=="string"&&e.push(t.default);for(let[n,r]of Object.entries(t))n!=="default"&&typeof r=="string"&&r.includes("/")&&e.push(r);return[...new Set(e)]}s(Q,"extractConfiguredModels");function Y(t,e){return C(t)?e:[]}s(Y,"mergedModelsForHarness");function Z(t){return{label:s((e,n)=>n?t.fg("accent",e):e,"label"),value:s((e,n)=>n?t.fg("accent",e):t.fg("muted",e),"value"),description:s(e=>t.fg("dim",e),"description"),cursor:t.fg("accent","\u2192 "),hint:s(e=>t.fg("dim",e),"hint")}}s(Z,"buildSettingsListTheme");function ee(t,e){let n=t.trim();if(!/^\d*\.?\d+$/.test(n))return;let r=parseFloat(n);if(!(r<e))return r}s(ee,"validateNumeric");var _=new Map([["k","\x1B[A"],["j","\x1B[B"]]);function te(t){let e=t,n=e.handleInput?.bind(e);return n&&(e.handleInput=r=>{let l=e.submenuComponent?void 0:_.get(r);n(l??r)}),t}s(te,"withVimKeys");function ne(t){return{selectedPrefix:s(()=>t.fg("accent","\u2192 "),"selectedPrefix"),selectedText:s(e=>t.fg("accent",e),"selectedText"),description:s(e=>t.fg("muted",e),"description"),scrollInfo:s(e=>t.fg("dim",e),"scrollInfo"),noMatch:s(e=>t.fg("dim",e),"noMatch")}}s(ne,"buildSelectListTheme");function ie(t,e,n){let r,l=new g(t,null,{onSelect:s(a=>{let o=e.onSelect(a);o&&r.activate(o)},"onSelect"),onCancel:e.onCancel},n);return r=new I(l),r}s(ie,"createSearchableSelect");function se(t){return t.length===1?`agent ${t[0]}`:`${t.length} agent(s)`}s(se,"agentSubject");export{g as a,O as b,j as c,K as d,I as e,q as f,T as g,X as h,J as i,Q as j,Y as k,Z as l,ee as m,te as n,ne as o,ie as p,se as q};
2
+ //# sourceMappingURL=chunk-64JHSRF7.js.map
@@ -1,2 +1,2 @@
1
- import{h as l,n as h}from"./chunk-WP65L6WI.js";import{a as r}from"./chunk-AOUEQXPY.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
2
- //# sourceMappingURL=chunk-YTDE2OUW.js.map
1
+ import{h as l,n as h}from"./chunk-64JHSRF7.js";import{a as r}from"./chunk-AOUEQXPY.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
2
+ //# sourceMappingURL=chunk-6RXCALXX.js.map
@@ -0,0 +1,16 @@
1
+ import{A as At,B as St,C as Tt,D as V,I as Rt,J as Q,K as Et,M as Se,N as It,O as X,b as gt,c as mt,e as ft,g as yt,i as wt,k as Ae,l as vt,p as kt,u as bt,v as z,w as xt}from"./chunk-KUEKLALM.js";import{$ as lt,A as Je,Aa as pt,Ca as j,Ga as ht,J as fe,Ja as xe,L as st,M as ye,P as we,Q as it,S as K,T,U as I,W as at,_ as dt,b as he,c as qe,ja as b,k as L,ka as G,l as Fe,la as y,m as Ke,n as ge,na as w,oa as C,p as Ye,pa as ve,qa as ke,sa as ct,u as ze,v as Ve,va as be,wa as Y,x as Qe,xa as O,y as Xe,ya as ut,z as Ze}from"./chunk-Y6XBNRLR.js";import{J as rt,K as ot,a as r,l as Ge,p as N,r as me,s as et,v as tt,w as F,y as nt}from"./chunk-AOUEQXPY.js";import{visibleWidth as Ie}from"@earendil-works/pi-tui";var Te="\u{1F920}",_t="\u{1F404}",Tn="\u{1F4A9}",Rn=2,En=1e3,Z=Ie(_t),In="76;175;80";function Cn(e){return`\x1B[48;2;${In}m${e}\x1B[49m`}r(Cn,"greenBackground");function Pt(e){return e===0?0:Math.max(Rn,Math.ceil(Math.sqrt(2*e)))}r(Pt,"pastureEdge");function Mt(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Mt,"emptyPasture");function On(e,t){let n=Pt(e.cows+e.droppings),o=Mt(n),i=Array.from({length:n*n},(s,d)=>d),a=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let s=0;s<a.length;s+=1){let d=s+Math.floor(t()*(i.length-s)),c=i[d];i[d]=i[s],i[s]=c,o[Math.floor(c/n)][c%n]=a[s]}return o}r(On,"grazedPasture");function J(e,t){let n=[];for(let o=0;o<e.length;o+=1)for(let i=0;i<e[o].length;i+=1)e[o][i]===t&&n.push({row:o,col:i});return n}r(J,"cellsOf");function _n(e,t){return[{row:e.row-1,col:e.col},{row:e.row,col:e.col+1},{row:e.row+1,col:e.col},{row:e.row,col:e.col-1}].filter(({row:o,col:i})=>o>=0&&o<t&&i>=0&&i<t)}r(_n,"neighboursOf");function Ct(e,t){return _n(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Ct,"openNeighboursOf");function Pn(e,t){let n=J(e,"cow").filter(d=>Ct(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Ct(o,e),a=i[Math.floor(t()*i.length)],s=e.map(d=>d.slice());return s[o.row][o.col]="empty",s[a.row][a.col]="cow",s}r(Pn,"moveHerd");function Ot(e,t,n,o){for(let i=0;i<n;i+=1){let a=J(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(Ot,"placeAtRandom");function Mn(e,t,n,o){let i=J(e,"cow"),a=J(e,"dropping"),s=i.length-t,d=a.length-n;for(;s>0&&d<0;){let c=i.pop();e[c.row][c.col]="dropping",s-=1,d+=1}for(;s>0;){let c=i.pop();e[c.row][c.col]="empty",s-=1}for(;d>0;){let c=a.pop();e[c.row][c.col]="empty",d-=1}Ot(e,"cow",-s,o),Ot(e,"dropping",-d,o)}r(Mn,"reconcileCounts");function $n(e,t,n){if(e===null)return On(t,n);let o=Pt(t.cows+t.droppings),i=Mt(o);for(let a=0;a<e.length&&a<o;a+=1)for(let s=0;s<e[a].length&&s<o;s+=1)i[a][s]=e[a][s];return Mn(i,t.cows,t.droppings,n),i}r($n,"reconcilePasture");var Nn={anchor:"top-right",width:Ie(Te),get offsetX(){return C()?.cowboyOffsetX??0},nonCapturing:!0},Hn={anchor:"top-right",offsetY:1,get width(){return C()?.pastureWidth??0},nonCapturing:!0};function Dn(e){return e==="cow"?_t:e==="dropping"?Tn:" ".repeat(Z)}r(Dn,"cellText");function Bn(e,t){return e.map(n=>t(n.map(Dn).join("")))}r(Bn,"drawnRows");function Ln(){return ke().list(["spawned"]).length}r(Ln,"liveAgentCount");function jn(){return ke().list(it).length}r(jn,"endedAgentCount");function Wn(){return{live:Ln(),ended:jn()}}r(Wn,"agentCounts");function Un(){return w().agent.grazingEnabled}r(Un,"grazingEnabled");var Re=class{constructor(t,n,o,i,a){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=a}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return Ie(Te)}get pastureWidth(){return this.drawnPasture().length*Z}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*Z-(t*Z-this.cowboyWidth)}render(){return this.frame(),[Te]}pastureRows(){return this.frame(),Bn(this.drawnPasture(),this.grass)}invalidate(){}attachCowboy(t){this.cowboyHandle=t}attachPasture(t){this.pastureHandle=t}dispose(){let t=this.drawnPasture().length>0&&(this.cowboyHandle!==null||this.pastureHandle!==null);this.disposed=!0,this.poll!==null&&(clearInterval(this.poll),this.poll=null),this.cowboyHandle?.hide(),this.cowboyHandle=null,this.pastureHandle?.hide(),this.pastureHandle=null,t&&this.tui.requestRender(!0)}drawnPasture(){return this.herd===null||!this.isGrazing()?[]:this.herd.pasture}frame(){if(this.disposed)return;let t=this.isGrazing();this.herd===null?(this.herd=this.place(this.countAgents()),this.grazing=t):t!==this.grazing&&this.recount(),this.pollWhile(t)}pollWhile(t){!t&&this.poll!==null?(clearInterval(this.poll),this.poll=null):t&&this.poll===null&&(this.poll=setInterval(()=>this.recount(),En))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,a=(this.grazing??o)&&(this.herd?.pasture.length??0)>0;if(this.herd===null||t!==this.herd.liveAgents||n!==this.herd.endedAgents)this.herd=this.place({live:t,ended:n});else if(o&&!i)this.herd={...this.herd,pasture:Pn(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let s=a&&this.drawnPasture().length===0;this.tui.requestRender(s)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:$n(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Ee=class{static{r(this,"PastureView")}render(){return C()?.pastureRows()??[]}invalidate(){}};function $t(e){Ce(),e.custom(t=>{let n=new Re(t,Wn,Un,Cn,Math.random);return ve(n),n},{overlay:!0,overlayOptions:Nn,onHandle:r(t=>C()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Ee,{overlay:!0,overlayOptions:Hn,onHandle:r(t=>C()?.attachPasture(t),"onHandle")})}r($t,"showExtensionIndicator");function Ce(){let e=C();ve(null),e?.dispose()}r(Ce,"hideExtensionIndicator");function ee(){return w().agent.extensionEnabled}r(ee,"isExtensionEnabled");function qn(){return ee()&&w().agent.showActiveIndicator}r(qn,"isActiveIndicatorShown");function te(e){qn()?$t(e):Ce()}r(te,"syncExtensionIndicator");function Ao(e,t){w().mutate.agent.setShowActiveIndicator(t),te(e)}r(Ao,"setShowActiveIndicator");import{Type as E}from"typebox";import{getMarkdownTheme as Bt,keyHint as Fn}from"@earendil-works/pi-coding-agent";import{Box as Kn,Container as Nt,Markdown as Lt,Spacer as Ht,Text as ne}from"@earendil-works/pi-tui";var Dt=4,Oe=class{constructor(t,n,o){this.formatHint=n;this.padX=o;this.markdown=new Lt(t,o,0,Bt())}formatHint;padX;static{r(this,"ReportPreview")}cachedWidth;cachedLines;markdown;render(t){if(this.cachedLines===void 0||this.cachedWidth!==t){let n=this.markdown.render(t),o=n.length-Dt;this.cachedLines=o>0?[...n.slice(0,Dt),...new ne(this.formatHint(o),this.padX,0).render(t)]:n,this.cachedWidth=t}return this.cachedLines}invalidate(){this.cachedWidth=void 0,this.cachedLines=void 0,this.markdown.invalidate()}},jt=r((e,t,n)=>{let o=typeof e=="object"&&typeof e.content=="string"?e.content:"",i=o.indexOf(`
2
+
3
+ `),a=(i<0?o:o.slice(0,i)).trim(),s=i<0?"":o.slice(i+2).trim(),d=/\b(error|stopped)\b/i.test(a),l=`${n.fg(d?"error":"success",d?"\u2717":"\u2713")} ${n.fg("toolTitle",n.bold(a||"Cowboy agent report"))}`,v=r(p=>n.bg(d?"toolErrorBg":"toolSuccessBg",p),"bg"),m=r(p=>{let g=new Kn(0,0,v);return g.addChild(p),g},"panel");if(!s)return m(new ne(l,t.outputPad,0));if(!t.expanded){let p="keyHint"in t&&typeof t.keyHint=="function"?t.keyHint("app.tools.expand","to expand"):Fn("app.tools.expand","to expand"),g=new Nt;return g.addChild(new ne(l,t.outputPad,0)),g.addChild(new Ht(1)),g.addChild(new Oe(s,A=>`${n.fg("muted",`... (${A} more lines,`)} ${p}${n.fg("muted",")")}`,t.outputPad)),m(g)}let u=new Nt;return u.addChild(new ne(l,t.outputPad,0)),u.addChild(new Ht(1)),u.addChild(new Lt(s,t.outputPad,0,Bt())),m(u)},"renderSubagentResult");import{Type as h}from"typebox";var Gn="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",Yn=`REQUIRED. Short 2-3 word task name (e.g. "fix login flow"). This single value names the agent's branch/tab/worktree/agent so you can recognize it at a glance, and the extension appends a unique spawn id so parallel spawns \u2014 and every entry in a batch \u2014 are always distinct. Limits: 3 words, 19 characters when slugged (lowercase, dashes). A longer name throws with the exact overshoot \u2014 retry with a shorter name. Missing name throws too. The same name twice in one call is rejected before anything spawns.`,zn=`Optional model for THIS agent as "provider/model-id". Omit it, or pass null, to leave it unset and use the configured default for this session and agent type \u2014 the usual case, and never a value to guess at. Pass it when the user asked for a specific model for this task. When a previous attempt failed with a provider/model error, pass a different model here and instruct the agent in plain text to continue where the failed attempt left off. A model that is not in this session's registry fails the call before anything is spawned.`,Vn=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${F.join(", ")}) and any harness a plugin registered in this session. Omit it, or pass null, to leave it unset and use the agent template's harness_type, then the configured default \u2014 never pass a harness the user did not ask for. A harness this session did not register, or this machine cannot launch, fails the call before anything is spawned \u2014 unlike the configured default, an explicit request never falls back to pi.`,Qn='Optional worktree for THIS agent. Omit it, or pass null, for "new": an isolated cow-<task>-<id> worktree, the default. Pass "inherit" to run in the parent session cwd with no worktree of its own, or {"path":"/absolute/checkout"} to run inside an existing worktree of this repository; that checkout is never removed by cleanup. Never pick a target the user did not ask for \u2014 omit the parameter to keep the default.',_e=h.Union([h.Literal("new"),h.Literal("inherit"),h.Object({path:h.String({description:"Absolute path of an existing git worktree of this repository."})},{additionalProperties:!1}),h.Null()],{description:Qn}),Xn=h.Object({prompt:h.String({description:Gn}),task_name:h.String({description:Yn}),agent_type:h.Optional(h.Union([h.String(),h.Null()])),model:h.Optional(h.Union([h.String(),h.Null()],{description:zn})),harness_type:h.Optional(h.Union([h.String(),h.Null()],{description:Vn})),worktree:h.Optional(_e)},{additionalProperties:!1,required:["prompt","task_name"]}),H=h.Object({agents:h.Array(Xn,{minItems:1}),run_in_background:h.Optional(h.Boolean())},{additionalProperties:!1,required:["agents"]});var f={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Pe=Object.values(f),k={type:"json_schema",strict:"prefer"};var Me="_configuredModel",$e="_configuredThinking";function _(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(_,"readModelKey");function re(e){return _(e.thinking)??_(e[$e])}r(re,"readThinkingRequest");function oe(e){let t=_(e.model);if(t)return{source:"call",key:t};let n=_(e[Me]);if(n)return{source:"configured",key:n}}r(oe,"readModelRequest");function W(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(W,"withoutModel");function se(e){switch(e.kind){case"resolved":return{model:e.model,key:e.modelKey,thinking:e.thinking};case"foreign":return{harness:e.harness,key:e.modelKey,name:e.modelName,thinking:e.thinking};case"level":return{levelOnly:!0,thinking:e.thinking};case"none":return}}r(se,"modelChoiceFor");function U(e){return`${e.provider}/${e.id}`}r(U,"modelKey");function Zn(e,t){if(t!==void 0&&!ye.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${ye.options.join(", ")}); launching "${U(e)}" with "${t}".`}r(Zn,"undeclaredLevelWarning");function Wt(e,t){let n=Zn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Wt,"resolvedModel");function Jn(e){return`No API key found for "${e}"`}r(Jn,"missingCredential");function Ut(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:N(o)}}return!Ge(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Jn(t.provider)}}r(Ut,"probeCredentials");function Ne(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ne,"refusal");function He(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return W(i);let d=Ut(n,o);if(d.verdict!=="unusable")return Wt(o,i);throw new Error(Ne(`The parent session's model "${U(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?me(e.key,n,void 0):me(e.key,n,o);if(!a){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return W(i)}let s=Ut(n,a);if(s.verdict!=="unusable")return Wt(a,i);throw e.source==="call"?new Error(Ne(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Ne(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(He,"resolvePiModel");async function er(e){try{return await e.listModels(e.harness)}catch{return[]}}r(er,"harnessModels");function tr(e,t,n){if(t===void 0||t.thinkingLevels.kind!=="closed")return;let{levels:o}=t.thinkingLevels;if(!o.includes(n))return o.length===0?`Model "${t.key}" (${e}) does not support thinking levels; launching with "${n}".`:`Thinking level "${n}" is not declared by ${e} model "${t.key}" (supported: ${o.join(", ")}); proceeding with "${n}".`}r(tr,"undeclaredLevelWarning");async function qt(e,t){if(!e)return W(t.thinking);let n=await er(t),o=n.find(a=>a.key===e.key),i=[];if(n.length>0&&!o&&i.push(`The ${t.harness} model list does not include "${e.key}"; launching with that key anyway.`),t.thinking!==void 0){let a=tr(t.harness,o,t.thinking);a!==void 0&&i.push(a)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(qt,"resolveForeignModel");async function ie(e,t){let{harness:n}=t;if(nt(n))return He(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return qt(e,o)}r(ie,"resolveSpawnModel");function D(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(D,"resultWithSeverity");function ae(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(ae,"foldSeverity");var De=`
4
+
5
+ ---
6
+
7
+ `,nr={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function R(e){let{items:t}=e;or(t,e),await e.prepare?.();let n=rr(e),o=[],i=[],a=r(({outcome:d,text:c})=>{o.push(d),i.push(c)},"record"),s;for(let d of t){let c=n.halt;if(c!==void 0&&s!==void 0){a(c.skip(d,s));continue}let l=await n.handle(d);a(l),c!==void 0&&c.halts(l.outcome)&&(s=d)}return D(ae(o.map(e.severity)),i.join(De),{[e.detailsKey]:o})}r(R,"runBatch");function rr(e){if("render"in e){let n=e.render,o=e.halt;return{handle:r(async i=>{let a=await e.handleItem(i);return{outcome:a,text:n(a)}},"handle"),halt:o===void 0?void 0:{halts:r(i=>o.on(i),"halts"),skip:r((i,a)=>{let s=o.skip(i,a);return{outcome:s,text:n(s)}},"skip")}}}let t=e.halt;return{handle:e.handleItem,halt:t===void 0?void 0:{halts:r(n=>t.on(n),"halts"),skip:t.skip}}}r(rr,"batchSteps");function or(e,{toolName:t,param:n}){let o=e.map(s=>s.trim()),i=o.filter((s,d)=>o.indexOf(s)!==d);if(i.length===0)return;let a=nr[n];throw new Error(`${t} received duplicate ${a.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(or,"rejectRepeatedKeys");var Ft={user:"STOPPED BY THE USER before completion \u2014 output is partial; the task was NOT finished",agent:"STOPPED BY YOU before completion \u2014 output is partial; the task was NOT finished"},sr={user:"STOPPED BY THE USER before the agent started \u2014 the task was NOT attempted",agent:"STOPPED BY YOU before the agent started \u2014 the task was NOT attempted"};function ir(e){if(!T(e)||e.status!=="stopped")return Ft.agent;let{stop:t}=e;return e.phase==="never-started"?sr[t.initiator]:Ft[t.initiator]}r(ir,"stopNote");function Kt(e){return!T(e)||e.status!=="stopped"?"":` (${ir(e)})`}r(Kt,"getStatusNote");async function ar(e,t){let n=j();return n!==null?await n.list(e):await O().require(e).listModels({pi:b(),modelCatalog:ut(t.modelRegistry)})}r(ar,"readHarnessModelList");function de(e){return async t=>{let n=await ar(t,e),o=ot(n);return o!==void 0&&e.hasUI&&e.ui.notify(o,"warning"),rt(n)}}r(de,"harnessModelReader");function P(e=y()){let t=e.listAgents(we).filter(n=>K(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(P,"formatActiveAgents");function Be(e,t){let n={type:e.display.type,description:e.display.description};e.display.taskSlug&&(n.taskSlug=e.display.taskSlug),e.display.worktree&&(n.worktreePath=e.display.worktree.path,n.worktreeBranch=e.display.worktree.branch),e.display.worktree?.kind==="owned"&&(n.worktreeManaged=!0);let o=e.execution.host;if(o&&(n.herdrAgent=o.name,n.herdrPane=o.paneId,n.herdrTab=o.tabId),t?.includeStatus&&(n.status=I(e.lifecycle)),t?.includeRunInfo){let i=T(e.lifecycle)?e.lifecycle.completedAt-at(e.lifecycle):0;n.durationMs=i,n.modelName=e.display.invocation?.modelName,n.modelId=e.display.invocation?.modelName,n.thinkingLevel=e.display.invocation?.thinkingLevel}return n}r(Be,"buildAgentDetails");function dr(e){if(!T(e))return{kind:"stopped"};switch(e.status){case"completed":return{kind:"completed",result:e.result};case"error":return{kind:"failed",error:e.error};case"stopped":return{kind:"stopped"};default:return tt(e)}}r(dr,"settledOutcome");function lr(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${I(e.lifecycle)}]`}r(lr,"settledHeadline");function cr(e){let t=e.lifecycle,n=T(t)?t.worktreeRetentionReason:void 0,o=e.display.orchestration,i=e.display.worktree?.kind==="owned"?e.display.worktree:void 0;return V(o.cues,"settled",Tt({outcome:dr(t),statusNote:Kt(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?kt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:w().multiplexer||st}))}r(cr,"formatResultContent");async function ur(e,t){let n=Ve(e);if(n.kind!=="picked")return n;let o=he(n.path),a=(o===void 0?null:await wt(b(),t.cwd))?.find(s=>he(s.path)===o);if(a===void 0)throw new Error(`Worktree "${n.path}" is not an existing checkout of this repository \u2014 nothing was spawned. Pass an absolute path from \`git worktree list\`, or "new"/"inherit".`);return{kind:"picked",path:a.path,branch:ze(a)}}r(ur,"resolveWorktreeRequest");var Le=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=Q(t.agent_type),a=t.prompt,s=typeof t.task_name=="string"?t.task_name.trim():"";if(!s)throw new Error('cowboy_agent requires a short 2-3 word task name (e.g. "fix login flow") via the `task_name` parameter \u2014 it names the agent\'s branch/tab/worktree/agent so you can recognize it at a glance.');let d=Qe(s),c=Et(),l=await bt(i,void 0,(S,ue)=>{n.ui.notify(S,ue)});if(l.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${i}. Candidates: ${l.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(l.kind==="not-found")throw new Error(`Unknown agent type: ${i} \u2014 nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);let v=It(t.harness_type),m=X(l.key,v),u=re(t),p=await ie(oe(t),{harness:m,registry:n.modelRegistry,parent:n.model,thinking:u,listModels:de(n)});for(let S of p.notices)n.ui.notify(S,"warning");let g=await ur(t.worktree,n),A=t.run_in_background!==!1;return new e({ctx:n,toolCallId:o,taskSlug:d,prompt:a,description:a.split(`
8
+ `)[0].slice(0,80)||a.slice(0,80),agentType:i,resolvedType:l.key,orchestrator:c,fork:z(i)?.fork??!1,modelChoice:se(p.resolved),requestedHarness:v,worktree:g,isBackground:A})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:a}=this.intent,s=b(),d=y().mintSpawnId(),c=await this.resolveWorktree(s,d),l=this.intent.modelChoice?.thinking??void 0,v=et(this.intent.modelChoice),{agentId:m,spawn:u}=await ct().spawn(n,{spawnId:d,type:a,prompt:this.intent.prompt,description:this.intent.description,taskSlug:i,orchestration:this.intent.orchestrator,modelChoice:this.intent.modelChoice,requestedHarness:this.intent.requestedHarness,fork:this.intent.fork,worktree:c,invocation:{modelName:v,thinkingLevel:l,fork:this.intent.fork},runInBackground:o,signal:o?void 0:t});if(this.intent.toolCallId&&(u.display.toolCallId=this.intent.toolCallId),!o){let S=Be(u,{includeRunInfo:!0,includeStatus:!0});if(S.agentId=m,T(u.lifecycle)&&u.lifecycle.status==="error")throw new Error(`agent ${m} stopped with an error: ${u.lifecycle.error||"no error message was recorded"}`);return{message:`${lr(u)}
9
+
10
+ ${cr(u)}`,details:S}}let p=c;if(u.lifecycle.phase==="queued"){let S=y().listAgents(we).filter(Sn=>Sn.lifecycle.phase==="spawned").length,ue=V(this.intent.orchestrator.cues,"queued",St({agentId:m,worktree:p,queueRunning:S})),pe=Be(u);return pe.agentId=m,pe.status="queued",{message:`[Agent queued] ${ue}`,details:pe}}let g=V(this.intent.orchestrator.cues,"spawned",At({agentId:m,worktree:p})),A=Be(u);return A.agentId=m,A.status="spawned",{message:`[Agent spawned] ${g}`,details:A}}async resolveWorktree(t,n){let o=this.intent.worktree;switch(o.kind){case"inherit":return;case"picked":return o;case"new":return this.expectedWorktree(t,n)}}async expectedWorktree(t,n){let o=await yt(t,G().cwd).catch(()=>{});if(o===void 0)return;let i=Je(w().agent.worktreeRoot,o);return{kind:"owned",path:Ze(i,this.intent.taskSlug,n),branch:Xe(this.intent.taskSlug,n)}}};async function Gt(e,t,n,o){if(e.agents.length>1&&e.run_in_background===!1)throw new Error("run_in_background: false requires exactly one agent");let i=e.agents.map(l=>({...l,run_in_background:e.run_in_background})),a=await Promise.all(i.map(l=>Le.parse(l,t,n)));pr(a);let s=await Promise.all(a.map(l=>l.run(o))),d=s.map(l=>l.message).join(De),c={agents:s.map(l=>l.details)};return{message:d,details:c}}r(Gt,"runDelegationBatch");function pr(e){let t=e.map(o=>o.intent.taskSlug),n=t.filter((o,i)=>t.indexOf(o)!==i);if(n.length!==0)throw new Error(`cowboy_agent received the same task_name more than once: ${[...new Set(n)].join(", ")} \u2014 nothing was spawned. Give every item in \`agents\` its own task_name.`)}r(pr,"rejectRepeatedTaskSlugs");var q=globalThis.__PI_COWBOY_DEV_MODE__===!0;import{Type as je}from"typebox";var hr="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Yt=je.Object({agent_ids:je.Array(je.String({minLength:1}),{minItems:1,description:hr})},{additionalProperties:!1,required:["agent_ids"]});function gr(e){let t=Array.isArray(e.agents)?e.agents:[];return ae(t.map(n=>typeof n=="object"&&n!==null&&n.status==="stopped"?"warning":"success"))}r(gr,"delegationSeverity");function mr(e){return{...e,agents:e.agents.map(t=>{let n={...t};return delete n.worktree,n})}}r(mr,"withoutWorktreeTarget");async function Vt(e,t,n,o,i){let{message:a,details:s}=await Gt(q?t:mr(t),i,e,n);return D(gr(s),a,s)}r(Vt,"executeAgentTool");var Qt={name:f.stopAgent,label:f.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping sends the agent's harness its own exit keys (its pane is left in place) and settles the agent as stopped once the process is confirmed gone. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Yt,execute:wr,constrainedSampling:k};function fr(e){switch(e.kind){case"stopped":return"success";case"failed":return"error";case"already-settled":case"unknown":case"refused":return"warning"}}r(fr,"stopSeverity");function yr(e){switch(e.kind){case"stopped":return`Stopped agent ${e.agentId}`;case"already-settled":return`Agent ${e.agentId} is already ${e.status}. Active agents: ${e.activeAgents}`;case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`;case"refused":return`Agent ${e.agentId} was not stopped: ${e.reason}`;case"failed":return`Failed to stop agent ${e.agentId}: ${e.error}`}}r(yr,"renderStopOutcome");async function wr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:yr,severity:fr,handleItem:r(async s=>{let d=y().getSpawn(s);if(!d)return{kind:"unknown",agentId:s,activeAgents:P()};if(y().isHandingOver(s))return{kind:"refused",agentId:s,reason:"it is being handed over to another harness \u2014 wait for the handover to finish, then stop the new run if you still want it stopped."};if(!K(d.lifecycle.phase))return{kind:"already-settled",agentId:s,status:I(d.lifecycle),activeAgents:P()};try{return await y().abort(s,"agent")?{kind:"stopped",agentId:s}:{kind:"failed",agentId:s,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:s,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}r(wr,"executeStopAgentTool");function zt(e,t,n,o){let i=z(n),a=t.model?`${t.model.provider}/${t.model.id}`:null,s=_(e.model),d=s??w().modelFor(n,a,i,o,O().family(o));if(d&&!s&&(e[Me]=d),e.thinking===void 0){let c=w().thinkingFor(n,i,o,O().family(o),t.thinkingLevel);c!==void 0&&(e[$e]=c)}}r(zt,"injectConfiguredDefaults");async function Ws(e,t){let n=e.input;if(e.toolName===f.handoverAgent){let i=Se(n.harness_type);if(i===void 0)return;let a=_(n.agent_id)??"",s=y().getSpawn(a)?.display.type??Rt();zt(n,t,s,i);return}if(e.toolName!==f.agent)return;let o=n.agents??[];for(let i of o){let a=Q(i.agent_type),s=Se(i.harness_type),d=X(a,s);zt(i,t,a,d)}}r(Ws,"toolCallListener");import{Type as We}from"typebox";var vr="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",Xt=We.Object({agent_ids:We.Array(We.String({minLength:1}),{minItems:1,description:vr})},{additionalProperties:!1,required:["agent_ids"]});function Zt(e){switch(e.kind){case"pane-absent":return"pane-absent";case"pane-not-working":return`pane-not-working: ${e.state}`;case"forced":return"forced";case"pane-working":return"pane-working";case"pane-unreadable":return`pane-unreadable: ${e.detail}`;case"artifacts-ambiguous":return"artifacts-ambiguous"}}r(Zt,"formatBasis");function kr(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${Zt(e.basis)})`}r(kr,"formatSettlement");function Jt(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`;case"agent-active":return`the agent is still ${e.phase} and has not reported a result \u2014 stop it with stop_cowboy_agent, then clean up`;case"recovered-refusal":return`no settlement was recorded and herdr still reports the agent at work (${Zt(e.basis)}) \u2014 stop it before retrying`;case"ambiguous-artifacts":return`two artifacts answer to this id (${e.candidates.join(", ")}) \u2014 nothing was removed; work out which run owns the id before removing either by hand`;case"space-in-use":return`its workspace is still in use by ${e.tenants.join(", ")} \u2014 the checkout is removed when the last agent there has been cleaned up`}}r(Jt,"formatKeptReason");function br(e){switch(e.kind){case"closed":return"closed";case"open":return"open";case"gone":return"gone (herdr has no such pane)";case"unknown":return"unknown (the pane was not read)"}}r(br,"paneText");function xr(e){return e.length===0?"none (the agent never had a pane)":e.map(t=>`${t.paneId} ${br(t)}`).join(", ")}r(xr,"panesText");function Ar(e){switch(e.kind){case"closed":return"pane closed";case"open":return"pane left open";case"gone":return"pane already gone";case"unknown":return"pane state unknown"}}r(Ar,"paneSummary");function Sr(e){if(e.length===0)return"no pane";if(e.length===1)return Ar(e[0]);let t=new Map;for(let o of e)t.set(o.kind,(t.get(o.kind)??0)+1);let n=[...t].map(([o,i])=>`${i} ${o}`).join(", ");return`${e.length} panes (${n})`}r(Sr,"panesSummary");function en(e){switch(e.kind){case"removed":return`removed (${e.path})`;case"removal-failed":return`NOT removed \u2014 ${e.detail} (${e.path})`;case"kept":return`kept${e.path?` (${e.path})`:" (worktree path not recorded)"}`;case"absent":return`already gone (${e.path})`;case"none":return"none (agent ran without a worktree)"}}r(en,"worktreeText");function tn(e){let t=e.branch;return`${t.kind==="deleted"?"deleted":t.kind==="kept"?`kept (${t.reason})`:t.kind==="delete-failed"?`NOT deleted \u2014 ${t.detail}`:"not applicable"}${e.branchName?` (${e.branchName})`:""}`}r(tn,"branchText");function Tr(e){return e?` forced${e.reason?` \u2014 ${Jt(e.reason)}`:""}`:""}r(Tr,"forcedClause");function Ue(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Jt(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${Tr(e.outcome.forced)}:`}r(Ue,"headline");function nn(e){let t=[Ue(e),` agent status: ${kr(e.settlement)}`,` panes: ${xr(e.panes)}`,` worktree: ${en(e.worktree)}`,` branch: ${tn(e)}`];if(e.source==="recovered"&&t.push(" recovered: no spawn record survived \u2014 this verdict rests on discovery (herdr's live read plus the worktree on disk)"),e.settlement.kind==="discovered"){let{path:n,present:o}=e.settlement.deliverable;t.push(o?` deliverable: UNREAD at ${n} \u2014 read it before deleting the directory`:` deliverable: none written (${n} does not exist)`)}return t.join(`
11
+ `)}r(nn,"renderCleanupReport");function Gs(e){let t=Sr(e.panes);return e.outcome.kind==="refused"?`${Ue(e)} ${t}`:`${Ue(e)} ${t}, worktree ${en(e.worktree)}, branch ${tn(e)}`}r(Gs,"summarizeCleanupReport");function Ys(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Ys,"cleanupNeedsAttention");var rn={name:f.cleanupAgent,label:f.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:Xt,execute:Ir,constrainedSampling:k};function Rr(e){return e.kind==="unknown"?"warning":e.report.outcome.kind==="torn-down"?"success":"warning"}r(Rr,"cleanupSeverity");function Er(e){switch(e.kind){case"cleaned":return nn(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(Er,"renderCleanupOutcome");async function Ir(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:Er,severity:Rr,handleItem:r(async s=>{let d=y();if(!d.getSpawn(s)&&(await d.locate(s)).kind==="not-found")return{kind:"unknown",agentId:s,activeAgents:P(d)};let c=await d.cleanup(s);return{kind:"cleaned",agentId:s,report:c}},"handleItem")})}r(Ir,"executeCleanupAgentTool");import*as an from"node:fs";import*as B from"node:path";import{Type as M}from"typebox";var Cr="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",Or="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",_r="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",on=M.Object({branches:M.Array(M.String({minLength:1}),{minItems:1,description:Cr}),target:M.Optional(M.String({description:Or})),repo:M.Optional(M.String({description:_r}))},{additionalProperties:!1,required:["branches"]});function sn(e){let t=B.normalize(e),{root:n}=B.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(sn,"normalizeRepoRoot");function Pr(e,t){return sn(e)===sn(t)}r(Pr,"isSameRepoRoot");function Mr(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(Mr,"formatOutsideRepoWarning");async function $r(e,t){let n=new mt(e),o=await n.probe(["rev-parse","--show-toplevel"],t);if(o===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: ${t} is not inside a git repository (git rev-parse --show-toplevel failed). Refusing to merge without a repo-scope check \u2014 run the session from inside a git checkout or pass an explicit \`repo\` inside one.`);let i=await n.probe(["rev-parse","--git-common-dir"],o);if(i===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: could not resolve the git directory for ${t}. Refusing to merge without a repo-scope check.`);let{mainRoot:a}=ft(i,o);if(!an.existsSync(B.join(a,".git")))throw new Error(`merge_cowboy_branch cannot verify the session repo: no main checkout found for ${t} (unsupported repo layout). Refusing to merge without a repo-scope check.`);return a}r($r,"resolveSessionMainRoot");var dn={name:f.mergeBranch,label:f.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:on,execute:jr,constrainedSampling:k};function Nr(e){switch(e.kind){case"merged":return"success";case"already-merged":case"unknown":case"not-attempted":return"warning";case"conflict":case"failed":return"error"}}r(Nr,"mergeSeverity");var Hr="has conflicts in:";function Dr(e){return e.includes(Hr)}r(Dr,"isConflictError");function Br(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
12
+ `).map(n=>n.trim()).filter(n=>n!==""):[]}r(Br,"parseConflictFiles");function Lr(e,t){return e.includes(`branch "${t}" does not exist`)}r(Lr,"isUnknownBranchError");async function jr(e,t,n,o,i){let a=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",s=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,d,c=r(()=>(d??=(async()=>{let l=G().cwd;if(typeof l!="string"||l.trim()==="")throw new Error("merge_cowboy_branch cannot verify the session repo: the session working directory is unavailable, so the repo-scope check is impossible. Refusing to merge without a repo-scope check.");return{sessionRoot:await $r(b(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:Nr,prepare:r(async()=>{Ae(a,"target");for(let l of t.branches)Ae(l.trim(),"branch");await c()},"prepare"),halt:{on:r(l=>l.kind==="conflict","on"),skip:r((l,v)=>{let m=l.trim(),u=`not attempted \u2014 the merge of "${v.trim()}" conflicted and is still in progress`;return{outcome:{kind:"not-attempted",branch:m,reason:u},text:`"${m}" ${u}.`}},"skip")},handleItem:r(async l=>{let{sessionRoot:v,cwd:m}=await c(),u=l.trim();try{let p=await vt(b(),{cwd:m,branch:u,target:a}),g=Pr(p.mainRoot,v)?void 0:Mr(p.mainRoot,v);if(g!==void 0)try{i.ui.notify(g,"warning")}catch{}let A=g!==void 0?`${g}
13
+ `:"";return p.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${A}"${u}" is already merged into "${p.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:p.target,output:p.output},text:`${A}Merged "${u}" into "${p.target}" in ${p.mainRoot}.`+(p.output?`
14
+ ${p.output}`:"")}}catch(p){let g=p instanceof Error?p.message:String(p);return Dr(g)?{outcome:{kind:"conflict",branch:u,target:a,files:Br(g)},text:`"${u}": ${g}`}:Lr(g,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${g}`}:{outcome:{kind:"failed",branch:u,error:g},text:`"${u}": ${g}`}}},"handleItem")})}r(jr,"executeMergeBranchTool");import{Type as le}from"typebox";var Wr="REQUIRED. One or more agent ids to steer (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A settled agent is revived by the delivery. A repeated id is rejected before anything is delivered \u2014 pass each id once.",Ur="REQUIRED. The single message delivered verbatim to every id in `agent_ids`. Plain instructions work best (e.g. \"stop refactoring; just fix the failing test and report\"). Delivery is fire-and-forget: nothing here waits for an agent to act on it. Because the text is entered into the agent's pi session, a command prefixed with `!` runs and adds its output to that agent's context, while `!!` runs it without adding the output to its context.",ln=le.Object({agent_ids:le.Array(le.String({minLength:1}),{minItems:1,description:Wr}),message:le.String({description:Ur})},{additionalProperties:!1,required:["agent_ids","message"]});var cn={name:f.steerAgent,label:f.steerAgent,description:"Send one message to one or more agents in one call: pass every id in `agent_ids` and the single `message` delivered to each. Each id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A repeated id in `agent_ids` is rejected before anything is delivered \u2014 pass each id once. A spawned agent receives the message before its next model call; a SETTLED one is REVIVED \u2014 spawned again, given the message, and it sends you another completion message when it settles again. That second result arrives only as that completion message: the spawn's result promise closed with the first turn and never opens again. Delivery is fire-and-forget: nothing here waits for an agent to act on it, so do not poll for a reply. The message is entered into the agent's pi session, so it can also be a bash command: `!command` runs the command and sends its output to the agent's context; `!!command` runs it without adding the output to the agent's context. A QUEUED agent cannot be steered \u2014 it has no pane yet; wait for a concurrency slot first. An agent whose pane is gone (cleaned up) cannot be steered either, and neither can an agent being TORN DOWN (wait for its report) or handed over (wait for the handover to finish). Every refusal states its reason and what to do about it.",parameters:ln,execute:Fr,constrainedSampling:k};function qr(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(qr,"steerSeverity");async function Fr(e,t,n,o,i){let a=t.message.trim();return R({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,severity:qr,prepare:r(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:r(async s=>{let d=y().getSpawn(s);if(!d){let m=`not found. Active agents: ${P()}`;return{outcome:{kind:"refused",agentId:s,reason:m},text:`Agent ${s} was not steered: ${m}`}}let c=I(d.lifecycle),l;try{l=await y().steer(s,a)}catch(m){l={kind:"refused",reason:`steering failed: ${N(m)}`}}if(l.kind==="refused")return{outcome:{kind:"refused",agentId:s,reason:l.reason},text:`Agent ${s} was not steered (${c}): ${l.reason}`};if(l.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:s,reason:l.reason},text:`Agent ${s} had settled (${c}) and the message reached its pane, but it was not revived: ${l.reason}`};let v=c!=="spawned"&&d.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:s},text:v?`Agent ${s} had settled (${c}) \u2014 revived: the message was delivered to its pane and the agent is spawned again. Merge nothing yet; a new completion message will arrive when it settles again.`:c==="spawned"?`Message delivered to spawned agent ${s}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${s} was delivered to (${c}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r(Fr,"executeSteerAgentTool");function Ri(e,t,n){return ge(e.ids(),t).filter(o=>o!==n)}r(Ri,"handoverTargets");function un(e,t,n){let o=e.trim();return o===""?{kind:"faulted",fault:{kind:"request-refused",detail:"`harness_type` is required \u2014 name the harness that runs the next run. Nothing was changed."}}:t.get(o)===void 0?{kind:"faulted",fault:{kind:"request-refused",detail:`Unknown harness_type "${o}": this session registered ${t.ids().join(", ")}. Nothing was changed \u2014 name a registered harness that runs the next run.`}}:Ke(o,n)?{kind:"ready",harness:o}:{kind:"faulted",fault:{kind:"request-refused",detail:`Harness "${o}" cannot be launched on this machine \u2014 this machine can launch ${ge(t.ids(),n).join(", ")}. Nothing was changed.`}}}r(un,"resolveHandoverTarget");import{Type as x}from"typebox";var Kr="REQUIRED. The id of the SETTLED agent to hand over, as printed by the cowboy_agent spawn result or a completion message. A live agent is refused, never stopped \u2014 stop it with stop_cowboy_agent and hand it over once it has settled.",Gr=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${F.join(", ")}) and any harness a plugin registered in this session. Unlike the configured default, an explicit harness never falls back: an ID this session did not register, or one this machine cannot launch, causes the call to be refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result and nothing changes.`,Yr=`Optional model for the next run as "provider/model-id", in the target harness's own vocabulary. Omit it, or pass null, to leave it unset and let the harness choose its default. A model that is not in this session's registry (or in the target harness's list) refuses the call before anything is stopped.`,zr="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",pn=x.Object({agent_id:x.String({minLength:1,description:Kr}),harness_type:x.String({description:Gr}),model:x.Optional(x.Union([x.String(),x.Null()],{description:Yr})),thinking:x.Optional(x.Union([x.String(),x.Null()],{description:zr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Vr(e,t){let n=un(e.harness_type,O(),pt());if(n.kind==="faulted")return{kind:"faulted",fault:n.fault};let o=n.harness;try{let i=await ie(oe(e),{harness:o,registry:t.modelRegistry,parent:t.model,thinking:re(e),listModels:de(t)});for(let a of i.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:o,modelChoice:se(i.resolved)}}catch(i){return{kind:"faulted",fault:{kind:"request-refused",detail:N(i)}}}}r(Vr,"resolveIntent");function Qr(e,t){return`Agent ${e} ${Xr(t)}`}r(Qr,"renderHandoverOutcome");function Xr(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":dt(e.loss);return`handed over from "${e.from}" to "${e.to}".${t} The ended run is archived; the next one runs in the same checkout and reports when it settles.`}switch(e.fault.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return e.fault.status==="queued"?"is still queued \u2014 it has not started, so there is no session to hand over. Wait for a concurrency slot (or stop it). Nothing was changed.":`is still ${e.fault.status} \u2014 stop it with stop_cowboy_agent and hand it over once it has settled. Nothing was changed.`;case"harness-cannot-export-session":return`was not handed over: harness "${e.fault.harness}" cannot export its own session, so there is nothing to hand over. Nothing was stopped or changed.`;case"never-started":return"was not handed over: it never started, so there is no session to export.";case"stop-failed":return`was not handed over: its run could not be stopped (${e.fault.detail}). Nothing was changed.`;case"session-empty":return`was not handed over: harness "${e.fault.harness}" returned an empty session. Nothing was changed: the run was not stopped.`;case"session-export-failed":return`was not handed over: harness "${e.fault.harness}" could not export its session (${e.fault.detail}). Nothing was changed: the run was not stopped.`;case"request-refused":return`was not handed over: ${e.fault.detail}`;case"launch-failed":return`ended its previous run but its next one did not start (${e.fault.detail}). It stays tracked and can be cleaned up.`}}r(Xr,"handoverReport");async function Zr(e,t,n,o,i){let a=t.agent_id.trim(),s=await Vr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await y().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return D(lt(d),Qr(a,d),{agentId:a,outcome:d})}r(Zr,"executeHandoverAgentTool");var hn={name:f.handoverAgent,label:f.handoverAgent,description:"Hand over one SETTLED agent to another harness in one call: pass its `agent_id` and the `harness_type` that executes its next run. The ended run is stopped, its session exported by the source harness, the run archived, and the next one launched in the same checkout with that session and its ID quoted in its task \u2014 so the work continues under the new harness instead of starting over. Nothing is removed: the ended run's pane and harness state stay until cleanup_cowboy_agent, which tears every run down at its own address. A live agent is REFUSED, never stopped \u2014 stop it with stop_cowboy_agent first. `harness_type` is required and, unlike a configured default, never falls back: if an ID was not registered in this session or cannot be launched on this machine, the call is refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result, naming the harness, and nothing is stopped or changed. The next run reports through its own completion message; this call returns when that run has started, not when it finishes.",parameters:pn,execute:Zr,constrainedSampling:k};import{Text as Jr}from"@earendil-works/pi-tui";var eo={success:"\u2713",warning:"!",error:"\u2717"};function to(e,t,n,o){let i=e.content.map(d=>d.text??"").join(`
15
+ `),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Jr(`${n.fg(a,eo[a])} ${s}`,0,0)}r(to,"renderCowboyToolResult");function $(e){return{...e,renderResult:to}}r($,"withCowboyRenderer");var no=Pe;function ro(e){return q?{...e,worktree:E.Optional(_e)}:e}r(ro,"offeredItemProperties");function oo(e){let t=E.Object(ro({prompt:H.properties.agents.items.properties.prompt,task_name:H.properties.agents.items.properties.task_name,agent_type:E.Optional(E.Union([E.String(),E.Null()],{description:`Optional agent type. Omit it, or pass null, to use the configured default agent type \u2014 never pass a type the user did not ask for. An unknown or ambiguous name is rejected before any agent in the batch spawns.${e.length>0?` Available: ${e.join(",")}`:""}`})),model:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type}),{additionalProperties:!1,required:["prompt","task_name"]});return E.Object({agents:E.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(oo,"cowboyAgentsSchemaWithTypes");var so=q?"Delegate one or more tasks to agents. Each agent gets a fresh pi process and, by default, an isolated worktree \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. Always omit optional parameters the user did not explicitly ask for \u2014 `agent_type`, `model`, `harness_type`, and `worktree` each take this session's configured default when unset, so never guess or fill them in on the user's behalf. When an agent settles, the completion message names its branch when it has one and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.":"Delegate one or more tasks to agents. Each agent gets an isolated worktree and a fresh pi process \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. When an agent settles, the completion message names its `cow-` branch and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.";function gn(e){let t=oo(xt()),n={name:f.agent,label:f.agent,description:so,parameters:t,execute:Vt,constrainedSampling:k};e.registerTool($(n))}r(gn,"registerAgentTool");function io(e,t){w().mutate.agent.setExtensionEnabled(t),t?ao(e):lo(e)}r(io,"setExtensionEnabled");function ao(e){let t=b();gn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...no])]),te(e)}r(ao,"activateExtension");function lo(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!Pe.includes(n))),te(e)}r(lo,"deactivateExtension");function aa(e){gn(e),e.registerTool($(Qt)),e.registerTool($(dn)),e.registerTool($(cn)),e.registerTool($(hn)),e.registerTool($(rn)),e.registerMessageRenderer("subagent-result",jt)}r(aa,"registerTools");var mn="cowboy",co={wt:"worktree",sp:"spawn",st:"status"};function da(e,t){e.registerCommand(mn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(da,"registerUnavailableCowboyCommand");function la(e){e.registerCommand(mn,{description:"Manage agents: status, spawn, settings. `status` lists spawned, queued and settled agents; `spawn` opens the spawn wizard; `worktree` creates one git worktree with no agent attached to it. `status`, `spawn` and `worktree` also answer to `st`, `sp` and `wt`. `enable`/`disable` load or unload the cowboy tools. Pass `model` (optionally a provider/model-id) to set the model agents use for this session \u2014 opens pi's model picker.",getArgumentCompletions:r(async t=>(await import("./model-picker-O3JKB6AX.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{ht(n);let[o,...i]=t.trim().split(/\s+/),a=co[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&xe()===null){n.ui.notify(fe,"warning");return}if(ee()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}io(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(xe()===null){n.ui.notify(fe,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-SJOY7VYX.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!ee()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-O3JKB6AX.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-OETWLG2Y.js");await l(n,s,j()?.options??new Map);return}if(s!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-OETWLG2Y.js");await c(n,j()?.options??new Map)},"handler")})}r(la,"registerCowboyCommand");import*as fn from"node:fs";import{tmpdir as uo}from"node:os";import*as ce from"node:path";async function yn(e,t){try{return await gt(e).probe(t),L(Ye)}catch{return L(["checkout"])}}r(yn,"detectCowAvailability");function wn(e){let t=ce.resolve(e??qe());for(;;){try{if(fn.statSync(t).isDirectory())return t}catch{}let n=ce.dirname(t);if(n===t)return uo();t=n}}r(wn,"probeTargetFor");function po(e){return(t,n,o)=>e.exec(t,n,o)}r(po,"execOf");function xa(e){return vn(e,be())}r(xa,"startCowSupportProbe");function Aa(e){let t=be();return Y(t,Fe()),vn(e,t)}r(Aa,"refreshCowSupportProbe");function vn(e,t){let n=wn(w().agent.worktreeRoot);return yn(po(e),n).then(o=>{Y(t,o)},()=>{Y(t,L(["checkout"]))})}r(vn,"probe");import kn from"node:fs";var ho="/tmp";function go(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(go,"handoverNameField");function bn(e){return`${[e.worktree,e.harness,e.sessionId].map(go).join("-")}.md`}r(bn,"handoverFileName");function xn(e){return`${ho}/${e}`}r(xn,"handoverFilePath");function mo(e){return kn.existsSync(e)}r(mo,"handoverFileExists");function Ea(e,t){let n=mo(e);return kn.writeFileSync(e,t,"utf8"),{replaced:n}}r(Ea,"writeHandoverFile");import*as An from"node:path";function _a(e,t){return e===void 0?`main-${t}`:An.basename(e.path)}r(_a,"exportWorktreeName");function Pa(e){return{kind:"prepared",defaultPath:xn(bn({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(Pa,"handoverExportArtifact");function Ma(e){switch(e.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return`is still ${e.status} \u2014 its session cannot be read while the run is in that state. Nothing was changed.`;case"harness-cannot-export-session":return`was not exported: harness "${e.harness}" cannot export its own session, so there is nothing to write.`;case"never-started":return"was not exported: it never started, so there is no session to export.";case"handover-in-progress":return`was not exported: ${e.detail}`;case"session-empty":return`was not exported: harness "${e.harness}" returned an empty session.`;case"session-export-failed":return`was not exported: harness "${e.harness}" could not export its session (${e.detail}).`}}r(Ma,"handoverExportFaultReason");function $a(e){if(e.kind==="prepared")return e.loss===void 0?"success":"warning";switch(e.fault.kind){case"agent-unknown":case"agent-not-settled":case"harness-cannot-export-session":case"never-started":case"handover-in-progress":return"warning";case"session-empty":case"session-export-failed":return"error"}}r($a,"handoverExportSeverity");export{Be as a,lr as b,cr as c,Ws as d,Jt as e,Gs as f,Ys as g,Ri as h,Qr as i,Ce as j,ee as k,Ao as l,mo as m,Ea as n,_a as o,Pa as p,Ma as q,$a as r,xa as s,Aa as t,io as u,ao as v,lo as w,aa as x,da as y,la as z};
16
+ //# sourceMappingURL=chunk-CYQTM6FQ.js.map
@@ -1,4 +1,4 @@
1
- import{A as et,Aa as Z,D as nt,E as Y,K as rt,Ka as J,M as ot,N as ke,O as F,T as it,b as pe,ea as at,fa as X,i as qe,j as Ke,m as fe,n as Qe,na as j,o as Ye,r as Q,ra as st,s as Xe,u as Ze,w as Je,xa as M,y as me}from"./chunk-UEMXTMQN.js";import{F as tt,a as i,p as W,u as ge,v as he}from"./chunk-AOUEQXPY.js";import*as x from"node:fs";import*as k from"node:path";var hn=`import ctypes, sys
1
+ import{A as et,Aa as Z,D as nt,E as Y,K as rt,Ka as J,M as ot,N as ke,O as F,T as it,b as pe,ea as at,fa as X,i as qe,j as Ke,m as fe,n as Qe,na as j,o as Ye,r as Q,ra as st,s as Xe,u as Ze,w as Je,xa as M,y as me}from"./chunk-Y6XBNRLR.js";import{F as tt,a as i,p as W,u as ge,v as he}from"./chunk-AOUEQXPY.js";import*as x from"node:fs";import*as k from"node:path";var hn=`import ctypes, sys
2
2
  libc = ctypes.CDLL(None, use_errno=True)
3
3
  # CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
4
4
  if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
@@ -23,4 +23,4 @@ Error: {{error}}{{/error}}{{#has_worktree}}
23
23
  `);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}i(Jn,"describeParseError");var er={label:"File",problem:"was skipped"};async function oe(e,t,n,r,o=er,a){try{await ne.promises.access(e)}catch{return[]}let c=(await ne.promises.readdir(e,{withFileTypes:!0})).filter(l=>l.isFile()&&l.name.endsWith(Xn)),d=[];for(let l of c){let u=_t.join(e,l.name),p;try{p=await ne.promises.readFile(u,"utf-8")}catch{continue}try{let m=t(p),v=a?.(m);if(v!==void 0)throw new Error(v);n(m)&&d.push(m)}catch(m){r?.(`[cowboy] ${o.label} file ${u} ${o.problem}: ${Jn(m)}`,"warning")}}return d}i(oe,"scanTemplateFilesInDir");import{z as P}from"zod";import $t from"mustache";function Wt(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}i(Wt,"worktreeVariables");function tr(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}i(tr,"outcomeVariables");function nr(e){return e?{...Wt(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}i(nr,"settledWorktreeVariables");function rr(e){return e.worktree?{agent_id:e.agentId,...Wt(e.worktree)}:{agent_id:e.agentId}}i(rr,"spawnCueContext");function jo(e){return{...rr(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}i(jo,"queuedCueContext");function Lo(e){let{outcome:t,statusNote:n,worktree:r,multiplexerId:o}=e;return{...tr(t),...n?{status_note:n}:{},...nr(r),...o!=null?{multiplexer_id:o}:{}}}i(Lo,"settledCueContext");var or={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},ir={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},ar={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},sr=Object.keys(or),cr=Object.keys(ir),dr=Object.keys(ar);function Ft(e){switch(e){case"spawned":return sr;case"queued":return cr;case"settled":return dr;default:return}}i(Ft,"cueVariables");var lr={ok:!0},ur="&",pr=new Set(["name",ur,"#","^"]);function Vo(e,t,n){return $t.render(e[t],n,void 0,{escape:i(r=>r==null?"":String(r),"escape")})}i(Vo,"renderCue");function fr(e){let t=e[4];return Array.isArray(t)?t:void 0}i(fr,"spanChildren");function It(e,t,n){for(let r of e){let[o,a]=r;if(o===">")return`partials are not supported: "{{>${a}}}"`;if(o==="=")return`delimiter changes are not supported: "{{=${a}=}}"`;if(pr.has(o)&&!t.includes(a))return`unknown variable "{{${a}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let s=fr(r);if(s){let c=It(s,t,n);if(c)return c}}}i(It,"findTemplateProblem");function Dt(e,t){let n=Ft(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let r;try{r=$t.parse(t)}catch(a){return{ok:!1,reason:`unparsable template: ${(a instanceof Error?a.message:String(a)).replace(/\s+/g," ").trim()}`}}let o=It(r,n,e);return o?{ok:!1,reason:o}:lr}i(Dt,"validateCueTemplate");var mr=["spawned","queued","settled"],gr=P.strictObject({spawned:P.string().optional(),queued:P.string().optional(),settled:P.string().optional()}).superRefine((e,t)=>{for(let n of mr){let r=e[n];if(r===void 0)continue;let o=Dt(n,r);o.ok||t.addIssue({code:"custom",message:o.reason,path:[n]})}}),Mt=P.strictObject({name:P.string().optional(),display_name:P.string().optional(),guidance:P.string().optional(),cues:gr.optional()});var hr={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function kr(e){return Mt.parse(re(e))}i(kr,"parseOrchestratorFile");async function z(e,t){return oe(e,kr,n=>n.name,t,hr)}i(z,"scanOrchestratorFilesInDir");function Pe(e,t,n,r){let o=new Map(e instanceof Map?e:Object.entries(e)),a=o.get("default")??O.default;for(let s of[t,n,r])for(let c of s)c.name&&o.set(c.name,wr(o.get(c.name)??yr(c.name,a),c));return o}i(Pe,"mergeOrchestrators");function yr(e,t){return{...t,name:e,displayName:e}}i(yr,"namedBase");function wr(e,t){return{...e,name:t.name??e.name,displayName:t.display_name??e.displayName,cues:{...e.cues,...t.cues},guidance:t.guidance??e.guidance}}i(wr,"applyOverride");function G(){return J().orchestrators}i(G,"registry");function si(e,t){let n=new Map;if(!t?.disableDefaultOrchestrators)for(let[r,o]of Object.entries(O))n.set(r,o);for(let[r,o]of e)n.set(r,o);G().orchestrators=n}i(si,"registerOrchestrators");function ci(e,t,n){G().scanDirs={user:e,project:t,shared:n??""}}i(ci,"setOrchestratorScanDirs");async function di(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,r=G().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):z(Ke,n),z(r.user,n),z(r.shared,n),z(r.project,n)]),l=Pe(t?new Map:O,o,[],[]);return Pe(l,a,s,c)}i(di,"scanAndMergeOrchestrators");function Se(e){let{orchestrators:t}=G();if(!e)return;let n=t.get(e);if(n)return n;let r=e.toLowerCase(),o=[];for(let[a,s]of t)a.toLowerCase()===r&&o.push(s);return o.length===1?o[0]:void 0}i(Se,"resolveOrchestrator");function li(){return[...G().orchestrators.values()].map(e=>e.name)}i(li,"getAvailableOrchestrators");import{z as f}from"zod";var Nt=f.union([f.boolean(),f.array(f.string())]),br={name:"is not a valid environment variable name",reserved:"is a reserved environment variable and cannot be overridden","not-string":"must be a string",control:"contains a control character"};function ae(e){return f.record(f.string(),f.unknown()).transform((t,n)=>at(t,{reserved:tt[e],report:i((r,o)=>n.addIssue({code:"custom",path:[r],message:br[o]}),"report")}))}i(ae,"envTable");var Bt={model:f.string().optional(),thinking:ot.optional(),extensions:Nt.optional(),skills:Nt.optional(),inlined_skills:f.array(f.string()).optional(),fork:f.boolean().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("pi").optional()},Cr=f.strictObject(Bt),vr=f.strictObject({model:f.string().optional(),variant:f.string().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("opencode").optional()}),xr=f.strictObject({model:f.string().optional(),thinking:f.string().optional(),env:ae("codex").optional()}),Rr=f.strictObject({model:f.string().optional(),thinking:f.string().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("claude").optional()});function _e(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}i(_e,"toToolFilter");function ie(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}i(ie,"nonEmptyEnv");var Tr=f.strictObject({include_context_files:f.boolean().optional(),pi:Cr.optional(),opencode:vr.optional(),codex:xr.optional(),claude:Rr.optional(),...Bt}).transform(({pi:e,opencode:t,codex:n,claude:r,...o})=>{let{model:a,thinking:s,tools:c,exclude_tools:d,env:l,...u}=o,{model:p,thinking:m,tools:v,exclude_tools:D,env:ue,...K}=A(e??{}),{model:R,variant:tn,tools:nn,exclude_tools:rn,env:on,...an}=A(t??{}),{model:sn,thinking:cn,env:dn,...ln}=A(n??{}),{model:un,thinking:pn,tools:fn,exclude_tools:mn,env:gn}=A(r??{}),ze=A({pi:p??a,opencode:R,codex:sn,claude:un}),Ge=A({pi:_e(v??c,D??d),opencode:_e(nn,rn),claude:_e(fn,mn)}),Ue=A({pi:m??s,opencode:tn,codex:cn,claude:pn}),Ve=A({pi:ie(X(l,ue)),opencode:ie(on),codex:ie(dn),claude:ie(gn)});return{...u,...K,...an,...ln,...Object.keys(ze).length>0?{modelsByFamily:ze}:{},...Object.keys(Ge).length>0?{toolsByFamily:Ge}:{},...Object.keys(Ue).length>0?{thinkingByFamily:Ue}:{},...Object.keys(Ve).length>0?{envByFamily:Ve}:{}}}),jt=f.strictObject({name:f.string().optional(),display_name:f.string().optional(),description:f.string().optional(),hidden:f.boolean().optional(),worktree_checkout_type:f.enum(Xe).optional(),system_prompt:f.string().optional(),harness_type:f.string().min(1).optional(),harness:Tr.optional()});function Er(e){return jt.parse(re(e))}i(Er,"parseAgentFile");var Ar={label:"Agent",problem:"is not a valid agent template and was skipped"};async function B(e,t,n){return oe(e,Er,r=>r.name,t,Ar,n)}i(B,"scanAgentFilesInDir");function se(e,t,n,r){let o=new Map;for(let[a,s]of e)o.set(a,{...s});return We(o,t),We(o,n),We(o,r),o}i(se,"mergeAgents");function We(e,t){for(let n of t){if(!n.name)continue;let r=e.get(n.name);if(r){let o={displayName:n.display_name,description:n.description??""},a=Lt(n),s=Or(r.modelsByFamily,a.modelsByFamily),c=Pr(r.toolsByFamily,a.toolsByFamily),d=Sr(r.thinkingByFamily,a.thinkingByFamily),l=_r(r.envByFamily,a.envByFamily);e.set(n.name,{...r,...a,...s?{modelsByFamily:s}:{},...c?{toolsByFamily:c}:{},...d?{thinkingByFamily:d}:{},...l?{envByFamily:l}:{},...o})}else e.set(n.name,{...Wr,...Lt(n)})}}i(We,"mergeAgentOverrides");function Or(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Or,"mergeModelsByFamily");function Pr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Pr,"mergeToolsByFamily");function Sr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Sr,"mergeThinkingByFamily");function _r(e,t){let n={...e};for(let[r,o]of Object.entries(t??{})){let a=r;n[a]=X(n[a],o)}return Object.keys(n).length>0?n:void 0}i(_r,"mergeEnvByFamily");function Lt(e){let{harness:t}=e,n={name:e.name,displayName:e.display_name,description:e.description,harnessType:e.harness_type,toolsByFamily:t?.toolsByFamily,extensions:t?.extensions,skills:t?.skills,inlinedSkills:t?.inlined_skills,modelsByFamily:t?.modelsByFamily,thinkingByFamily:t?.thinkingByFamily,envByFamily:t?.envByFamily,hidden:e.hidden,fork:t?.fork,includeContextFiles:t?.include_context_files,worktreeCheckoutType:e.worktree_checkout_type,systemPrompt:e.system_prompt};return A(n)}i(Lt,"fromTemplate");var Wr={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Fe=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return J().agents}i(S,"registry");function U(e){let t=e.harness_type;if(t===void 0)return;let n=M();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}i(U,"unregisteredHarness");function _i(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[r,o]of Fe)n.set(r,o);for(let[r,o]of e)n.set(r,o);S().agents=n}i(_i,"registerAgents");function Wi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}i(Wi,"setAgentScanDirs");async function Fr(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,r=S().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):B(qe,n,U),B(r.user,n,U),B(r.shared,n,U),B(r.project,n,U)]),l=se(t?new Map:Fe,o,[],[]);return se(l,a,s,c)}i(Fr,"scanAndMerge");async function $r(e,t){let n=await Fr(t),{agents:r}=S(),o=0;for(let[a,s]of n)r.has(a)||(r.set(a,s),o++);if(e){let a=await B(e,t?.notify,U),s=se(new Map,[],[],a);for(let[c,d]of s)r.has(c)||(r.set(c,d),o++)}return o}i($r,"discoverNewAgents");function V(e){let{agents:t}=S();if(!e)return{kind:"not-found"};if(t.has(e))return{kind:"resolved",key:e};let n=e.toLowerCase(),r=[];for(let o of t.keys())o.toLowerCase()===n&&r.push(o);return r.length===1?{kind:"resolved",key:r[0]}:r.length>1?{kind:"ambiguous",candidates:r}:{kind:"not-found"}}i(V,"resolveType");async function Fi(e,t,n){let r=V(e);return r.kind==="not-found"&&(await $r(t,{notify:n}),r=V(e)),r}i(Fi,"resolveTypeOrDiscover");function ce(e){let t=V(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}i(ce,"getAgentConfig");function $i(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}i($i,"getAvailableTypes");function Ii(){return[...S().agents.keys()]}i(Ii,"getAllTypes");function Ht(e,t,n,r){return{skills:e??n,extensions:t??r}}i(Ht,"applyGlobalDefaults");function Di(e,t=!0,n=!0){let r=ce(e);if(r){let{skills:a,extensions:s,...c}=r,d=Ht(a,s,t,n);return{displayName:c.displayName??c.name,description:c.description,...d}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Ht(void 0,void 0,t,n)}}i(Di,"getConfig");function zt(e){return typeof e=="string"&&e!==""?e:void 0}i(zt,"configuredString");function Ir(){let e=zt(j().agent.defaultAgentType);if(e===void 0)return ke;let t=V(e);return t.kind==="resolved"?t.key:ke}i(Ir,"resolveDefaultAgentType");function Dr(){let e=zt(j().agent.defaultOrchestrator);return e===void 0?F:e===F||Se(e)?e:F}i(Dr,"resolveDefaultOrchestratorName");function Ui(e){return typeof e=="string"&&e!==""?e:Ir()}i(Ui,"resolveAgentTypeParam");function Vi(){let e=Dr();return Se(e)??(e===F?O[F]:void 0)??O[F]}i(Vi,"resolveDefaultOrchestrator");function Gt(e){return ce(e)?.worktreeCheckoutType??j().agent.worktreeCheckoutType}i(Gt,"resolveWorktreeCheckoutType");function Ut(e){return typeof e=="string"&&e.trim()!==""?e:void 0}i(Ut,"harnessParam");function qi(e){let t=Ut(e);if(t!==void 0&&M().get(t)!==void 0)return fe(t,Z())?t:void 0}i(qi,"requestedHarnessId");function Ki(e){let t=Ut(e);if(t===void 0)return;let n=M();if(n.get(t)===void 0)throw new Error(`Unknown harness_type "${t}": valid harnesses are ${n.ids().join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);let r=Z();if(!fe(t,r))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${Qe(n.ids(),r).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}i(Ki,"resolveRequestedHarness");function Qi(e,t){if(t!==void 0)return t;let n=ce(e)?.harnessType??j().agent.harnessType;return M().resolve(n,Z())}i(Qi,"resolveHarnessType");function $e(e){return{kind:"recorded",phase:e.lifecycle.phase}}i($e,"recordedSettlement");function Vt(e,t){let n=e.worktree;return n!==null&&n.repoCwd!==void 0?{kind:"worktree",worktree:{workspaceId:n.workspaceId,worktreePath:n.path,repoCwd:n.repoCwd,branchName:e.branch},panes:t}:e.worktreeManaged?{kind:"worktree-unlocatable",branchName:e.branch,worktreePath:n?.path??null,panes:t}:{kind:"no-worktree",panes:t}}i(Vt,"planRecovered");async function Ie(e,t,n){if(t?.force!==void 0)return{kind:"removable"};let r=await e(n.worktreePath);return r===void 0?{kind:"kept",reason:{kind:"unverifiable",detail:"git status probe failed"}}:r?{kind:"kept",reason:{kind:"dirty"}}:{kind:"removable"}}i(Ie,"assessRemovability");function qt(e){if(e===void 0)return{kind:"allow",basis:{kind:"pane-absent"}};switch(e.state){case"working":return{kind:"refuse",basis:{kind:"pane-working"}};case"idle":case"blocked":case"done":case"unknown":return{kind:"allow",basis:{kind:"pane-not-working",state:e.state}};default:return he(e.state)}}i(qt,"recoveryGate");function De(e){switch(e.kind){case"pane-working":return{kind:"recovered-refusal",basis:e};case"pane-unreadable":return{kind:"unverifiable",detail:`the pane state could not be read (${e.detail})`};case"pane-absent":case"pane-not-working":case"forced":case"artifacts-ambiguous":return{kind:"unverifiable",detail:"the run's end could not be established"}}}i(De,"recoveryRefusalReason");function q(e,t,n,r,o){let a=n.kind==="worktree"?{kind:"kept",path:n.worktree.worktreePath}:n.kind==="worktree-unlocatable"?{kind:"kept",path:n.worktreePath}:{kind:"none"};return{agentId:e,source:t,outcome:{kind:"refused",reason:o.reason,forceable:o.forceable},branchName:n.kind==="worktree"?n.worktree.branchName:n.kind==="worktree-unlocatable"?n.branchName:void 0,settlement:r,panes:n.panes.map(s=>({kind:"open",paneId:s.paneId})),worktree:a,branch:{kind:"not-applicable"}}}i(q,"keptReport");function Kt(e,t,n,r){return{agentId:e,source:t,outcome:{kind:"refused",reason:{kind:"ambiguous-artifacts",candidates:r},forceable:!1},settlement:n,panes:[],worktree:{kind:"kept",path:null},branch:{kind:"not-applicable"}}}i(Kt,"ambiguousReport");function Me(e){return e?.force!==void 0?{forced:e.force}:{}}i(Me,"forcedFields");function Qt(e,t,n,r,o,a){return{agentId:e,source:t,outcome:{kind:"torn-down",...Me(a)},branchName:n.kind==="worktree"?n.worktree.branchName:void 0,settlement:r,panes:o.panes,worktree:o.worktree,branch:o.branch}}i(Qt,"assembleReport");function Ji(e){return e.outcome.kind==="refused"&&e.outcome.forceable}i(Ji,"isForceableRefusal");function Ne(e){return e.worktree.kind==="removed"||e.worktree.kind==="absent"?!0:e.worktree.kind==="none"?e.panes.every(t=>t.kind==="closed"):!1}i(Ne,"shouldDropSpawn");function de(e){return e.workspaceId!==void 0?"multiplexer":"git"}i(de,"removalMechanismOf");function Yt(e,t){if(t.kind==="retained")return{kind:"leave-open"};let n=t.workspaceId===void 0||e.workspaceId===t.workspaceId;if(t.mechanism==="multiplexer"&&n)return{kind:"closed-with-workspace"};switch(t.mechanism){case"multiplexer":case"git":case null:return e.paneCreated?{kind:"close"}:{kind:"leave-open"};default:return he(t.mechanism)}}i(Yt,"paneDispositionFor");var Mr=rt("cleanup");function Nr(e,t){let n=e.pane,r=n?.workspaceId??e.worktree?.workspaceId;if(!(n===null||r===void 0))return{multiplexer:t,name:e.branch,paneId:n.paneId,tabId:n.tabId,workspaceId:r,paneCreated:e.paneCreated}}i(Nr,"hostRefFor");async function Xt(e,t,n){let r=n!==void 0&&t.workspaceId!==void 0;return(r?await e.removeWorktree(n):await e.removeGitWorktree(t.worktreePath,t.repoCwd))?{kind:"removed",path:t.worktreePath}:{kind:"removal-failed",path:t.worktreePath,detail:r?"herdr did not confirm the worktree removal":"git did not confirm the worktree removal"}}i(Xt,"removeOwnedTree");async function le(e,t,n){let r=[];for(let o of t)switch(Yt(o,n).kind){case"closed-with-workspace":r.push({kind:"closed",paneId:o.paneId});break;case"close":await e.closePane(o),r.push({kind:"closed",paneId:o.paneId});break;case"leave-open":r.push({kind:"open",paneId:o.paneId});break}return r}i(le,"paneOutcomes");async function Br(e,t){let n=[];for(let r of t){let o;try{o=await e.observe(r)}catch{n.push({kind:"unknown",paneId:r.paneId});continue}n.push(o===void 0?{kind:"gone",paneId:r.paneId}:{kind:"open",paneId:r.paneId})}return n}i(Br,"paneOutcomesForAbsentTree");async function jr(e,t,n){if(t.kind==="no-worktree")return{panes:await le(e,t.panes,{kind:"removed",mechanism:null,workspaceId:void 0}),worktree:{kind:"none"},branch:{kind:"not-applicable"}};let{worktree:r,panes:o}=t,a=await Xt(e,r,n);return a.kind==="removed"?{panes:await le(e,o,{kind:"removed",mechanism:de(r),workspaceId:r.workspaceId}),worktree:a,branch:await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd})}:{panes:await le(e,o,{kind:"retained"}),worktree:a,branch:{kind:"not-applicable"}}}i(jr,"removeResources");function Be(e){return{async removeWorktree(t,n){let{worktree:r,panes:o,address:a}=t;try{if(!await e.worktreeExists(r.worktreePath))return{kind:"absent",path:r.worktreePath};let s=await Ie(e.isWorktreeDirty,n,r);if(s.kind==="kept")return{kind:"kept",path:r.worktreePath,reason:s.reason};let c=await Xt(e,r,a);if(c.kind==="removal-failed")return c;let d=de(r);await le(e,o,{kind:"removed",mechanism:d,workspaceId:r.workspaceId});let l=await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd});return{kind:"removed",path:r.worktreePath,branchName:r.branchName,via:d,branch:l}}catch(s){return{kind:"removal-failed",path:r.worktreePath,detail:W(s)}}}}}i(Be,"createWorktreeTeardown");async function Lr(e,t,n){if(t.kind!=="worktree"||n===void 0||de(t.worktree)!=="multiplexer")return{kind:"exclusive"};try{let r=await e.otherTenants({workspaceId:n.workspaceId,checkoutPath:t.worktree.worktreePath},n.paneId);return r.length===0?{kind:"exclusive"}:{kind:"shared",tenants:r}}catch(r){return{kind:"unreadable",detail:W(r)}}}i(Lr,"spaceTenancy");function Hr(e,t){let n=e===void 0?[]:[e];for(let r of t===void 0?[]:t.execution.history)n.some(o=>o.paneId===r.host.paneId)||n.push(r.host);return n}i(Hr,"environmentPanes");function zr(e,t){if(e===void 0)return[];let n=e.execution.history.map(o=>({harness:o.harness,paneId:o.host.paneId,cwd:o.cwd})),r=e.execution.harness===void 0?[]:[{harness:e.execution.harness,paneId:t.pane?.paneId??null,cwd:t.worktree?.path??null}];return[...n,...r]}i(zr,"teardownRuns");function aa(e){let t=Be(e);function n(a,s){return{kind:"discovered",basis:s,deliverable:e.deliverable(a)}}i(n,"recovered");async function r(a,s,c,d){if(c!==void 0){let p=$e(c);return it(c.lifecycle)?{kind:"torn-down",settlement:p}:{kind:"refused",settlement:p,reason:{kind:"agent-active",phase:c.lifecycle.phase},forceable:!1}}if(d?.force!==void 0)return{kind:"torn-down",settlement:n(a,{kind:"forced"})};let l;if(s.pane!==null)try{l=await e.observe(s.pane)}catch(p){let m={kind:"pane-unreadable",detail:W(p)};return{kind:"refused",settlement:n(a,m),reason:De(m),forceable:!0}}let u=qt(l);return u.kind==="allow"?{kind:"torn-down",settlement:n(a,u.basis)}:{kind:"refused",settlement:n(a,u.basis),reason:De(u.basis),forceable:!0}}i(r,"verdictFor");async function o(a,s,c){let d=s.getSpawn(a),l=await e.locate(a,d);if(l.kind==="not-found")throw new Error(`Agent ${a} not found.`);if(l.kind==="ambiguous")return Kt(a,d===void 0?"recovered":"tracked",d===void 0?n(a,{kind:"artifacts-ambiguous"}):$e(d),l.candidates.map(R=>R.worktreePath));let u=Nr(l,e.multiplexer),p=Vt(l,Hr(u,d)),m=await r(a,l,d,c);if(m.kind==="refused")return q(a,l.source,p,m.settlement,{reason:m.reason,forceable:m.forceable});let v=await Lr(e,p,u);if(v.kind!=="exclusive")return q(a,l.source,p,m.settlement,{reason:v.kind==="shared"?{kind:"space-in-use",tenants:v.tenants}:{kind:"unverifiable",detail:`could not check the workspace for other agents (${v.detail})`},forceable:!1});let D=zr(d,l);if(D.length>0)try{await e.teardownEnvironment({subagentId:a,runs:D})}catch(R){Mr.warn("environment teardown failed during cleanup",{spawnId:a,error:W(R)})}if(p.kind==="worktree-unlocatable"){if(p.worktreePath!==null&&!await e.worktreeExists(p.worktreePath)){let R={agentId:a,source:l.source,outcome:{kind:"torn-down",...Me(c)},branchName:p.branchName,settlement:m.settlement,panes:await Br(e,p.panes),worktree:{kind:"absent",path:p.worktreePath},branch:{kind:"not-applicable"}};return Ne(R)&&d!==void 0&&s.dropSpawn(d),R}return q(a,l.source,p,m.settlement,{reason:{kind:"unverifiable",detail:"missing worktree path or repo cwd"},forceable:!1})}if(p.kind==="worktree"){let R=await Ie(e.isWorktreeDirty,c,p.worktree);if(R.kind==="kept")return q(a,l.source,p,m.settlement,{reason:R.reason,forceable:!0})}let ue=await jr(e,p,u),K=Qt(a,l.source,p,m.settlement,ue,c);return Ne(K)&&d!==void 0&&s.dropSpawn(d),K}return i(o,"cleanupAgent"),{...t,cleanupAgent:o}}i(aa,"createCleanup");import*as Zt from"node:path";async function Gr(e,t,n){let r=await ve(e,["rev-parse","--verify","--quiet",`refs/heads/${n}`],t,E);return r===void 0?!0:r.code===0}i(Gr,"branchExisted");async function Jt(e,t){let n=t.branch.trim();if(n==="")throw new h("worktree checkout requires a branch name");let r=await te(e,t.repoCwd),o=Zt.resolve(t.path),a=t.materialization??Ye,s=t.dirtyCheckout??Q,c=await Gr(e,r,n),d=await ve(e,["worktree","add",...Ct(a),"-b",n,o,t.base??"HEAD"],r,E);if(d===void 0||d.code!==0)throw await $(e,r,o),c||await N(e,n,r),new h(d===void 0?`git worktree add for "${n}" could not run (worktree removed)`:`git worktree add for "${n}" failed (worktree removed): ${(d.stderr||d.stdout||`exit ${d.code}`).slice(0,300)}`);let l=await yt(e,["branch","--show-current"],o);if(l!==n)throw await $(e,r,o),await N(e,n,r),new h(l===void 0?`worktree created at ${o} but its branch could not be verified (worktree removed)`:`worktree created at ${o} is on branch "${l||"(detached)"}", not the requested "${n}" (worktree removed). The branch "${l}" still exists.`);let u;try{u=await vt(e,o,a,s)}catch(p){await $(e,r,o),await N(e,n,r);let m=p instanceof Error?p.message:String(p);throw new h(`worktree created but ${a} materialization failed (worktree removed): ${m}`)}if(u.kind==="cow-fallback"){let p=s==="dirty"?" The parent's uncommitted work was not carried over.":"";t.notify?.(`[cowboy] ${u.reason}${p} Nothing is shared with the parent checkout.`,"warning")}return{path:o,branch:n,repoCwd:r,materialization:u}}i(Jt,"createWorktreeCheckout");function Ca(e){return e.kind==="checkout"?e.branch:me(e.taskSlug??Je(e.type),e.id)}i(Ca,"spawnAgentName");function Ur(e){try{let t=_.statSync(e,{bigint:!0});return`${t.dev}:${t.ino}`}catch{return I.resolve(e)}}i(Ur,"canonicalRepoKey");async function va(e){let t=await Le.allocate(e.pi,{naming:{kind:"generated",taskSlug:e.taskSlug??e.agentType,id:e.spawnId},parentCwd:e.parentCwd,worktreeRoot:e.worktreeRoot,materialization:e.materialization,dirtyCheckout:Gt(e.agentType),notify:e.notify,host:e.host}),n=t.worktree,r=t.hostRef;return n===void 0||r===void 0?{kind:"parent-cwd"}:{kind:"owned",hostRef:r,worktree:n}}i(va,"provisionOwnedCheckout");var Le=class e{static{i(this,"AgentSandbox")}branch;projectTrusted;host;placement;current={kind:"bound"};constructor(t,n,r,o){this.host=t,this.placement=n,this.branch=r,this.projectTrusted=o}static async allocate(t,n){let{naming:r,parentCwd:o,worktreeRoot:a,materialization:s,dirtyCheckout:c,notify:d,host:l}=n,u=r.kind==="generated"?me(r.taskSlug,r.id):r.branch.trim();if(r.kind==="explicit"&&u==="")throw new Error("explicit worktree naming requires a branch name");let p;try{p=await te(t,o)}catch{return d?.("[cowboy] Parent is not inside a git repository \u2014 spawning in the parent cwd without a worktree","warning"),new e(l,{kind:"parent-cwd"},u,!0)}let m=await qr(t,{repoCwd:p,path:I.join(et(a,p),u),branch:u,materialization:s,dirtyCheckout:c,notify:d,host:l});return new e(l,{kind:"worktree",checkout:{path:m.path,branch:m.branch,repoCwd:m.repoCwd},ref:m.ref},u,!0)}get state(){return this.current}get worktree(){return this.placement.kind==="worktree"?{path:this.placement.checkout.path,branch:this.placement.checkout.branch}:void 0}get hostRef(){return this.placement.kind==="worktree"?this.placement.ref:void 0}async teardown(t,n){let r=this.placement;if(r.kind==="parent-cwd")return this.current={kind:"destroyed"},{kind:"absent"};if(this.current.kind==="destroyed")return{kind:"absent",path:r.checkout.path};let o=await Be(Yr(t,this.host)).removeWorktree({worktree:{workspaceId:r.ref.workspaceId,worktreePath:r.checkout.path,repoCwd:r.checkout.repoCwd,branchName:r.checkout.branch},address:r.ref,panes:[r.ref]},n);return this.current=Vr(o),o}};function Vr(e){switch(e.kind){case"kept":return{kind:"preserved",reason:e.reason};case"removed":case"absent":return{kind:"destroyed"};case"removal-failed":return{kind:"teardown-failed",detail:e.detail}}}i(Vr,"stateAfterTeardown");async function qr(e,t){let n=I.resolve(t.path);return _.mkdirSync(I.dirname(n),{recursive:!0}),st().run(Ur(t.repoCwd),()=>Qr(e,t.host,{...t,path:n}))}i(qr,"createAdoptedWorktree");async function Kr(e,t,n){let r=await bt(e,t),o=pe(n),a=o===void 0?void 0:r?.find(s=>pe(s.path)===o);if(a!==void 0)return{path:a.path,branch:Ze(a),repoCwd:t,materialization:{kind:"reused"}}}i(Kr,"existingCheckout");async function Qr(e,t,n){let{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:d}=n,l=await Kr(e,r,o),u;if(l!==void 0)u=l;else try{u=await Jt(e,{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:d})}catch(m){throw je(m,await en(e,r,o))}let p;try{p=await t.hostAt({unit:"pane",cwd:u.path,label:a,name:a,checkout:{path:u.path,repoCwd:r,branch:u.branch}})}catch(m){if(l!==void 0)throw je(m,"existing worktree kept");let v=await en(e,r,u.path),D=await N(e,u.branch,r);throw je(m,`${v}. ${He(u.branch,D)}`)}return{path:u.path,branch:u.branch,repoCwd:r,materialization:u.materialization,ref:p}}i(Qr,"adoptWorktree");function Yr(e,t){return{isWorktreeDirty:i(n=>Pt(e,n),"isWorktreeDirty"),worktreeExists:i(async n=>_.existsSync(n),"worktreeExists"),removeWorktree:i(n=>t.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(n,r)=>(await $(e,r,n),!_.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>At(e,n,r=>t.isAttached(r,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:i(async n=>{await t.release(n,"placement")},"closePane"),teardownEnvironment:i(async()=>{},"teardownEnvironment")}}i(Yr,"cleanupDeps");async function en(e,t,n){return await $(e,t,n),_.existsSync(n)?`worktree ${n} NOT removed \u2014 inspect it manually`:`worktree ${n} removed`}i(en,"removeFailedCheckout");function je(e,t){return new Error(`could not create the herdr worktree: ${W(e)}
24
24
 
25
25
  Launch-failure cleanup: ${t}.`)}i(je,"createFailureMessage");function He(e,t){switch(t.kind){case"deleted":return`branch ${e} deleted`;case"kept":return`branch ${e} kept (${t.reason})`;case"delete-failed":return`branch ${e} NOT deleted \u2014 ${t.detail}`;case"not-applicable":return`branch ${e} already gone`}}i(He,"formatLaunchedBranchOutcome");function xa(e){switch(e.kind){case"removed":return e.via==="multiplexer"?`Launch-failure cleanup: worktree ${e.path} removed \u2014 its workspace, tab, and pane were closed with it. ${He(e.branchName,e.branch)}.`:`Launch-failure cleanup: worktree ${e.path} removed. ${He(e.branchName,e.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${e.path} KEPT \u2014 ${St(e.reason)}. No agent spawn exists for it, so extension cleanup cannot see it \u2014 inspect and remove it manually.`;case"removal-failed":return`Launch-failure cleanup FAILED for worktree ${e.path}: ${e.detail} \u2014 it may still exist, and no agent spawn exists for it, so inspect it manually.`;case"absent":return"Launch-failure cleanup: no worktree residue was left behind."}}i(xa,"formatLaunchCleanupNote");export{Zr as a,ht as b,b as c,yt as d,L as e,no as f,te as g,$ as h,bt as i,ao as j,xt as k,wo as l,At as m,Pt as n,Ro as o,St as p,Fe as q,_i as r,Wi as s,Fr as t,Fi as u,ce as v,$i as w,Ii as x,Di as y,O as z,rr as A,jo as B,Lo as C,Vo as D,si as E,ci as F,di as G,li as H,Ir as I,Ui as J,Vi as K,Gt as L,qi as M,Ki as N,Qi as O,Ji as P,aa as Q,Ca as R,va as S,Le as T,qr as U,xa as V};
26
- //# sourceMappingURL=chunk-3FQQMEHD.js.map
26
+ //# sourceMappingURL=chunk-KUEKLALM.js.map