pi-cowboy 0.22.2 → 0.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +16 -1
  2. package/dist/agents/agent-assets.d.ts +11 -2
  3. package/dist/agents/agent-cleanup.d.ts +6 -22
  4. package/dist/agents/agent-environment.d.ts +6 -0
  5. package/dist/agents/agent-host.d.ts +3 -3
  6. package/dist/agents/agent-manager.d.ts +5 -1
  7. package/dist/agents/batch.d.ts +2 -1
  8. package/dist/agents/cleanup-policy.d.ts +15 -16
  9. package/dist/agents/handover.d.ts +71 -0
  10. package/dist/agents/harness/claude/session-export.d.ts +7 -0
  11. package/dist/agents/harness/claude/staging.d.ts +9 -1
  12. package/dist/agents/harness/codex-session-schema.d.ts +90 -0
  13. package/dist/agents/harness/codex-session.d.ts +17 -0
  14. package/dist/agents/harness/opencode/session-export.d.ts +39 -0
  15. package/dist/agents/harness/pi-compatible.d.ts +3 -1
  16. package/dist/agents/harness/pi-session.d.ts +12 -0
  17. package/dist/agents/harness/pi-store.d.ts +8 -0
  18. package/dist/agents/harness/pi.d.ts +2 -0
  19. package/dist/agents/harness/pig-store.d.ts +7 -0
  20. package/dist/agents/harness/stop-keys.d.ts +2 -0
  21. package/dist/agents/harness.d.ts +53 -0
  22. package/dist/agents/run-state.d.ts +1 -0
  23. package/dist/agents/schemas/handover.schema.d.ts +8 -0
  24. package/dist/agents/subagent-session.d.ts +8 -1
  25. package/dist/agents/tool-cleanup.d.ts +16 -2
  26. package/dist/agents/tool-execution.d.ts +21 -2
  27. package/dist/agents/tool-handover.d.ts +28 -0
  28. package/dist/agents/tool-merge.d.ts +18 -2
  29. package/dist/agents/tool-renderer.d.ts +21 -0
  30. package/dist/agents/tool-result.d.ts +9 -2
  31. package/dist/agents/tool-steer.d.ts +17 -2
  32. package/dist/{chunk-F526OOT6.js → chunk-277WT5MT.js} +2 -2
  33. package/dist/chunk-J5TU3AFX.js +2 -0
  34. package/dist/chunk-M42XWVYW.js +45 -0
  35. package/dist/{chunk-WL3QYM2F.js → chunk-MZROKRT4.js} +2 -2
  36. package/dist/chunk-S4BS2R6G.js +26 -0
  37. package/dist/chunk-TFQCH2TO.js +14 -0
  38. package/dist/config/config-store.d.ts +1 -0
  39. package/dist/config/layered-config.d.ts +2 -3
  40. package/dist/cowboy-tools.d.ts +13 -0
  41. package/dist/dev-mode.d.ts +1 -0
  42. package/dist/index.js +18 -18
  43. package/dist/infrastructure/herdr/agent-exit.d.ts +12 -0
  44. package/dist/infrastructure/herdr/agents.d.ts +0 -1
  45. package/dist/infrastructure/herdr/index.d.ts +1 -1
  46. package/dist/{menu-worktree-command-SXLBWK4D.js → menu-worktree-command-THJ3VSWU.js} +2 -2
  47. package/dist/{menus-Q3TEDIPV.js → menus-KXKDXZRN.js} +3 -3
  48. package/dist/{model-picker-IIXU4GJP.js → model-picker-FMMQY4KI.js} +2 -2
  49. package/dist/models/model-precedence.d.ts +1 -0
  50. package/dist/models/model-request-types.d.ts +8 -2
  51. package/dist/plugin/index.d.ts +1 -1
  52. package/dist/plugin/index.js +1 -1
  53. package/dist/predicates.d.ts +1 -0
  54. package/dist/registration.d.ts +3 -8
  55. package/dist/spawn/sandbox.d.ts +22 -0
  56. package/dist/subagent/result-artifacts.d.ts +1 -0
  57. package/dist/subagent/supervisor.d.ts +2 -0
  58. package/dist/types.d.ts +11 -0
  59. package/package.json +2 -2
  60. package/dist/chunk-254PTGN5.js +0 -2
  61. package/dist/chunk-CTBFJWEE.js +0 -10
  62. package/dist/chunk-KMXT7XW7.js +0 -15
  63. package/dist/chunk-PDV4AFO7.js +0 -24
  64. package/dist/infrastructure/herdr/agent-stopper.d.ts +0 -14
@@ -1,2 +1,2 @@
1
- import{za as x}from"./chunk-CTBFJWEE.js";import{a as s,e as f,l as C}from"./chunk-254PTGN5.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-WL3QYM2F.js.map
1
+ import{Ca as x}from"./chunk-M42XWVYW.js";import{a as s,e as f,l as C}from"./chunk-J5TU3AFX.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-MZROKRT4.js.map
@@ -0,0 +1,26 @@
1
+ import{B as Xe,C as K,Fa as X,J as Ze,L as Je,M as fe,N as W,S as et,ca as tt,da as Q,h as ze,i as Ge,l as le,la as B,m as Ue,n as Ve,pa as nt,q,r as qe,va as D,w as Ke,y as Qe,ya as Y}from"./chunk-M42XWVYW.js";import{a as i,d as I,i as ue,j as pe,s as Ye}from"./chunk-J5TU3AFX.js";import*as v from"node:fs";import*as k from"node:path";var pn=`import ctypes, sys
2
+ libc = ctypes.CDLL(None, use_errno=True)
3
+ # CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
4
+ if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
5
+ sys.exit(1)
6
+ `,fn=10*6e4,mn=1024,gn={darwin:["python3"],linux:[]},hn={darwin:{python3:"install the Xcode Command Line Tools: xcode-select --install"}},kn={darwin:"macOS",linux:"Linux"};function yn(e=process.platform){return(gn[e]??[]).filter(n=>Xe(n)===void 0)}i(yn,"missingClonePrograms");function Vr(e=process.platform){let t=yn(e);if(t.length===0)return;let n=kn[e]??e;return`Copy-on-write worktrees need ${t.map(o=>{let a=hn[e]?.[o];return a===void 0?o:`${o}: ${a}`}).join(", ")}, which ${t.length===1?"is":"are"} not on PATH on ${n}. pi-cowboy stays inactive in this session. Install ${t.length===1?"it":"them"} and start a new session.`}i(Vr,"missingCloneProgramReport");var y=class extends Error{constructor(n,r,o=[]){super(r);this.reason=n;this.failures=o;this.name="CowCloneError"}reason;failures;static{i(this,"CowCloneError")}};async function ct(e,t,n){let r=k.resolve(e.wtPath),o=k.resolve(e.mainRoot),a=await rt(r),s=await rt(o);if(a===s)throw new y("setup","the worktree is the main checkout; refusing to materialize");if(he(a,s))throw new y("setup","the worktree contains the main checkout; refusing to materialize");await n.probe(r);let c=t.kind==="all"?await ge(`cannot read ${o}`,()=>bn(o,r,n)):await ge(`cannot prepare the ignored paths in ${r}`,()=>Cn(o,r,t.rels));t.kind==="all"&&await ge(`cannot wipe ${r}`,()=>wn(r,n));let l=[];for(let d of c)try{await n.cloneEntry(d.src,d.dst)}catch(f){if(f instanceof y&&f.reason!=="entry-failed")throw f;l.push({path:d.src,message:f instanceof Error?f.message:String(f)})}if(l.length>0)throw new y("entry-failed",`${l.length} ${l.length===1?"entry":"entries"} could not be cloned`,l);return{mechanism:c.length===0?"empty":n.mechanism}}i(ct,"materializeCowClone");async function rt(e){try{return await v.promises.realpath(e)}catch{return e}}i(rt,"resolvedRoot");function dt(e,t){return he(e,t)||he(t,e)}i(dt,"overlapsPath");function he(e,t){let n=k.resolve(e),r=k.resolve(t);return r===n||r.startsWith(n+k.sep)}i(he,"containsPath");async function wn(e,t){for(let n of await t.list(e))n.name!==".git"&&await lt(k.join(e,n.name),n)}i(wn,"wipeWorktree");async function lt(e,t){if(!t.isDirectory()){await me(()=>v.promises.unlink(e));return}let n=await me(()=>v.promises.readdir(e,{withFileTypes:!0}));for(let r of n??[])await lt(k.join(e,r.name),r);await me(()=>v.promises.rmdir(e))}i(lt,"removeEntry");async function me(e){try{return await e()}catch(t){if(t?.code!=="ENOENT")throw t;return}}i(me,"ignoreMissing");async function bn(e,t,n){let r=[];for(let{name:o}of await n.list(e)){if(o===".git")continue;let a=k.join(e,o);dt(a,t)||r.push({src:a,dst:k.join(t,o)})}return r}i(bn,"mainEntries");async function Cn(e,t,n){let r=[];for(let o of n){let a=o.replace(/[/\\]+$/,"");if(a===""||a===".git"||a.startsWith(".git/")||a.startsWith(".git\\"))continue;let s=k.join(e,a);if(dt(s,t)||!await vn(s))continue;let c=k.join(t,a);await v.promises.mkdir(k.dirname(c),{recursive:!0}),r.push({src:s,dst:c})}return r}i(Cn,"seedEntries");async function vn(e){try{return await v.promises.lstat(e),!0}catch{return!1}}i(vn,"exists");async function ge(e,t){try{return await t()}catch(n){throw n instanceof y?n:new y("setup",`${e}: ${n instanceof Error?n.message:String(n)}`)}}i(ge,"withSetupContext");function ut(e,t=fn){let n=i(o=>v.promises.readdir(o,{withFileTypes:!0}),"list"),r={cp:K("cp"),du:K("du"),python:K("python3")};switch(process.platform){case"darwin":return{mechanism:"clonefile",list:n,probe:i(o=>it(e,o,r,t,pt),"probe"),cloneEntry:i((o,a)=>Rn(e,r,o,a,t),"cloneEntry")};case"linux":return{mechanism:"reflink",list:n,probe:i(o=>it(e,o,r,t,st),"probe"),cloneEntry:i((o,a)=>st(e,r,o,a,t),"cloneEntry")};default:return{mechanism:"empty",list:n,probe:i(()=>Promise.reject(ot()),"probe"),cloneEntry:i(()=>Promise.reject(ot()),"cloneEntry")}}}i(ut,"defaultCowCloneDeps");function ot(){return new y("unsupported",`copy-on-write worktree materialization is not implemented on ${process.platform}`)}i(ot,"unsupportedPlatform");function xn(){return new Date().toISOString().replace(/:/g,"-")}i(xn,"utcTimestamp");async function it(e,t,n,r,o){let a=k.join(t,`.cow-probe-${process.pid}-${xn()}`),s=k.join(a,"p");try{if(await v.promises.mkdir(a,{recursive:!0}),!(await v.promises.lstat(a)).isDirectory())throw new y("setup",`${a} is not a directory; refusing to probe the volume through it`);await v.promises.mkdir(s,{recursive:!0}),await v.promises.writeFile(k.join(s,"f"),"x"),await o(e,n,s,k.join(a,"p-clone"),r)}catch(c){throw c instanceof y&&c.reason==="entry-failed"?new y("unsupported",`copy-on-write is not supported on the worktree volume: ${c.message}`):c}finally{await v.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}}i(it,"probe");async function Rn(e,t,n,r,o){return(await v.promises.lstat(n)).isDirectory()?await Tn(e,t,n,o)>=mn?pt(e,t,n,r,o):at(e,t,n,r,o,["-R"]):at(e,t,n,r,o,[])}i(Rn,"darwinEntry");async function Tn(e,t,n,r){try{let o=await Z(e,t.du,["-sk",n],r,`du -sk ${n}`);return Number.parseInt(o.trim().split(/\s+/)[0]??"",10)||0}catch{return 0}}i(Tn,"directoryKb");function pt(e,t,n,r,o){return Z(e,t.python,["-c",pn,n,r],o,`clonefile ${n}`,"could not start python3 (needed to clone a worktree on macOS)").then(()=>{})}i(pt,"clonefileChild");function at(e,t,n,r,o,a){return Z(e,t.cp,["-P","-c",...a,n,r],o,`cp -c ${n}`).then(()=>{})}i(at,"copyChild");function st(e,t,n,r,o){return Z(e,t.cp,["-P","--reflink=always","-R",n,r],o,`cp --reflink ${n}`).then(()=>{})}i(st,"reflinkChild");async function Z(e,t,n,r,o,a){let s=await e(t,[...n],{timeout:r}).catch(c=>{throw new y("launch",`${a??`could not start ${t}`}: ${c instanceof Error?c.message:String(c)}`)});if(s.killed)throw new y("timeout",`${o} exceeded ${Math.round(r/1e3)}s`);if(s.code!==0){let c=s.stderr.trim().split(`
7
+ `).at(-1)??"";throw new y("entry-failed",`${o} exited ${String(s.code)}${c===""?"":`: ${c}`}`)}return s.stdout}i(Z,"run");import*as ke from"node:fs";import*as T from"node:path";var En=3e4,E=6e4,h=class extends Error{static{i(this,"GitError")}constructor(t){super(t),this.name="GitError"}},b=class{constructor(t){this.pi=t}pi;static{i(this,"GitCommandRunner")}async run(t,n,r=ue){try{let o=await this.pi.exec("git",[...t],{cwd:n,timeout:r});return o.killed?void 0:{code:o.code,stdout:o.stdout.trim(),stderr:o.stderr.trim()}}catch{return}}async probe(t,n,r={}){let o=await this.run(t,n,r.timeoutMs??En);if(!(o===void 0||o.code!==0))return o.stdout}async exec(t,n,r){let o=await this.run(t,n,r);if(o===void 0)throw new h(`git ${t.join(" ")} failed in ${n}: the command could not be run`);if(o.code!==0)throw new h(`git ${t.join(" ")} failed in ${n} (exit ${o.code}): ${(o.stderr||o.stdout||`exit code ${o.code}`).trim().slice(0,500)}`);return o.stdout}async test(t,n,r){let o=await this.run(t,n,r);return o!==void 0&&o.code===0}async lines(t,n,r=`
8
+ `){let o=await this.probe(t,n);if(o!==void 0)return o.split(r).filter(a=>a!=="")}async helper(t,n,r){try{let o=await this.pi.exec(t,[...n],{...r.cwd===void 0?{}:{cwd:r.cwd},timeout:r.timeoutMs});return{code:o.code,stdout:o.stdout,stderr:o.stderr}}catch(o){return{code:1,stdout:"",stderr:o instanceof Error?o.message:String(o)}}}};async function ye(e,t,n,r=ue){return new b(e).run(t,n,r)}i(ye,"gitRun");async function ft(e,t,n){return new b(e).probe(t,n)}i(ft,"gitProbe");function j(e,t){let n=T.isAbsolute(e)?e:T.resolve(t,e);return{commonDir:n,mainRoot:T.dirname(n)}}i(j,"locateMainCheckout");function Yr(e){let t=T.resolve(e);for(;;){if(ke.existsSync(T.join(t,".git")))return!0;let n=T.dirname(t);if(n===t)return!1;t=n}}i(Yr,"isInsideGitRepository");async function J(e,t){let r=await new b(e).probe(["rev-parse","--git-common-dir"],t);if(r===void 0)throw new h(`cannot create worktree: ${t} is not inside a git repository`);let{mainRoot:o}=j(r,t);if(!ke.existsSync(T.join(o,".git")))throw new h(`cannot create worktree: main checkout not found for ${t}`);return o}i(J,"resolveMainCheckout");var mt=5e3,L=class{constructor(t,n,r){this.runner=t;this.path=n;this.branch=r}runner;path;branch;static{i(this,"GitWorktree")}async status(t){return this.runner.probe(["status","--porcelain"],this.path,t)}async isDirty(){let t=await this.status();if(t!==void 0)return t!==""}async remove(t=!0,n=this.path){await this.runner.run(t?["worktree","remove","--force",this.path]:["worktree","remove",this.path],n,E)}};async function F(e,t,n){await new L(new b(e),n).remove(!0,t)}i(F,"removeGitWorktree");async function we(e,t,n){let r=await e.run(["rev-parse","--verify","--quiet",`refs/heads/${t}`],n);if(r===void 0)throw new h(`git rev-parse --verify refs/heads/${t} could not run in ${n}`);return r.code===0}i(we,"refExists");async function be(e,t,n){let r=await e.run(["branch","-D","--",t],n);if(r===void 0)throw new h(`git branch -D ${t} could not run in ${n}`);return r.code!==0?{kind:"delete-failed",detail:(r.stderr||r.stdout||`git branch -D exited ${r.code}`).trim().slice(0,200)}:{kind:"deleted"}}i(be,"deleteBranchRef");async function M(e,t,n){let r=new b(e);try{return await we(r,t,n)?await be(r,t,n):{kind:"not-applicable"}}catch(o){return{kind:"delete-failed",detail:o instanceof Error?o.message:String(o)}}}i(M,"deleteCreatedBranch");function An(e){let t=[];for(let n of e.split(/\n\n+/)){if(!n.trim())continue;let r="",o=null,a=!1;for(let s of n.split(`
9
+ `))s.startsWith("worktree ")?r=s.slice(9):s.startsWith("branch refs/heads/")?o=s.slice(18):s==="detached"&&(a=!0);r&&t.push({path:r,branch:o,isDetached:a})}return t}i(An,"parseWorktreeList");async function eo(e,t){let n=await new b(e).probe(["worktree","list","--porcelain"],t,{timeoutMs:mt});return n===void 0?null:An(n)}i(eo,"listGitWorktrees");async function to(e,t){let n=await new b(e).probe(["rev-parse","--git-common-dir"],t,{timeoutMs:mt});return n!==void 0&&n!==""}i(to,"isGitRepo");import*as C from"node:fs";import{tmpdir as On}from"node:os";import*as g from"node:path";var Pn=`main checkout has uncommitted changes and the dirty-checkout policy is "clean"; tracked files stay as git's checkout, ignored state CoW-seeded`,Sn="main checkout has uncommitted changes; its tracked edits and untracked files were cloned into the worktree",_n="the worktree volume cannot clone; the checkout was completed by git instead";function gt(e){return e==="copy-on-write"?["--no-checkout"]:[]}i(gt,"worktreeAddArgs");function Wn(e){let t=[];for(let n of e){if(!n.startsWith("!! "))continue;let r=n.slice(3);r===""||r.includes(`
10
+ `)||t.push(r)}return t}i(Wn,"ignoredSeedPaths");var Ce=class{constructor(t,n){this.runner=t;this.exec=n}runner;exec;static{i(this,"CowCloneMaterializer")}async materialize(t,n,r){return n==="checkout"?this.checkout(t,r):this.clone(t,r)}async clone(t,n){let r=g.resolve(t),o=await this.mainCheckoutOf(r),s=await this.mainStatus(o)===""?{kind:"clean-parent"}:{kind:"dirty-parent",policy:n},c=s.kind==="clean-parent"||s.policy==="dirty";try{await this.cloneWorkingTree(r,o,c?{kind:"all"}:{kind:"seed",rels:await this.ignoredRels(o)})}catch(l){if(!(l instanceof y)||l.reason!=="unsupported")throw l;return await this.fallbackToCheckout(r),{kind:"cow-fallback",reason:_n}}return await this.completeCheckout(r,c),await this.verifyMaterialization(r,o,s),s.kind==="clean-parent"?{kind:"cow",clone:{mode:"cow"}}:{kind:"cow",clone:c?{mode:"cow",reason:Sn}:{mode:"seeded",reason:Pn}}}async checkout(t,n){if(n==="dirty"){let r=g.resolve(t);await this.applyUncommitted(await this.mainCheckoutOf(r),r)}return{kind:"checkout"}}async applyUncommitted(t,n){let r=C.mkdtempSync(g.join(On(),"pi-cowboy-wip-")),o=g.join(r,"wip.patch");try{if(!await this.runner.test(["diff","HEAD","--binary","--no-renames",`--output=${o}`],t,E))throw new h("checkout worktree materialization failed: could not read the main checkout's tracked changes");if(!C.existsSync(o)||C.statSync(o).size===0)return;if(!await this.runner.test(["apply","--whitespace=nowarn",o],n,E))throw new h("checkout worktree materialization failed: could not apply the main checkout's tracked changes to the worktree")}finally{C.rmSync(r,{recursive:!0,force:!0})}}async mainCheckoutOf(t){let n;try{C.statSync(t).isDirectory()||w("target is not a directory"),C.lstatSync(g.join(t,".git")).isFile()||w("target is not a linked worktree (.git is not a file)"),n=C.readFileSync(g.join(t,".git"),"utf8")}catch(d){if(d instanceof h)throw d;w("target is not a git worktree")}let r=await this.runner.probe(["rev-parse","--git-common-dir"],t);r===void 0&&w("git rev-parse --git-common-dir failed");let{commonDir:o,mainRoot:a}=j(r,t);C.existsSync(g.join(a,".git"))||w("main checkout not found"),g.resolve(a)===g.resolve(t)&&w("target is the main checkout"),ve(t,a)&&w("main checkout lives inside the worktree");let s=n.trim(),c=s.startsWith("gitdir:")?s.slice(7).trim():"";c===""&&w("malformed .git worktree marker");let l=g.isAbsolute(c)?c:g.resolve(t,c);return l.startsWith(o+g.sep)||w("worktree gitdir is outside this repo"),C.existsSync(l)||w("worktree gitdir missing"),a}async mainStatus(t){let n=await this.runner.probe(["status","--porcelain"],t);return n===void 0&&w("could not read main checkout status"),n}async cloneWorkingTree(t,n,r){try{await ct({wtPath:t,mainRoot:n},r,ut(this.exec))}catch(o){if(o instanceof y&&o.reason==="unsupported")throw o;w(o instanceof y?o.message:String(o))}}async fallbackToCheckout(t){await this.runner.test(["reset","--hard","HEAD"],t,E)||w("the worktree volume cannot clone and its checkout could not be completed")}async ignoredRels(t){let n=await this.runner.lines(["status","--ignored","--porcelain","-z"],t,"\0");return n===void 0&&w("could not read main checkout ignored files"),Wn(n)}async completeCheckout(t,n){(n?await this.runner.test(["reset","-q"],t,E):await this.runner.test(["checkout","-q","HEAD","--","."],t,E))||w(n?"could not refresh the worktree index after materialization":"could not materialize tracked files in the worktree")}async verifyMaterialization(t,n,r){function o(l,d){let f=[...l].sort(),u=[...d].sort();return f.length===u.length&&f.every((m,x)=>m===u[x])}i(o,"samePaths");let a=i(l=>l.filter(d=>!$n(n,d,t)),"carried");if(r.kind==="clean-parent")return this.assertClean(t,"a clean parent");if(r.policy==="clean")return this.assertClean(t,'the "clean" dirty-checkout policy');let s=await this.changeLists(n),c=await this.changeLists(t);(!o(a(s.tracked),c.tracked)||!o(a(s.untracked),c.untracked))&&w("worktree does not mirror the main checkout's uncommitted changes")}async changeLists(t){let n=await this.runner.lines(["diff","HEAD","--name-only","-z"],t,"\0");n===void 0&&w("could not read tracked changes");let r=await this.runner.lines(["ls-files","--others","--exclude-standard","-z"],t,"\0");return r===void 0&&w("could not read untracked files"),{tracked:n,untracked:r}}async assertClean(t,n){await this.runner.probe(["status","--porcelain"],t)!==""&&w(`${n} should leave the worktree clean, but it is not`)}};async function ht(e,t,n,r=q){return new Ce(new b(e),Fn(e)).materialize(t,n,r)}i(ht,"materializeWorktree");function Fn(e){return(t,n,r)=>e.exec(t,n,r)}i(Fn,"execOf");function w(e){throw new h(`copy-on-write worktree materialization failed: ${e}`)}i(w,"cowFail");function ve(e,t){let n=g.relative(g.resolve(e),g.resolve(t));return n===""||!n.startsWith("..")&&!g.isAbsolute(n)}i(ve,"isWithin");function $n(e,t,n){let r=g.resolve(e,t),o=g.resolve(n);return ve(r,o)||ve(o,r)}i($n,"overlapsWorktree");import*as wt from"node:fs";import*as bt from"node:path";import{z as In}from"zod";var Dn=12e4,Mn=/^-|\.\.|@\{|[^A-Za-z0-9._/-]/,Nn=In.string().check(e=>{let t=e.value===""?"is empty":Bn(e.value);t!==void 0&&e.issues.push({code:"custom",input:e.value,message:t})});function Bn(e){let t=Mn.exec(e)?.[0];if(t!==void 0)return t==="-"?'starts with "-": git would parse that as a command-line flag, not a branch name':t===".."?'contains "..": revision ranges are not branch names':t==="@{"?'contains "@{": reflog/date syntax is not a branch name':`contains invalid character ${jn(t)}: branch names may only use letters, digits, ".", "_", "/", and "-"`}i(Bn,"refusalClauseFor");function jn(e){let t=e.charCodeAt(0);return t<=32||t===127?`U+${t.toString(16).toUpperCase().padStart(4,"0")}`:JSON.stringify(e)}i(jn,"describeRefChar");function kt(e,t){let n=Nn.safeParse(e);if(n.success)return;let r=n.error.issues.map(o=>o.message).join("; ");throw new Error(`refusing to merge: the ${t} ref ${JSON.stringify(e)} ${r}.`)}i(kt,"assertValidBranchRef");var xe=class{constructor(t){this.runner=t}runner;static{i(this,"BranchMerger")}async merge(t){let n=t.branch.trim();kt(n,"branch");let r=(t.target??"main").trim();kt(r,"target");let o=await this.runner.probe(["rev-parse","--show-toplevel"],t.cwd);if(o===void 0)throw new Error(`cannot merge "${n}": ${t.cwd} is not inside a git repository`);let a=await this.runner.probe(["rev-parse","--git-common-dir"],o);if(a===void 0)throw new Error(`cannot merge "${n}": could not resolve the repo's git directory`);let{mainRoot:s}=j(a,o);if(!wt.existsSync(bt.join(s,".git")))throw new Error(`cannot merge "${n}": no main checkout found (unsupported repo layout)`);let c=await this.runner.probe(["branch","--show-current"],s);if(c!==r)throw new Error(c===void 0?`refusing to merge "${n}": could not read the current branch of the main checkout (${s})`:`refusing to merge "${n}": the main checkout (${s}) is on branch "${c||"(detached)"}", not the merge target "${r}". A merge would land on "${c||"(detached)"}" instead of "${r}".`);if(n===r)throw new Error(`refusing to merge "${n}" into itself (already on "${r}")`);if(!await this.runner.test(["rev-parse","--verify","--quiet",`refs/heads/${n}`],s))throw new Error(`refusing to merge: branch "${n}" does not exist in ${s}.`);let d=await this.runner.probe(["status","--porcelain"],s);if(d===void 0)throw new Error(`refusing to merge "${n}": could not read the status of the main checkout (${s})`);if(d!=="")throw new Error(`refusing to merge "${n}": the main checkout (${s}) has uncommitted changes. Nothing was merged.`);let f=await this.runner.run(["merge-base","--is-ancestor","--",n,"HEAD"],s);if(!f)throw new Error(`refusing to merge "${n}": could not read its merge ancestry`);if(f.code===0)return{merged:!1,alreadyMerged:!0,target:r,mainRoot:s};let u=await this.runner.run(["merge","--no-edit","--",n],s,Dn);if(!u)throw new Error(`merge of "${n}" into "${r}" failed to run (transport error); the checkout was not modified`);if(u.code===0)return{merged:!0,target:r,mainRoot:s,output:u.stdout||u.stderr||void 0};let m=await this.runner.probe(["diff","--name-only","--diff-filter=U"],s);throw m!==void 0&&m!==""?new Error(yt(n,r,s,m)):await this.runner.test(["rev-parse","--verify","--quiet","MERGE_HEAD"],s)?new Error(yt(n,r,s,void 0)):new Error(`merge of "${n}" into "${r}" failed: ${u.stderr||u.stdout||`exit code ${u.code}`}`)}};function yt(e,t,n,r){let o=r===void 0?`has conflicts in: (the conflicting files could not be listed \u2014 \`git diff --name-only --diff-filter=U\` did not run in ${n})`:`has conflicts in:
11
+ ${r}`;return`merge of "${e}" into "${t}" ${o}
12
+ The merge is still in progress in ${n}. No conflict was resolved automatically.`}i(yt,"conflictMessage");var Re=class{constructor(t){this.runner=t}runner;static{i(this,"BranchCleaner")}async delete(t,n){let{branch:r,worktreePath:o,repoCwd:a}=t;if(!r.startsWith("cow-"))return{kind:"not-applicable"};try{if(!await we(this.runner,r,a))return{kind:"not-applicable"};let s=await this.runner.run(["merge-base","--is-ancestor","--",r,"HEAD"],a);if(s===void 0)throw new h(`git merge-base --is-ancestor -- ${r} HEAD could not run in ${a}`);return s.code!==0?{kind:"kept",reason:"unmerged"}:n&&await n(o)?{kind:"kept",reason:"checked-out"}:await be(this.runner,r,a)}catch(s){return{kind:"delete-failed",detail:s instanceof Error?s.message:String(s)}}}};async function mo(e,t){return new xe(new b(e)).merge(t)}i(mo,"mergeBranchIntoTarget");async function Ct(e,t,n){return new Re(new b(e)).delete(t,n)}i(Ct,"deleteWorktreeBranch");function vt(e,t){return new L(new b(e),t)}i(vt,"worktree");async function xt(e,t){return vt(e,t).isDirty()}i(xt,"isWorktreeDirty");async function wo(e,t){let n=await vt(e,t).isDirty();return n===void 0?{kind:"unverifiable",detail:"git status probe failed"}:n?{kind:"dirty"}:null}i(wo,"worktreeRetentionReason");function Rt(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`}}i(Rt,"formatRetentionClause");import*as _ from"node:fs";import*as $ from"node:path";var Ln=`Success! You delegated to an agent. A notification will arrive when done - USER: do not poll, don't check status and don't duplicate the delegated work!{{#has_worktree}}
13
+ (Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
14
+
15
+ Agent ID: {{agent_id}}`,Hn=`Agent QUEUED \u2014 the concurrency limit is reached ({{queue_running}} {{queue_running_label}} already spawned), so this task is waiting for a slot. It is NOT spawned yet: the process has not started. It will start automatically when another agent settles; you'll get a message when it starts and when it settles. Do NOT re-delegate \u2014 this task IS in flight.{{#has_worktree}}
16
+ (Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
17
+
18
+ Agent ID: {{agent_id}}`,zn=`{{result}}{{#error}}
19
+
20
+ Error: {{error}}{{/error}}{{#has_worktree}}
21
+ (Worktree: {{worktree_path}} (branch {{worktree_branch}}){{#retention}} \u2014 KEPT: {{retention}}{{/retention}}.{{#process_alive}} The agent process and its {{multiplexer_id}} pane stay until you call cleanup_cowboy_agent \u2014 its pane is closed, which ends that process.{{/process_alive}} {{#retention}}Clean the worktree up, then call cleanup_cowboy_agent to remove it.{{/retention}}{{^retention}}The worktree stays until you call cleanup_cowboy_agent to remove it \u2014 call it once the branch is merged or rejected.{{/retention}}){{/has_worktree}}{{status_note}}`,O={default:{name:"default",displayName:"Default",guidance:"Update your report file each time you make a commit",cues:{spawned:Ln,queued:Hn,settled:zn}}};import*as ee from"node:fs";import*as Tt from"node:path";import{parse as Gn,TomlError as Un}from"smol-toml";import{z as Vn}from"zod";var qn=".toml";function te(e){return Gn(e.replace(/^\uFEFF/,""))}i(te,"parseTemplateToml");function A(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0))}i(A,"compactDefined");function Kn(e){let t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}i(Kn,"describeZodIssue");function Qn(e){if(e instanceof Vn.ZodError)return e.issues.map(Kn).join("; ").replace(/\s+/g," ").trim();if(e instanceof Un){let[n]=e.message.split(`
22
+
23
+ `);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}i(Qn,"describeParseError");var Yn={label:"File",problem:"was skipped"};async function ne(e,t,n,r,o=Yn,a){try{await ee.promises.access(e)}catch{return[]}let c=(await ee.promises.readdir(e,{withFileTypes:!0})).filter(d=>d.isFile()&&d.name.endsWith(qn)),l=[];for(let d of c){let f=Tt.join(e,d.name),u;try{u=await ee.promises.readFile(f,"utf-8")}catch{continue}try{let m=t(u),x=a?.(m);if(x!==void 0)throw new Error(x);n(m)&&l.push(m)}catch(m){r?.(`[cowboy] ${o.label} file ${f} ${o.problem}: ${Qn(m)}`,"warning")}}return l}i(ne,"scanTemplateFilesInDir");import{z as P}from"zod";import Ot from"mustache";function Et(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}i(Et,"worktreeVariables");function Xn(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}i(Xn,"outcomeVariables");function Zn(e){return e?{...Et(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}i(Zn,"settledWorktreeVariables");function Jn(e){return e.worktree?{agent_id:e.agentId,...Et(e.worktree)}:{agent_id:e.agentId}}i(Jn,"spawnCueContext");function Io(e){return{...Jn(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}i(Io,"queuedCueContext");function Do(e){let{outcome:t,statusNote:n,worktree:r,multiplexerId:o}=e;return{...Xn(t),...n?{status_note:n}:{},...Zn(r),...o!=null?{multiplexer_id:o}:{}}}i(Do,"settledCueContext");var er={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},tr={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},nr={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},rr=Object.keys(er),or=Object.keys(tr),ir=Object.keys(nr);function At(e){switch(e){case"spawned":return rr;case"queued":return or;case"settled":return ir;default:return}}i(At,"cueVariables");var ar={ok:!0},sr="&",cr=new Set(["name",sr,"#","^"]);function Lo(e,t,n){return Ot.render(e[t],n,void 0,{escape:i(r=>r==null?"":String(r),"escape")})}i(Lo,"renderCue");function dr(e){let t=e[4];return Array.isArray(t)?t:void 0}i(dr,"spanChildren");function Pt(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(cr.has(o)&&!t.includes(a))return`unknown variable "{{${a}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let s=dr(r);if(s){let c=Pt(s,t,n);if(c)return c}}}i(Pt,"findTemplateProblem");function St(e,t){let n=At(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let r;try{r=Ot.parse(t)}catch(a){return{ok:!1,reason:`unparsable template: ${(a instanceof Error?a.message:String(a)).replace(/\s+/g," ").trim()}`}}let o=Pt(r,n,e);return o?{ok:!1,reason:o}:ar}i(St,"validateCueTemplate");var lr=["spawned","queued","settled"],ur=P.strictObject({spawned:P.string().optional(),queued:P.string().optional(),settled:P.string().optional()}).superRefine((e,t)=>{for(let n of lr){let r=e[n];if(r===void 0)continue;let o=St(n,r);o.ok||t.addIssue({code:"custom",message:o.reason,path:[n]})}}),_t=P.strictObject({name:P.string().optional(),display_name:P.string().optional(),guidance:P.string().optional(),cues:ur.optional()});var pr={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function fr(e){return _t.parse(te(e))}i(fr,"parseOrchestratorFile");async function H(e,t){return ne(e,fr,n=>n.name,t,pr)}i(H,"scanOrchestratorFilesInDir");function Te(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,gr(o.get(c.name)??mr(c.name,a),c));return o}i(Te,"mergeOrchestrators");function mr(e,t){return{...t,name:e,displayName:e}}i(mr,"namedBase");function gr(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(gr,"applyOverride");function z(){return X().orchestrators}i(z,"registry");function ni(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);z().orchestrators=n}i(ni,"registerOrchestrators");function ri(e,t,n){z().scanDirs={user:e,project:t,shared:n??""}}i(ri,"setOrchestratorScanDirs");async function oi(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,r=z().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):H(Ge,n),H(r.user,n),H(r.shared,n),H(r.project,n)]),d=Te(t?new Map:O,o,[],[]);return Te(d,a,s,c)}i(oi,"scanAndMergeOrchestrators");function Ee(e){let{orchestrators:t}=z();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(Ee,"resolveOrchestrator");function ii(){return[...z().orchestrators.values()].map(e=>e.name)}i(ii,"getAvailableOrchestrators");import{z as p}from"zod";var Wt=p.union([p.boolean(),p.array(p.string())]),hr={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 oe(e){return p.record(p.string(),p.unknown()).transform((t,n)=>tt(t,{reserved:Ye[e],report:i((r,o)=>n.addIssue({code:"custom",path:[r],message:hr[o]}),"report")}))}i(oe,"envTable");var Ft={model:p.string().optional(),thinking:Je.optional(),extensions:Wt.optional(),skills:Wt.optional(),inlined_skills:p.array(p.string()).optional(),fork:p.boolean().optional(),tools:p.array(p.string()).optional(),exclude_tools:p.array(p.string()).optional(),env:oe("pi").optional()},kr=p.strictObject(Ft),yr=p.strictObject({model:p.string().optional(),variant:p.string().optional(),tools:p.array(p.string()).optional(),exclude_tools:p.array(p.string()).optional(),env:oe("opencode").optional()}),wr=p.strictObject({model:p.string().optional(),thinking:p.string().optional(),env:oe("codex").optional()}),br=p.strictObject({model:p.string().optional(),thinking:p.string().optional(),tools:p.array(p.string()).optional(),exclude_tools:p.array(p.string()).optional(),env:oe("claude").optional()});function Ae(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}i(Ae,"toToolFilter");function re(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}i(re,"nonEmptyEnv");var Cr=p.strictObject({include_context_files:p.boolean().optional(),pi:kr.optional(),opencode:yr.optional(),codex:wr.optional(),claude:br.optional(),...Ft}).transform(({pi:e,opencode:t,codex:n,claude:r,...o})=>{let{model:a,thinking:s,tools:c,exclude_tools:l,env:d,...f}=o,{model:u,thinking:m,tools:x,exclude_tools:de,env:V,...R}=A(e??{}),{model:Yt,variant:Xt,tools:Zt,exclude_tools:Jt,env:en,...tn}=A(t??{}),{model:nn,thinking:rn,env:on,...an}=A(n??{}),{model:sn,thinking:cn,tools:dn,exclude_tools:ln,env:un}=A(r??{}),Be=A({pi:u??a,opencode:Yt,codex:nn,claude:sn}),je=A({pi:Ae(x??c,de??l),opencode:Ae(Zt,Jt),claude:Ae(dn,ln)}),Le=A({pi:m??s,opencode:Xt,codex:rn,claude:cn}),He=A({pi:re(Q(d,V)),opencode:re(en),codex:re(on),claude:re(un)});return{...f,...R,...tn,...an,...Object.keys(Be).length>0?{modelsByFamily:Be}:{},...Object.keys(je).length>0?{toolsByFamily:je}:{},...Object.keys(Le).length>0?{thinkingByFamily:Le}:{},...Object.keys(He).length>0?{envByFamily:He}:{}}}),$t=p.strictObject({name:p.string().optional(),display_name:p.string().optional(),description:p.string().optional(),hidden:p.boolean().optional(),worktree_checkout_type:p.enum(qe).optional(),system_prompt:p.string().optional(),harness_type:p.string().min(1).optional(),harness:Cr.optional()});function vr(e){return $t.parse(te(e))}i(vr,"parseAgentFile");var xr={label:"Agent",problem:"is not a valid agent template and was skipped"};async function N(e,t,n){return ne(e,vr,r=>r.name,t,xr,n)}i(N,"scanAgentFilesInDir");function ie(e,t,n,r){let o=new Map;for(let[a,s]of e)o.set(a,{...s});return Oe(o,t),Oe(o,n),Oe(o,r),o}i(ie,"mergeAgents");function Oe(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=It(n),s=Rr(r.modelsByFamily,a.modelsByFamily),c=Tr(r.toolsByFamily,a.toolsByFamily),l=Er(r.thinkingByFamily,a.thinkingByFamily),d=Ar(r.envByFamily,a.envByFamily);e.set(n.name,{...r,...a,...s?{modelsByFamily:s}:{},...c?{toolsByFamily:c}:{},...l?{thinkingByFamily:l}:{},...d?{envByFamily:d}:{},...o})}else e.set(n.name,{...Or,...It(n)})}}i(Oe,"mergeAgentOverrides");function Rr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Rr,"mergeModelsByFamily");function Tr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Tr,"mergeToolsByFamily");function Er(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Er,"mergeThinkingByFamily");function Ar(e,t){let n={...e};for(let[r,o]of Object.entries(t??{})){let a=r;n[a]=Q(n[a],o)}return Object.keys(n).length>0?n:void 0}i(Ar,"mergeEnvByFamily");function It(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(It,"fromTemplate");var Or={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Pe=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return X().agents}i(S,"registry");function G(e){let t=e.harness_type;if(t===void 0)return;let n=D();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}i(G,"unregisteredHarness");function Ei(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[r,o]of Pe)n.set(r,o);for(let[r,o]of e)n.set(r,o);S().agents=n}i(Ei,"registerAgents");function Ai(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}i(Ai,"setAgentScanDirs");async function Pr(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,r=S().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):N(ze,n,G),N(r.user,n,G),N(r.shared,n,G),N(r.project,n,G)]),d=ie(t?new Map:Pe,o,[],[]);return ie(d,a,s,c)}i(Pr,"scanAndMerge");async function Sr(e,t){let n=await Pr(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 N(e,t?.notify,G),s=ie(new Map,[],[],a);for(let[c,l]of s)r.has(c)||(r.set(c,l),o++)}return o}i(Sr,"discoverNewAgents");function U(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(U,"resolveType");async function Oi(e,t,n){let r=U(e);return r.kind==="not-found"&&(await Sr(t,{notify:n}),r=U(e)),r}i(Oi,"resolveTypeOrDiscover");function ae(e){let t=U(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}i(ae,"getAgentConfig");function Pi(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}i(Pi,"getAvailableTypes");function Si(){return[...S().agents.keys()]}i(Si,"getAllTypes");function Dt(e,t,n,r){return{skills:e??n,extensions:t??r}}i(Dt,"applyGlobalDefaults");function _i(e,t=!0,n=!0){let r=ae(e);if(r){let{skills:a,extensions:s,...c}=r,l=Dt(a,s,t,n);return{displayName:c.displayName??c.name,description:c.description,...l}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Dt(void 0,void 0,t,n)}}i(_i,"getConfig");function Mt(e){return typeof e=="string"&&e!==""?e:void 0}i(Mt,"configuredString");function _r(){let e=Mt(B().agent.defaultAgentType);if(e===void 0)return fe;let t=U(e);return t.kind==="resolved"?t.key:fe}i(_r,"resolveDefaultAgentType");function Wr(){let e=Mt(B().agent.defaultOrchestrator);return e===void 0?W:e===W||Ee(e)?e:W}i(Wr,"resolveDefaultOrchestratorName");function ji(e){return typeof e=="string"&&e!==""?e:_r()}i(ji,"resolveAgentTypeParam");function Li(){let e=Wr();return Ee(e)??(e===W?O[W]:void 0)??O[W]}i(Li,"resolveDefaultOrchestrator");function Nt(e){return ae(e)?.worktreeCheckoutType??B().agent.worktreeCheckoutType}i(Nt,"resolveWorktreeCheckoutType");function Bt(e){return typeof e=="string"&&e.trim()!==""?e:void 0}i(Bt,"harnessParam");function Hi(e){let t=Bt(e);if(t!==void 0&&D().get(t)!==void 0)return le(t,Y())?t:void 0}i(Hi,"requestedHarnessId");function zi(e){let t=Bt(e);if(t===void 0)return;let n=D();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=Y();if(!le(t,r))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${Ue(n.ids(),r).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}i(zi,"resolveRequestedHarness");function Gi(e,t){if(t!==void 0)return t;let n=ae(e)?.harnessType??B().agent.harnessType;return D().resolve(n,Y())}i(Gi,"resolveHarnessType");function Se(e){return{kind:"recorded",phase:e.lifecycle.phase}}i(Se,"recordedSettlement");function jt(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(jt,"planRecovered");async function _e(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(_e,"assessRemovability");function Lt(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 pe(e.state)}}i(Lt,"recoveryGate");function We(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(We,"recoveryRefusalReason");function se(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(se,"keptReport");function Ht(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(Ht,"ambiguousReport");function Fe(e){return e?.force!==void 0?{forced:e.force}:{}}i(Fe,"forcedFields");function zt(e,t,n,r,o,a){return{agentId:e,source:t,outcome:{kind:"torn-down",...Fe(a)},branchName:n.kind==="worktree"?n.worktree.branchName:void 0,settlement:r,panes:o.panes,worktree:o.worktree,branch:o.branch}}i(zt,"assembleReport");function Ki(e){return e.outcome.kind==="refused"&&e.outcome.forceable}i(Ki,"isForceableRefusal");function $e(e){return e.worktree.kind==="removed"||e.worktree.kind==="absent"?!0:e.worktree.kind==="none"?e.panes.every(t=>t.kind==="closed"):!1}i($e,"shouldDropSpawn");function Ie(e){return e.workspaceId!==void 0?"multiplexer":"git"}i(Ie,"removalMechanismOf");function Gt(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 pe(t.mechanism)}}i(Gt,"paneDispositionFor");var Fr=Ze("cleanup");function $r(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($r,"hostRefFor");async function Ut(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(Ut,"removeOwnedTree");async function ce(e,t,n){let r=[];for(let o of t)switch(Gt(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(ce,"paneOutcomes");async function Ir(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(Ir,"paneOutcomesForAbsentTree");async function Dr(e,t,n){if(t.kind==="no-worktree")return{panes:await ce(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 Ut(e,r,n);return a.kind==="removed"?{panes:await ce(e,o,{kind:"removed",mechanism:Ie(r),workspaceId:r.workspaceId}),worktree:a,branch:await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd})}:{panes:await ce(e,o,{kind:"retained"}),worktree:a,branch:{kind:"not-applicable"}}}i(Dr,"removeResources");function De(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 _e(e.isWorktreeDirty,n,r);if(s.kind==="kept")return{kind:"kept",path:r.worktreePath,reason:s.reason};let c=await Ut(e,r,a);if(c.kind==="removal-failed")return c;let l=Ie(r);await ce(e,o,{kind:"removed",mechanism:l,workspaceId:r.workspaceId});let d=await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd});return{kind:"removed",path:r.worktreePath,branchName:r.branchName,via:l,branch:d}}catch(s){return{kind:"removal-failed",path:r.worktreePath,detail:I(s)}}}}}i(De,"createWorktreeTeardown");function Mr(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(Mr,"environmentPanes");function Nr(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(Nr,"teardownRuns");function ta(e){let t=De(e);function n(a,s){return{kind:"discovered",basis:s,deliverable:e.deliverable(a)}}i(n,"recovered");async function r(a,s,c,l){if(c!==void 0){let u=Se(c);return et(c.lifecycle)?{kind:"torn-down",settlement:u}:{kind:"refused",settlement:u,reason:{kind:"agent-active",phase:c.lifecycle.phase},forceable:!1}}if(l?.force!==void 0)return{kind:"torn-down",settlement:n(a,{kind:"forced"})};let d;if(s.pane!==null)try{d=await e.observe(s.pane)}catch(u){let m={kind:"pane-unreadable",detail:I(u)};return{kind:"refused",settlement:n(a,m),reason:We(m),forceable:!0}}let f=Lt(d);return f.kind==="allow"?{kind:"torn-down",settlement:n(a,f.basis)}:{kind:"refused",settlement:n(a,f.basis),reason:We(f.basis),forceable:!0}}i(r,"verdictFor");async function o(a,s,c){let l=s.getSpawn(a),d=await e.locate(a,l);if(d.kind==="not-found")throw new Error(`Agent ${a} not found.`);if(d.kind==="ambiguous")return Ht(a,l===void 0?"recovered":"tracked",l===void 0?n(a,{kind:"artifacts-ambiguous"}):Se(l),d.candidates.map(R=>R.worktreePath));let f=$r(d,e.multiplexer),u=jt(d,Mr(f,l)),m=await r(a,d,l,c);if(m.kind==="refused")return se(a,d.source,u,m.settlement,{reason:m.reason,forceable:m.forceable});let x=Nr(l,d);if(x.length>0)try{await e.teardownEnvironment({subagentId:a,runs:x})}catch(R){Fr.warn("environment teardown failed during cleanup",{spawnId:a,error:I(R)})}if(u.kind==="worktree-unlocatable"){if(u.worktreePath!==null&&!await e.worktreeExists(u.worktreePath)){let R={agentId:a,source:d.source,outcome:{kind:"torn-down",...Fe(c)},branchName:u.branchName,settlement:m.settlement,panes:await Ir(e,u.panes),worktree:{kind:"absent",path:u.worktreePath},branch:{kind:"not-applicable"}};return $e(R)&&l!==void 0&&s.dropSpawn(l),R}return se(a,d.source,u,m.settlement,{reason:{kind:"unverifiable",detail:"missing worktree path or repo cwd"},forceable:!1})}if(u.kind==="worktree"){let R=await _e(e.isWorktreeDirty,c,u.worktree);if(R.kind==="kept")return se(a,d.source,u,m.settlement,{reason:R.reason,forceable:!0})}let de=await Dr(e,u,f),V=zt(a,d.source,u,m.settlement,de,c);return $e(V)&&l!==void 0&&s.dropSpawn(l),V}return i(o,"cleanupAgent"),{...t,cleanupAgent:o}}i(ta,"createCleanup");import*as Vt from"node:path";async function Br(e,t,n){let r=await ye(e,["rev-parse","--verify","--quiet",`refs/heads/${n}`],t,E);return r===void 0?!0:r.code===0}i(Br,"branchExisted");async function qt(e,t){let n=t.branch.trim();if(n==="")throw new h("worktree checkout requires a branch name");let r=await J(e,t.repoCwd),o=Vt.resolve(t.path),a=t.materialization??Ve,s=t.dirtyCheckout??q,c=await Br(e,r,n),l=await ye(e,["worktree","add",...gt(a),"-b",n,o,t.base??"HEAD"],r,E);if(l===void 0||l.code!==0)throw await F(e,r,o),c||await M(e,n,r),new h(l===void 0?`git worktree add for "${n}" could not run (worktree removed)`:`git worktree add for "${n}" failed (worktree removed): ${(l.stderr||l.stdout||`exit ${l.code}`).slice(0,300)}`);let d=await ft(e,["branch","--show-current"],o);if(d!==n)throw await F(e,r,o),await M(e,n,r),new h(d===void 0?`worktree created at ${o} but its branch could not be verified (worktree removed)`:`worktree created at ${o} is on branch "${d||"(detached)"}", not the requested "${n}" (worktree removed). The branch "${d}" still exists.`);let f;try{f=await ht(e,o,a,s)}catch(u){await F(e,r,o),await M(e,n,r);let m=u instanceof Error?u.message:String(u);throw new h(`worktree created but ${a} materialization failed (worktree removed): ${m}`)}if(f.kind==="cow-fallback"){let u=s==="dirty"?" The parent's uncommitted work was not carried over.":"";t.notify?.(`[cowboy] ${f.reason}${u} Nothing is shared with the parent checkout.`,"warning")}return{path:o,branch:n,repoCwd:r,materialization:f}}i(qt,"createWorktreeCheckout");function jr(e){try{let t=_.statSync(e,{bigint:!0});return`${t.dev}:${t.ino}`}catch{return $.resolve(e)}}i(jr,"canonicalRepoKey");async function ga(e){let t=await Me.allocate(e.pi,{naming:{kind:"generated",taskSlug:e.taskSlug??e.agentType,id:e.spawnId},parentCwd:e.parentCwd,worktreeRoot:e.worktreeRoot,materialization:e.materialization,dirtyCheckout:Nt(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(ga,"provisionOwnedCheckout");var Me=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:l,host:d}=n,f=r.kind==="generated"?Ke(r.taskSlug,r.id):r.branch.trim();if(r.kind==="explicit"&&f==="")throw new Error("explicit worktree naming requires a branch name");let u;try{u=await J(t,o)}catch{return l?.("[cowboy] Parent is not inside a git repository \u2014 spawning in the parent cwd without a worktree","warning"),new e(d,{kind:"parent-cwd"},f,!0)}let m=await Hr(t,{repoCwd:u,path:$.join(Qe(a,u),f),branch:f,materialization:s,dirtyCheckout:c,notify:l,host:d});return new e(d,{kind:"worktree",checkout:{path:m.path,branch:m.branch,repoCwd:m.repoCwd},ref:m.ref},f,!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 De(Gr(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=Lr(o),o}};function Lr(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(Lr,"stateAfterTeardown");async function Hr(e,t){let n=$.resolve(t.path);return _.mkdirSync($.dirname(n),{recursive:!0}),nt().run(jr(t.repoCwd),()=>zr(e,t.host,{...t,path:n}))}i(Hr,"createAdoptedWorktree");async function zr(e,t,n){let{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:l}=n,d;try{d=await qt(e,{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:l})}catch(u){throw Qt(u,await Kt(e,r,o))}let f;try{f=await t.hostAt({unit:"pane",cwd:d.path,label:a,name:a,checkout:{path:d.path,repoCwd:r,branch:d.branch}})}catch(u){let m=await Kt(e,r,d.path),x=await M(e,d.branch,r);throw Qt(u,`${m}. ${Ne(d.branch,x)}`)}return{path:d.path,branch:d.branch,repoCwd:r,materialization:d.materialization,ref:f}}i(zr,"adoptWorktree");function Gr(e,t){return{isWorktreeDirty:i(n=>xt(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 F(e,r,n),!_.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>Ct(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(Gr,"cleanupDeps");async function Kt(e,t,n){return await F(e,t,n),_.existsSync(n)?`worktree ${n} NOT removed \u2014 inspect it manually`:`worktree ${n} removed`}i(Kt,"removeFailedCheckout");function Qt(e,t){return new Error(`could not create the herdr worktree: ${I(e)}
24
+
25
+ Launch-failure cleanup: ${t}.`)}i(Qt,"createFailureMessage");function Ne(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(Ne,"formatLaunchedBranchOutcome");function ha(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. ${Ne(e.branchName,e.branch)}.`:`Launch-failure cleanup: worktree ${e.path} removed. ${Ne(e.branchName,e.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${e.path} KEPT \u2014 ${Rt(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(ha,"formatLaunchCleanupNote");export{Vr as a,ut as b,b as c,ft as d,j as e,Yr as f,J as g,F as h,eo as i,to as j,kt as k,mo as l,Ct as m,xt as n,wo as o,Rt as p,Pe as q,Ei as r,Ai as s,Pr as t,Oi as u,ae as v,Pi as w,Si as x,_i as y,O as z,Jn as A,Io as B,Do as C,Lo as D,ni as E,ri as F,oi as G,ii as H,_r as I,ji as J,Li as K,Nt as L,Hi as M,zi as N,Gi as O,Ki as P,ta as Q,ga as R,Me as S,Hr as T,ha as U};
26
+ //# sourceMappingURL=chunk-S4BS2R6G.js.map
@@ -0,0 +1,14 @@
1
+ import{A as pt,B as gt,C as ht,D as Z,J,K as mt,M as ft,N as yt,O as ee,b as rt,c as it,e as st,g as at,k as Se,l as dt,p as lt,u as ct,v as X,w as ut}from"./chunk-S4BS2R6G.js";import{Ba as ot,D as Xe,Ea as ke,I as me,K as Ze,L as fe,O as ye,P as Je,R as F,S as x,T as O,V as et,Z as tt,b as Le,ha as S,ia as z,j,ja as w,k as je,l as Ue,la as y,m as qe,ma as _,na as we,o as We,oa as ve,qa as nt,ta as be,ua as V,v as Ke,va as C,w as Ge,wa as N,x as Ye,y as Fe,ya as Q}from"./chunk-M42XWVYW.js";import{a as o,d as $,f as he,g as ze,j as Ve,k as K,l as Qe,u as G,v as Y}from"./chunk-J5TU3AFX.js";import{visibleWidth as Re}from"@earendil-works/pi-tui";var Ae="\u{1F920}",bt="\u{1F404}",nn="\u{1F4A9}",on=2,rn=1e3,te=Re(bt),sn="76;175;80";function an(e){return`\x1B[48;2;${sn}m${e}\x1B[49m`}o(an,"greenBackground");function kt(e){return e===0?0:Math.max(on,Math.ceil(Math.sqrt(2*e)))}o(kt,"pastureEdge");function St(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}o(St,"emptyPasture");function dn(e,t){let n=kt(e.cows+e.droppings),r=St(n),s=Array.from({length:n*n},(i,d)=>d),a=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let i=0;i<a.length;i+=1){let d=i+Math.floor(t()*(s.length-i)),c=s[d];s[d]=s[i],s[i]=c,r[Math.floor(c/n)][c%n]=a[i]}return r}o(dn,"grazedPasture");function ne(e,t){let n=[];for(let r=0;r<e.length;r+=1)for(let s=0;s<e[r].length;s+=1)e[r][s]===t&&n.push({row:r,col:s});return n}o(ne,"cellsOf");function ln(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:r,col:s})=>r>=0&&r<t&&s>=0&&s<t)}o(ln,"neighboursOf");function wt(e,t){return ln(e,t.length).filter(({row:n,col:r})=>t[n][r]==="empty")}o(wt,"openNeighboursOf");function cn(e,t){let n=ne(e,"cow").filter(d=>wt(d,e).length>0);if(n.length===0||t()>=.05)return e;let r=n[Math.floor(t()*n.length)],s=wt(r,e),a=s[Math.floor(t()*s.length)],i=e.map(d=>d.slice());return i[r.row][r.col]="empty",i[a.row][a.col]="cow",i}o(cn,"moveHerd");function vt(e,t,n,r){for(let s=0;s<n;s+=1){let a=ne(e,"empty"),i=a[Math.floor(r()*a.length)];e[i.row][i.col]=t}}o(vt,"placeAtRandom");function un(e,t,n,r){let s=ne(e,"cow"),a=ne(e,"dropping"),i=s.length-t,d=a.length-n;for(;i>0&&d<0;){let c=s.pop();e[c.row][c.col]="dropping",i-=1,d+=1}for(;i>0;){let c=s.pop();e[c.row][c.col]="empty",i-=1}for(;d>0;){let c=a.pop();e[c.row][c.col]="empty",d-=1}vt(e,"cow",-i,r),vt(e,"dropping",-d,r)}o(un,"reconcileCounts");function pn(e,t,n){if(e===null)return dn(t,n);let r=kt(t.cows+t.droppings),s=St(r);for(let a=0;a<e.length&&a<r;a+=1)for(let i=0;i<e[a].length&&i<r;i+=1)s[a][i]=e[a][i];return un(s,t.cows,t.droppings,n),s}o(pn,"reconcilePasture");var gn={anchor:"top-right",width:Re(Ae),get offsetX(){return _()?.cowboyOffsetX??0},nonCapturing:!0},hn={anchor:"top-right",offsetY:1,get width(){return _()?.pastureWidth??0},nonCapturing:!0};function mn(e){return e==="cow"?bt:e==="dropping"?nn:" ".repeat(te)}o(mn,"cellText");function fn(e,t){return e.map(n=>t(n.map(mn).join("")))}o(fn,"drawnRows");function yn(){return ve().list(["spawned"]).length}o(yn,"liveAgentCount");function wn(){return ve().list(Je).length}o(wn,"endedAgentCount");function vn(){return{live:yn(),ended:wn()}}o(vn,"agentCounts");function bn(){return y().agent.grazingEnabled}o(bn,"grazingEnabled");var Te=class{constructor(t,n,r,s,a){this.tui=t;this.countAgents=n;this.isGrazing=r;this.grass=s;this.random=a}tui;countAgents;isGrazing;grass;random;static{o(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return Re(Ae)}get pastureWidth(){return this.drawnPasture().length*te}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*te-(t*te-this.cowboyWidth)}render(){return this.frame(),[Ae]}pastureRows(){return this.frame(),fn(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(),rn))}recount(){let{live:t,ended:n}=this.countAgents(),r=this.isGrazing(),s=r!==this.grazing,a=(this.grazing??r)&&(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(r&&!s)this.herd={...this.herd,pasture:cn(this.herd.pasture,this.random)};else if(!s)return;if(this.grazing=r,this.pollWhile(r),r||s){let i=a&&this.drawnPasture().length===0;this.tui.requestRender(i)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:pn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},xe=class{static{o(this,"PastureView")}render(){return _()?.pastureRows()??[]}invalidate(){}};function At(e){Oe(),e.custom(t=>{let n=new Te(t,vn,bn,an,Math.random);return we(n),n},{overlay:!0,overlayOptions:gn,onHandle:o(t=>_()?.attachCowboy(t),"onHandle")}),e.custom(()=>new xe,{overlay:!0,overlayOptions:hn,onHandle:o(t=>_()?.attachPasture(t),"onHandle")})}o(At,"showExtensionIndicator");function Oe(){let e=_();we(null),e?.dispose()}o(Oe,"hideExtensionIndicator");function oe(){return y().agent.extensionEnabled}o(oe,"isExtensionEnabled");function kn(){return oe()&&y().agent.showActiveIndicator}o(kn,"isActiveIndicatorShown");function re(e){kn()?At(e):Oe()}o(re,"syncExtensionIndicator");function Yo(e,t){y().mutate.agent.setShowActiveIndicator(t),re(e)}o(Yo,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as Io}from"@earendil-works/pi-tui";var _e=globalThis.__PI_COWBOY_DEV_MODE__===!0;import{Type as m}from"typebox";var Sn="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.",An=`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.`,Tn=`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.`,xn=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${K.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.`,Rn=m.Object({prompt:m.String({description:Sn}),task_name:m.String({description:An}),agent_type:m.Optional(m.Union([m.String(),m.Null()])),model:m.Optional(m.Union([m.String(),m.Null()],{description:Tn})),harness_type:m.Optional(m.Union([m.String(),m.Null()],{description:xn}))},{additionalProperties:!1,required:["prompt","task_name"]}),D=m.Object({agents:m.Array(Rn,{minItems:1}),run_in_background:m.Optional(m.Boolean())},{additionalProperties:!1,required:["agents"]});var h={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},ie=Object.values(h),k={type:"json_schema",strict:"prefer"};var Ce="_configuredModel",Ie="_configuredThinking";function H(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}o(H,"readModelKey");function se(e){return H(e.thinking)??H(e[Ie])}o(se,"readThinkingRequest");function ae(e){let t=H(e.model);if(t)return{source:"call",key:t};let n=H(e[Ce]);if(n)return{source:"configured",key:n}}o(ae,"readModelRequest");function U(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}o(U,"withoutModel");function de(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}}o(de,"modelChoiceFor");function q(e){return`${e.provider}/${e.id}`}o(q,"modelKey");function On(e,t){if(t!==void 0&&!fe.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${fe.options.join(", ")}); launching "${q(e)}" with "${t}".`}o(On,"undeclaredLevelWarning");function Tt(e,t){let n=On(e,t);return{resolved:{kind:"resolved",model:e,modelKey:q(e),thinking:t??null},notices:n===void 0?[]:[n]}}o(Tt,"resolvedModel");function _n(e){return`No API key found for "${e}"`}o(_n,"missingCredential");function xt(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(r){return{verdict:"inconclusive",reason:$(r)}}return!Xe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:_n(t.provider)}}o(xt,"probeCredentials");function Ee(e,t){return`${e}: ${t}. Nothing was spawned.`}o(Ee,"refusal");function Pe(e,t){let{registry:n,parent:r,thinking:s}=t;if(!e){if(!r)return U(s);let d=xt(n,r);if(d.verdict!=="unusable")return Tt(r,s);throw new Error(Ee(`The parent session's model "${q(r)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?he(e.key,n,void 0):he(e.key,n,r);if(!a){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return U(s)}let i=xt(n,a);if(i.verdict!=="unusable")return Tt(a,s);throw e.source==="call"?new Error(Ee(`Model "${q(a)}" cannot authenticate in this session`,i.reason)):new Error(Ee(`The subagent model "${q(a)}" for this configured default cannot authenticate in this session`,i.reason))}o(Pe,"resolvePiModel");async function Cn(e){try{return await e.listModels(e.harness)}catch{return[]}}o(Cn,"harnessModels");function In(e,t,n){if(t===void 0||t.thinkingLevels.kind!=="closed")return;let{levels:r}=t.thinkingLevels;if(!r.includes(n))return r.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: ${r.join(", ")}); proceeding with "${n}".`}o(In,"undeclaredLevelWarning");async function Rt(e,t){if(!e)return U(t.thinking);let n=await Cn(t),r=n.find(a=>a.key===e.key),s=[];if(n.length>0&&!r&&s.push(`The ${t.harness} model list does not include "${e.key}"; launching with that key anyway.`),t.thinking!==void 0){let a=In(t.harness,r,t.thinking);a!==void 0&&s.push(a)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:r?.label??e.key,thinking:t.thinking??null},notices:s}}o(Rt,"resolveForeignModel");async function le(e,t){let{harness:n}=t;if(Qe(n))return Pe(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let r={harness:n,listModels:t.listModels,thinking:t.thinking};return Rt(e,r)}o(le,"resolveSpawnModel");function B(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}o(B,"resultWithSeverity");function ce(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}o(ce,"foldSeverity");var Me=`
2
+
3
+ ---
4
+
5
+ `,En={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function R(e){let{items:t}=e;Mn(t,e),await e.prepare?.();let n=Pn(e),r=[],s=[],a=o(({outcome:d,text:c})=>{r.push(d),s.push(c)},"record"),i;for(let d of t){let c=n.halt;if(c!==void 0&&i!==void 0){a(c.skip(d,i));continue}let l=await n.handle(d);a(l),c!==void 0&&c.halts(l.outcome)&&(i=d)}return B(ce(r.map(e.severity)),s.join(Me),{[e.detailsKey]:r})}o(R,"runBatch");function Pn(e){if("render"in e){let n=e.render,r=e.halt;return{handle:o(async s=>{let a=await e.handleItem(s);return{outcome:a,text:n(a)}},"handle"),halt:r===void 0?void 0:{halts:o(s=>r.on(s),"halts"),skip:o((s,a)=>{let i=r.skip(s,a);return{outcome:i,text:n(i)}},"skip")}}}let t=e.halt;return{handle:e.handleItem,halt:t===void 0?void 0:{halts:o(n=>t.on(n),"halts"),skip:t.skip}}}o(Pn,"batchSteps");function Mn(e,{toolName:t,param:n}){let r=e.map(i=>i.trim()),s=r.filter((i,d)=>r.indexOf(i)!==d);if(s.length===0)return;let a=En[n];throw new Error(`${t} received duplicate ${a.plural} in \`${n}\`: ${[...new Set(s)].join(", ")}. No item was handled.`)}o(Mn,"rejectRepeatedKeys");var Ot={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"},$n={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 Nn(e){if(!x(e)||e.status!=="stopped")return Ot.agent;let{stop:t}=e;return e.phase==="never-started"?$n[t.initiator]:Ot[t.initiator]}o(Nn,"stopNote");function _t(e){return!x(e)||e.status!=="stopped"?"":` (${Nn(e)})`}o(_t,"getStatusNote");function I(e=w()){let t=e.listAgents(ye).filter(n=>F(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}o(I,"formatActiveAgents");function $e(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 r=e.execution.host;if(r&&(n.herdrAgent=r.name,n.herdrPane=r.paneId,n.herdrTab=r.tabId),t?.includeStatus&&(n.status=O(e.lifecycle)),t?.includeRunInfo){let s=x(e.lifecycle)?e.lifecycle.completedAt-et(e.lifecycle):0;n.durationMs=s,n.modelName=e.display.invocation?.modelName,n.modelId=e.display.invocation?.modelName,n.thinkingLevel=e.display.invocation?.thinkingLevel}return n}o($e,"buildAgentDetails");function Dn(e){if(!x(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 Ve(e)}}o(Dn,"settledOutcome");function Hn(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${O(e.lifecycle)}]`}o(Hn,"settledHeadline");function Bn(e){let t=e.lifecycle,n=x(t)?t.worktreeRetentionReason:void 0,r=e.display.orchestration,s=e.display.worktree?.kind==="owned"?e.display.worktree:void 0;return Z(r.cues,"settled",ht({outcome:Dn(t),statusNote:_t(t)||void 0,worktree:s?{path:s.path,branch:s.branch,retention:n?lt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:y().multiplexer||Ze}))}o(Bn,"formatResultContent");var Ne=class e{static{o(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,r){let s=J(t.agent_type),a=t.prompt,i=typeof t.task_name=="string"?t.task_name.trim():"";if(!i)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=Ke(i),c=mt(),l=await ct(s,void 0,(b,T)=>{n.ui.notify(b,T)});if(l.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${s}. Candidates: ${l.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(l.kind==="not-found")throw new Error(`Unknown agent type: ${s} \u2014 nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);let v=yt(t.harness_type),g=ee(l.key,v),u=se(t),p=await le(ae(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:u,listModels:o(async b=>{let T=await C().require(b).listModels({pi:S(),modelCatalog:N(n.modelRegistry)}),W=Y(T);return W!==void 0&&n.hasUI&&n.ui.notify(W,"warning"),G(T)},"listModels")});for(let b of p.notices)n.ui.notify(b,"warning");let f=t.run_in_background!==!1;return new e({ctx:n,toolCallId:r,taskSlug:d,prompt:a,description:a.split(`
6
+ `)[0].slice(0,80)||a.slice(0,80),agentType:s,resolvedType:l.key,orchestrator:c,fork:X(s)?.fork??!1,modelChoice:de(p.resolved),requestedHarness:v,isBackground:f})}async run(t){let{ctx:n,isBackground:r,taskSlug:s,resolvedType:a}=this.intent,i=S(),d=w().mintSpawnId(),c=await this.expectedWorktree(i,d),l=this.intent.modelChoice?.thinking??void 0,v=ze(this.intent.modelChoice),{agentId:g,spawn:u}=await nt().spawn(n,{spawnId:d,type:a,prompt:this.intent.prompt,description:this.intent.description,taskSlug:s,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:r,signal:r?void 0:t});if(this.intent.toolCallId&&(u.display.toolCallId=this.intent.toolCallId),!r){let T=$e(u,{includeRunInfo:!0,includeStatus:!0});if(T.agentId=g,x(u.lifecycle)&&u.lifecycle.status==="error")throw new Error(`agent ${g} stopped with an error: ${u.lifecycle.error||"no error message was recorded"}`);return{message:`${Hn(u)}
7
+
8
+ ${Bn(u)}`,details:T}}let p=c;if(u.lifecycle.phase==="queued"){let T=w().listAgents(ye).filter(tn=>tn.lifecycle.phase==="spawned").length,W=Z(this.intent.orchestrator.cues,"queued",gt({agentId:g,worktree:p,queueRunning:T})),ge=$e(u);return ge.agentId=g,ge.status="queued",{message:`[Agent queued] ${W}`,details:ge}}let f=Z(this.intent.orchestrator.cues,"spawned",pt({agentId:g,worktree:p})),b=$e(u);return b.agentId=g,b.status="spawned",{message:`[Agent spawned] ${f}`,details:b}}async expectedWorktree(t,n){let r=await at(t,z().cwd).catch(()=>{});if(r===void 0)return;let s=Fe(y().agent.worktreeRoot,r);return{kind:"owned",path:Ye(s,this.intent.taskSlug,n),branch:Ge(this.intent.taskSlug,n)}}};async function Ct(e,t,n,r){if(e.agents.length>1&&e.run_in_background===!1)throw new Error("run_in_background: false requires exactly one agent");let s=e.agents.map(l=>({...l,run_in_background:e.run_in_background})),a=await Promise.all(s.map(l=>Ne.parse(l,t,n)));Ln(a);let i=await Promise.all(a.map(l=>l.run(r))),d=i.map(l=>l.message).join(Me),c={agents:i.map(l=>l.details)};return{message:d,details:c}}o(Ct,"runDelegationBatch");function Ln(e){let t=e.map(r=>r.intent.taskSlug),n=t.filter((r,s)=>t.indexOf(r)!==s);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.`)}o(Ln,"rejectRepeatedTaskSlugs");import{Type as De}from"typebox";var jn="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).",It=De.Object({agent_ids:De.Array(De.String({minLength:1}),{minItems:1,description:jn})},{additionalProperties:!1,required:["agent_ids"]});function Un(e){let t=Array.isArray(e.agents)?e.agents:[];return ce(t.map(n=>typeof n=="object"&&n!==null&&n.status==="stopped"?"warning":"success"))}o(Un,"delegationSeverity");async function Et(e,t,n,r,s){let{message:a,details:i}=await Ct(t,s,e,n);return B(Un(i),a,i)}o(Et,"executeAgentTool");var Pt={name:h.stopAgent,label:h.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:It,execute:Kn,constrainedSampling:k};function qn(e){switch(e.kind){case"stopped":return"success";case"failed":return"error";case"already-settled":case"unknown":case"refused":return"warning"}}o(qn,"stopSeverity");function Wn(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}`}}o(Wn,"renderStopOutcome");async function Kn(e,t,n,r,s){let a=t.agent_ids;return R({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:Wn,severity:qn,handleItem:o(async i=>{let d=w().getSpawn(i);if(!d)return{kind:"unknown",agentId:i,activeAgents:I()};if(w().isHandingOver(i))return{kind:"refused",agentId:i,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(!F(d.lifecycle.phase))return{kind:"already-settled",agentId:i,status:O(d.lifecycle),activeAgents:I()};try{return await w().abort(i,"agent")?{kind:"stopped",agentId:i}:{kind:"failed",agentId:i,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:i,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}o(Kn,"executeStopAgentTool");async function ei(e,t){if(e.toolName!=="cowboy_agent")return;let r=e.input.agents??[],s=t.model?`${t.model.provider}/${t.model.id}`:null;for(let a of r){let i=a.agent_type,d=J(i),c=X(d),l=ft(a.harness_type),v=ee(d,l),g=H(a.model),u=g??y().modelFor(d,s,c,v);if(u&&!g&&(a[Ce]=u),a.thinking===void 0){let p=y().thinkingFor(d,c,v,t.thinkingLevel);p!==void 0&&(a[Ie]=p)}}}o(ei,"toolCallListener");import{Type as He}from"typebox";var Gn="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).",Mt=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:Gn})},{additionalProperties:!1,required:["agent_ids"]});function $t(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"}}o($t,"formatBasis");function Yn(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${$t(e.basis)})`}o(Yn,"formatSettlement");function Nt(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 (${$t(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`}}o(Nt,"formatKeptReason");function Fn(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)"}}o(Fn,"paneText");function zn(e){return e.length===0?"none (the agent never had a pane)":e.map(t=>`${t.paneId} ${Fn(t)}`).join(", ")}o(zn,"panesText");function Vn(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"}}o(Vn,"paneSummary");function Qn(e){if(e.length===0)return"no pane";if(e.length===1)return Vn(e[0]);let t=new Map;for(let r of e)t.set(r.kind,(t.get(r.kind)??0)+1);let n=[...t].map(([r,s])=>`${s} ${r}`).join(", ");return`${e.length} panes (${n})`}o(Qn,"panesSummary");function Dt(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)"}}o(Dt,"worktreeText");function Ht(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})`:""}`}o(Ht,"branchText");function Xn(e){return e?` forced${e.reason?` \u2014 ${Nt(e.reason)}`:""}`:""}o(Xn,"forcedClause");function Be(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Nt(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${Xn(e.outcome.forced)}:`}o(Be,"headline");function Bt(e){let t=[Be(e),` agent status: ${Yn(e.settlement)}`,` panes: ${zn(e.panes)}`,` worktree: ${Dt(e.worktree)}`,` branch: ${Ht(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:r}=e.settlement.deliverable;t.push(r?` deliverable: UNREAD at ${n} \u2014 read it before deleting the directory`:` deliverable: none written (${n} does not exist)`)}return t.join(`
9
+ `)}o(Bt,"renderCleanupReport");function ii(e){let t=Qn(e.panes);return e.outcome.kind==="refused"?`${Be(e)} ${t}`:`${Be(e)} ${t}, worktree ${Dt(e.worktree)}, branch ${Ht(e)}`}o(ii,"summarizeCleanupReport");function si(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}o(si,"cleanupNeedsAttention");var Lt={name:h.cleanupAgent,label:h.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:Mt,execute:eo,constrainedSampling:k};function Zn(e){return e.kind==="unknown"?"warning":e.report.outcome.kind==="torn-down"?"success":"warning"}o(Zn,"cleanupSeverity");function Jn(e){switch(e.kind){case"cleaned":return Bt(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}o(Jn,"renderCleanupOutcome");async function eo(e,t,n,r,s){let a=t.agent_ids;return R({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:Jn,severity:Zn,handleItem:o(async i=>{let d=w();if(!d.getSpawn(i)&&(await d.locate(i)).kind==="not-found")return{kind:"unknown",agentId:i,activeAgents:I(d)};let c=await d.cleanup(i);return{kind:"cleaned",agentId:i,report:c}},"handleItem")})}o(eo,"executeCleanupAgentTool");import*as qt from"node:fs";import*as L from"node:path";import{Type as E}from"typebox";var to="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.",no="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",oo="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.",jt=E.Object({branches:E.Array(E.String({minLength:1}),{minItems:1,description:to}),target:E.Optional(E.String({description:no})),repo:E.Optional(E.String({description:oo}))},{additionalProperties:!1,required:["branches"]});function Ut(e){let t=L.normalize(e),{root:n}=L.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}o(Ut,"normalizeRepoRoot");function ro(e,t){return Ut(e)===Ut(t)}o(ro,"isSameRepoRoot");function io(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}o(io,"formatOutsideRepoWarning");async function so(e,t){let n=new it(e),r=await n.probe(["rev-parse","--show-toplevel"],t);if(r===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 s=await n.probe(["rev-parse","--git-common-dir"],r);if(s===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}=st(s,r);if(!qt.existsSync(L.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}o(so,"resolveSessionMainRoot");var Wt={name:h.mergeBranch,label:h.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:jt,execute:go,constrainedSampling:k};function ao(e){switch(e.kind){case"merged":return"success";case"already-merged":case"unknown":case"not-attempted":return"warning";case"conflict":case"failed":return"error"}}o(ao,"mergeSeverity");var lo="has conflicts in:";function co(e){return e.includes(lo)}o(co,"isConflictError");function uo(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
10
+ `).map(n=>n.trim()).filter(n=>n!==""):[]}o(uo,"parseConflictFiles");function po(e,t){return e.includes(`branch "${t}" does not exist`)}o(po,"isUnknownBranchError");async function go(e,t,n,r,s){let a=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",i=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,d,c=o(()=>(d??=(async()=>{let l=z().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 so(S(),l),cwd:i??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:ao,prepare:o(async()=>{Se(a,"target");for(let l of t.branches)Se(l.trim(),"branch");await c()},"prepare"),halt:{on:o(l=>l.kind==="conflict","on"),skip:o((l,v)=>{let g=l.trim(),u=`not attempted \u2014 the merge of "${v.trim()}" conflicted and is still in progress`;return{outcome:{kind:"not-attempted",branch:g,reason:u},text:`"${g}" ${u}.`}},"skip")},handleItem:o(async l=>{let{sessionRoot:v,cwd:g}=await c(),u=l.trim();try{let p=await dt(S(),{cwd:g,branch:u,target:a}),f=ro(p.mainRoot,v)?void 0:io(p.mainRoot,v);if(f!==void 0)try{s.ui.notify(f,"warning")}catch{}let b=f!==void 0?`${f}
11
+ `:"";return p.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${b}"${u}" is already merged into "${p.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:p.target,output:p.output},text:`${b}Merged "${u}" into "${p.target}" in ${p.mainRoot}.`+(p.output?`
12
+ ${p.output}`:"")}}catch(p){let f=p instanceof Error?p.message:String(p);return co(f)?{outcome:{kind:"conflict",branch:u,target:a,files:uo(f)},text:`"${u}": ${f}`}:po(f,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${f}`}:{outcome:{kind:"failed",branch:u,error:f},text:`"${u}": ${f}`}}},"handleItem")})}o(go,"executeMergeBranchTool");import{Type as ue}from"typebox";var ho="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.",mo="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.",Kt=ue.Object({agent_ids:ue.Array(ue.String({minLength:1}),{minItems:1,description:ho}),message:ue.String({description:mo})},{additionalProperties:!1,required:["agent_ids","message"]});var Gt={name:h.steerAgent,label:h.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:Kt,execute:yo,constrainedSampling:k};function fo(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}o(fo,"steerSeverity");async function yo(e,t,n,r,s){let a=t.message.trim();return R({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,severity:fo,prepare:o(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:o(async i=>{let d=w().getSpawn(i);if(!d){let g=`not found. Active agents: ${I()}`;return{outcome:{kind:"refused",agentId:i,reason:g},text:`Agent ${i} was not steered: ${g}`}}let c=O(d.lifecycle),l;try{l=await w().steer(i,a)}catch(g){l={kind:"refused",reason:`steering failed: ${$(g)}`}}if(l.kind==="refused")return{outcome:{kind:"refused",agentId:i,reason:l.reason},text:`Agent ${i} was not steered (${c}): ${l.reason}`};if(l.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:i,reason:l.reason},text:`Agent ${i} 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:i},text:v?`Agent ${i} 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 ${i}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${i} was delivered to (${c}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}o(yo,"executeSteerAgentTool");import{Type as A}from"typebox";var wo="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.",vo=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${K.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.`,bo=`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.`,ko="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",Yt=A.Object({agent_id:A.String({minLength:1,description:wo}),harness_type:A.String({description:vo}),model:A.Optional(A.Union([A.String(),A.Null()],{description:bo})),thinking:A.Optional(A.Union([A.String(),A.Null()],{description:ko}))},{additionalProperties:!1,required:["agent_id","harness_type"]});function So(e){let t=e.trim();if(t==="")return{kind:"faulted",fault:{kind:"request-refused",detail:"`harness_type` is required \u2014 name the harness that runs the next run. Nothing was changed."}};let n=C();if(n.get(t)===void 0)return{kind:"faulted",fault:{kind:"request-refused",detail:`Unknown harness_type "${t}": this session registered ${n.ids().join(", ")}. Nothing was changed \u2014 name a registered harness that runs the next run.`}};let r=Q();return Ue(t,r)?{kind:"ready",harness:t}:{kind:"faulted",fault:{kind:"request-refused",detail:`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${qe(n.ids(),r).join(", ")}. Nothing was changed.`}}}o(So,"resolveTargetHarness");async function Ao(e,t){let n=So(e.harness_type);if(n.kind==="faulted")return n;let r=n.harness;try{let s=await le(ae(e),{harness:r,registry:t.modelRegistry,parent:t.model,thinking:se(e),listModels:o(async a=>{let i=await C().require(a).listModels({pi:S(),modelCatalog:N(t.modelRegistry)}),d=Y(i);return d!==void 0&&t.hasUI&&t.ui.notify(d,"warning"),G(i)},"listModels")});for(let a of s.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:r,modelChoice:de(s.resolved)}}catch(s){return{kind:"faulted",fault:{kind:"request-refused",detail:$(s)}}}}o(Ao,"resolveIntent");function To(e,t){return`Agent ${e} ${xo(t)}`}o(To,"renderHandoverOutcome");function xo(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":` ${e.loss.excluded} of ${e.loss.total} session records could not be read and were omitted from the transcript.`;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.`}}o(xo,"handoverReport");async function Ro(e,t,n,r,s){let a=t.agent_id.trim(),i=await Ao(t,s),d=i.kind==="faulted"?{kind:"faulted",fault:i.fault}:await w().handover(a,{harness:i.harness,modelChoice:i.modelChoice});return B(tt(d),To(a,d),{agentId:a,outcome:d})}o(Ro,"executeHandoverAgentTool");var Ft={name:h.handoverAgent,label:h.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:Yt,execute:Ro,constrainedSampling:k};import{Text as Oo}from"@earendil-works/pi-tui";var _o={success:"\u2713",warning:"!",error:"\u2717"};function Co(e,t,n,r){let s=e.content.map(d=>d.text??"").join(`
13
+ `),a=r.isError?"error":e.details?.severity??"success",i=a==="success"?s:n.fg(a,s);return new Oo(`${n.fg(a,_o[a])} ${i}`,0,0)}o(Co,"renderCowboyToolResult");function P(e){return{...e,renderResult:Co}}o(P,"withCowboyRenderer");var Eo=_e?ie:ie.filter(e=>e!==h.handoverAgent);function Po(e){let t=M.Object({prompt:D.properties.agents.items.properties.prompt,task_name:D.properties.agents.items.properties.task_name,agent_type:M.Optional(M.Union([M.String(),M.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:D.properties.agents.items.properties.model,harness_type:D.properties.agents.items.properties.harness_type},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:D.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}o(Po,"cowboyAgentsSchemaWithTypes");function Vt(e){let t=Po(ut()),n={name:h.agent,label:h.agent,description:"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.",parameters:t,execute:Et,constrainedSampling:k};e.registerTool(P(n))}o(Vt,"registerAgentTool");function Mo(e,t){y().mutate.agent.setExtensionEnabled(t),t?$o(e):No(e)}o(Mo,"setExtensionEnabled");function $o(e){let t=S();Vt(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Eo])]),re(e)}o($o,"activateExtension");function No(e){let t=S();t.setActiveTools(t.getActiveTools().filter(n=>!ie.includes(n))),re(e)}o(No,"deactivateExtension");function fs(e){Vt(e),e.registerTool(P(Pt)),e.registerTool(P(Wt)),e.registerTool(P(Gt)),_e&&e.registerTool(P(Ft)),e.registerTool(P(Lt)),e.registerMessageRenderer("subagent-result",(t,n,r)=>{let s=typeof t=="object"&&typeof t.content=="string"?t.content:"",a=/\b(error|stopped)\b/.test(s.slice(0,200)),i=r.fg(a?"error":"success",a?"\u2717":"\u2713");return new Io(`${i} ${s}`,0,0)})}o(fs,"registerTools");async function zt(e,t){let n=await C().listModelOptions({pi:e,modelCatalog:N(t.modelRegistry)},Q());for(let r of n.notices)t.ui.notify(r,"warning");return n.options}o(zt,"harnessModelOptions");var Qt="cowboy",Do={wt:"worktree",sp:"spawn",st:"status"};function ys(e,t){e.registerCommand(Qt,{description:t,handler:o(async(n,r)=>{r.ui.notify(t,"warning")},"handler")})}o(ys,"registerUnavailableCowboyCommand");function ws(e){e.registerCommand(Qt,{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:o(async t=>(await import("./model-picker-FMMQY4KI.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:o(async(t,n)=>{ot(n);let[r,...s]=t.trim().split(/\s+/),a=Do[r]??r,i=[a,...s].join(" ");if(i==="enable"||i==="disable"){let l=i==="enable";if(l&&ke()===null){n.ui.notify(me,"warning");return}if(oe()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}Mo(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(ke()===null){n.ui.notify(me,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-THJ3VSWU.js");await l(n,s.join(" "));return}if((a==="model"||i==="spawn"||i==="status")&&!oe()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-FMMQY4KI.js");await l(s.join(" "),n);return}if(i==="spawn"||i==="status"){let{showAgentsActionMenu:l}=await import("./menus-KXKDXZRN.js");await l(n,i,await zt(e,n));return}if(i!==""){n.ui.notify(`Unknown option "${r}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-KXKDXZRN.js");await c(n,await zt(e,n))},"handler")})}o(ws,"registerCowboyCommand");import*as Xt from"node:fs";import{tmpdir as Ho}from"node:os";import*as pe from"node:path";async function Zt(e,t){try{return await rt(e).probe(t),j(We)}catch{return j(["checkout"])}}o(Zt,"detectCowAvailability");function Jt(e){let t=pe.resolve(e??Le());for(;;){try{if(Xt.statSync(t).isDirectory())return t}catch{}let n=pe.dirname(t);if(n===t)return Ho();t=n}}o(Jt,"probeTargetFor");function Bo(e){return(t,n,r)=>e.exec(t,n,r)}o(Bo,"execOf");function Es(e){return en(e,be())}o(Es,"startCowSupportProbe");function Ps(e){let t=be();return V(t,je()),en(e,t)}o(Ps,"refreshCowSupportProbe");function en(e,t){let n=Jt(y().agent.worktreeRoot);return Zt(Bo(e),n).then(r=>{V(t,r)},()=>{V(t,j(["checkout"]))})}o(en,"probe");export{$e as a,Hn as b,Bn as c,ei as d,Nt as e,ii as f,si as g,Oe as h,oe as i,Yo as j,Es as k,Ps as l,Mo as m,$o as n,No as o,fs as p,ys as q,ws as r};
14
+ //# sourceMappingURL=chunk-TFQCH2TO.js.map
@@ -25,6 +25,7 @@ interface ResolvedAgentSettings {
25
25
  readonly worktreeRoot: string | undefined;
26
26
  readonly worktreeMaterialization: WorktreeMaterialization;
27
27
  readonly worktreeCheckoutType: WorktreeCheckoutType;
28
+ readonly handoverMaxExcludedRatio: number;
28
29
  readonly harnessType: AnyHarnessId;
29
30
  }
30
31
  interface ConfigStoreDeps {
@@ -2,8 +2,7 @@ import type { SubagentsConfig } from "../models/model-precedence.js";
2
2
  import { type ConfigIO, type ConfigPaths, type ConfigTarget, type RawConfig } from "./config-io.js";
3
3
  export declare class LayeredConfig {
4
4
  private io;
5
- private globalRaw;
6
- private projectLayer;
5
+ private files;
7
6
  constructor(io?: ConfigIO);
8
7
  get paths(): ConfigPaths;
9
8
  get effective(): SubagentsConfig;
@@ -15,6 +14,6 @@ export declare class LayeredConfig {
15
14
  reload(): void;
16
15
  mutate(target: "global" | "project", update: (raw: RawConfig) => void): boolean;
17
16
  clear(target: ConfigTarget | "all", update: (raw: RawConfig) => void, clearSession: () => void): void;
17
+ private loadedOrWarn;
18
18
  private globalWritableOrWarn;
19
- private projectLayerToWrite;
20
19
  }
@@ -0,0 +1,13 @@
1
+ export declare const COWBOY_TOOLS: {
2
+ readonly agent: "cowboy_agent";
3
+ readonly stopAgent: "stop_cowboy_agent";
4
+ readonly mergeBranch: "merge_cowboy_branch";
5
+ readonly steerAgent: "steer_cowboy_agent";
6
+ readonly handoverAgent: "handover_cowboy_agent";
7
+ readonly cleanupAgent: "cleanup_cowboy_agent";
8
+ };
9
+ export declare const COWBOY_TOOL_NAMES: readonly string[];
10
+ export declare const CONSTRAINED_SAMPLING: {
11
+ readonly type: "json_schema";
12
+ readonly strict: "prefer";
13
+ };
@@ -0,0 +1 @@
1
+ export declare const DEV_MODE: boolean;