pi-cowboy 0.27.0 → 0.27.3

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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- **✨ NEW FEATURE - Cross-harness handover: pi-cowboy can now handover sessions between harnesses automatically. Ask pi to hand over a cowboy agent from one harness to another, or [use the menu](docs/Menu.md#handing-over-and-exporting).**
1
+ **✨ NEW FEATURE - Cross-harness handover: pi-cowboy can now handover sessions between harnesses automatically. Ask pi to hand over a cowboy agent from one harness to another, or [use the menu](https://github.com/electric-dragon-80000v/pi-cowboy/blob/main/docs/Menu.md#handing-over-and-exporting).**
2
2
  <p align="center">
3
3
  <img src="https://raw.githubusercontent.com/electric-dragon-80000v/pi-cowboy/main/docs/assets/logo-labeled-readme.png" alt="pi-cowboy">
4
4
  </p>
@@ -9,7 +9,6 @@
9
9
 
10
10
  **License:** MIT
11
11
 
12
-
13
12
  `
14
13
  `pi-cowboy` is a multi-agent orchestrator for [pi](https://pi.dev). Break a large job into focused subtasks, hand them off to background agents running in parallel, and consolidate them when they finish.
15
14
 
@@ -25,7 +24,7 @@ Give each agent a smaller, isolated subtask. A single task with clear instructio
25
24
 
26
25
  ### Foreign harness support
27
26
 
28
- `pi-cowboy` can orchestrate Claude Code, Codex, OpenCode, and more: start work on Pi, continue on Claude Code, finish on OpenCode. Do you need support for something else? Create an issue on [GitHub](https://github.com/electric-dragon-80000v/pi-cowboy/issues/new).
27
+ `pi-cowboy` can orchestrate Claude Code, Codex, OpenCode, and more: start work on Pi, continue on Claude Code, finish on OpenCode. Hit the 5 hour limit in the middle of your Claude Code session? Ask pi-cowboy to hand it over to Codex and it will carry over your Claude session automatically. No session dumps, no re-explaining, it just picks up right where you left off Do you need support for another harness? Create an issue on [GitHub](https://github.com/electric-dragon-80000v/pi-cowboy/issues/new), or write your own [plugin](https://github.com/electric-dragon-80000v/pi-cowboy/blob/main/docs/Plugins.md) for it.
29
28
 
30
29
  ### Parallel work with minimal disk overhead
31
30
 
@@ -1,2 +1,2 @@
1
- import{Da as x}from"./chunk-GYO352IF.js";import{a as s,e as f,l as C}from"./chunk-XXNZAWMK.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-ROCBRG4A.js.map
1
+ import{Da as x}from"./chunk-NF3DL7IL.js";import{a as s,e as f,l as C}from"./chunk-XXNZAWMK.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-5Q6BGTTQ.js.map
@@ -1,4 +1,4 @@
1
- import{B as Ze,C as K,Ga as X,J as Je,L as et,M as me,N as W,S as tt,da as nt,ea as Q,h as Ge,i as Ue,l as le,m as Ve,ma as B,n as qe,q,qa as rt,r as Ke,u as Qe,w as ue,wa as D,y as Ye,za as Y}from"./chunk-GYO352IF.js";import{a as i,d as I,i as pe,j as fe,s as Xe}from"./chunk-XXNZAWMK.js";import*as v from"node:fs";import*as k from"node:path";var fn=`import ctypes, sys
1
+ import{B as Ze,C as K,Ga as X,J as Je,L as et,M as me,N as W,S as tt,da as nt,ea as Q,h as Ge,i as Ue,l as le,m as Ve,ma as B,n as qe,q,qa as rt,r as Ke,u as Qe,w as ue,wa as D,y as Ye,za as Y}from"./chunk-NF3DL7IL.js";import{a as i,d as I,i as pe,j as fe,s as Xe}from"./chunk-XXNZAWMK.js";import*as v from"node:fs";import*as k from"node:path";var fn=`import ctypes, sys
2
2
  libc = ctypes.CDLL(None, use_errno=True)
3
3
  # CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
4
4
  if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
@@ -23,4 +23,4 @@ Error: {{error}}{{/error}}{{#has_worktree}}
23
23
  `);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}i(Yn,"describeParseError");var Xn={label:"File",problem:"was skipped"};async function ne(e,t,n,r,o=Xn,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(Kn)),l=[];for(let d of c){let f=Et.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}: ${Yn(m)}`,"warning")}}return l}i(ne,"scanTemplateFilesInDir");import{z as P}from"zod";import Pt from"mustache";function At(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}i(At,"worktreeVariables");function Zn(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}i(Zn,"outcomeVariables");function Jn(e){return e?{...At(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}i(Jn,"settledWorktreeVariables");function er(e){return e.worktree?{agent_id:e.agentId,...At(e.worktree)}:{agent_id:e.agentId}}i(er,"spawnCueContext");function Do(e){return{...er(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}i(Do,"queuedCueContext");function Mo(e){let{outcome:t,statusNote:n,worktree:r,multiplexerId:o}=e;return{...Zn(t),...n?{status_note:n}:{},...Jn(r),...o!=null?{multiplexer_id:o}:{}}}i(Mo,"settledCueContext");var tr={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},nr={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},rr={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},or=Object.keys(tr),ir=Object.keys(nr),ar=Object.keys(rr);function Ot(e){switch(e){case"spawned":return or;case"queued":return ir;case"settled":return ar;default:return}}i(Ot,"cueVariables");var sr={ok:!0},cr="&",dr=new Set(["name",cr,"#","^"]);function Ho(e,t,n){return Pt.render(e[t],n,void 0,{escape:i(r=>r==null?"":String(r),"escape")})}i(Ho,"renderCue");function lr(e){let t=e[4];return Array.isArray(t)?t:void 0}i(lr,"spanChildren");function St(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(dr.has(o)&&!t.includes(a))return`unknown variable "{{${a}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let s=lr(r);if(s){let c=St(s,t,n);if(c)return c}}}i(St,"findTemplateProblem");function _t(e,t){let n=Ot(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let r;try{r=Pt.parse(t)}catch(a){return{ok:!1,reason:`unparsable template: ${(a instanceof Error?a.message:String(a)).replace(/\s+/g," ").trim()}`}}let o=St(r,n,e);return o?{ok:!1,reason:o}:sr}i(_t,"validateCueTemplate");var ur=["spawned","queued","settled"],pr=P.strictObject({spawned:P.string().optional(),queued:P.string().optional(),settled:P.string().optional()}).superRefine((e,t)=>{for(let n of ur){let r=e[n];if(r===void 0)continue;let o=_t(n,r);o.ok||t.addIssue({code:"custom",message:o.reason,path:[n]})}}),Wt=P.strictObject({name:P.string().optional(),display_name:P.string().optional(),guidance:P.string().optional(),cues:pr.optional()});var fr={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function mr(e){return Wt.parse(te(e))}i(mr,"parseOrchestratorFile");async function H(e,t){return ne(e,mr,n=>n.name,t,fr)}i(H,"scanOrchestratorFilesInDir");function Ee(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,hr(o.get(c.name)??gr(c.name,a),c));return o}i(Ee,"mergeOrchestrators");function gr(e,t){return{...t,name:e,displayName:e}}i(gr,"namedBase");function hr(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(hr,"applyOverride");function z(){return X().orchestrators}i(z,"registry");function ri(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(ri,"registerOrchestrators");function oi(e,t,n){z().scanDirs={user:e,project:t,shared:n??""}}i(oi,"setOrchestratorScanDirs");async function ii(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,r=z().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):H(Ue,n),H(r.user,n),H(r.shared,n),H(r.project,n)]),d=Ee(t?new Map:O,o,[],[]);return Ee(d,a,s,c)}i(ii,"scanAndMergeOrchestrators");function Ae(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(Ae,"resolveOrchestrator");function ai(){return[...z().orchestrators.values()].map(e=>e.name)}i(ai,"getAvailableOrchestrators");import{z as p}from"zod";var Ft=p.union([p.boolean(),p.array(p.string())]),kr={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)=>nt(t,{reserved:Xe[e],report:i((r,o)=>n.addIssue({code:"custom",path:[r],message:kr[o]}),"report")}))}i(oe,"envTable");var $t={model:p.string().optional(),thinking:et.optional(),extensions:Ft.optional(),skills:Ft.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()},yr=p.strictObject($t),wr=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()}),br=p.strictObject({model:p.string().optional(),thinking:p.string().optional(),env:oe("codex").optional()}),Cr=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 Oe(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}i(Oe,"toToolFilter");function re(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}i(re,"nonEmptyEnv");var vr=p.strictObject({include_context_files:p.boolean().optional(),pi:yr.optional(),opencode:wr.optional(),codex:br.optional(),claude:Cr.optional(),...$t}).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:Xt,variant:Zt,tools:Jt,exclude_tools:en,env:tn,...nn}=A(t??{}),{model:rn,thinking:on,env:an,...sn}=A(n??{}),{model:cn,thinking:dn,tools:ln,exclude_tools:un,env:pn}=A(r??{}),je=A({pi:u??a,opencode:Xt,codex:rn,claude:cn}),Le=A({pi:Oe(x??c,de??l),opencode:Oe(Jt,en),claude:Oe(ln,un)}),He=A({pi:m??s,opencode:Zt,codex:on,claude:dn}),ze=A({pi:re(Q(d,V)),opencode:re(tn),codex:re(an),claude:re(pn)});return{...f,...R,...nn,...sn,...Object.keys(je).length>0?{modelsByFamily:je}:{},...Object.keys(Le).length>0?{toolsByFamily:Le}:{},...Object.keys(He).length>0?{thinkingByFamily:He}:{},...Object.keys(ze).length>0?{envByFamily:ze}:{}}}),It=p.strictObject({name:p.string().optional(),display_name:p.string().optional(),description:p.string().optional(),hidden:p.boolean().optional(),worktree_checkout_type:p.enum(Ke).optional(),system_prompt:p.string().optional(),harness_type:p.string().min(1).optional(),harness:vr.optional()});function xr(e){return It.parse(te(e))}i(xr,"parseAgentFile");var Rr={label:"Agent",problem:"is not a valid agent template and was skipped"};async function N(e,t,n){return ne(e,xr,r=>r.name,t,Rr,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 Pe(o,t),Pe(o,n),Pe(o,r),o}i(ie,"mergeAgents");function Pe(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=Dt(n),s=Tr(r.modelsByFamily,a.modelsByFamily),c=Er(r.toolsByFamily,a.toolsByFamily),l=Ar(r.thinkingByFamily,a.thinkingByFamily),d=Or(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,{...Pr,...Dt(n)})}}i(Pe,"mergeAgentOverrides");function Tr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Tr,"mergeModelsByFamily");function Er(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Er,"mergeToolsByFamily");function Ar(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Ar,"mergeThinkingByFamily");function Or(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(Or,"mergeEnvByFamily");function Dt(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(Dt,"fromTemplate");var Pr={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Se=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 Ai(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[r,o]of Se)n.set(r,o);for(let[r,o]of e)n.set(r,o);S().agents=n}i(Ai,"registerAgents");function Oi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}i(Oi,"setAgentScanDirs");async function Sr(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,r=S().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):N(Ge,n,G),N(r.user,n,G),N(r.shared,n,G),N(r.project,n,G)]),d=ie(t?new Map:Se,o,[],[]);return ie(d,a,s,c)}i(Sr,"scanAndMerge");async function _r(e,t){let n=await Sr(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(_r,"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 Pi(e,t,n){let r=U(e);return r.kind==="not-found"&&(await _r(t,{notify:n}),r=U(e)),r}i(Pi,"resolveTypeOrDiscover");function ae(e){let t=U(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}i(ae,"getAgentConfig");function Si(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}i(Si,"getAvailableTypes");function _i(){return[...S().agents.keys()]}i(_i,"getAllTypes");function Mt(e,t,n,r){return{skills:e??n,extensions:t??r}}i(Mt,"applyGlobalDefaults");function Wi(e,t=!0,n=!0){let r=ae(e);if(r){let{skills:a,extensions:s,...c}=r,l=Mt(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",...Mt(void 0,void 0,t,n)}}i(Wi,"getConfig");function Nt(e){return typeof e=="string"&&e!==""?e:void 0}i(Nt,"configuredString");function Wr(){let e=Nt(B().agent.defaultAgentType);if(e===void 0)return me;let t=U(e);return t.kind==="resolved"?t.key:me}i(Wr,"resolveDefaultAgentType");function Fr(){let e=Nt(B().agent.defaultOrchestrator);return e===void 0?W:e===W||Ae(e)?e:W}i(Fr,"resolveDefaultOrchestratorName");function Li(e){return typeof e=="string"&&e!==""?e:Wr()}i(Li,"resolveAgentTypeParam");function Hi(){let e=Fr();return Ae(e)??(e===W?O[W]:void 0)??O[W]}i(Hi,"resolveDefaultOrchestrator");function Bt(e){return ae(e)?.worktreeCheckoutType??B().agent.worktreeCheckoutType}i(Bt,"resolveWorktreeCheckoutType");function jt(e){return typeof e=="string"&&e.trim()!==""?e:void 0}i(jt,"harnessParam");function zi(e){let t=jt(e);if(t!==void 0&&D().get(t)!==void 0)return le(t,Y())?t:void 0}i(zi,"requestedHarnessId");function Gi(e){let t=jt(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 ${Ve(n.ids(),r).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}i(Gi,"resolveRequestedHarness");function Ui(e,t){if(t!==void 0)return t;let n=ae(e)?.harnessType??B().agent.harnessType;return D().resolve(n,Y())}i(Ui,"resolveHarnessType");function _e(e){return{kind:"recorded",phase:e.lifecycle.phase}}i(_e,"recordedSettlement");function Lt(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(Lt,"planRecovered");async function We(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(We,"assessRemovability");function Ht(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 fe(e.state)}}i(Ht,"recoveryGate");function Fe(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(Fe,"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 zt(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(zt,"ambiguousReport");function $e(e){return e?.force!==void 0?{forced:e.force}:{}}i($e,"forcedFields");function Gt(e,t,n,r,o,a){return{agentId:e,source:t,outcome:{kind:"torn-down",...$e(a)},branchName:n.kind==="worktree"?n.worktree.branchName:void 0,settlement:r,panes:o.panes,worktree:o.worktree,branch:o.branch}}i(Gt,"assembleReport");function Qi(e){return e.outcome.kind==="refused"&&e.outcome.forceable}i(Qi,"isForceableRefusal");function Ie(e){return e.worktree.kind==="removed"||e.worktree.kind==="absent"?!0:e.worktree.kind==="none"?e.panes.every(t=>t.kind==="closed"):!1}i(Ie,"shouldDropSpawn");function De(e){return e.workspaceId!==void 0?"multiplexer":"git"}i(De,"removalMechanismOf");function Ut(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 fe(t.mechanism)}}i(Ut,"paneDispositionFor");var $r=Je("cleanup");function Ir(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(Ir,"hostRefFor");async function Vt(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(Vt,"removeOwnedTree");async function ce(e,t,n){let r=[];for(let o of t)switch(Ut(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 Dr(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(Dr,"paneOutcomesForAbsentTree");async function Mr(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 Vt(e,r,n);return a.kind==="removed"?{panes:await ce(e,o,{kind:"removed",mechanism:De(r),workspaceId:r.workspaceId}),worktree:a,branch:await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd})}:{panes:await ce(e,o,{kind:"retained"}),worktree:a,branch:{kind:"not-applicable"}}}i(Mr,"removeResources");function Me(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 We(e.isWorktreeDirty,n,r);if(s.kind==="kept")return{kind:"kept",path:r.worktreePath,reason:s.reason};let c=await Vt(e,r,a);if(c.kind==="removal-failed")return c;let l=De(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(Me,"createWorktreeTeardown");function Nr(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(Nr,"environmentPanes");function Br(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(Br,"teardownRuns");function na(e){let t=Me(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=_e(c);return tt(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:Fe(m),forceable:!0}}let f=Ht(d);return f.kind==="allow"?{kind:"torn-down",settlement:n(a,f.basis)}:{kind:"refused",settlement:n(a,f.basis),reason:Fe(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 zt(a,l===void 0?"recovered":"tracked",l===void 0?n(a,{kind:"artifacts-ambiguous"}):_e(l),d.candidates.map(R=>R.worktreePath));let f=Ir(d,e.multiplexer),u=Lt(d,Nr(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=Br(l,d);if(x.length>0)try{await e.teardownEnvironment({subagentId:a,runs:x})}catch(R){$r.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",...$e(c)},branchName:u.branchName,settlement:m.settlement,panes:await Dr(e,u.panes),worktree:{kind:"absent",path:u.worktreePath},branch:{kind:"not-applicable"}};return Ie(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 We(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 Mr(e,u,f),V=Gt(a,d.source,u,m.settlement,de,c);return Ie(V)&&l!==void 0&&s.dropSpawn(l),V}return i(o,"cleanupAgent"),{...t,cleanupAgent:o}}i(na,"createCleanup");import*as qt from"node:path";async function jr(e,t,n){let r=await we(e,["rev-parse","--verify","--quiet",`refs/heads/${n}`],t,E);return r===void 0?!0:r.code===0}i(jr,"branchExisted");async function Kt(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=qt.resolve(t.path),a=t.materialization??qe,s=t.dirtyCheckout??q,c=await jr(e,r,n),l=await we(e,["worktree","add",...ht(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 mt(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 kt(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(Kt,"createWorktreeCheckout");function ha(e){return e.kind==="checkout"?e.branch:ue(e.taskSlug??Qe(e.type),e.id)}i(ha,"spawnAgentName");function Lr(e){try{let t=_.statSync(e,{bigint:!0});return`${t.dev}:${t.ino}`}catch{return $.resolve(e)}}i(Lr,"canonicalRepoKey");async function ka(e){let t=await Ne.allocate(e.pi,{naming:{kind:"generated",taskSlug:e.taskSlug??e.agentType,id:e.spawnId},parentCwd:e.parentCwd,worktreeRoot:e.worktreeRoot,materialization:e.materialization,dirtyCheckout:Bt(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(ka,"provisionOwnedCheckout");var Ne=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"?ue(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 zr(t,{repoCwd:u,path:$.join(Ye(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 Me(Ur(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=Hr(o),o}};function Hr(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(Hr,"stateAfterTeardown");async function zr(e,t){let n=$.resolve(t.path);return _.mkdirSync($.dirname(n),{recursive:!0}),rt().run(Lr(t.repoCwd),()=>Gr(e,t.host,{...t,path:n}))}i(zr,"createAdoptedWorktree");async function Gr(e,t,n){let{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:l}=n,d;try{d=await Kt(e,{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:l})}catch(u){throw Yt(u,await Qt(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 Qt(e,r,d.path),x=await M(e,d.branch,r);throw Yt(u,`${m}. ${Be(d.branch,x)}`)}return{path:d.path,branch:d.branch,repoCwd:r,materialization:d.materialization,ref:f}}i(Gr,"adoptWorktree");function Ur(e,t){return{isWorktreeDirty:i(n=>Rt(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=>vt(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(Ur,"cleanupDeps");async function Qt(e,t,n){return await F(e,t,n),_.existsSync(n)?`worktree ${n} NOT removed \u2014 inspect it manually`:`worktree ${n} removed`}i(Qt,"removeFailedCheckout");function Yt(e,t){return new Error(`could not create the herdr worktree: ${I(e)}
24
24
 
25
25
  Launch-failure cleanup: ${t}.`)}i(Yt,"createFailureMessage");function Be(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(Be,"formatLaunchedBranchOutcome");function ya(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. ${Be(e.branchName,e.branch)}.`:`Launch-failure cleanup: worktree ${e.path} removed. ${Be(e.branchName,e.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${e.path} KEPT \u2014 ${Tt(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(ya,"formatLaunchCleanupNote");export{qr as a,pt as b,b as c,mt as d,j as e,Xr as f,J as g,F as h,to as i,no as j,yt as k,go as l,vt as m,Rt as n,bo as o,Tt as p,Se as q,Ai as r,Oi as s,Sr as t,Pi as u,ae as v,Si as w,_i as x,Wi as y,O as z,er as A,Do as B,Mo as C,Ho as D,ri as E,oi as F,ii as G,ai as H,Wr as I,Li as J,Hi as K,Bt as L,zi as M,Gi as N,Ui as O,Qi as P,na as Q,ha as R,ka as S,Ne as T,zr as U,ya as V};
26
- //# sourceMappingURL=chunk-NF2BSEPU.js.map
26
+ //# sourceMappingURL=chunk-F77A4UCS.js.map
@@ -1,4 +1,4 @@
1
- import{A as L,a as o,c as Nt,d as b,j as Be,k as Ve,l as M,m as Hn,n as Dt,o as jt,q as $t,t as p,u as ze,v as Ft,w as Gt,x as H,y as C,z as Ut}from"./chunk-XXNZAWMK.js";import*as le from"node:path";import*as Kt from"node:fs";import{homedir as Ln,tmpdir as ms}from"node:os";import*as _ from"node:path";import{fileURLToPath as Bt}from"node:url";var Wt={name:"pi-cowboy",version:"0.27.0",type:"module",packageManager:"pnpm@12.9.1",description:"Agent orchestrator for pi: can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",keywords:["pi-package","pi","pi-agent","pi-coding-agent","pi-extension","subagents","herdr","ai","agents"],license:"MIT",author:"electric-dragon-80000v",homepage:"https://github.com/electric-dragon-80000v/pi-cowboy#readme",repository:{type:"git",url:"git+https://github.com/electric-dragon-80000v/pi-cowboy.git"},bugs:{url:"https://github.com/electric-dragon-80000v/pi-cowboy/issues"},engines:{node:">=24.20.0",pnpm:">=12"},main:"./dist/index.js",types:"./dist/index.d.ts",files:["dist/","!dist/**/*.js.map","!dist/**/.*","agents/","orchestrators/","!orchestrators/with-code-review.toml","README.md","LICENSE"],exports:{".":"./dist/index.js","./plugin":"./dist/plugin/index.js","./package.json":"./package.json"},scripts:{format:"prettier --write src/ test/ scripts/ lint/ docs/","format:check":"prettier --check src/ test/ scripts/ lint/ docs/",typecheck:"tsc6 --noEmit","find-unused":"node --disable-warning=ExperimentalWarning scripts/find-unused.ts",build:"node scripts/build.ts && tsc6 -p tsconfig.build.json",prepack:"pnpm run build",test:"pnpm run build && vitest run","test:unit":"vitest run --project unit","test:integration":"pnpm run build && vitest run --project integration-no-cow --project integration-cow","test:integration-no-cow":"pnpm run build && vitest run --project integration-no-cow","test:integration-cow":"pnpm run build && vitest run --project integration-cow","dev:install":"pi remove . 2>/dev/null; pi install ./dev",lint:"oxlint","lint:fix":"oxlint --fix",commitlint:"commitlint",release:"semantic-release","release:stage":"npm stage publish","release:approve":"scripts/publish.sh",prepare:"husky"},pi:{image:"https://raw.githubusercontent.com/electric-dragon-80000v/pi-cowboy/main/docs/assets/logo-pi-package-landscape.png",video:"https://github.com/electric-dragon-80000v/pi-cowboy/raw/refs/heads/main/docs/assets/pi-cowboy.mp4",extensions:["./dist/index.js"]},peerDependencies:{"@earendil-works/pi-ai":"*","@earendil-works/pi-coding-agent":"*","@earendil-works/pi-tui":"*",typebox:"*"},devDependencies:{"@commitlint/cli":"^21.2.3","@commitlint/config-conventional":"^21.2.3","@commitlint/types":"^21.2.3","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/exec":"^7.1.0","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/estree":"^1.0.9","@types/mustache":"^4.2.6","@types/node":"^26.6.4","@vitest/coverage-v8":"5.0.3","@vitest/ui":"^5.0.3",esbuild:"^0.28.2",eslint:"^10.12.0","eslint-plugin-import-x":"^4.17.1",husky:"^9.1.7",oxlint:"1.90.0","oxlint-tsgolint":"7.0.2005",prettier:"^3.9.9","semantic-release":"^25.0.9",typescript:"npm:@typescript/typescript6@^6.0.2",vitest:"^5.0.3"},dependencies:{"jsonc-parser":"^3.3.1",mustache:"^4.2.0","smol-toml":"^1.9.0",yaml:"^2.9.1",zod:"^4.6.5"}};var Nn=Wt.name,ys="PI_CODING_AGENT_DIR";function hs(){let n=process.env[ys];return n?E(n):_.join(Ln(),".pi","agent")}o(hs,"agentDir");function E(n){return n==="~"?Ln():n.startsWith("~/")?_.join(Ln(),n.slice(2)):n}o(E,"expandTilde");function A(n){try{return Kt.realpathSync.native(n)}catch{return}}o(A,"canonicalPath");function Ye(){return _.join(hs(),Nn)}o(Ye,"defaultExtensionDir");function Vt(){return _.join(Ye(),"worktrees")}o(Vt,"defaultWorktreeRoot");function xs(){return _.join(ms(),"pi-cowboy")}o(xs,"subagentResultDir");function B(n){return _.join(xs(),n)}o(B,"subagentResultDirFor");function Tl(n){return _.join(B(n),"result.md")}o(Tl,"subagentResultFileFor");var bs="system.md",Es="prompt.md";function Cl(n){return _.join(B(n),bs)}o(Cl,"subagentSystemFileFor");var vs="env.sh";function zt(n){return _.join(B(n),vs)}o(zt,"subagentEnvFileFor");function _l(n){return _.join(B(n),Es)}o(_l,"subagentTaskFileFor");var Dn="cowboy-subagent-";function de(n){return`${Dn}${n}`}o(de,"subagentTokenFor");var Ol=Bt(new URL("../agents/",import.meta.url)),Pl=Bt(new URL("../orchestrators/",import.meta.url));function Ll(n){return{status:"known",available:new Set(n)}}o(Ll,"probed");function jn(){return{status:"unknown"}}o(jn,"unprobed");function Se(n,e){return e.status==="unknown"||e.available.has(n)}o(Se,"isAvailable");function Nl(n,e){return n.filter(t=>Se(t,e))}o(Nl,"selectable");function Yt(n,e){return e.status==="known"&&e.available.has(n)}o(Yt,"isProven");import{randomBytes as ws}from"node:crypto";import{Buffer as Ae}from"buffer";var ce="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Xt="*~$=U",Xe=class extends Error{static{o(this,"InvalidChecksumCharacterError")}constructor(e){super(e),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},$n=class extends Error{static{o(this,"InvalidChecksumError")}constructor(e){super(e),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Je=class{static{o(this,"CrockfordBase32")}static encode(e,t){Ae.isBuffer(e)?e=Ae.from(e):e=this.createBuffer(e);let r=t?.variant??"crockford",s=t?.checksum??!1;if(r==="ulid"){if(s)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(e)}let i=[],a=0,d=0;for(let u of e)for(d=d<<8|u,a+=8;a>=5;)i.push(d>>>a-5&31),a-=5;a>0&&i.push(d<<5-a&31);let c=i.map(u=>ce.charAt(u)).join("");return s&&(c+=this.computeChecksum(e)),c}static computeChecksum(e){let t=0;for(let r of e)t=(t*256+r)%37;return(ce+Xt).charAt(t)}static decode(e,t){e=e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let r=t?.variant??"crockford",s=t?.checksum??!1;if(r==="ulid"){if(s)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(e,t)}let i=null;if(s){if(e.length===0)throw new Xe("Cannot validate checksum: input is empty");let u=e.charAt(e.length-1);if((ce+Xt).indexOf(u)===-1)throw new Xe(`Invalid checksum character: ${u}`);i=u,e=e.slice(0,-1)}let a=[],d=0,c=0;for(let u of e){let m=ce.indexOf(u);if(m===-1)throw new Error(`Invalid base 32 character found in string: ${u}`);d+=5,d>=8?(d-=8,a.push(c|m>>d),c=m<<8-d&255):c|=m<<8-d}if((c>0||d>=5)&&a.push(c),i!==null){let u=this.computeChecksum(a);if(i!==u)throw new $n(`Checksum mismatch: expected '${u}' but found '${i}'`)}return t?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(e){try{return this.decode(e,{checksum:!0}),!0}catch{return!1}}static encodeUlid(e){if(e.length===0)return"";let t=0n;for(let i of e)t=t<<8n|BigInt(i);let r=[];for(;t>0n;){let i=Number(t%32n);r.unshift(ce.charAt(i)),t/=32n}let s=Math.ceil(e.length*8/5);return r.join("").padStart(s,"0")}static decodeUlid(e,t){if(e.length===0)return t?.asNumber===!0?0n:Ae.from([]);let r=0n;for(let d of e){let c=ce.indexOf(d);if(c===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);r=r*32n+BigInt(c)}let s=Math.floor(e.length*5/8),i=[],a=r;for(;a>0n;)i.unshift(Number(a&0xffn)),a>>=8n;for(r===0n&&i.push(0);i.length<s;)i.unshift(0);return t?.asNumber===!0?this.asNumber(i):this.asBuffer(i)}static createBuffer(e){if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("Input must be a safe integer");e=BigInt(e)}if(e<0n)throw new Error("Input cannot be a negative number");let t=[];for(;e>0n;)t.unshift(Number(e&0xffn)),e>>=8n;return Ae.from(t)}static asNumber(e){let t=0n;return e.forEach(r=>{t<<=8n,t|=BigInt(r)}),t}static asBuffer(e){return Ae.from(e.map(t=>t.toString(16).padStart(2,"0")).join(""),"hex")}};var qt="0123456789abcdefghjkmnpqrstvwxyz",qe=8,ks=5,Jt=32,Fn=class extends Error{static{o(this,"SpawnIdExhaustedError")}constructor(e){super(`Could not mint a unique spawn id after ${e} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function Gn(){return Je.encode(ws(ks)).toLowerCase()}o(Gn,"generateSpawnId");function Qt(n,e=Gn){for(let t=0;t<Jt;t++){let r=e();if(!n(r))return r}throw new Fn(Jt)}o(Qt,"generateUniqueSpawnId");var Qe="cow-",Re="copy-on-write",Xl=["copy-on-write","checkout"];function Jl(n){if(n==="copy-on-write"||n==="checkout")return n}o(Jl,"parseWorktreeMaterialization");function tr(n,e){return Se("copy-on-write",e)?n??Re:"checkout"}o(tr,"resolveWorktreeMaterialization");var Ze="clean",ql=["dirty","clean"];function Ql(n){if(n==="dirty"||n==="clean")return n}o(Ql,"parseWorktreeCheckoutType");var Zt=3,Ss=32,er=Ss-Qe.length-1-qe;function As(n){return n.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}o(As,"slugifyWorktreeType");function Rs(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(e=>e.length>0)}o(Rs,"taskNameWords");function Zl(n){let e=Rs(n);if(e.length===0)throw new Error("Task name is empty \u2014 provide a short 2-3 word name.");if(e.length>Zt)throw new Error(`Task name "${n}" gives the branch name "${e.join("-")}" with ${e.length} words. The limit is ${Zt} words.`);let t=e.join("-");if(t.length>er)throw new Error(`Task name "${n}" gives the branch name "${t}" with ${t.length} characters. The limit is ${er} characters, because herdr limits agent names to 32 characters.`);return t}o(Zl,"buildTaskSlug");function Is(n,e){return`${Qe}${As(n)}-${e}`}o(Is,"buildWorktreeBranch");function eu(n,e,t){return le.join(n,Is(e,t))}o(eu,"buildWorktreePath");function nu(n,e){return n&&n.trim()!==""?le.isAbsolute(n)?n:le.resolve(e,n):Vt()}o(nu,"resolveWorktreeRoot");function nr(n){return(A(n)??n.replace(/\\/g,"/")).replace(/\/+$/,"")}o(nr,"normalizeRoot");function tu(n,e){return e!==""&&n.startsWith(Qe)&&n.length>e.length&&n.endsWith(`-${e}`)}o(tu,"isSpawnArtifactName");function ru(n,e){let t=nr(n),r=nr(e);return t!==r&&!t.startsWith(`${r}/`)?!1:(t.split("/").filter(Boolean).pop()??"").startsWith(Qe)}o(ru,"isExtensionWorktree");import{getSupportedThinkingLevels as El}from"@earendil-works/pi-ai";var en=class{static{o(this,"RepoLock")}tails=new Map;async run(e,t){let r=(this.tails.get(e)??Promise.resolve()).then(t),s=r.then(()=>{},()=>{});this.tails.set(e,s);try{return await r}finally{this.tails.get(e)===s&&this.tails.delete(e)}}};import*as ue from"node:fs";import*as nn from"node:path";function F(n){for(let e of(process.env.PATH??"").split(nn.delimiter)){if(e==="")continue;let t=nn.join(e,n);try{if(!ue.statSync(t).isFile())continue;return ue.accessSync(t,ue.constants.X_OK),t}catch{}}}o(F,"commandPath");function du(n){return F(n)??n}o(du,"resolveCommand");import{readFile as Wn,readdir as Cs}from"node:fs/promises";import*as Te from"node:path";import{z as Ie}from"zod";var Ts=`[${qt}]{${qe}}`;function Un(n,e){return new RegExp(`^cow-${e}-${Ts}$`).test(n)}o(Un,"isTaskAgentName");function g(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}o(g,"isRecord");function w(n){if(typeof n!="string")return;let e=n.trim();return e===""?void 0:e}o(w,"nonEmpty");var rr=3,_s="sessionDir",Os=Ie.object({type:Ie.string(),text:Ie.string().optional()}),Ps=Ie.array(Ie.unknown());function tn(n){return`--${(A(n)??Te.resolve(n)).replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}o(tn,"sessionBucketName");async function pe(n){let e;try{e=await Wn(Te.join(n,"settings.json"),"utf8")}catch{return}let t;try{t=JSON.parse(e)}catch{return}if(g(t))return w(t[_s])}o(pe,"readSessionDirSetting");async function Ms(n,e,t){let r;try{r=await Cs(n,{withFileTypes:!0})}catch{throw new p("session-not-found",`no session record under ${n} for ${t} (subagent ${e})`)}let s=[];for(let i of r){if(!i.isFile()||!i.name.endsWith(".jsonl"))continue;let a=Te.join(n,i.name);await Hs(a)===e&&s.push(a)}if(s.length===0)throw new p("session-not-found",`no session record under ${n} for ${t} (subagent ${e})`);if(s.length>1)throw new p("ambiguous-session",`more than one session record under ${n} names subagent ${e}: ${s.join(", ")}`);return s[0]}o(Ms,"findSessionFile");async function Hs(n){let e;try{e=await Wn(n,"utf8")}catch{return}let t;for(let r of e.split(`
1
+ import{A as L,a as o,c as Nt,d as b,j as Be,k as Ve,l as M,m as Hn,n as Dt,o as jt,q as $t,t as p,u as ze,v as Ft,w as Gt,x as H,y as C,z as Ut}from"./chunk-XXNZAWMK.js";import*as le from"node:path";import*as Kt from"node:fs";import{homedir as Ln,tmpdir as ms}from"node:os";import*as _ from"node:path";import{fileURLToPath as Bt}from"node:url";var Wt={name:"pi-cowboy",version:"0.27.3",type:"module",packageManager:"pnpm@12.9.1",description:"\u{1F920} Agent orchestrator for pi. It can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents and handover sessions in between them. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",keywords:["pi-package","pi","pi-agent","pi-coding-agent","pi-extension","subagents","herdr","ai","agents"],license:"MIT",author:"electric-dragon-80000v",homepage:"https://github.com/electric-dragon-80000v/pi-cowboy#readme",repository:{type:"git",url:"git+https://github.com/electric-dragon-80000v/pi-cowboy.git"},bugs:{url:"https://github.com/electric-dragon-80000v/pi-cowboy/issues"},engines:{node:">=24.20.0",pnpm:">=12"},main:"./dist/index.js",types:"./dist/index.d.ts",files:["dist/","!dist/**/*.js.map","!dist/**/.*","agents/","orchestrators/","!orchestrators/with-code-review.toml","README.md","LICENSE"],exports:{".":"./dist/index.js","./plugin":"./dist/plugin/index.js","./package.json":"./package.json"},scripts:{format:"prettier --write src/ test/ scripts/ lint/ docs/","format:check":"prettier --check src/ test/ scripts/ lint/ docs/",typecheck:"tsc6 --noEmit","find-unused":"node --disable-warning=ExperimentalWarning scripts/find-unused.ts",build:"node scripts/build.ts && tsc6 -p tsconfig.build.json",prepack:"pnpm run build",test:"pnpm run build && vitest run","test:unit":"vitest run --project unit","test:integration":"pnpm run build && vitest run --project integration-no-cow --project integration-cow","test:integration-no-cow":"pnpm run build && vitest run --project integration-no-cow","test:integration-cow":"pnpm run build && vitest run --project integration-cow","dev:install":"pi remove . 2>/dev/null; pi install ./dev",lint:"oxlint","lint:fix":"oxlint --fix",commitlint:"commitlint",release:"semantic-release","release:stage":"npm stage publish","release:approve":"scripts/publish.sh",prepare:"husky"},pi:{image:"https://raw.githubusercontent.com/electric-dragon-80000v/pi-cowboy/main/docs/assets/logo-pi-package-landscape.png",video:"https://github.com/electric-dragon-80000v/pi-cowboy/raw/refs/heads/main/docs/assets/pi-cowboy.mp4",extensions:["./dist/index.js"]},peerDependencies:{"@earendil-works/pi-ai":"*","@earendil-works/pi-coding-agent":"*","@earendil-works/pi-tui":"*",typebox:"*"},devDependencies:{"@commitlint/cli":"^21.2.3","@commitlint/config-conventional":"^21.2.3","@commitlint/types":"^21.2.3","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/exec":"^7.1.0","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/estree":"^1.0.9","@types/mustache":"^4.2.6","@types/node":"^26.6.4","@vitest/coverage-v8":"5.0.3","@vitest/ui":"^5.0.3",esbuild:"^0.28.2",eslint:"^10.12.0","eslint-plugin-import-x":"^4.17.1",husky:"^9.1.7",oxlint:"1.90.0","oxlint-tsgolint":"7.0.2005",prettier:"^3.9.9","semantic-release":"^25.0.9",typescript:"npm:@typescript/typescript6@^6.0.2",vitest:"^5.0.3"},dependencies:{"jsonc-parser":"^3.3.1",mustache:"^4.2.0","smol-toml":"^1.9.0",yaml:"^2.9.1",zod:"^4.6.5"}};var Nn=Wt.name,ys="PI_CODING_AGENT_DIR";function hs(){let n=process.env[ys];return n?E(n):_.join(Ln(),".pi","agent")}o(hs,"agentDir");function E(n){return n==="~"?Ln():n.startsWith("~/")?_.join(Ln(),n.slice(2)):n}o(E,"expandTilde");function A(n){try{return Kt.realpathSync.native(n)}catch{return}}o(A,"canonicalPath");function Ye(){return _.join(hs(),Nn)}o(Ye,"defaultExtensionDir");function Vt(){return _.join(Ye(),"worktrees")}o(Vt,"defaultWorktreeRoot");function xs(){return _.join(ms(),"pi-cowboy")}o(xs,"subagentResultDir");function B(n){return _.join(xs(),n)}o(B,"subagentResultDirFor");function Tl(n){return _.join(B(n),"result.md")}o(Tl,"subagentResultFileFor");var bs="system.md",Es="prompt.md";function Cl(n){return _.join(B(n),bs)}o(Cl,"subagentSystemFileFor");var vs="env.sh";function zt(n){return _.join(B(n),vs)}o(zt,"subagentEnvFileFor");function _l(n){return _.join(B(n),Es)}o(_l,"subagentTaskFileFor");var Dn="cowboy-subagent-";function de(n){return`${Dn}${n}`}o(de,"subagentTokenFor");var Ol=Bt(new URL("../agents/",import.meta.url)),Pl=Bt(new URL("../orchestrators/",import.meta.url));function Ll(n){return{status:"known",available:new Set(n)}}o(Ll,"probed");function jn(){return{status:"unknown"}}o(jn,"unprobed");function Se(n,e){return e.status==="unknown"||e.available.has(n)}o(Se,"isAvailable");function Nl(n,e){return n.filter(t=>Se(t,e))}o(Nl,"selectable");function Yt(n,e){return e.status==="known"&&e.available.has(n)}o(Yt,"isProven");import{randomBytes as ws}from"node:crypto";import{Buffer as Ae}from"buffer";var ce="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Xt="*~$=U",Xe=class extends Error{static{o(this,"InvalidChecksumCharacterError")}constructor(e){super(e),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},$n=class extends Error{static{o(this,"InvalidChecksumError")}constructor(e){super(e),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Je=class{static{o(this,"CrockfordBase32")}static encode(e,t){Ae.isBuffer(e)?e=Ae.from(e):e=this.createBuffer(e);let r=t?.variant??"crockford",s=t?.checksum??!1;if(r==="ulid"){if(s)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(e)}let i=[],a=0,d=0;for(let u of e)for(d=d<<8|u,a+=8;a>=5;)i.push(d>>>a-5&31),a-=5;a>0&&i.push(d<<5-a&31);let c=i.map(u=>ce.charAt(u)).join("");return s&&(c+=this.computeChecksum(e)),c}static computeChecksum(e){let t=0;for(let r of e)t=(t*256+r)%37;return(ce+Xt).charAt(t)}static decode(e,t){e=e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let r=t?.variant??"crockford",s=t?.checksum??!1;if(r==="ulid"){if(s)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(e,t)}let i=null;if(s){if(e.length===0)throw new Xe("Cannot validate checksum: input is empty");let u=e.charAt(e.length-1);if((ce+Xt).indexOf(u)===-1)throw new Xe(`Invalid checksum character: ${u}`);i=u,e=e.slice(0,-1)}let a=[],d=0,c=0;for(let u of e){let m=ce.indexOf(u);if(m===-1)throw new Error(`Invalid base 32 character found in string: ${u}`);d+=5,d>=8?(d-=8,a.push(c|m>>d),c=m<<8-d&255):c|=m<<8-d}if((c>0||d>=5)&&a.push(c),i!==null){let u=this.computeChecksum(a);if(i!==u)throw new $n(`Checksum mismatch: expected '${u}' but found '${i}'`)}return t?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(e){try{return this.decode(e,{checksum:!0}),!0}catch{return!1}}static encodeUlid(e){if(e.length===0)return"";let t=0n;for(let i of e)t=t<<8n|BigInt(i);let r=[];for(;t>0n;){let i=Number(t%32n);r.unshift(ce.charAt(i)),t/=32n}let s=Math.ceil(e.length*8/5);return r.join("").padStart(s,"0")}static decodeUlid(e,t){if(e.length===0)return t?.asNumber===!0?0n:Ae.from([]);let r=0n;for(let d of e){let c=ce.indexOf(d);if(c===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);r=r*32n+BigInt(c)}let s=Math.floor(e.length*5/8),i=[],a=r;for(;a>0n;)i.unshift(Number(a&0xffn)),a>>=8n;for(r===0n&&i.push(0);i.length<s;)i.unshift(0);return t?.asNumber===!0?this.asNumber(i):this.asBuffer(i)}static createBuffer(e){if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("Input must be a safe integer");e=BigInt(e)}if(e<0n)throw new Error("Input cannot be a negative number");let t=[];for(;e>0n;)t.unshift(Number(e&0xffn)),e>>=8n;return Ae.from(t)}static asNumber(e){let t=0n;return e.forEach(r=>{t<<=8n,t|=BigInt(r)}),t}static asBuffer(e){return Ae.from(e.map(t=>t.toString(16).padStart(2,"0")).join(""),"hex")}};var qt="0123456789abcdefghjkmnpqrstvwxyz",qe=8,ks=5,Jt=32,Fn=class extends Error{static{o(this,"SpawnIdExhaustedError")}constructor(e){super(`Could not mint a unique spawn id after ${e} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function Gn(){return Je.encode(ws(ks)).toLowerCase()}o(Gn,"generateSpawnId");function Qt(n,e=Gn){for(let t=0;t<Jt;t++){let r=e();if(!n(r))return r}throw new Fn(Jt)}o(Qt,"generateUniqueSpawnId");var Qe="cow-",Re="copy-on-write",Xl=["copy-on-write","checkout"];function Jl(n){if(n==="copy-on-write"||n==="checkout")return n}o(Jl,"parseWorktreeMaterialization");function tr(n,e){return Se("copy-on-write",e)?n??Re:"checkout"}o(tr,"resolveWorktreeMaterialization");var Ze="clean",ql=["dirty","clean"];function Ql(n){if(n==="dirty"||n==="clean")return n}o(Ql,"parseWorktreeCheckoutType");var Zt=3,Ss=32,er=Ss-Qe.length-1-qe;function As(n){return n.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}o(As,"slugifyWorktreeType");function Rs(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(e=>e.length>0)}o(Rs,"taskNameWords");function Zl(n){let e=Rs(n);if(e.length===0)throw new Error("Task name is empty \u2014 provide a short 2-3 word name.");if(e.length>Zt)throw new Error(`Task name "${n}" gives the branch name "${e.join("-")}" with ${e.length} words. The limit is ${Zt} words.`);let t=e.join("-");if(t.length>er)throw new Error(`Task name "${n}" gives the branch name "${t}" with ${t.length} characters. The limit is ${er} characters, because herdr limits agent names to 32 characters.`);return t}o(Zl,"buildTaskSlug");function Is(n,e){return`${Qe}${As(n)}-${e}`}o(Is,"buildWorktreeBranch");function eu(n,e,t){return le.join(n,Is(e,t))}o(eu,"buildWorktreePath");function nu(n,e){return n&&n.trim()!==""?le.isAbsolute(n)?n:le.resolve(e,n):Vt()}o(nu,"resolveWorktreeRoot");function nr(n){return(A(n)??n.replace(/\\/g,"/")).replace(/\/+$/,"")}o(nr,"normalizeRoot");function tu(n,e){return e!==""&&n.startsWith(Qe)&&n.length>e.length&&n.endsWith(`-${e}`)}o(tu,"isSpawnArtifactName");function ru(n,e){let t=nr(n),r=nr(e);return t!==r&&!t.startsWith(`${r}/`)?!1:(t.split("/").filter(Boolean).pop()??"").startsWith(Qe)}o(ru,"isExtensionWorktree");import{getSupportedThinkingLevels as El}from"@earendil-works/pi-ai";var en=class{static{o(this,"RepoLock")}tails=new Map;async run(e,t){let r=(this.tails.get(e)??Promise.resolve()).then(t),s=r.then(()=>{},()=>{});this.tails.set(e,s);try{return await r}finally{this.tails.get(e)===s&&this.tails.delete(e)}}};import*as ue from"node:fs";import*as nn from"node:path";function F(n){for(let e of(process.env.PATH??"").split(nn.delimiter)){if(e==="")continue;let t=nn.join(e,n);try{if(!ue.statSync(t).isFile())continue;return ue.accessSync(t,ue.constants.X_OK),t}catch{}}}o(F,"commandPath");function du(n){return F(n)??n}o(du,"resolveCommand");import{readFile as Wn,readdir as Cs}from"node:fs/promises";import*as Te from"node:path";import{z as Ie}from"zod";var Ts=`[${qt}]{${qe}}`;function Un(n,e){return new RegExp(`^cow-${e}-${Ts}$`).test(n)}o(Un,"isTaskAgentName");function g(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}o(g,"isRecord");function w(n){if(typeof n!="string")return;let e=n.trim();return e===""?void 0:e}o(w,"nonEmpty");var rr=3,_s="sessionDir",Os=Ie.object({type:Ie.string(),text:Ie.string().optional()}),Ps=Ie.array(Ie.unknown());function tn(n){return`--${(A(n)??Te.resolve(n)).replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}o(tn,"sessionBucketName");async function pe(n){let e;try{e=await Wn(Te.join(n,"settings.json"),"utf8")}catch{return}let t;try{t=JSON.parse(e)}catch{return}if(g(t))return w(t[_s])}o(pe,"readSessionDirSetting");async function Ms(n,e,t){let r;try{r=await Cs(n,{withFileTypes:!0})}catch{throw new p("session-not-found",`no session record under ${n} for ${t} (subagent ${e})`)}let s=[];for(let i of r){if(!i.isFile()||!i.name.endsWith(".jsonl"))continue;let a=Te.join(n,i.name);await Hs(a)===e&&s.push(a)}if(s.length===0)throw new p("session-not-found",`no session record under ${n} for ${t} (subagent ${e})`);if(s.length>1)throw new p("ambiguous-session",`more than one session record under ${n} names subagent ${e}: ${s.join(", ")}`);return s[0]}o(Ms,"findSessionFile");async function Hs(n){let e;try{e=await Wn(n,"utf8")}catch{return}let t;for(let r of e.split(`
2
2
  `)){if(r.trim()==="")continue;let s;try{s=JSON.parse(r)}catch{continue}!g(s)||s.type!=="session_info"||(t=w(s.name))}return t}o(Hs,"readLatestSessionName");async function Ls(n){let e=await js(n),t=!e.endsWith(`
3
3
  `),r=e.split(`
4
4
  `);t||r.pop();let s=Ns(r,t,n);return{sessionId:s.header.id,records:Ds(r,s.index,t)}}o(Ls,"readSessionFile");function Ns(n,e,t){for(let r=0;r<n.length;r++){let s=n[r];if(s.trim()==="")continue;let i;try{i=JSON.parse(s)}catch{if(e&&r===n.length-1)break;throw new p("malformed-record",`malformed session record in ${t} at line ${r+1}`)}if(!g(i))throw new p("malformed-record",`malformed session record in ${t} at line ${r+1}`);return{index:r,header:$s(i,t)}}throw new p("malformed-record",`session record ${t} has no session header`)}o(Ns,"findSessionHeader");function*Ds(n,e,t){for(let r=0;r<n.length;r++){let s=n[r];if(s.trim()==="")continue;if(r===e){yield{kind:"dont-export",content:s};continue}let i;try{i=JSON.parse(s)}catch{if(t&&r===n.length-1)break;yield{kind:"unparseable",content:s};continue}if(!g(i)){yield{kind:"unparseable",content:s};continue}yield Fs(i,s)}}o(Ds,"sessionRecords");async function js(n){try{return await Wn(n,"utf8")}catch(e){throw new p("unreadable-record",`cannot read session record ${n}: ${b(e)}`)}}o(js,"readSessionFileContent");function $s(n,e){if(n.type!=="session")throw new p("malformed-record",`session record ${e} does not start with a session header`);let t=n.version;if(typeof t!="number"||!Number.isInteger(t))throw new p("malformed-record",`session record ${e} has no numeric version`);if(t!==rr)throw new p("unsupported-version",`session record ${e} uses version ${t}; this export reads version ${rr}`);let r=w(n.id);if(r===void 0)throw new p("missing-session-id",`session record ${e} names no session id`);return{id:r}}o($s,"readHeader");function Fs(n,e){if(n.type==="compaction")return Gs(n,e);if(n.type!=="message")return{kind:"dont-export",content:e};if(!g(n.message))return{kind:"unparseable",content:e};let t=n.message.role;if(t!=="user"&&t!=="assistant")return{kind:"dont-export",content:e};let r=Ps.safeParse(n.message.content);if(!r.success)return{kind:"unparseable",content:e};let s=Us(r.data);return s===""?{kind:"dont-export",content:e}:{kind:"export",turn:{role:t==="user"?"User":"Assistant",text:s}}}o(Fs,"readTurn");function Gs(n,e){if(typeof n.summary!="string")return{kind:"unparseable",content:e};let t=or(n.summary);return t===""?{kind:"dont-export",content:e}:{kind:"compaction",summary:t}}o(Gs,"readCompaction");function Us(n){let e=[];for(let t of n){let r=Os.safeParse(t);if(!r.success||r.data.type!=="text"||r.data.text===void 0)continue;let s=or(r.data.text);s!==""&&e.push(s)}return e.length===0?"":e.join(`
@@ -44,4 +44,4 @@ ${Yo(i.turn.text)}`;break;case"dont-export":break;case"unparseable":r+=1;break}}
44
44
  `).map(t=>{let r=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(t);if(r!==null){let a=r[1];return e===void 0?e=a:a[0]===e[0]&&a.length>=e.length&&r[2].trim()===""&&(e=void 0),t}if(e!==void 0)return t;let s=/^( {0,3})#{1,6}(?=\s|$)/.exec(t);if(s===null)return t;let i=s[1];return`${i}\\${t.slice(i.length)}`}).join(`
45
45
  `)}o(Yo,"escapeContentHeadings");async function Rm(n,e,t,r){let s=n.get(e);if(s===void 0||!Gt(s))return{kind:"faulted",fault:{kind:"harness-cannot-export-session",harness:e}};let i;try{i=await s.readHandoverRecords(t)}catch(c){return{kind:"faulted",fault:{kind:"session-export-failed",harness:e,detail:c instanceof Error?c.message:String(c),...c instanceof p?{exportFault:c.fault}:{}}}}if(i.sessionId.trim()==="")return{kind:"faulted",fault:{kind:"session-export-failed",harness:e,detail:"the harness named no session id for the run it exported"}};let a=Pc(i),d=a.loss;return d!==void 0&&d.total>0&&d.excluded/d.total>r.maxExcludedRatio?{kind:"faulted",fault:{kind:"session-export-failed",harness:e,detail:Oc(d,r)}}:a.session.trim()===""?{kind:"faulted",fault:{kind:"session-empty",harness:e}}:{kind:"exported",sessionId:a.sessionId,session:a.session,...d===void 0?{}:{loss:d}}}o(Rm,"exportRunSession");var Mc="<<pi-cowboy-handover",Hc=">>";function Lc(n){let e=n.map(({harness:t,sessionId:r})=>({harness:t,sessionId:r}));return`${Mc} ${JSON.stringify(e)}${Hc}`}o(Lc,"renderHandoverMarker");function Im(n){return[n.taskSlug===void 0?"You are continuing this task in this workspace.":`You are continuing work on task "${n.taskSlug}" in this workspace.`,`This task was previously handled by another agent harness (${n.sourceName}).`,`The previous run's session id is "${n.current.sessionId}".`,Lc([...n.previous,n.current]),"","The session of the previous run is quoted below. Review it together with the current state of the files in this repository, then proceed with the task.","","---","",n.session,""].join(`
46
46
  `)}o(Im,"renderHandoverTask");var Xo=4;function se(n){let e=n.indexOf("/"),t=n.indexOf(":"),r=t>0&&(e<0||t<e),s="pi",i=n;if(r){if(s=n.slice(0,t),s.trim()==="")return;i=n.slice(t+1)}let a=i.indexOf("/");if(a<0)return i===""?void 0:{kind:"provider",harness:s,provider:i};let d=i.slice(0,a),c=i.slice(a+1);if(!(d===""||c===""))return{kind:"model",harness:s,provider:d,model:c}}o(se,"parsePoolKey");function qo(n,e,t){return`${n}:${e}/${t}`}o(qo,"qualifiedModelKey");function Qo(n,e){return`${n}:${e}`}o(Qo,"qualifiedProviderKey");function Nc(n){let e=se(n);return e?.kind==="model"?qo(e.harness,e.provider,e.model):void 0}o(Nc,"modelPoolKeyOf");function Dc(n){let e=se(n);return e?.kind==="provider"?Qo(e.harness,e.provider):void 0}o(Dc,"providerPoolKeyOf");function Rt(n){return Math.max(1,n)}o(Rt,"clampLimit");var Jo=class{static{o(this,"ConcurrencyPools")}modelPools=new Map;providerPools=new Map;harnessPools=new Map;globalPool={limit:Xo,spawned:0};queue=[];reservations=new Map;constructor(e){this.setLimits(e??{default:Xo,harnesses:{},providers:{},models:{}})}setConcurrency(e){this.setLimits(e),this.drainQueue()}admitSpawn(e,t){let r=this.applicablePools(e);return this.hasRoom(r)?{kind:"start",reservation:r}:(this.queue.push({id:t.id,identity:e,start:t.start}),{kind:"queue"})}reserve(e,t){for(let r of t)r.spawned++;this.reservations.set(e,t)}reacquire(e,t){this.reservations.has(e)||this.reserve(e,this.applicablePools(t))}release(e){let t=this.reservations.get(e);if(t){for(let r of t)r.spawned=Math.max(0,r.spawned-1);this.reservations.delete(e)}this.cancelQueued(e),this.drainQueue()}cancelQueued(e){this.queue=this.queue.filter(t=>t.id!==e)}clearQueue(){this.queue=[]}queuePosition(e){return this.queue.findIndex(t=>t.id===e)+1}setLimits(e){this.globalPool.limit=Rt(e.default),this.syncHarnessPools(e.harnesses),this.syncPools(this.providerPools,e.providers,Dc),this.syncPools(this.modelPools,e.models,Nc)}syncHarnessPools(e){let t=new Map;for(let[r,s]of Object.entries(e))r.trim()!==""&&typeof s=="number"&&t.set(r,Rt(s));for(let[r,s]of t){let i=this.harnessPools.get(r);i?i.limit=s:this.harnessPools.set(r,{limit:s,spawned:0})}for(let r of this.harnessPools.keys())t.has(r)||this.harnessPools.delete(r)}syncPools(e,t,r){let s=new Map;for(let[i,a]of Object.entries(t)){let d=r(i);d!==void 0&&a!==void 0&&s.set(d,Rt(a))}for(let[i,a]of s){let d=e.get(i);d?d.limit=a:e.set(i,{limit:a,spawned:0})}for(let i of e.keys())s.has(i)||e.delete(i)}applicablePools(e){let t=[];if(e.modelKey){let s=se(e.modelKey);if(s?.kind==="model"){let i=this.modelPools.get(qo(e.harness,s.provider,s.model));i&&t.push(i);let a=this.providerPools.get(Qo(e.harness,s.provider));a&&t.push(a)}}let r=this.harnessPools.get(e.harness);return r&&t.push(r),t.push(this.globalPool),t}hasRoom(e){return e.every(t=>t.spawned<t.limit)}drainQueue(){let e=[];for(let t of this.queue){let r=this.applicablePools(t.identity);if(!this.hasRoom(r)){e.push(t);continue}t.start(r)}this.queue=e}};var De="defaultModelByHarness",ie="defaultThinkingByHarness",ve="thinking",Rn=["default","defaultAgentType","defaultOrchestrator","systemPromptMode","includeContextFiles","defaultThinking",ie,ve,"loadSkillsImplicitly","loadExtensionsImplicitly","disableDefaultAgents","extensionEnabled","showActiveIndicator","grazingEnabled","worktreeRoot","worktreeMaterialization","worktreeCheckoutType","handoverMaxExcludedRatio","harnessType"];import*as P from"node:fs";import*as ke from"node:path";import{z as $}from"zod";function Zo(n,e,t){return Dt(n)?$t(n,t)?"reserved":typeof e!="string"?"not-string":jt(e)?"control":null:"name"}o(Zo,"envProblem");function es(n,e){let t={};for(let[r,s]of Object.entries(n)){if(s===void 0)continue;let i=Zo(r,s,e.reserved);if(i!==null){e.report(r,i,s);continue}t[r]=s}return t}o(es,"sanitizeEnv");function Lm(n,e){return n===void 0?e:e===void 0?n:{...n,...e}}o(Lm,"mergeEnv");function Nm(n){for(let[e,t]of Object.entries(n)){let r=Zo(e,t,[]);if(r!==null)throw new Error(`Invalid environment variable ${e}: ${r}`)}return n}o(Nm,"trustedEnv");import{z as jc}from"zod";var It=jc.number().int().min(1),we="positive integer";function In(n){return It.safeParse(n).success}o(In,"isConcurrencyLimit");var $c="Set it again in the /cowboy menu, or edit or delete the file to fix it.",$e="Edit or delete the key in that file to fix it.",Fc={schema:$.number().min(0).max(1),expected:"a number from 0 to 1",fix:$e},Tt={schema:$.union([$.string(),$.null()]),expected:"string or null"},ae={schema:$.boolean(),expected:"boolean"},Gc={schema:$.enum(["replace","inherit","custom"]),expected:'"replace" | "inherit" | "custom"'},Uc={schema:$.enum(["off","minimal","low","medium","high","xhigh","max"]),expected:'"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"'},Wc={schema:$.enum(["copy-on-write","checkout"]),expected:'"copy-on-write" | "checkout"'},Kc={schema:$.enum(["dirty","clean"]),expected:'"dirty" | "clean"'},ts=$.string().min(1).refine(n=>/\S/.test(n)),je={schema:ts,expected:"non-empty string"},rs=Ve.map(n=>`"${n}"`).join(" | "),Bc=`an object keyed by a harness id (${rs} or a plugin's), with string or null values`,Vc=`an object keyed by a harness id (${rs} or a plugin's), with a non-empty thinking token or null per entry`,zc="an object keyed by an agent type, with a non-empty thinking token or null per entry",Yc="non-empty string or null",Xc=o(n=>typeof n=="string"||n===null,"isModelKeyOrNull"),Jc=o(n=>n===null||typeof n=="string"&&/\S/.test(n),"isThinkingTokenOrNull"),qc={default:Tt,defaultAgentType:je,defaultOrchestrator:je,systemPromptMode:Gc,includeContextFiles:ae,defaultThinking:Uc,loadSkillsImplicitly:ae,loadExtensionsImplicitly:ae,disableDefaultAgents:ae,extensionEnabled:ae,showActiveIndicator:ae,grazingEnabled:ae,worktreeRoot:je,worktreeMaterialization:Wc,worktreeCheckoutType:Kc,handoverMaxExcludedRatio:Fc,harnessType:je};function Qc(n){return Array.isArray(n)?"array":n===null?"null":typeof n=="object"?"object":typeof n}o(Qc,"describeValue");function Fe(n,e,t,r,s){return`[subagents] Incompatible value in ${n}: "${e}" is ${Qc(t)}, expected ${r}. ${s}`}o(Fe,"incompatibleWarning");function S(n,e,t,r,s=$c){console.warn(Fe(n,e,t,r,s))}o(S,"warnIncompatible");var q="object";function Ct(n,e){let t={};if(!g(n))return S(e,"(config)",n,q),t;if(n.agent!==void 0)if(!g(n.agent))S(e,"agent",n.agent,q);else{let r=rl(n.agent,e);Object.keys(r).length>0&&(t.agent=r)}if(n.concurrency!==void 0){let r=ol(n.concurrency,e);Object.keys(r).length>0&&(t.concurrency=r)}if(n.harness!==void 0){let r=Zc(n.harness,e);r!==void 0&&(t.harness=r)}if(n.multiplexer!==void 0){let r=ts.safeParse(n.multiplexer);r.success?t.multiplexer=r.data:S(e,"multiplexer",n.multiplexer,je.expected)}return t}o(Ct,"validateRawLayer");function Zc(n,e){if(!g(n)){console.warn(Fe(e,"harness",n,q,$e));return}let t={};for(let[r,s]of Object.entries(n))if(s!==void 0){if(!g(s)){console.warn(Fe(e,`harness.${r}`,s,q,$e));continue}t[r]=el(s,r,e)}return Object.keys(t).length>0?t:void 0}o(Zc,"cleanHarnessSections");function el(n,e,t){if(n.env===void 0)return n;let r=tl(n.env,e,t),s={...n};return delete s.env,r===void 0?s:{...s,env:r}}o(el,"cleanHarnessSlice");var nl={name:"a valid environment variable name",reserved:"a variable that is not reserved","not-string":"string",control:"a value without control characters"};function tl(n,e,t){if(!g(n)){S(t,`harness.${e}.env`,n,q);return}let r=es(n,{reserved:[],report:o((s,i,a)=>{let d=i==="name"||i==="reserved";S(t,`harness.${e}.env.${s}`,d?s:a,nl[i])},"report")});return Object.keys(r).length>0?r:void 0}o(tl,"cleanHarnessEnv");function rl(n,e){let t={};for(let[r,s]of Object.entries(n)){if(s===void 0)continue;if(r===De){let d=ns(s,e,{keyPath:`agent.${r}`,expected:Bc,valueExpected:Tt.expected,accepts:Xc});d!==void 0&&(t[r]=d);continue}if(r===ie||r===ve){let d=ns(s,e,{keyPath:`agent.${r}`,expected:r===ie?Vc:zc,valueExpected:Yc,accepts:Jc});d!==void 0&&(t[r]=d);continue}let i=qc[r]??Tt,a=i.schema.safeParse(s);a.success?t[r]=a.data:S(e,`agent.${r}`,s,i.expected,i.fix)}return t}o(rl,"cleanAgentEntries");function ns(n,e,{keyPath:t,expected:r,valueExpected:s,accepts:i}){if(!g(n)){S(e,t,n,r);return}let a={};for(let[d,c]of Object.entries(n))if(c!==void 0){if(!/\S/.test(d)){S(e,`${t}.${d}`,d,"non-empty key");continue}i(c)?a[d]=c:S(e,`${t}.${d}`,c,s)}return Object.keys(a).length>0?a:void 0}o(ns,"cleanEntryMap");function ol(n,e){let t={};if(!g(n))return S(e,"concurrency",n,q),t;n.default!==void 0&&(In(n.default)?t.default=n.default:S(e,"concurrency.default",n.default,we));let r=n.harnesses;if(r!==void 0)if(!g(r))S(e,"concurrency.harnesses",r,q);else{let i={};for(let[a,d]of Object.entries(r)){if(!/\S/.test(a)){S(e,`concurrency.harnesses.${a}`,a,"non-empty harness id");continue}In(d)?i[a]=d:S(e,`concurrency.harnesses.${a}`,d,we)}Object.keys(i).length>0&&(t.harnesses=i)}let s={providers:{level:"provider",expected:'a provider key "provider" or "<harness>:<provider>"'},models:{level:"model",expected:'a model key "provider/model" or "<harness>:<provider>/<model>"'}};for(let i of["providers","models"]){let a=n[i];if(a===void 0)continue;if(!g(a)){S(e,`concurrency.${i}`,a,q);continue}let{level:d,expected:c}=s[i],u={};for(let[m,Q]of Object.entries(a)){if(se(m)?.kind!==d){S(e,`concurrency.${i}.${m}`,m,c);continue}In(Q)?u[m]=Q:S(e,`concurrency.${i}.${m}`,Q,we)}Object.keys(u).length>0&&(t[i]=u)}return t}o(ol,"cleanConcurrencySection");var is="config.json";function Ge(){return ke.join(Ye(),is)}o(Ge,"configPath");function ay(){return ke.join(Ye(),"prompt.md")}o(ay,"customPromptPath");var sl={default:4},il={default:null,defaultAgentType:vn,defaultOrchestrator:wn,systemPromptMode:"replace",includeContextFiles:!0,disableDefaultAgents:!1,extensionEnabled:!0,showActiveIndicator:!0,grazingEnabled:!0,worktreeMaterialization:Re,worktreeCheckoutType:Ze,handoverMaxExcludedRatio:An,harnessType:"pi"},_t=new Set(["default","defaultThinking",De,ie,ve]),al=new Set([De,ie,ve]);function Ot(n){return _t.has(n)||!Rn.includes(n)}o(Ot,"isProjectAllowedAgentKey");function Ue(n){let e=n?ke.join(n,Nn,is):null,t=n?"absent":"untrusted",r=null,s=!1;return{load:o(()=>{let i=cl(),a=i.raw;if(s=i.malformed,e){let d=ll(e);d===null?(r=null,t="absent"):d==="malformed"?(r=null,t="malformed"):(r=d.raw,t="loaded")}else r=null,t="untrusted";return{global:a,project:r,projectStatus:t}},"load"),isGlobalWritable:o(()=>!s,"isGlobalWritable"),paths:o(()=>({global:Ge(),project:e??void 0}),"paths"),saveGlobal:o(i=>{if(s){console.warn("[subagents] Refusing to write global config (malformed); change not saved");return}ss(Ge(),i)},"saveGlobal"),saveProject:o(i=>{if(!e||t==="malformed"||t==="untrusted"){console.warn(`[subagents] Refusing to write project config (${t}); change not saved`);return}ss(e,i)},"saveProject")}}o(Ue,"createConfigIO");function as(n,e){let t={...n.agent};if(e?.agent){for(let[r,s]of Object.entries(e.agent))if(Ot(r)){if(al.has(r)&&g(t[r])&&g(s)){t[r]={...t[r],...s};continue}t[r]=s}}return{agent:t,concurrency:dl(n.concurrency,e?.concurrency),multiplexer:n.multiplexer}}o(as,"mergeLayers");function dl(...n){let e={},t={},r={},s={};for(let i of n)i&&(i.default!==void 0&&(e.default=i.default),Object.assign(t,i.harnesses??{}),Object.assign(r,i.providers??{}),Object.assign(s,i.models??{}));return Object.keys(t).length>0&&(e.harnesses=t),Object.keys(r).length>0&&(e.providers=r),Object.keys(s).length>0&&(e.models=s),e}o(dl,"mergeRawConcurrency");function Pt(n){return{agent:{...il,...n.agent},concurrency:{...sl,...n.concurrency},multiplexer:n.multiplexer??kt()}}o(Pt,"mergeDefaults");function cl(){let n;try{n=P.readFileSync(Ge(),"utf-8")}catch(t){return t?.code==="ENOENT"?{raw:{},malformed:!1}:os(t)}let e;try{e=JSON.parse(n)}catch(t){return os(t)}return{raw:Ct(e,Ge()),malformed:!1}}o(cl,"readGlobalRaw");function os(n){return console.warn(`[subagents] Ignoring malformed global config ${Ge()}: ${b(n)}`),{raw:{},malformed:!0}}o(os,"warnMalformedGlobal");function ll(n){if(!P.existsSync(n))return null;let e;try{e=P.readFileSync(n,"utf-8")}catch(t){return console.warn(`[subagents] Ignoring malformed project config ${n}: ${b(t)}`),"malformed"}return ul(e,n)}o(ll,"readProjectRaw");function ul(n,e){let t;try{t=JSON.parse(n)}catch(s){return console.warn(`[subagents] Ignoring malformed project config ${e}: ${b(s)}`),"malformed"}if(!g(t))return console.warn(`[subagents] Ignoring malformed project config ${e}: not a JSON object`),"malformed";let r=t;return r.agent!==void 0&&!g(r.agent)?Tn(e,"agent"):r.concurrency!==void 0&&!g(r.concurrency)?Tn(e,"concurrency"):r.concurrency?.providers!==void 0&&!g(r.concurrency.providers)?Tn(e,"concurrency.providers"):r.concurrency?.models!==void 0&&!g(r.concurrency.models)?Tn(e,"concurrency.models"):{raw:Ct(r,e)}}o(ul,"parseProjectContents");function Tn(n,e){return console.warn(`[subagents] Ignoring malformed project config ${n}: "${e}" is not a JSON object`),"malformed"}o(Tn,"malformedSection");function ss(n,e){let t=n+".tmp";try{P.mkdirSync(ke.dirname(n),{recursive:!0}),P.writeFileSync(t,JSON.stringify(e,null,2),"utf-8"),P.renameSync(t,n)}catch(r){console.error(`[subagents] Failed to save config: ${b(r)}`)}}o(ss,"writeJsonAtomic");var pl=Ue();function fl(n){return n.project?{kind:"present",raw:n.project}:n.projectStatus==="untrusted"||n.projectStatus==="malformed"?{kind:"refused",status:n.projectStatus}:{kind:"creatable"}}o(fl,"projectLayerFrom");function Mt(n){return n.kind==="present"?n.raw:null}o(Mt,"projectRawOf");var gl="[subagents] Refusing to write config before the first load; change not saved",Cn=class{static{o(this,"LayeredConfig")}io;files=null;constructor(e=pl){this.io=e}get paths(){return this.io.paths()}get effective(){let e=this.files;return e===null?Pt({}):Pt(as(e.globalRaw,Mt(e.projectLayer)))}get global(){return this.files?.globalRaw??{}}get project(){let e=this.files;return e===null?null:Mt(e.projectLayer)}get isProjectWritable(){let e=this.files;return e!==null&&e.projectLayer.kind!=="refused"}get isGlobalWritable(){return this.files!==null&&this.io.isGlobalWritable()}setProjectDir(e){this.io=Ue(e)}reload(){let e=this.io.load();this.files={globalRaw:e.global,projectLayer:fl(e)}}mutate(e,t){let r=this.loadedOrWarn();if(r===null)return!1;if(e==="global")return this.globalWritableOrWarn()?(t(r.globalRaw),this.io.saveGlobal(r.globalRaw),!0):!1;let s=ml(r);return s===null?!1:(t(s),this.io.saveProject(s),!0)}clear(e,t,r){if((e==="session"||e==="all")&&r(),e==="session")return;let s=this.loadedOrWarn();if(s===null)return;(e==="global"||e==="all")&&this.globalWritableOrWarn()&&(t(s.globalRaw),this.io.saveGlobal(s.globalRaw));let i=Mt(s.projectLayer);i&&(e==="project"||e==="all")&&(t(i),this.io.saveProject(i))}loadedOrWarn(){return this.files!==null?this.files:(console.warn(gl),null)}globalWritableOrWarn(){return this.isGlobalWritable?!0:(console.warn("[subagents] Refusing to write global config (malformed); change not saved"),!1)}};function ml(n){let e=n.projectLayer;if(e.kind==="present")return e.raw;if(e.kind==="refused")return console.warn(`[subagents] Project config target unavailable (${e.status}); change ignored`),null;let t={};return n.projectLayer={kind:"present",raw:t},t}o(ml,"projectLayerToWrite");var yl=Ue();function ds(n){let e=n?.agent;return e?Object.keys(e).some(t=>Ot(t)&&e[t]!==void 0):!1}o(ds,"agentLayerHasModelSettings");function _n(n,e){return n?.agent!=null&&n.agent[e]!==void 0}o(_n,"layerHasAgentKey");function We(n,e){return n!=null&&Object.hasOwn(n,e)}o(We,"layerCarriesEntry");function hl(n){let e=$o.safeParse(n);if(!e.success)throw new RangeError(`Invalid pi thinking level ${JSON.stringify(n)}`);return e.data}o(hl,"piThinkingLevel");function On(n){return M(n)?"pi":n}o(On,"thinkingSlot");function xl(n){return Object.values(n).some(e=>e!=null)}o(xl,"sessionOverridesHasModelSettings");function Ht(n){return n.default!==void 0||n.harnesses!=null&&Object.keys(n.harnesses).length>0||n.providers!=null&&Object.keys(n.providers).length>0||n.models!=null&&Object.keys(n.models).length>0}o(Ht,"concurrencyLayerHasSettings");var bl=new Set(Rn.filter(n=>!_t.has(n)));function Ke(n){return typeof n=="string"&&/\S/.test(n)?n:void 0}o(Ke,"nonBlankString");function Pn(n){if(!It.safeParse(n).success)throw new RangeError(`Invalid concurrency limit ${JSON.stringify(n)}: expected ${we}.`)}o(Pn,"assertConcurrencyLimit");function Lt(n){return n.defaultModelByHarness??{}}o(Lt,"rawHarnessDefaults");function cs(n){return n.defaultThinkingByHarness??{}}o(cs,"rawThinkingByHarness");function ls(n){return n.thinking??{}}o(ls,"rawThinkingByType");var Mn=class{static{o(this,"ConfigStore")}layers;sessionOverrides={default:null};sessionThinking={};sessionHarnessDefaults={};sessionThinkingDefaults={};sessionConcurrencyLayer={};manager;constructor(e=yl){this.layers=new Cn(e)}setProjectDir(e){this.layers.setProjectDir(e)}get isProjectWritable(){return this.layers.isProjectWritable}get agent(){let e=this.layers.effective.agent;return{defaultModel:e.default,defaultAgentType:e.defaultAgentType??vn,defaultOrchestrator:e.defaultOrchestrator??wn,systemPromptMode:e.systemPromptMode??"replace",includeContextFiles:e.includeContextFiles??!0,defaultThinking:e.defaultThinking,loadSkillsImplicitly:e.loadSkillsImplicitly??!0,loadExtensionsImplicitly:e.loadExtensionsImplicitly??!0,disableDefaultAgents:e.disableDefaultAgents??!1,extensionEnabled:e.extensionEnabled??!0,showActiveIndicator:e.showActiveIndicator??!0,grazingEnabled:e.grazingEnabled===!0,worktreeRoot:e.worktreeRoot,worktreeMaterialization:e.worktreeMaterialization??Re,worktreeCheckoutType:e.worktreeCheckoutType??Ze,handoverMaxExcludedRatio:e.handoverMaxExcludedRatio??An,harnessType:e.harnessType??"pi"}}get multiplexer(){return this.layers.effective.multiplexer}harnessConfigLayers(){return{global:this.layers.global.harness??{},project:this.layers.project?.harness??{}}}harnessEnv(e){let t=this.layers.global.harness?.[e]?.env;return g(t)?t:void 0}reportHarnessConfigIssue(e,t){let r=this.layers.paths,s=t.layer==="project"?r.project??r.global:r.global;console.warn(Fe(s,`harness.${e}${t.keyPath===""?"":`.${t.keyPath}`}`,t.got,t.expected,$e))}get concurrency(){let e=this.layers.effective.concurrency,t=this.sessionConcurrencyLayer;return{default:t.default??e.default,harnesses:{...e.harnesses,...t.harnesses},providers:{...e.providers,...t.providers},models:{...e.models,...t.models}}}get sessionDefaultModel(){return this.sessionOverrides.default??null}sessionModelOverride(e){return this.sessionOverrides[e]??null}defaultModelForHarness(e){return Ke(this.sessionHarnessDefaults[e])??Uo(this.layers.effective.agent,e)}sessionThinkingOverride(e){return this.sessionThinking[e]??null}defaultThinkingForHarness(e){return Ke(this.sessionThinkingDefaults[On(e)])??Bo(this.layers.effective.agent,e)}thinkingFor(e,t,r,s){return Vo({subagentType:e,agentConfig:t,harnessFamily:ut(r),config:this.layers.effective,harnessDefault:this.defaultThinkingForHarness(r),parentThinking:s,sessionThinking:this.sessionThinking})}configuredHarnessIds(){let e=new Set([this.agent.harnessType]);for(let r of Object.keys(Lt(this.layers.effective.agent)))e.add(r);for(let r of Object.keys(this.concurrency.harnesses))e.add(r);let t=this.harnessConfigLayers();for(let r of Object.keys(t.global))e.add(r);for(let r of Object.keys(t.project))e.add(r);for(let r of[...Object.keys(this.concurrency.providers),...Object.keys(this.concurrency.models)]){let s=se(r);s!==void 0&&e.add(s.harness)}return[...e]}modelOverrideLevels(e){return{session:this.sessionModelOverride(e)!==null,global:_n(this.layers.global,e),project:_n(this.layers.project,e)}}harnessDefaultModelLevels(e){return{session:Ke(this.sessionHarnessDefaults[e])!==void 0,global:We(this.layers.global.agent?.defaultModelByHarness,e),project:We(this.layers.project?.agent?.defaultModelByHarness,e)}}harnessDefaultThinkingLevels(e){return{session:Ke(this.sessionThinkingDefaults[On(e)])!==void 0,global:this.harnessThinkingAt(this.layers.global,e),project:this.harnessThinkingAt(this.layers.project,e)}}harnessThinkingAt(e,t){return M(t)?_n(e,"defaultThinking"):We(e?.agent?.defaultThinkingByHarness,t)}thinkingOverrideLevels(e){return{session:this.sessionThinking[e]!=null,global:We(this.layers.global.agent?.thinking,e),project:We(this.layers.project?.agent?.thinking,e)}}hasProjectModelKey(e){return _n(this.layers.project,e)}hasProjectThinkingKey(e){return Ne(this.layers.project?.agent?.thinking?.[e])}modelSettingsLevels(){return{session:xl(this.sessionOverrides)||Object.keys(this.sessionHarnessDefaults).length>0||Object.values(this.sessionThinking).some(e=>e!=null)||Object.values(this.sessionThinkingDefaults).some(e=>Ke(e)!==void 0),global:ds(this.layers.global),project:ds(this.layers.project)}}get projectConcurrency(){return{...this.layers.project?.concurrency}}get globalConcurrency(){return{...this.layers.global.concurrency}}get sessionConcurrency(){return{...this.sessionConcurrencyLayer}}concurrencySettingsLevels(){return{session:Ht(this.sessionConcurrencyLayer),global:Ht(this.layers.global.concurrency??{}),project:Ht(this.layers.project?.concurrency??{})}}agentConfigSnapshot(){return this.layers.effective.agent}modelFor(e,t,r,s){return Ko({subagentType:e,agentConfig:r,harnessFamily:ut(s),config:this.layers.effective,harnessDefault:this.defaultModelForHarness(s),parentModelId:t,sessionOverrides:this.sessionOverrides})}mutate={agent:{setDefaultModel:o((e,t="global")=>{this.setAgentModelKey("default",e,t)},"setDefaultModel"),setModelOverride:o((e,t,r="global")=>{this.setAgentModelKey(e,t,r)},"setModelOverride"),clearModelOverride:o((e,t="global")=>{this.layers.clear(t,r=>{r.agent&&delete r.agent[e]},()=>{delete this.sessionOverrides[e]})},"clearModelOverride"),clearAllModelOverrides:o((e="global")=>{this.layers.clear(e,t=>this.clearAgentModelKeys(t),()=>{this.sessionOverrides={default:null},this.sessionThinking={},this.sessionHarnessDefaults={},this.sessionThinkingDefaults={}})},"clearAllModelOverrides"),setDefaultAgentType:o(e=>this.setAgentLayerEntry("defaultAgentType",e,"global"),"setDefaultAgentType"),setDefaultOrchestrator:o(e=>this.setAgentLayerEntry("defaultOrchestrator",e,"global"),"setDefaultOrchestrator"),setSystemPromptMode:o(e=>this.setAgentLayerEntry("systemPromptMode",e,"global"),"setSystemPromptMode"),setIncludeContextFiles:o(e=>this.setAgentLayerEntry("includeContextFiles",e,"global"),"setIncludeContextFiles"),setDefaultThinking:o((e,t="global")=>{this.setAgentLayerEntry("defaultThinking",e,t)},"setDefaultThinking"),setLoadSkillsImplicitly:o(e=>this.setAgentLayerEntry("loadSkillsImplicitly",e,"global"),"setLoadSkillsImplicitly"),setLoadExtensionsImplicitly:o(e=>this.setAgentLayerEntry("loadExtensionsImplicitly",e,"global"),"setLoadExtensionsImplicitly"),setDisableDefaultAgents:o(e=>this.setAgentLayerEntry("disableDefaultAgents",e,"global"),"setDisableDefaultAgents"),setExtensionEnabled:o(e=>this.setAgentLayerEntry("extensionEnabled",e,"global"),"setExtensionEnabled"),setShowActiveIndicator:o(e=>this.setAgentLayerEntry("showActiveIndicator",e,"global"),"setShowActiveIndicator"),setGrazingEnabled:o(e=>this.setAgentLayerEntry("grazingEnabled",e,"global"),"setGrazingEnabled"),setWorktreeRoot:o(e=>this.setAgentLayerEntry("worktreeRoot",e,"global"),"setWorktreeRoot"),setWorktreeMaterialization:o(e=>this.setAgentLayerEntry("worktreeMaterialization",e,"global"),"setWorktreeMaterialization"),setWorktreeCheckoutType:o(e=>this.setAgentLayerEntry("worktreeCheckoutType",e,"global"),"setWorktreeCheckoutType"),setHarnessType:o(e=>this.setAgentLayerEntry("harnessType",e,"global"),"setHarnessType"),setHarnessDefaultModel:o((e,t,r="global")=>{if(r==="session"){this.sessionHarnessDefaults[e]=t;return}this.layers.mutate(r,s=>{s.agent??={},s.agent.defaultModelByHarness={...Lt(s.agent),[e]:t}})},"setHarnessDefaultModel"),clearHarnessDefaultModel:o((e,t="global")=>{this.layers.clear(t,r=>{if(!r.agent)return;let s=Lt(r.agent);delete s[e],Object.keys(s).length===0?delete r.agent.defaultModelByHarness:r.agent.defaultModelByHarness=s},()=>{delete this.sessionHarnessDefaults[e]})},"clearHarnessDefaultModel"),setThinkingOverride:o((e,t,r="global")=>{if(r==="session"){this.sessionThinking[e]=t;return}this.layers.mutate(r,s=>{s.agent??={},s.agent.thinking={...ls(s.agent),[e]:t}})},"setThinkingOverride"),clearThinkingOverride:o((e,t="global")=>{this.layers.clear(t,r=>{if(!r.agent)return;let s=ls(r.agent);delete s[e],Object.keys(s).length===0?delete r.agent.thinking:r.agent.thinking=s},()=>{delete this.sessionThinking[e]})},"clearThinkingOverride"),setHarnessDefaultThinking:o((e,t,r="global")=>{if(r==="session"){this.sessionThinkingDefaults[On(e)]=t;return}if(M(e)){let s=t===null?void 0:hl(t);this.setAgentLayerEntry("defaultThinking",s,r);return}this.layers.mutate(r,s=>{s.agent??={},s.agent.defaultThinkingByHarness={...cs(s.agent),[e]:t}})},"setHarnessDefaultThinking"),clearHarnessDefaultThinking:o((e,t="global")=>{this.layers.clear(t,r=>{if(!r.agent)return;if(M(e)){delete r.agent.defaultThinking;return}let s=cs(r.agent);delete s[e],Object.keys(s).length===0?delete r.agent.defaultThinkingByHarness:r.agent.defaultThinkingByHarness=s},()=>{delete this.sessionThinkingDefaults[On(e)]})},"clearHarnessDefaultThinking")},concurrency:{setDefault:o((e,t="global")=>{Pn(e),this.applyConcurrencyWrite(t,r=>{r.default=e})},"setDefault"),setHarness:o((e,t,r="global")=>{Pn(t),this.applyConcurrencyWrite(r,s=>{s.harnesses={...s.harnesses,[e]:t}})},"setHarness"),setProvider:o((e,t,r="global")=>{Pn(t),this.applyConcurrencyWrite(r,s=>{s.providers={...s.providers,[e]:t}})},"setProvider"),setModel:o((e,t,r="global")=>{Pn(t),this.applyConcurrencyWrite(r,s=>{s.models={...s.models,[e]:t}})},"setModel"),removeHarness:o((e,t="global")=>{this.removeConcurrencyEntry("harnesses",e,t)},"removeHarness"),removeProvider:o((e,t="global")=>{this.removeConcurrencyEntry("providers",e,t)},"removeProvider"),removeDefault:o((e="global")=>{this.removeConcurrencyEntry("default",void 0,e)},"removeDefault"),removeModel:o((e,t="global")=>{this.removeConcurrencyEntry("models",e,t)},"removeModel"),clearAll:o((e="global")=>{this.layers.clear(e,t=>{delete t.concurrency},()=>{this.sessionConcurrencyLayer={}}),this.applyConcurrency()},"clearAll")},session:{setOverride:o((e,t)=>{this.sessionOverrides[e]=t},"setOverride"),clearOverride:o(e=>{delete this.sessionOverrides[e]},"clearOverride"),clearAll:o(()=>{this.sessionOverrides={default:null}},"clearAll")}};reload(){this.layers.reload(),this.sessionOverrides={default:null},this.sessionThinking={},this.sessionHarnessDefaults={},this.sessionThinkingDefaults={},this.sessionConcurrencyLayer={},this.applyConcurrency()}setDeps(e){e.manager!==void 0&&(this.manager=e.manager),this.applyConcurrency()}dispose(){this.manager=void 0}setAgentLayerEntry(e,t,r){this.layers.mutate(r,s=>{s.agent??={},t===void 0?delete s.agent[e]:s.agent[e]=t})}setAgentModelKey(e,t,r){if(r==="session"){this.sessionOverrides[e]=t;return}this.setAgentLayerEntry(e,t,r)}applyConcurrencyWrite(e,t){if(e==="session")t(this.sessionConcurrencyLayer);else if(!this.layers.mutate(e,r=>{r.concurrency??={},t(r.concurrency)}))return;this.applyConcurrency()}clearAgentModelKeys(e){if(e.agent)for(let t of Object.keys(e.agent))bl.has(t)||delete e.agent[t]}removeConcurrencyEntry(e,t,r){let s=o(i=>{if(!i)return;if(e==="default"){delete i.default;return}if(t===void 0)return;if(e==="harnesses"){i.harnesses&&delete i.harnesses[t];return}let a=i[e];a&&delete a[t]},"removeFrom");this.layers.clear(r,i=>s(i.concurrency),()=>s(this.sessionConcurrencyLayer)),this.applyConcurrency()}applyConcurrency(){this.manager?.setConcurrency(this.concurrency)}};var us={user:"",project:"",shared:""};function vl(){return{agents:{agents:new Map,scanDirs:us},orchestrators:{orchestrators:new Map,scanDirs:us}}}o(vl,"createSessionTemplates");var l={pi:null,sessionCtx:null,manager:null,store:new Mn,coordinator:null,runtime:null,agentSpawns:new kn,repoLock:new en,sessionTemplates:vl(),indicatorMarker:null,harnesses:lt(),multiplexers:St(),cowAvailability:jn(),cowAvailabilityClaim:0,harnessAvailability:jn(),uiFlowClaim:0,uiFlows:new WeakMap};function Dy(){if(l.pi===null)throw new Error("pi instance read before the extension factory bound it");return l.pi}o(Dy,"getPiInstance");function jy(){if(l.sessionCtx===null)throw new Error("session context read before session_start fired");return l.sessionCtx}o(jy,"getSessionCtx");function $y(){if(l.manager===null)throw new Error("agent manager read outside a live session");return l.manager}o($y,"getManager");function Fy(){return l.manager}o(Fy,"getManagerOrNull");function Gy(){return l.store}o(Gy,"getStore");function Uy(){return l.indicatorMarker}o(Uy,"getIndicatorMarker");function Wy(n){l.indicatorMarker=n}o(Wy,"setIndicatorMarker");function Ky(){return l.agentSpawns}o(Ky,"getAgentSpawns");function By(){return l.repoLock}o(By,"getRepoLock");function Vy(){if(l.coordinator===null)throw new Error("spawn coordinator read outside a live session");return l.coordinator}o(Vy,"getCoordinator");function zy(){return l.coordinator}o(zy,"getCoordinatorOrNull");function Yy(){return l.cowAvailability}o(Yy,"getCowAvailability");function Xy(){return l.cowAvailabilityClaim+=1,l.cowAvailabilityClaim}o(Xy,"beginCowAvailabilityProbe");function Jy(n,e){return n!==l.cowAvailabilityClaim?!1:(l.cowAvailability=e,!0)}o(Jy,"setCowAvailability");function qy(){return l.harnesses}o(qy,"getHarnessRegistry");function Qy(n){return{getAvailable:o(()=>n.getAvailable().map(e=>({provider:e.provider,id:e.id,thinkingLevels:El(e)})),"getAvailable")}}o(Qy,"piModelCatalog");function Zy(){let n=lt(),e=St();return l.harnesses=n,l.multiplexers=e,{harnesses:n,multiplexers:e}}o(Zy,"installSessionRegistries");function eh(){return l.harnessAvailability}o(eh,"getHarnessAvailability");function nh(n){l.harnessAvailability=n}o(nh,"setHarnessAvailability");function th(){return tr(l.store.agent.worktreeMaterialization,l.cowAvailability)}o(th,"getWorktreeMaterialization");function rh(n){l.uiFlowClaim+=1,l.uiFlows.set(n,l.uiFlowClaim)}o(rh,"beginUiFlow");function oh(n){let e=l.uiFlows.get(n);return e===void 0||e===l.uiFlowClaim}o(oh,"ownsUiFlow");function sh(){return l.harnesses.resolve(l.store.agent.harnessType,l.harnessAvailability)}o(sh,"getHarnessType");function ih(){return l.runtime}o(ih,"getRuntime");function ah(){return l.sessionTemplates}o(ah,"getSessionTemplates");function dh(n){l.pi=n}o(dh,"setPiInstance");function ch(n){l.sessionCtx=n}o(ch,"setSessionCtx");function lh(n){l.manager=n}o(lh,"setManager");function uh(n){l.coordinator=n}o(uh,"setCoordinator");function ph(n){l.runtime=n}o(ph,"setRuntime");function fh(n){l.sessionTemplates=n}o(fh,"setSessionTemplates");var wl=new RegExp(`${Dn}([A-Za-z0-9_-]+)`);function gh(n=process.argv){for(let e of n){let t=wl.exec(e);if(t)return t[1]}}o(gh,"detectSubagentSpawn");function xh(n){let e=n.theme.fg("success","\u2713"),t=n.theme.fg("error","\u2717");return{pending:o(r=>n.notify(`${r} \u2026`,"info"),"pending"),succeeded:o((r,s="info")=>n.notify(`${e} ${r}`,s),"succeeded"),failed:o((r,s)=>n.notify(`${t} ${r}: ${b(s)}`,"error"),"failed"),outcome:o((r,s)=>r==="error"?n.notify(`${t} ${s}`,"error"):n.notify(`${e} ${s}`,r==="warning"?"warning":"info"),"outcome")}}o(xh,"actionReport");export{hs as a,Vt as b,B as c,Tl as d,Cl as e,zt as f,_l as g,Ol as h,Pl as i,Ll as j,jn as k,Se as l,Nl as m,Re as n,Xl as o,Jl as p,Ze as q,ql as r,Ql as s,Ss as t,As as u,Zl as v,Is as w,eu as x,nu as y,tu as z,ru as A,F as B,du as C,g as D,ge as E,U as F,ut as G,Jf as H,eg as I,bn as J,K,$o as L,vn as M,wn as N,Rc as O,Ic as P,Go as Q,im as R,am as S,dm as T,cm as U,lm as V,Cc as W,xm as X,_c as Y,Sm as Z,Am as _,Rm as $,Im as aa,se as ba,Jo as ca,es as da,Lm as ea,Nm as fa,ay as ga,vl as ha,Dy as ia,jy as ja,$y as ka,Fy as la,Gy as ma,Uy as na,Wy as oa,Ky as pa,By as qa,Vy as ra,zy as sa,Yy as ta,Xy as ua,Jy as va,qy as wa,Qy as xa,Zy as ya,eh as za,nh as Aa,th as Ba,rh as Ca,oh as Da,sh as Ea,ih as Fa,ah as Ga,dh as Ha,ch as Ia,lh as Ja,uh as Ka,ph as La,fh as Ma,gh as Na,xh as Oa};
47
- //# sourceMappingURL=chunk-GYO352IF.js.map
47
+ //# sourceMappingURL=chunk-NF3DL7IL.js.map
@@ -1,4 +1,4 @@
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 ot,c as st,e as it,g as at,k as xe,l as dt,p as lt,u as ct,v as X,w as ut}from"./chunk-NF2BSEPU.js";import{Ca as rt,D as Qe,Fa as be,I as me,K as Xe,L as fe,O as ye,P as Ze,R as Y,S as T,T as I,V as Je,Z as et,_ as tt,b as Le,ia as x,j,ja as z,k as je,ka as w,l as Ue,m as ge,ma as y,na as E,o as qe,oa as we,pa as ve,ra as nt,ua as ke,v as We,va as V,w as Fe,wa as O,x as Ke,xa as N,y as Ge,za as Q}from"./chunk-GYO352IF.js";import{a as r,d as $,f as he,g as Ye,j as ze,k as F,l as Ve,u as K,v as G}from"./chunk-XXNZAWMK.js";import{visibleWidth as Re}from"@earendil-works/pi-tui";var Ae="\u{1F920}",kt="\u{1F404}",an="\u{1F4A9}",dn=2,ln=1e3,te=Re(kt),cn="76;175;80";function un(e){return`\x1B[48;2;${cn}m${e}\x1B[49m`}r(un,"greenBackground");function bt(e){return e===0?0:Math.max(dn,Math.ceil(Math.sqrt(2*e)))}r(bt,"pastureEdge");function xt(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(xt,"emptyPasture");function pn(e,t){let n=bt(e.cows+e.droppings),o=xt(n),i=Array.from({length:n*n},(s,d)=>d),a=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let s=0;s<a.length;s+=1){let d=s+Math.floor(t()*(i.length-s)),c=i[d];i[d]=i[s],i[s]=c,o[Math.floor(c/n)][c%n]=a[s]}return o}r(pn,"grazedPasture");function ne(e,t){let n=[];for(let o=0;o<e.length;o+=1)for(let i=0;i<e[o].length;i+=1)e[o][i]===t&&n.push({row:o,col:i});return n}r(ne,"cellsOf");function gn(e,t){return[{row:e.row-1,col:e.col},{row:e.row,col:e.col+1},{row:e.row+1,col:e.col},{row:e.row,col:e.col-1}].filter(({row:o,col:i})=>o>=0&&o<t&&i>=0&&i<t)}r(gn,"neighboursOf");function wt(e,t){return gn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(wt,"openNeighboursOf");function hn(e,t){let n=ne(e,"cow").filter(d=>wt(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=wt(o,e),a=i[Math.floor(t()*i.length)],s=e.map(d=>d.slice());return s[o.row][o.col]="empty",s[a.row][a.col]="cow",s}r(hn,"moveHerd");function vt(e,t,n,o){for(let i=0;i<n;i+=1){let a=ne(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(vt,"placeAtRandom");function mn(e,t,n,o){let i=ne(e,"cow"),a=ne(e,"dropping"),s=i.length-t,d=a.length-n;for(;s>0&&d<0;){let c=i.pop();e[c.row][c.col]="dropping",s-=1,d+=1}for(;s>0;){let c=i.pop();e[c.row][c.col]="empty",s-=1}for(;d>0;){let c=a.pop();e[c.row][c.col]="empty",d-=1}vt(e,"cow",-s,o),vt(e,"dropping",-d,o)}r(mn,"reconcileCounts");function fn(e,t,n){if(e===null)return pn(t,n);let o=bt(t.cows+t.droppings),i=xt(o);for(let a=0;a<e.length&&a<o;a+=1)for(let s=0;s<e[a].length&&s<o;s+=1)i[a][s]=e[a][s];return mn(i,t.cows,t.droppings,n),i}r(fn,"reconcilePasture");var yn={anchor:"top-right",width:Re(Ae),get offsetX(){return E()?.cowboyOffsetX??0},nonCapturing:!0},wn={anchor:"top-right",offsetY:1,get width(){return E()?.pastureWidth??0},nonCapturing:!0};function vn(e){return e==="cow"?kt:e==="dropping"?an:" ".repeat(te)}r(vn,"cellText");function kn(e,t){return e.map(n=>t(n.map(vn).join("")))}r(kn,"drawnRows");function bn(){return ve().list(["spawned"]).length}r(bn,"liveAgentCount");function xn(){return ve().list(Ze).length}r(xn,"endedAgentCount");function An(){return{live:bn(),ended:xn()}}r(An,"agentCounts");function Sn(){return y().agent.grazingEnabled}r(Sn,"grazingEnabled");var Se=class{constructor(t,n,o,i,a){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=a}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return 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(),kn(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(),ln))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,a=(this.grazing??o)&&(this.herd?.pasture.length??0)>0;if(this.herd===null||t!==this.herd.liveAgents||n!==this.herd.endedAgents)this.herd=this.place({live:t,ended:n});else if(o&&!i)this.herd={...this.herd,pasture:hn(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let s=a&&this.drawnPasture().length===0;this.tui.requestRender(s)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:fn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Te=class{static{r(this,"PastureView")}render(){return E()?.pastureRows()??[]}invalidate(){}};function At(e){Ie(),e.custom(t=>{let n=new Se(t,An,Sn,un,Math.random);return we(n),n},{overlay:!0,overlayOptions:yn,onHandle:r(t=>E()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Te,{overlay:!0,overlayOptions:wn,onHandle:r(t=>E()?.attachPasture(t),"onHandle")})}r(At,"showExtensionIndicator");function Ie(){let e=E();we(null),e?.dispose()}r(Ie,"hideExtensionIndicator");function re(){return y().agent.extensionEnabled}r(re,"isExtensionEnabled");function Tn(){return re()&&y().agent.showActiveIndicator}r(Tn,"isActiveIndicatorShown");function oe(e){Tn()?At(e):Ie()}r(oe,"syncExtensionIndicator");function Xr(e,t){y().mutate.agent.setShowActiveIndicator(t),oe(e)}r(Xr,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as Pr}from"@earendil-works/pi-tui";import{Type as h}from"typebox";var Rn="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.",In=`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.`,En=`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.`,On=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${F.join(", ")}) and any harness a plugin registered in this session. Omit it, or pass null, to leave it unset and use the agent template's harness_type, then the configured default \u2014 never pass a harness the user did not ask for. A harness this session did not register, or this machine cannot launch, fails the call before anything is spawned \u2014 unlike the configured default, an explicit request never falls back to pi.`,Cn=h.Object({prompt:h.String({description:Rn}),task_name:h.String({description:In}),agent_type:h.Optional(h.Union([h.String(),h.Null()])),model:h.Optional(h.Union([h.String(),h.Null()],{description:En})),harness_type:h.Optional(h.Union([h.String(),h.Null()],{description:On}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=h.Object({agents:h.Array(Cn,{minItems:1}),run_in_background:h.Optional(h.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Ee=Object.values(m),b={type:"json_schema",strict:"prefer"};var Oe="_configuredModel",Ce="_configuredThinking";function D(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(D,"readModelKey");function se(e){return D(e.thinking)??D(e[Ce])}r(se,"readThinkingRequest");function ie(e){let t=D(e.model);if(t)return{source:"call",key:t};let n=D(e[Oe]);if(n)return{source:"configured",key:n}}r(ie,"readModelRequest");function U(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(U,"withoutModel");function ae(e){switch(e.kind){case"resolved":return{model:e.model,key:e.modelKey,thinking:e.thinking};case"foreign":return{harness:e.harness,key:e.modelKey,name:e.modelName,thinking:e.thinking};case"level":return{levelOnly:!0,thinking:e.thinking};case"none":return}}r(ae,"modelChoiceFor");function q(e){return`${e.provider}/${e.id}`}r(q,"modelKey");function _n(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}".`}r(_n,"undeclaredLevelWarning");function St(e,t){let n=_n(e,t);return{resolved:{kind:"resolved",model:e,modelKey:q(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(St,"resolvedModel");function Pn(e){return`No API key found for "${e}"`}r(Pn,"missingCredential");function Tt(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:$(o)}}return!Qe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Pn(t.provider)}}r(Tt,"probeCredentials");function _e(e,t){return`${e}: ${t}. Nothing was spawned.`}r(_e,"refusal");function Pe(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return U(i);let d=Tt(n,o);if(d.verdict!=="unusable")return St(o,i);throw new Error(_e(`The parent session's model "${q(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?he(e.key,n,void 0):he(e.key,n,o);if(!a){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return U(i)}let s=Tt(n,a);if(s.verdict!=="unusable")return St(a,i);throw e.source==="call"?new Error(_e(`Model "${q(a)}" cannot authenticate in this session`,s.reason)):new Error(_e(`The subagent model "${q(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(Pe,"resolvePiModel");async function Mn(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Mn,"harnessModels");function $n(e,t,n){if(t===void 0||t.thinkingLevels.kind!=="closed")return;let{levels:o}=t.thinkingLevels;if(!o.includes(n))return o.length===0?`Model "${t.key}" (${e}) does not support thinking levels; launching with "${n}".`:`Thinking level "${n}" is not declared by ${e} model "${t.key}" (supported: ${o.join(", ")}); proceeding with "${n}".`}r($n,"undeclaredLevelWarning");async function Rt(e,t){if(!e)return U(t.thinking);let n=await Mn(t),o=n.find(a=>a.key===e.key),i=[];if(n.length>0&&!o&&i.push(`The ${t.harness} model list does not include "${e.key}"; launching with that key anyway.`),t.thinking!==void 0){let a=$n(t.harness,o,t.thinking);a!==void 0&&i.push(a)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(Rt,"resolveForeignModel");async function de(e,t){let{harness:n}=t;if(Ve(n))return Pe(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Rt(e,o)}r(de,"resolveSpawnModel");function B(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(B,"resultWithSeverity");function le(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(le,"foldSeverity");var Me=`
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 ot,c as st,e as it,g as at,k as xe,l as dt,p as lt,u as ct,v as X,w as ut}from"./chunk-F77A4UCS.js";import{Ca as rt,D as Qe,Fa as be,I as me,K as Xe,L as fe,O as ye,P as Ze,R as Y,S as T,T as I,V as Je,Z as et,_ as tt,b as Le,ia as x,j,ja as z,k as je,ka as w,l as Ue,m as ge,ma as y,na as E,o as qe,oa as we,pa as ve,ra as nt,ua as ke,v as We,va as V,w as Fe,wa as O,x as Ke,xa as N,y as Ge,za as Q}from"./chunk-NF3DL7IL.js";import{a as r,d as $,f as he,g as Ye,j as ze,k as F,l as Ve,u as K,v as G}from"./chunk-XXNZAWMK.js";import{visibleWidth as Re}from"@earendil-works/pi-tui";var Ae="\u{1F920}",kt="\u{1F404}",an="\u{1F4A9}",dn=2,ln=1e3,te=Re(kt),cn="76;175;80";function un(e){return`\x1B[48;2;${cn}m${e}\x1B[49m`}r(un,"greenBackground");function bt(e){return e===0?0:Math.max(dn,Math.ceil(Math.sqrt(2*e)))}r(bt,"pastureEdge");function xt(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(xt,"emptyPasture");function pn(e,t){let n=bt(e.cows+e.droppings),o=xt(n),i=Array.from({length:n*n},(s,d)=>d),a=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let s=0;s<a.length;s+=1){let d=s+Math.floor(t()*(i.length-s)),c=i[d];i[d]=i[s],i[s]=c,o[Math.floor(c/n)][c%n]=a[s]}return o}r(pn,"grazedPasture");function ne(e,t){let n=[];for(let o=0;o<e.length;o+=1)for(let i=0;i<e[o].length;i+=1)e[o][i]===t&&n.push({row:o,col:i});return n}r(ne,"cellsOf");function gn(e,t){return[{row:e.row-1,col:e.col},{row:e.row,col:e.col+1},{row:e.row+1,col:e.col},{row:e.row,col:e.col-1}].filter(({row:o,col:i})=>o>=0&&o<t&&i>=0&&i<t)}r(gn,"neighboursOf");function wt(e,t){return gn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(wt,"openNeighboursOf");function hn(e,t){let n=ne(e,"cow").filter(d=>wt(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=wt(o,e),a=i[Math.floor(t()*i.length)],s=e.map(d=>d.slice());return s[o.row][o.col]="empty",s[a.row][a.col]="cow",s}r(hn,"moveHerd");function vt(e,t,n,o){for(let i=0;i<n;i+=1){let a=ne(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(vt,"placeAtRandom");function mn(e,t,n,o){let i=ne(e,"cow"),a=ne(e,"dropping"),s=i.length-t,d=a.length-n;for(;s>0&&d<0;){let c=i.pop();e[c.row][c.col]="dropping",s-=1,d+=1}for(;s>0;){let c=i.pop();e[c.row][c.col]="empty",s-=1}for(;d>0;){let c=a.pop();e[c.row][c.col]="empty",d-=1}vt(e,"cow",-s,o),vt(e,"dropping",-d,o)}r(mn,"reconcileCounts");function fn(e,t,n){if(e===null)return pn(t,n);let o=bt(t.cows+t.droppings),i=xt(o);for(let a=0;a<e.length&&a<o;a+=1)for(let s=0;s<e[a].length&&s<o;s+=1)i[a][s]=e[a][s];return mn(i,t.cows,t.droppings,n),i}r(fn,"reconcilePasture");var yn={anchor:"top-right",width:Re(Ae),get offsetX(){return E()?.cowboyOffsetX??0},nonCapturing:!0},wn={anchor:"top-right",offsetY:1,get width(){return E()?.pastureWidth??0},nonCapturing:!0};function vn(e){return e==="cow"?kt:e==="dropping"?an:" ".repeat(te)}r(vn,"cellText");function kn(e,t){return e.map(n=>t(n.map(vn).join("")))}r(kn,"drawnRows");function bn(){return ve().list(["spawned"]).length}r(bn,"liveAgentCount");function xn(){return ve().list(Ze).length}r(xn,"endedAgentCount");function An(){return{live:bn(),ended:xn()}}r(An,"agentCounts");function Sn(){return y().agent.grazingEnabled}r(Sn,"grazingEnabled");var Se=class{constructor(t,n,o,i,a){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=a}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return 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(),kn(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(),ln))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,a=(this.grazing??o)&&(this.herd?.pasture.length??0)>0;if(this.herd===null||t!==this.herd.liveAgents||n!==this.herd.endedAgents)this.herd=this.place({live:t,ended:n});else if(o&&!i)this.herd={...this.herd,pasture:hn(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let s=a&&this.drawnPasture().length===0;this.tui.requestRender(s)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:fn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Te=class{static{r(this,"PastureView")}render(){return E()?.pastureRows()??[]}invalidate(){}};function At(e){Ie(),e.custom(t=>{let n=new Se(t,An,Sn,un,Math.random);return we(n),n},{overlay:!0,overlayOptions:yn,onHandle:r(t=>E()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Te,{overlay:!0,overlayOptions:wn,onHandle:r(t=>E()?.attachPasture(t),"onHandle")})}r(At,"showExtensionIndicator");function Ie(){let e=E();we(null),e?.dispose()}r(Ie,"hideExtensionIndicator");function re(){return y().agent.extensionEnabled}r(re,"isExtensionEnabled");function Tn(){return re()&&y().agent.showActiveIndicator}r(Tn,"isActiveIndicatorShown");function oe(e){Tn()?At(e):Ie()}r(oe,"syncExtensionIndicator");function Xr(e,t){y().mutate.agent.setShowActiveIndicator(t),oe(e)}r(Xr,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as Pr}from"@earendil-works/pi-tui";import{Type as h}from"typebox";var Rn="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.",In=`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.`,En=`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.`,On=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${F.join(", ")}) and any harness a plugin registered in this session. Omit it, or pass null, to leave it unset and use the agent template's harness_type, then the configured default \u2014 never pass a harness the user did not ask for. A harness this session did not register, or this machine cannot launch, fails the call before anything is spawned \u2014 unlike the configured default, an explicit request never falls back to pi.`,Cn=h.Object({prompt:h.String({description:Rn}),task_name:h.String({description:In}),agent_type:h.Optional(h.Union([h.String(),h.Null()])),model:h.Optional(h.Union([h.String(),h.Null()],{description:En})),harness_type:h.Optional(h.Union([h.String(),h.Null()],{description:On}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=h.Object({agents:h.Array(Cn,{minItems:1}),run_in_background:h.Optional(h.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Ee=Object.values(m),b={type:"json_schema",strict:"prefer"};var Oe="_configuredModel",Ce="_configuredThinking";function D(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(D,"readModelKey");function se(e){return D(e.thinking)??D(e[Ce])}r(se,"readThinkingRequest");function ie(e){let t=D(e.model);if(t)return{source:"call",key:t};let n=D(e[Oe]);if(n)return{source:"configured",key:n}}r(ie,"readModelRequest");function U(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(U,"withoutModel");function ae(e){switch(e.kind){case"resolved":return{model:e.model,key:e.modelKey,thinking:e.thinking};case"foreign":return{harness:e.harness,key:e.modelKey,name:e.modelName,thinking:e.thinking};case"level":return{levelOnly:!0,thinking:e.thinking};case"none":return}}r(ae,"modelChoiceFor");function q(e){return`${e.provider}/${e.id}`}r(q,"modelKey");function _n(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}".`}r(_n,"undeclaredLevelWarning");function St(e,t){let n=_n(e,t);return{resolved:{kind:"resolved",model:e,modelKey:q(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(St,"resolvedModel");function Pn(e){return`No API key found for "${e}"`}r(Pn,"missingCredential");function Tt(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:$(o)}}return!Qe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Pn(t.provider)}}r(Tt,"probeCredentials");function _e(e,t){return`${e}: ${t}. Nothing was spawned.`}r(_e,"refusal");function Pe(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return U(i);let d=Tt(n,o);if(d.verdict!=="unusable")return St(o,i);throw new Error(_e(`The parent session's model "${q(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?he(e.key,n,void 0):he(e.key,n,o);if(!a){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return U(i)}let s=Tt(n,a);if(s.verdict!=="unusable")return St(a,i);throw e.source==="call"?new Error(_e(`Model "${q(a)}" cannot authenticate in this session`,s.reason)):new Error(_e(`The subagent model "${q(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(Pe,"resolvePiModel");async function Mn(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Mn,"harnessModels");function $n(e,t,n){if(t===void 0||t.thinkingLevels.kind!=="closed")return;let{levels:o}=t.thinkingLevels;if(!o.includes(n))return o.length===0?`Model "${t.key}" (${e}) does not support thinking levels; launching with "${n}".`:`Thinking level "${n}" is not declared by ${e} model "${t.key}" (supported: ${o.join(", ")}); proceeding with "${n}".`}r($n,"undeclaredLevelWarning");async function Rt(e,t){if(!e)return U(t.thinking);let n=await Mn(t),o=n.find(a=>a.key===e.key),i=[];if(n.length>0&&!o&&i.push(`The ${t.harness} model list does not include "${e.key}"; launching with that key anyway.`),t.thinking!==void 0){let a=$n(t.harness,o,t.thinking);a!==void 0&&i.push(a)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(Rt,"resolveForeignModel");async function de(e,t){let{harness:n}=t;if(Ve(n))return Pe(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Rt(e,o)}r(de,"resolveSpawnModel");function B(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(B,"resultWithSeverity");function le(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(le,"foldSeverity");var Me=`
2
2
 
3
3
  ---
4
4
 
@@ -10,5 +10,5 @@ ${qn(u)}`,details:S}}let p=c;if(u.lifecycle.phase==="queued"){let S=w().listAgen
10
10
  `).map(n=>n.trim()).filter(n=>n!==""):[]}r(hr,"parseConflictFiles");function mr(e,t){return e.includes(`branch "${t}" does not exist`)}r(mr,"isUnknownBranchError");async function fr(e,t,n,o,i){let a=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",s=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,d,c=r(()=>(d??=(async()=>{let l=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 cr(x(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:ur,prepare:r(async()=>{xe(a,"target");for(let l of t.branches)xe(l.trim(),"branch");await c()},"prepare"),halt:{on:r(l=>l.kind==="conflict","on"),skip:r((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:r(async l=>{let{sessionRoot:v,cwd:g}=await c(),u=l.trim();try{let p=await dt(x(),{cwd:g,branch:u,target:a}),f=dr(p.mainRoot,v)?void 0:lr(p.mainRoot,v);if(f!==void 0)try{i.ui.notify(f,"warning")}catch{}let k=f!==void 0?`${f}
11
11
  `:"";return p.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${k}"${u}" is already merged into "${p.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:p.target,output:p.output},text:`${k}Merged "${u}" into "${p.target}" in ${p.mainRoot}.`+(p.output?`
12
12
  ${p.output}`:"")}}catch(p){let f=p instanceof Error?p.message:String(p);return gr(f)?{outcome:{kind:"conflict",branch:u,target:a,files:hr(f)},text:`"${u}": ${f}`}:mr(f,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${f}`}:{outcome:{kind:"failed",branch:u,error:f},text:`"${u}": ${f}`}}},"handleItem")})}r(fr,"executeMergeBranchTool");import{Type as ce}from"typebox";var yr="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.",wr="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.",Ft=ce.Object({agent_ids:ce.Array(ce.String({minLength:1}),{minItems:1,description:yr}),message:ce.String({description:wr})},{additionalProperties:!1,required:["agent_ids","message"]});var Kt={name:m.steerAgent,label:m.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:Ft,execute:kr,constrainedSampling:b};function vr(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(vr,"steerSeverity");async function kr(e,t,n,o,i){let a=t.message.trim();return R({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,severity:vr,prepare:r(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:r(async s=>{let d=w().getSpawn(s);if(!d){let g=`not found. Active agents: ${C()}`;return{outcome:{kind:"refused",agentId:s,reason:g},text:`Agent ${s} was not steered: ${g}`}}let c=I(d.lifecycle),l;try{l=await w().steer(s,a)}catch(g){l={kind:"refused",reason:`steering failed: ${$(g)}`}}if(l.kind==="refused")return{outcome:{kind:"refused",agentId:s,reason:l.reason},text:`Agent ${s} was not steered (${c}): ${l.reason}`};if(l.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:s,reason:l.reason},text:`Agent ${s} had settled (${c}) and the message reached its pane, but it was not revived: ${l.reason}`};let v=c!=="spawned"&&d.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:s},text:v?`Agent ${s} had settled (${c}) \u2014 revived: the message was delivered to its pane and the agent is spawned again. Merge nothing yet; a new completion message will arrive when it settles again.`:c==="spawned"?`Message delivered to spawned agent ${s}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${s} was delivered to (${c}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r(kr,"executeSteerAgentTool");function Fs(e,t,n){return ge(e.ids(),t).filter(o=>o!==n)}r(Fs,"handoverTargets");function Gt(e,t,n){let o=e.trim();return o===""?{kind:"faulted",fault:{kind:"request-refused",detail:"`harness_type` is required \u2014 name the harness that runs the next run. Nothing was changed."}}:t.get(o)===void 0?{kind:"faulted",fault:{kind:"request-refused",detail:`Unknown harness_type "${o}": this session registered ${t.ids().join(", ")}. Nothing was changed \u2014 name a registered harness that runs the next run.`}}:Ue(o,n)?{kind:"ready",harness:o}:{kind:"faulted",fault:{kind:"request-refused",detail:`Harness "${o}" cannot be launched on this machine \u2014 this machine can launch ${ge(t.ids(),n).join(", ")}. Nothing was changed.`}}}r(Gt,"resolveHandoverTarget");import{Type as A}from"typebox";var br="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.",xr=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${F.join(", ")}) and any harness a plugin registered in this session. Unlike the configured default, an explicit harness never falls back: an ID this session did not register, or one this machine cannot launch, causes the call to be refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result and nothing changes.`,Ar=`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.`,Sr="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:br}),harness_type:A.String({description:xr}),model:A.Optional(A.Union([A.String(),A.Null()],{description:Ar})),thinking:A.Optional(A.Union([A.String(),A.Null()],{description:Sr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Tr(e,t){let n=Gt(e.harness_type,O(),Q());if(n.kind==="faulted")return{kind:"faulted",fault:n.fault};let o=n.harness;try{let i=await de(ie(e),{harness:o,registry:t.modelRegistry,parent:t.model,thinking:se(e),listModels:r(async a=>{let s=await O().require(a).listModels({pi:x(),modelCatalog:N(t.modelRegistry)}),d=G(s);return d!==void 0&&t.hasUI&&t.ui.notify(d,"warning"),K(s)},"listModels")});for(let a of i.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:o,modelChoice:ae(i.resolved)}}catch(i){return{kind:"faulted",fault:{kind:"request-refused",detail:$(i)}}}}r(Tr,"resolveIntent");function Rr(e,t){return`Agent ${e} ${Ir(t)}`}r(Rr,"renderHandoverOutcome");function Ir(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":et(e.loss);return`handed over from "${e.from}" to "${e.to}".${t} The ended run is archived; the next one runs in the same checkout and reports when it settles.`}switch(e.fault.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return e.fault.status==="queued"?"is still queued \u2014 it has not started, so there is no session to hand over. Wait for a concurrency slot (or stop it). Nothing was changed.":`is still ${e.fault.status} \u2014 stop it with stop_cowboy_agent and hand it over once it has settled. Nothing was changed.`;case"harness-cannot-export-session":return`was not handed over: harness "${e.fault.harness}" cannot export its own session, so there is nothing to hand over. Nothing was stopped or changed.`;case"never-started":return"was not handed over: it never started, so there is no session to export.";case"stop-failed":return`was not handed over: its run could not be stopped (${e.fault.detail}). Nothing was changed.`;case"session-empty":return`was not handed over: harness "${e.fault.harness}" returned an empty session. Nothing was changed: the run was not stopped.`;case"session-export-failed":return`was not handed over: harness "${e.fault.harness}" could not export its session (${e.fault.detail}). Nothing was changed: the run was not stopped.`;case"request-refused":return`was not handed over: ${e.fault.detail}`;case"launch-failed":return`ended its previous run but its next one did not start (${e.fault.detail}). It stays tracked and can be cleaned up.`}}r(Ir,"handoverReport");async function Er(e,t,n,o,i){let a=t.agent_id.trim(),s=await Tr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await w().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return B(tt(d),Rr(a,d),{agentId:a,outcome:d})}r(Er,"executeHandoverAgentTool");var zt={name:m.handoverAgent,label:m.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:Er,constrainedSampling:b};import{Text as Or}from"@earendil-works/pi-tui";var Cr={success:"\u2713",warning:"!",error:"\u2717"};function _r(e,t,n,o){let i=e.content.map(d=>d.text??"").join(`
13
- `),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Or(`${n.fg(a,Cr[a])} ${s}`,0,0)}r(_r,"renderCowboyToolResult");function P(e){return{...e,renderResult:_r}}r(P,"withCowboyRenderer");var Mr=Ee;function $r(e){let t=M.Object({prompt:H.properties.agents.items.properties.prompt,task_name:H.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:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r($r,"cowboyAgentsSchemaWithTypes");function Qt(e){let t=$r(ut()),n={name:m.agent,label:m.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:_t,constrainedSampling:b};e.registerTool(P(n))}r(Qt,"registerAgentTool");function Nr(e,t){y().mutate.agent.setExtensionEnabled(t),t?Hr(e):Dr(e)}r(Nr,"setExtensionEnabled");function Hr(e){let t=x();Qt(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Mr])]),oe(e)}r(Hr,"activateExtension");function Dr(e){let t=x();t.setActiveTools(t.getActiveTools().filter(n=>!Ee.includes(n))),oe(e)}r(Dr,"deactivateExtension");function Si(e){Qt(e),e.registerTool(P(Pt)),e.registerTool(P(Wt)),e.registerTool(P(Kt)),e.registerTool(P(zt)),e.registerTool(P(Lt)),e.registerMessageRenderer("subagent-result",(t,n,o)=>{let i=typeof t=="object"&&typeof t.content=="string"?t.content:"",a=/\b(error|stopped)\b/.test(i.slice(0,200)),s=o.fg(a?"error":"success",a?"\u2717":"\u2713");return new Pr(`${s} ${i}`,0,0)})}r(Si,"registerTools");async function Vt(e,t){let n=await O().listModelOptions({pi:e,modelCatalog:N(t.modelRegistry)},Q());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Vt,"harnessModelOptions");var Xt="cowboy",Br={wt:"worktree",sp:"spawn",st:"status"};function Ti(e,t){e.registerCommand(Xt,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Ti,"registerUnavailableCowboyCommand");function Ri(e){e.registerCommand(Xt,{description:"Manage agents: status, spawn, settings. `status` lists spawned, queued and settled agents; `spawn` opens the spawn wizard; `worktree` creates one git worktree with no agent attached to it. `status`, `spawn` and `worktree` also answer to `st`, `sp` and `wt`. `enable`/`disable` load or unload the cowboy tools. Pass `model` (optionally a provider/model-id) to set the model agents use for this session \u2014 opens pi's model picker.",getArgumentCompletions:r(async t=>(await import("./model-picker-I2L5LYS7.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{rt(n);let[o,...i]=t.trim().split(/\s+/),a=Br[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&be()===null){n.ui.notify(me,"warning");return}if(re()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}Nr(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(be()===null){n.ui.notify(me,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-FGIFMYRD.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!re()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-I2L5LYS7.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-QMEWZXAL.js");await l(n,s,await Vt(e,n));return}if(s!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-QMEWZXAL.js");await c(n,await Vt(e,n))},"handler")})}r(Ri,"registerCowboyCommand");import*as Zt from"node:fs";import{tmpdir as Lr}from"node:os";import*as ue from"node:path";async function Jt(e,t){try{return await ot(e).probe(t),j(qe)}catch{return j(["checkout"])}}r(Jt,"detectCowAvailability");function en(e){let t=ue.resolve(e??Le());for(;;){try{if(Zt.statSync(t).isDirectory())return t}catch{}let n=ue.dirname(t);if(n===t)return Lr();t=n}}r(en,"probeTargetFor");function jr(e){return(t,n,o)=>e.exec(t,n,o)}r(jr,"execOf");function Li(e){return tn(e,ke())}r(Li,"startCowSupportProbe");function ji(e){let t=ke();return V(t,je()),tn(e,t)}r(ji,"refreshCowSupportProbe");function tn(e,t){let n=en(y().agent.worktreeRoot);return Jt(jr(e),n).then(o=>{V(t,o)},()=>{V(t,j(["checkout"]))})}r(tn,"probe");import nn from"node:fs";var Ur="/tmp";function qr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(qr,"handoverNameField");function rn(e){return`cowboy-handover_${[e.worktree,e.harness,e.sessionId].map(qr).join("_")}.md`}r(rn,"handoverFileName");function on(e){return`${Ur}/${e}`}r(on,"handoverFilePath");function Wr(e){return nn.existsSync(e)}r(Wr,"handoverFileExists");function Fi(e,t){let n=Wr(e);return nn.writeFileSync(e,t,"utf8"),{replaced:n}}r(Fi,"writeHandoverFile");function zi(e){return{kind:"prepared",path:on(rn({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(zi,"handoverExportArtifact");function Vi(e){switch(e.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return`is still ${e.status} \u2014 only a settled run has a session to export. Nothing was changed.`;case"harness-cannot-export-session":return`was not exported: harness "${e.harness}" cannot export its own session, so there is nothing to write.`;case"never-started":return"was not exported: it never started, so there is no session to export.";case"handover-in-progress":return`was not exported: ${e.detail}`;case"session-empty":return`was not exported: harness "${e.harness}" returned an empty session.`;case"session-export-failed":return`was not exported: harness "${e.harness}" could not export its session (${e.detail}).`}}r(Vi,"handoverExportFaultReason");function Qi(e){if(e.kind==="prepared")return e.loss===void 0?"success":"warning";switch(e.fault.kind){case"agent-unknown":case"agent-not-settled":case"harness-cannot-export-session":case"never-started":case"handover-in-progress":return"warning";case"session-empty":case"session-export-failed":return"error"}}r(Qi,"handoverExportSeverity");export{$e as a,Un as b,qn as c,ss as d,Nt as e,cs as f,us as g,Fs as h,Rr as i,Ie as j,re as k,Xr as l,Wr as m,Fi as n,zi as o,Vi as p,Qi as q,Li as r,ji as s,Nr as t,Hr as u,Dr as v,Si as w,Ti as x,Ri as y};
14
- //# sourceMappingURL=chunk-CAWIXE4E.js.map
13
+ `),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Or(`${n.fg(a,Cr[a])} ${s}`,0,0)}r(_r,"renderCowboyToolResult");function P(e){return{...e,renderResult:_r}}r(P,"withCowboyRenderer");var Mr=Ee;function $r(e){let t=M.Object({prompt:H.properties.agents.items.properties.prompt,task_name:H.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:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r($r,"cowboyAgentsSchemaWithTypes");function Qt(e){let t=$r(ut()),n={name:m.agent,label:m.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:_t,constrainedSampling:b};e.registerTool(P(n))}r(Qt,"registerAgentTool");function Nr(e,t){y().mutate.agent.setExtensionEnabled(t),t?Hr(e):Dr(e)}r(Nr,"setExtensionEnabled");function Hr(e){let t=x();Qt(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Mr])]),oe(e)}r(Hr,"activateExtension");function Dr(e){let t=x();t.setActiveTools(t.getActiveTools().filter(n=>!Ee.includes(n))),oe(e)}r(Dr,"deactivateExtension");function Si(e){Qt(e),e.registerTool(P(Pt)),e.registerTool(P(Wt)),e.registerTool(P(Kt)),e.registerTool(P(zt)),e.registerTool(P(Lt)),e.registerMessageRenderer("subagent-result",(t,n,o)=>{let i=typeof t=="object"&&typeof t.content=="string"?t.content:"",a=/\b(error|stopped)\b/.test(i.slice(0,200)),s=o.fg(a?"error":"success",a?"\u2717":"\u2713");return new Pr(`${s} ${i}`,0,0)})}r(Si,"registerTools");async function Vt(e,t){let n=await O().listModelOptions({pi:e,modelCatalog:N(t.modelRegistry)},Q());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Vt,"harnessModelOptions");var Xt="cowboy",Br={wt:"worktree",sp:"spawn",st:"status"};function Ti(e,t){e.registerCommand(Xt,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Ti,"registerUnavailableCowboyCommand");function Ri(e){e.registerCommand(Xt,{description:"Manage agents: status, spawn, settings. `status` lists spawned, queued and settled agents; `spawn` opens the spawn wizard; `worktree` creates one git worktree with no agent attached to it. `status`, `spawn` and `worktree` also answer to `st`, `sp` and `wt`. `enable`/`disable` load or unload the cowboy tools. Pass `model` (optionally a provider/model-id) to set the model agents use for this session \u2014 opens pi's model picker.",getArgumentCompletions:r(async t=>(await import("./model-picker-CRQCRAYT.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{rt(n);let[o,...i]=t.trim().split(/\s+/),a=Br[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&be()===null){n.ui.notify(me,"warning");return}if(re()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}Nr(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(be()===null){n.ui.notify(me,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-3KBKYTRL.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!re()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-CRQCRAYT.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-FNRNSUTM.js");await l(n,s,await Vt(e,n));return}if(s!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-FNRNSUTM.js");await c(n,await Vt(e,n))},"handler")})}r(Ri,"registerCowboyCommand");import*as Zt from"node:fs";import{tmpdir as Lr}from"node:os";import*as ue from"node:path";async function Jt(e,t){try{return await ot(e).probe(t),j(qe)}catch{return j(["checkout"])}}r(Jt,"detectCowAvailability");function en(e){let t=ue.resolve(e??Le());for(;;){try{if(Zt.statSync(t).isDirectory())return t}catch{}let n=ue.dirname(t);if(n===t)return Lr();t=n}}r(en,"probeTargetFor");function jr(e){return(t,n,o)=>e.exec(t,n,o)}r(jr,"execOf");function Li(e){return tn(e,ke())}r(Li,"startCowSupportProbe");function ji(e){let t=ke();return V(t,je()),tn(e,t)}r(ji,"refreshCowSupportProbe");function tn(e,t){let n=en(y().agent.worktreeRoot);return Jt(jr(e),n).then(o=>{V(t,o)},()=>{V(t,j(["checkout"]))})}r(tn,"probe");import nn from"node:fs";var Ur="/tmp";function qr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(qr,"handoverNameField");function rn(e){return`cowboy-handover_${[e.worktree,e.harness,e.sessionId].map(qr).join("_")}.md`}r(rn,"handoverFileName");function on(e){return`${Ur}/${e}`}r(on,"handoverFilePath");function Wr(e){return nn.existsSync(e)}r(Wr,"handoverFileExists");function Fi(e,t){let n=Wr(e);return nn.writeFileSync(e,t,"utf8"),{replaced:n}}r(Fi,"writeHandoverFile");function zi(e){return{kind:"prepared",path:on(rn({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(zi,"handoverExportArtifact");function Vi(e){switch(e.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return`is still ${e.status} \u2014 only a settled run has a session to export. Nothing was changed.`;case"harness-cannot-export-session":return`was not exported: harness "${e.harness}" cannot export its own session, so there is nothing to write.`;case"never-started":return"was not exported: it never started, so there is no session to export.";case"handover-in-progress":return`was not exported: ${e.detail}`;case"session-empty":return`was not exported: harness "${e.harness}" returned an empty session.`;case"session-export-failed":return`was not exported: harness "${e.harness}" could not export its session (${e.detail}).`}}r(Vi,"handoverExportFaultReason");function Qi(e){if(e.kind==="prepared")return e.loss===void 0?"success":"warning";switch(e.fault.kind){case"agent-unknown":case"agent-not-settled":case"harness-cannot-export-session":case"never-started":case"handover-in-progress":return"warning";case"session-empty":case"session-export-failed":return"error"}}r(Qi,"handoverExportSeverity");export{$e as a,Un as b,qn as c,ss as d,Nt as e,cs as f,us as g,Fs as h,Rr as i,Ie as j,re as k,Xr as l,Wr as m,Fi as n,zi as o,Vi as p,Qi as q,Li as r,ji as s,Nr as t,Hr as u,Dr as v,Si as w,Ti as x,Ri as y};
14
+ //# sourceMappingURL=chunk-XWEYV2EP.js.map
@@ -1,2 +1,2 @@
1
- import{h as l,n as h}from"./chunk-ROCBRG4A.js";import{a as r}from"./chunk-XXNZAWMK.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
2
- //# sourceMappingURL=chunk-67VN34QV.js.map
1
+ import{h as l,n as h}from"./chunk-5Q6BGTTQ.js";import{a as r}from"./chunk-XXNZAWMK.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
2
+ //# sourceMappingURL=chunk-ZZFQQC33.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as ke,b as Et,c as Ct,d as Tt,j as Lt,k as q,o as Dt,r as jt,u as $t,v as Se,w as Wt,x as qt,y as Nt}from"./chunk-CAWIXE4E.js";import{E as At,F as xt,G as Rt,O as It,Q as Ot,R as Ht,S as Mt,a as pt,f as gt,g as K,h as ht,m as ft,n as mt,o as yt,q as vt,r as wt,s as kt,t as St,v as Pt,y as bt}from"./chunk-NF2BSEPU.js";import{$ as Xe,A as Ne,Aa as ot,Ba as at,E as X,F as U,Fa as G,G as Qe,Ha as lt,I as he,Ia as dt,J as T,Ja as ve,Ka as we,La as te,Ma as ut,Na as ct,O as J,Oa as Ft,Q as ze,R as Ve,S as B,T as L,U as Ye,V as fe,a as E,aa as Je,c as Oe,ca as Ze,d as I,da as et,e as He,ea as me,f as Me,fa as tt,g as De,ga as nt,ha as rt,ia as R,j as je,ja as Z,la as ye,ma as b,pa as F,sa as ee,u as $e,w as We,wa as A,y as qe,ya as st,z as Y,za as it}from"./chunk-GYO352IF.js";import{a as i,b as _e,d as y,h as M,i as Ue,r as Be,s as Ge,x as Ke}from"./chunk-XXNZAWMK.js";import*as O from"node:path";function re(t,e){let r=t.at(0);if(r)return{kind:"spawn",spawn:r};let n=e.at(0);return n?{kind:"multiplexer",attempt:n}:{kind:"none"}}i(re,"findTaskDedup");var D=class extends Error{static{i(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",s=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?L(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${s} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},ne=class{constructor(e){this.deps=e}deps;static{i(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let s=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,s);try{return await s}finally{this.admissionBySlug.get(r)===s&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let p=this.deps.listAgents().filter(g=>g.display.taskSlug===e.taskSlug&&Ve(g.lifecycle.phase)),c=re(p,await this.deps.findTaskAttempts(e.taskSlug));if(c.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:c.kind==="spawn"?c.spawn.id:c.attempt.name}}let{type:r,prompt:n,runInBackground:s,signal:o,...l}=e,a={...l,isBackground:s,signal:o},d=this.deps.spawn(r,n,a);return this.deps.getSpawn(d)?.lifecycle.phase==="queued"?{status:"queued",agentId:d,queuePosition:this.deps.queuePosition(d)}:{status:"admitted",agentId:d}}};import _t from"node:fs";var se=class{constructor(e){this.resultFile=e}resultFile;static{i(this,"FileDeliverable")}async readDeliverable(){try{let e=_t.statSync(this.resultFile).mtimeMs,r=_t.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import Ut from"node:fs";import*as Bt from"node:path";function Q(t){try{Ut.rmSync(Bt.dirname(t),{recursive:!0,force:!0})}catch{}}i(Q,"removeResultArtifacts");function Gt(t){try{Ut.rmSync(t,{force:!0})}catch{}}i(Gt,"removeResultFile");import*as N from"node:fs";import*as ie from"node:path";var Yn=T("assets");async function Kt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}i(Kt,"probeList");function Xn(t,e,r){let n=r(e);return t?.find(s=>r(s.path)===n)}i(Xn,"matchWorktree");function zt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}i(zt,"paneOf");function Qt(t,e,r){let n=r(e),s=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return s===void 0?void 0:zt(s)}i(Qt,"paneInWorktree");function Jn(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:zt(r)}i(Jn,"paneInWorkspace");function Zn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}i(e,"root");async function r(a,d){let u=await e(),p=[],c=new Set,g=i(h=>{let m=t.canonicalizePath(h.path);c.has(m)||(c.add(m),p.push(h))},"push");for(let h of d??[]){let m=ie.basename(h.path);Y(m,a)&&(u!==void 0&&!Ne(h.path,u)||g({path:h.path,branch:h.branch!==void 0&&Y(h.branch,a)?h.branch:m,workspaceId:h.workspaceId}))}if(p.length>0||u===void 0)return p;for(let h of await t.listRootEntries(u))Y(h,a)&&g({path:ie.join(u,h),branch:h});return p}i(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}i(n,"candidateSummary");async function s(a,d,u,p){let c=d.execution.host,g=d.display.worktree,h=g?.kind==="owned",m=c?{paneId:c.paneId,tabId:c.tabId,workspaceId:c.workspaceId}:null,f="tracked",w=g?.kind==="owned"?g.path:void 0,P=c?.workspaceId;if(w!==void 0){let x=Xn(u,w,t.canonicalizePath);x!==void 0&&(P=x.workspaceId)}let S=w===void 0?m:Qt(p,w,t.canonicalizePath)??m,k=w===void 0?null:{path:w,workspaceId:P,repoCwd:await t.resolveRepoCwd(w)};return{kind:"located",source:f,id:a,branch:g?.branch??We(d.display.taskSlug??$e(d.display.type),d.id),worktreeManaged:h||k!==null,paneCreated:c?.paneCreated===!0,worktree:k,pane:S}}i(s,"locateTracked");async function o(a,d,u){let p=await r(a,d);if(p.length===0)return{kind:"not-found",id:a};if(p.length>1)return{kind:"ambiguous",id:a,candidates:p.map(n)};let c=p[0],g=Qt(u,c.path,t.canonicalizePath)??Jn(u,c.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:c.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:c.path,workspaceId:c.workspaceId,repoCwd:await t.resolveRepoCwd(c.path)},pane:g}}i(o,"locateDiscovered");async function l(a,d){let u=await Kt(t.listWorktrees),p=await Kt(t.listPlacements),c=u.ok?u.entries:void 0,g=p.ok?p.entries:void 0;return d===void 0?o(a,c,g):s(a,d,c,g)}return i(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:i(a=>t.readPane(a.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}i(Zn,"createAgentAssets");function Vt(t,e,r){return Zn({multiplexer:r.multiplexer,canonicalizePath:i(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:i(n=>{let s=I(n);return{path:s,present:N.existsSync(s)}},"deliverable"),listWorktrees:i(()=>r.listWorktrees(),"listWorktrees"),listPlacements:i(()=>r.listPlacements(),"listPlacements"),readPane:i(n=>r.observePane(n),"readPane"),worktreeRoot:i(async()=>{let n=Z().cwd;if(!n)return;let s=await K(t,n).catch(()=>{});return s===void 0?void 0:qe(b().agent.worktreeRoot,s)},"worktreeRoot"),listRootEntries:i(async n=>{try{return await N.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:i(async n=>{try{return await K(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:i(n=>mt(t,n),"isWorktreeDirty"),worktreeExists:i(async n=>N.existsSync(n),"worktreeExists"),removeWorktree:i(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(n,s)=>(await ht(t,s,n),!N.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>ft(t,n,s=>e.isAttached(s,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:i(async n=>{await e.release(n,"placement")},"closePane"),teardownEnvironment:i(async({subagentId:n,runs:s})=>{let o=A();for(let l of s)try{await o.get(l.harness)?.teardown({pi:t,paneId:l.paneId,cwd:l.cwd,subagentId:n})}catch(a){Yn.warn("harness teardown failed during environment teardown",{subagentId:n,harness:l.harness,error:y(a)})}},"teardownEnvironment")})}i(Vt,"createMultiplexerAgentAssets");var C=T("supervisor"),er=2e3;function tr(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}i(tr,"deferred");var oe=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??er,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp,this.stopProcess=n.stopProcess??((s,o)=>e.waitUntilGone(s,{timeoutMs:o}))}host;deliverable;static{i(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=tr();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,r){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:r};try{await this.host.start(r,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(n){throw this.isWatching()&&(this.phase={kind:"idle"}),n}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},C.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),C.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{C.error("poll loop failed",{errorMessage:y(r)})}),this.settlement.promise}async stop(e){let r=this.phase;if(r.kind!=="watching"||this.outcome!==null)return!1;let{ref:n}=r,s=await this.stopProcess(n,e).catch(o=>(C.debug("stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:s,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),s}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let r=this.phase;r.kind==="watching"&&(C.debug(e,{paneId:r.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,C.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let r=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);r.unref(),this.wakeLoop=()=>{clearTimeout(r),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!nr(this.held,e)){this.held=e,C.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return C.debug("readDeliverable failed",{errorMessage:y(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function nr(t,e){return t.content===e.content&&t.mtime===e.mtime}i(nr,"sameReport");function ae(t){let e=t.transport.createDeliverable(t.resultFile);return new oe(t.host,e,t.supervisorOptions)}i(ae,"createPaneSupervisor");function Yt(t,e){t.host=e}i(Yt,"placeExecution");function Xt(t,e){t.harness=e}i(Xt,"engageExecution");function Jt(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}i(Jt,"endExecutionRun");import Ae from"node:fs";import $ from"node:path";import{SettingsManager as Pr}from"@earendil-works/pi-coding-agent";import gr from"node:fs";import{loadProjectContextFiles as hr}from"@earendil-works/pi-coding-agent";function Zt(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
1
+ import{a as ke,b as Et,c as Ct,d as Tt,j as Lt,k as q,o as Dt,r as jt,u as $t,v as Se,w as Wt,x as qt,y as Nt}from"./chunk-XWEYV2EP.js";import{E as At,F as xt,G as Rt,O as It,Q as Ot,R as Ht,S as Mt,a as pt,f as gt,g as K,h as ht,m as ft,n as mt,o as yt,q as vt,r as wt,s as kt,t as St,v as Pt,y as bt}from"./chunk-F77A4UCS.js";import{$ as Xe,A as Ne,Aa as ot,Ba as at,E as X,F as U,Fa as G,G as Qe,Ha as lt,I as he,Ia as dt,J as T,Ja as ve,Ka as we,La as te,Ma as ut,Na as ct,O as J,Oa as Ft,Q as ze,R as Ve,S as B,T as L,U as Ye,V as fe,a as E,aa as Je,c as Oe,ca as Ze,d as I,da as et,e as He,ea as me,f as Me,fa as tt,g as De,ga as nt,ha as rt,ia as R,j as je,ja as Z,la as ye,ma as b,pa as F,sa as ee,u as $e,w as We,wa as A,y as qe,ya as st,z as Y,za as it}from"./chunk-NF3DL7IL.js";import{a as i,b as _e,d as y,h as M,i as Ue,r as Be,s as Ge,x as Ke}from"./chunk-XXNZAWMK.js";import*as O from"node:path";function re(t,e){let r=t.at(0);if(r)return{kind:"spawn",spawn:r};let n=e.at(0);return n?{kind:"multiplexer",attempt:n}:{kind:"none"}}i(re,"findTaskDedup");var D=class extends Error{static{i(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",s=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?L(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${s} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},ne=class{constructor(e){this.deps=e}deps;static{i(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let s=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,s);try{return await s}finally{this.admissionBySlug.get(r)===s&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let p=this.deps.listAgents().filter(g=>g.display.taskSlug===e.taskSlug&&Ve(g.lifecycle.phase)),c=re(p,await this.deps.findTaskAttempts(e.taskSlug));if(c.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:c.kind==="spawn"?c.spawn.id:c.attempt.name}}let{type:r,prompt:n,runInBackground:s,signal:o,...l}=e,a={...l,isBackground:s,signal:o},d=this.deps.spawn(r,n,a);return this.deps.getSpawn(d)?.lifecycle.phase==="queued"?{status:"queued",agentId:d,queuePosition:this.deps.queuePosition(d)}:{status:"admitted",agentId:d}}};import _t from"node:fs";var se=class{constructor(e){this.resultFile=e}resultFile;static{i(this,"FileDeliverable")}async readDeliverable(){try{let e=_t.statSync(this.resultFile).mtimeMs,r=_t.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import Ut from"node:fs";import*as Bt from"node:path";function Q(t){try{Ut.rmSync(Bt.dirname(t),{recursive:!0,force:!0})}catch{}}i(Q,"removeResultArtifacts");function Gt(t){try{Ut.rmSync(t,{force:!0})}catch{}}i(Gt,"removeResultFile");import*as N from"node:fs";import*as ie from"node:path";var Yn=T("assets");async function Kt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}i(Kt,"probeList");function Xn(t,e,r){let n=r(e);return t?.find(s=>r(s.path)===n)}i(Xn,"matchWorktree");function zt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}i(zt,"paneOf");function Qt(t,e,r){let n=r(e),s=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return s===void 0?void 0:zt(s)}i(Qt,"paneInWorktree");function Jn(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:zt(r)}i(Jn,"paneInWorkspace");function Zn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}i(e,"root");async function r(a,d){let u=await e(),p=[],c=new Set,g=i(h=>{let m=t.canonicalizePath(h.path);c.has(m)||(c.add(m),p.push(h))},"push");for(let h of d??[]){let m=ie.basename(h.path);Y(m,a)&&(u!==void 0&&!Ne(h.path,u)||g({path:h.path,branch:h.branch!==void 0&&Y(h.branch,a)?h.branch:m,workspaceId:h.workspaceId}))}if(p.length>0||u===void 0)return p;for(let h of await t.listRootEntries(u))Y(h,a)&&g({path:ie.join(u,h),branch:h});return p}i(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}i(n,"candidateSummary");async function s(a,d,u,p){let c=d.execution.host,g=d.display.worktree,h=g?.kind==="owned",m=c?{paneId:c.paneId,tabId:c.tabId,workspaceId:c.workspaceId}:null,f="tracked",w=g?.kind==="owned"?g.path:void 0,P=c?.workspaceId;if(w!==void 0){let x=Xn(u,w,t.canonicalizePath);x!==void 0&&(P=x.workspaceId)}let S=w===void 0?m:Qt(p,w,t.canonicalizePath)??m,k=w===void 0?null:{path:w,workspaceId:P,repoCwd:await t.resolveRepoCwd(w)};return{kind:"located",source:f,id:a,branch:g?.branch??We(d.display.taskSlug??$e(d.display.type),d.id),worktreeManaged:h||k!==null,paneCreated:c?.paneCreated===!0,worktree:k,pane:S}}i(s,"locateTracked");async function o(a,d,u){let p=await r(a,d);if(p.length===0)return{kind:"not-found",id:a};if(p.length>1)return{kind:"ambiguous",id:a,candidates:p.map(n)};let c=p[0],g=Qt(u,c.path,t.canonicalizePath)??Jn(u,c.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:c.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:c.path,workspaceId:c.workspaceId,repoCwd:await t.resolveRepoCwd(c.path)},pane:g}}i(o,"locateDiscovered");async function l(a,d){let u=await Kt(t.listWorktrees),p=await Kt(t.listPlacements),c=u.ok?u.entries:void 0,g=p.ok?p.entries:void 0;return d===void 0?o(a,c,g):s(a,d,c,g)}return i(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:i(a=>t.readPane(a.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}i(Zn,"createAgentAssets");function Vt(t,e,r){return Zn({multiplexer:r.multiplexer,canonicalizePath:i(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:i(n=>{let s=I(n);return{path:s,present:N.existsSync(s)}},"deliverable"),listWorktrees:i(()=>r.listWorktrees(),"listWorktrees"),listPlacements:i(()=>r.listPlacements(),"listPlacements"),readPane:i(n=>r.observePane(n),"readPane"),worktreeRoot:i(async()=>{let n=Z().cwd;if(!n)return;let s=await K(t,n).catch(()=>{});return s===void 0?void 0:qe(b().agent.worktreeRoot,s)},"worktreeRoot"),listRootEntries:i(async n=>{try{return await N.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:i(async n=>{try{return await K(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:i(n=>mt(t,n),"isWorktreeDirty"),worktreeExists:i(async n=>N.existsSync(n),"worktreeExists"),removeWorktree:i(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(n,s)=>(await ht(t,s,n),!N.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>ft(t,n,s=>e.isAttached(s,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:i(async n=>{await e.release(n,"placement")},"closePane"),teardownEnvironment:i(async({subagentId:n,runs:s})=>{let o=A();for(let l of s)try{await o.get(l.harness)?.teardown({pi:t,paneId:l.paneId,cwd:l.cwd,subagentId:n})}catch(a){Yn.warn("harness teardown failed during environment teardown",{subagentId:n,harness:l.harness,error:y(a)})}},"teardownEnvironment")})}i(Vt,"createMultiplexerAgentAssets");var C=T("supervisor"),er=2e3;function tr(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}i(tr,"deferred");var oe=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??er,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp,this.stopProcess=n.stopProcess??((s,o)=>e.waitUntilGone(s,{timeoutMs:o}))}host;deliverable;static{i(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=tr();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,r){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:r};try{await this.host.start(r,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(n){throw this.isWatching()&&(this.phase={kind:"idle"}),n}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},C.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),C.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{C.error("poll loop failed",{errorMessage:y(r)})}),this.settlement.promise}async stop(e){let r=this.phase;if(r.kind!=="watching"||this.outcome!==null)return!1;let{ref:n}=r,s=await this.stopProcess(n,e).catch(o=>(C.debug("stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:s,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),s}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let r=this.phase;r.kind==="watching"&&(C.debug(e,{paneId:r.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,C.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let r=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);r.unref(),this.wakeLoop=()=>{clearTimeout(r),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!nr(this.held,e)){this.held=e,C.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return C.debug("readDeliverable failed",{errorMessage:y(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function nr(t,e){return t.content===e.content&&t.mtime===e.mtime}i(nr,"sameReport");function ae(t){let e=t.transport.createDeliverable(t.resultFile);return new oe(t.host,e,t.supervisorOptions)}i(ae,"createPaneSupervisor");function Yt(t,e){t.host=e}i(Yt,"placeExecution");function Xt(t,e){t.harness=e}i(Xt,"engageExecution");function Jt(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}i(Jt,"endExecutionRun");import Ae from"node:fs";import $ from"node:path";import{SettingsManager as Pr}from"@earendil-works/pi-coding-agent";import gr from"node:fs";import{loadProjectContextFiles as hr}from"@earendil-works/pi-coding-agent";function Zt(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
2
2
  `):""}i(Zt,"buildOrchestrationGuidance");import{formatSkillsForPrompt as rr}from"@earendil-works/pi-coding-agent";function sr(t){let e=t;return e=e.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g,`
3
3
  `),e=e.replace(/\n?(?:The following skills provide[\s\S]*?)?<\s*available_skills\s*>[\s\S]*?<\/\s*available_skills\s*>\n?/g,`
4
4
  `),e=e.replace(/\n?Current date:.*\n?/g,`
@@ -1,3 +1,3 @@
1
- import{a as M,b as y}from"./chunk-67VN34QV.js";import{U as H,d as g,g as R,j as P}from"./chunk-NF2BSEPU.js";import{b as S,o as D}from"./chunk-ROCBRG4A.js";import{Ba as v,Fa as x,Oa as _,ia as I,ma as T,r as p,s as b,t as E,y as A}from"./chunk-GYO352IF.js";import{a as t,d as N}from"./chunk-XXNZAWMK.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=E,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
1
+ import{a as M,b as y}from"./chunk-ZZFQQC33.js";import{U as H,d as g,g as R,j as P}from"./chunk-F77A4UCS.js";import{b as S,o as D}from"./chunk-5Q6BGTTQ.js";import{Ba as v,Fa as x,Oa as _,ia as I,ma as T,r as p,s as b,t as E,y as A}from"./chunk-NF3DL7IL.js";import{a as t,d as N}from"./chunk-XXNZAWMK.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=E,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
2
2
  `)}t(Y,"describeCreatedWorktree");async function J(e,r,o,a){if($.existsSync(a))return`Cannot create the worktree: ${a} already exists. Pick another name.`;if(await g(e,["rev-parse","--verify","--quiet",`refs/heads/${o}`],r)!==void 0)return`Cannot create the worktree: the branch "${o}" already exists. Pick another name.`}t(J,"describeCollision");async function pe(e,r){let o=new S(e),a=t((n,i)=>e.ui.notify(n,i),"notify"),s=await o.open(({theme:n,close:i})=>new y(L({prefill:r,notify:a,onDone:t(m=>i(m),"onDone"),onCancel:t(()=>i(),"onCancel")}),{title:"Worktree Name",theme:n,passthroughKeys:!0}));if(s===void 0)return;let k=T(),c=I();if(!await P(c,e.cwd)){a("Cannot create a worktree: this session is not inside a git repository.","error");return}let d;try{d=await R(c,e.cwd)}catch(n){a(`Cannot create a worktree: ${N(n)}`,"error");return}let G=await g(c,["status","--porcelain"],d)==="",u=k.agent.worktreeCheckoutType;if(!G){let n=await o.open(({theme:i,close:m})=>{let h=new X(p.map(l=>({value:l,label:l,description:q[l]})),p.length,D(i));return h.setSelectedIndex(p.indexOf(k.agent.worktreeCheckoutType)),h.onSelect=l=>m(b(l.value)),h.onCancel=()=>m(),new y(h,{title:"Worktree Checkout",theme:i,onCancel:t(()=>m(),"onCancel")})});if(n===void 0)return;u=n}let C=z.join(A(k.agent.worktreeRoot,d),s),w=await J(c,d,s,C);if(w!==void 0){a(w,"error");return}let f=_(e.ui);f.pending(`Creating worktree ${s}`);let W;try{W=await H(c,{repoCwd:d,path:C,branch:s,materialization:v(),dirtyCheckout:u,notify:a,host:x().host})}catch(n){f.failed("Worktree creation failed",n);return}f.succeeded(Y(W,u))}t(pe,"showWorktreeCommandMenu");export{pe as showWorktreeCommandMenu};
3
- //# sourceMappingURL=menu-worktree-command-FGIFMYRD.js.map
3
+ //# sourceMappingURL=menu-worktree-command-3KBKYTRL.js.map
@@ -1,4 +1,4 @@
1
- import{e as Re,f as Xt,g as et,h as Zt,i as Jt,l as Qt,m as sn,n as an,p as De,q as nt,s as ln,t as cn}from"./chunk-CAWIXE4E.js";import{a as on,b as j}from"./chunk-67VN34QV.js";import{H as Ut,I as qt,K as zt,L as Yt,O as oe,P as tn,T as nn,V as rn,i as Wt,j as Kt,v as U,w as Pe,x as Gt,z as Bt}from"./chunk-NF2BSEPU.js";import{a as pe,b as W,c as ie,d as se,e as He,f as fe,g as q,h as je,i as tt,j as Fe,k as we,l as _,m as en,n as Y,o as Z,p as _e,q as Te}from"./chunk-ROCBRG4A.js";import{Ba as Le,Ea as Vt,Fa as Ee,G as Ze,H as Q,L as At,M as xt,N as $t,Oa as X,Q as Ae,R as Ce,S as xe,T as Lt,U as Et,V as Pt,W as Rt,X as Ht,Y as jt,Z as Ft,_ as _t,a as ht,b as yt,ba as $e,ga as Je,ia as le,ja as me,ka as Dt,l as Xe,la as ee,m as ke,ma as L,o as vt,p as bt,r as kt,ra as Nt,s as St,t as Ct,ta as Qe,wa as B,za as re}from"./chunk-GYO352IF.js";import{a as t,d as ue,e as wt,f as Se,g as Tt,k as Ot,l as ne,m as Mt,w as It}from"./chunk-XXNZAWMK.js";import{SettingsList as er}from"@earendil-works/pi-tui";import{SettingsManager as nr}from"@earendil-works/pi-coding-agent";async function dn(e,n){return nr.create(e,n??ht()).getDefaultThinkingLevel()}t(dn,"getPiDefaultThinkingLevel");import{SettingsList as ur}from"@earendil-works/pi-tui";var rr={queued:{icon:"\u25C6",color:"accent"},spawned:{icon:"\u25C8",color:"accent"},completed:{icon:"\u2713",color:"success"},error:{icon:"\u2717",color:"error"},stopped:{icon:"\u25A0",color:"dim"}};function un(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=rr[e];return n.fg(o.color,o.icon)}t(un,"statusIcon");function rt(e){if(!Number.isFinite(e)||e<1e3)return"<1s";let n=Math.floor(e/1e3),o=Math.floor(n/3600),r=Math.floor(n%3600/60),i=n%60,s=[];return o>0&&s.push(`${o}h`),r>0&&s.push(`${r}m`),(i>0||s.length===0)&&s.push(`${i}s`),s.join(" ")}t(rt,"formatMs");function mn(e){let n=U(e);return n?.displayName??n?.name??"Agent"}t(mn,"getDisplayName");function ae(e){return`${e.fg("accent","\u2022")} `}t(ae,"agentBulletPrefix");function pn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(pn,"truncatePath");function Ne(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(Ne,"formatSlotLimit");function fn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:i,harnessDefaultFor:s,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:c}=e,d=new Map;for(let u of n){let g=o[u],{model:k,source:y}=Rt({subagentType:u,harnessFamily:l(u),agentConfig:g,config:{agent:r},harnessDefault:s(u),parentModelId:c,sessionOverrides:i});if(!ot(i,r,u,e.sessionThinking))continue;let v=y==="session-per-type"||y==="session-default"?"[session]":a(u)?"[project]":"",{level:p,source:b}=it({type:u,agentConfig:g,harnessFamily:l(u),config:r,harnessDefault:e.harnessDefaultThinkingFor(u),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),C=b==="session-per-type"?" [session]":b==="parent"?" [parent]":b==="config-per-type"&&e.hasProjectThinkingKey(u)?" [project]":"",I=d.get(k)??[];I.push({type:u,thinking:p,thinkingTag:C,tag:v}),d.set(k,I)}return[...d.entries()].sort((u,g)=>u[0]===g[0]?0:u[0]===null?-1:g[0]===null?1:u[0]<g[0]?-1:1).map(([u,g])=>({modelId:u,rows:g}))}t(fn,"buildModelGroups");function ot(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(ot,"hasExplicitPerTypeOverride");function it(e){let n=jt({subagentType:e.type,harnessFamily:e.harnessFamily,agentConfig:e.agentConfig,config:{agent:e.config},harnessDefault:e.harnessDefault,parentThinking:e.parentThinking,sessionThinking:e.sessionThinking});return n!==void 0?{level:n.value,source:n.source}:{level:e.harnessFamily==="pi"?Ht:null,source:void 0}}t(it,"displayedThinking");import{SettingsList as sr}from"@earendil-works/pi-tui";import{matchesKey as Oe,SelectList as or,truncateToWidth as ir}from"@earendil-works/pi-tui";function gn(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],i=Y(new or(r,5,Z(e.theme)));return i.onSelect=s=>{s.value==="Yes"?(e.onConfirm(),o("Yes")):o()},i.onCancel=()=>o(),i}}t(gn,"createConfirmSubmenu");function Ve(e){return se({invalidate(){},render(o){let r=Math.max(0,o-4),i=t(l=>` ${ir(l,r,"...",!0)}`,"line"),s=[i(e.theme.bold(e.message))];if(e.detail)for(let l of e.detail.split(`
1
+ import{e as Re,f as Xt,g as et,h as Zt,i as Jt,l as Qt,m as sn,n as an,p as De,q as nt,s as ln,t as cn}from"./chunk-XWEYV2EP.js";import{a as on,b as j}from"./chunk-ZZFQQC33.js";import{H as Ut,I as qt,K as zt,L as Yt,O as oe,P as tn,T as nn,V as rn,i as Wt,j as Kt,v as U,w as Pe,x as Gt,z as Bt}from"./chunk-F77A4UCS.js";import{a as pe,b as W,c as ie,d as se,e as He,f as fe,g as q,h as je,i as tt,j as Fe,k as we,l as _,m as en,n as Y,o as Z,p as _e,q as Te}from"./chunk-5Q6BGTTQ.js";import{Ba as Le,Ea as Vt,Fa as Ee,G as Ze,H as Q,L as At,M as xt,N as $t,Oa as X,Q as Ae,R as Ce,S as xe,T as Lt,U as Et,V as Pt,W as Rt,X as Ht,Y as jt,Z as Ft,_ as _t,a as ht,b as yt,ba as $e,ga as Je,ia as le,ja as me,ka as Dt,l as Xe,la as ee,m as ke,ma as L,o as vt,p as bt,r as kt,ra as Nt,s as St,t as Ct,ta as Qe,wa as B,za as re}from"./chunk-NF3DL7IL.js";import{a as t,d as ue,e as wt,f as Se,g as Tt,k as Ot,l as ne,m as Mt,w as It}from"./chunk-XXNZAWMK.js";import{SettingsList as er}from"@earendil-works/pi-tui";import{SettingsManager as nr}from"@earendil-works/pi-coding-agent";async function dn(e,n){return nr.create(e,n??ht()).getDefaultThinkingLevel()}t(dn,"getPiDefaultThinkingLevel");import{SettingsList as ur}from"@earendil-works/pi-tui";var rr={queued:{icon:"\u25C6",color:"accent"},spawned:{icon:"\u25C8",color:"accent"},completed:{icon:"\u2713",color:"success"},error:{icon:"\u2717",color:"error"},stopped:{icon:"\u25A0",color:"dim"}};function un(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=rr[e];return n.fg(o.color,o.icon)}t(un,"statusIcon");function rt(e){if(!Number.isFinite(e)||e<1e3)return"<1s";let n=Math.floor(e/1e3),o=Math.floor(n/3600),r=Math.floor(n%3600/60),i=n%60,s=[];return o>0&&s.push(`${o}h`),r>0&&s.push(`${r}m`),(i>0||s.length===0)&&s.push(`${i}s`),s.join(" ")}t(rt,"formatMs");function mn(e){let n=U(e);return n?.displayName??n?.name??"Agent"}t(mn,"getDisplayName");function ae(e){return`${e.fg("accent","\u2022")} `}t(ae,"agentBulletPrefix");function pn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(pn,"truncatePath");function Ne(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(Ne,"formatSlotLimit");function fn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:i,harnessDefaultFor:s,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:c}=e,d=new Map;for(let u of n){let g=o[u],{model:k,source:y}=Rt({subagentType:u,harnessFamily:l(u),agentConfig:g,config:{agent:r},harnessDefault:s(u),parentModelId:c,sessionOverrides:i});if(!ot(i,r,u,e.sessionThinking))continue;let v=y==="session-per-type"||y==="session-default"?"[session]":a(u)?"[project]":"",{level:p,source:b}=it({type:u,agentConfig:g,harnessFamily:l(u),config:r,harnessDefault:e.harnessDefaultThinkingFor(u),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),C=b==="session-per-type"?" [session]":b==="parent"?" [parent]":b==="config-per-type"&&e.hasProjectThinkingKey(u)?" [project]":"",I=d.get(k)??[];I.push({type:u,thinking:p,thinkingTag:C,tag:v}),d.set(k,I)}return[...d.entries()].sort((u,g)=>u[0]===g[0]?0:u[0]===null?-1:g[0]===null?1:u[0]<g[0]?-1:1).map(([u,g])=>({modelId:u,rows:g}))}t(fn,"buildModelGroups");function ot(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(ot,"hasExplicitPerTypeOverride");function it(e){let n=jt({subagentType:e.type,harnessFamily:e.harnessFamily,agentConfig:e.agentConfig,config:{agent:e.config},harnessDefault:e.harnessDefault,parentThinking:e.parentThinking,sessionThinking:e.sessionThinking});return n!==void 0?{level:n.value,source:n.source}:{level:e.harnessFamily==="pi"?Ht:null,source:void 0}}t(it,"displayedThinking");import{SettingsList as sr}from"@earendil-works/pi-tui";import{matchesKey as Oe,SelectList as or,truncateToWidth as ir}from"@earendil-works/pi-tui";function gn(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],i=Y(new or(r,5,Z(e.theme)));return i.onSelect=s=>{s.value==="Yes"?(e.onConfirm(),o("Yes")):o()},i.onCancel=()=>o(),i}}t(gn,"createConfirmSubmenu");function Ve(e){return se({invalidate(){},render(o){let r=Math.max(0,o-4),i=t(l=>` ${ir(l,r,"...",!0)}`,"line"),s=[i(e.theme.bold(e.message))];if(e.detail)for(let l of e.detail.split(`
2
2
  `))s.push(i(l));return s.push(i(e.theme.fg("dim","Y yes \xB7 N no"))),s},handleInput(o){if(Oe(o,"y")||Oe(o,"shift+y")){e.onYes();return}(Oe(o,"n")||Oe(o,"shift+n")||Oe(o,"escape"))&&e.onNo()}})}t(Ve,"createKeyConfirm");var ar={session:{label:"Session",setDescription:"Not saved",clearDescription:"Removes from the session"},global:{label:"Global",setDescription:"Saves to the global config file",clearDescription:"Removes from the global config file"},project:{label:"Project",setDescription:"Saves to the project config file",clearDescription:"Removes from the project config file"}};function st(e,n){let o=ar[e];return{id:e,label:o.label,currentValue:"",description:n?o.clearDescription:o.setDescription}}t(st,"levelItem");function ge(e){let n=[];return e.offered.session&&n.push(st("session",e.clearMode===!0)),e.offered.global&&n.push(st("global",e.clearMode===!0)),e.offered.project&&n.push(st("project",e.clearMode===!0)),e.includeClear&&n.push({id:"clear",label:"Clear...",currentValue:""}),e.includeAll&&n.push({id:"all",label:"All levels",currentValue:""}),n}t(ge,"buildLevelItems");function te(e){return(n,o)=>{let r=e.items.map(s=>({...s,submenu:t((l,a)=>{let c=e.onPick(s.id,a,()=>o());return c||(a(s.id),ie)},"submenu")})),i=Y(new sr(r,r.length,_(e.theme),(s,l)=>o(l),()=>o()));return se(i)}}t(te,"createLevelPickerSubmenu");function We(e){let n=e.availableLevels,o=e.includeAll===!0,r=(e.includeSession??!0)&&(!n||n.session),i=!n||n.global,s=e.projectOffered&&(!n||n.project),l=[r,i,s].filter(Boolean).length,a=e.showClear===!0?e.onClear:void 0,c=ge({offered:{session:r,global:i,project:s},clearMode:o,includeClear:a!==void 0,includeAll:n?l>=2:e.includeAll===!0});return te({theme:e.theme,items:c,onPick:t((d,u)=>d==="clear"?he({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,availableLevels:e.availableLevels,onClear:t(g=>a?.(g),"onClear")})("",u):e.onPick(d,u),"onPick")})}t(We,"createTargetSelectSubmenu");function he(e){return We({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,includeAll:!0,availableLevels:e.availableLevels,onPick:t(n=>e.onClear(n),"onPick")})}t(he,"createClearPickerSubmenu");function Ke(e){return(n,o)=>We({theme:e.theme,projectOffered:e.projectOffered,includeAll:!0,availableLevels:e.availableLevels,onPick:t((r,i)=>gn({message:e.message(r),theme:e.theme,onConfirm:t(()=>e.onConfirm(r),"onConfirm")})(n,i),"onPick")})(n,o)}t(Ke,"createClearAllSubmenu");import{Input as hn}from"@earendil-works/pi-tui";function at(e,n){let o=n.min??1,r=t(s=>s===0?"\u2265 0":`\u2265 ${s}`,"fmtLabel"),i=t(s=>e.ui.notify(s,"error"),"onError");return(s,l)=>{let a=new hn;return a.setValue(s),a.onSubmit=c=>{let d=c.trim();if(!d||/^unlimited$/i.test(d))switch(n.kind){case"required":i(`Invalid value \u2014 must be a number ${r(o)}`);return;case"defaulted":n.onValid?.(n.default),l(String(n.default));return;case"optional":n.onEmpty?.(),l("");return}let u=en(d,o);if(u===void 0){i(`Invalid value \u2014 must be a number ${r(o)}`);return}n.onValid?.(u),l(String(u))},a.onEscape=()=>l(),a}}t(at,"createNumericSubmenu");function ye(e,n){return(o,r)=>{let i=new hn;return i.setValue(o),i.onSubmit=s=>{let l=s.trim();if(!l){if(n?.required){e.ui.notify("Cannot be empty","error");return}r();return}r(l)},i.onEscape=()=>r(),i}}t(ye,"createInputSubmenu");var yn="__custom__",ve="__none__";function lr(e,n){let o=[];if(e.kind!=="none"){for(let r of e.levels)o.push({id:r,label:r==="off"?"Off":r.charAt(0).toUpperCase()+r.slice(1),currentValue:n===r?"(current)":""});e.kind==="advisory"&&o.push({id:yn,label:"Custom token...",currentValue:"",description:"A level or variant this harness advertises beyond its own list."})}return o.push({id:ve,label:"None",currentValue:n===null?"(current)":"",description:"Use the template, configured default, or parent session's level."}),o}t(lr,"valueItems");function vn(e){return te({theme:e.theme,items:lr(e.offering,e.current),onPick:t((n,o)=>{if(n===yn)return ye(e.ctx)(e.current??"",r=>{if(r===void 0){o();return}e.onPick(r),o(r)});e.onPick(n===ve?null:n)},"onPick")})}t(vn,"createThinkingValuePicker");function bn(e){let n=e.currentModel??null,o=e.showClear===!0?e.onClear:void 0;return te({theme:e.theme,items:ge({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:o!==void 0}),onPick:t((r,i,s)=>{if(r==="clear")return he({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(a=>o?.(a),"onClear")})("",i);let l=r;return new pe(tt(e.modelOptions,n,e.mergedModels),n,{onSelect:t(a=>{e.onSet(l,a),a==null?s():i(a)},"onSelect"),onCancel:t(()=>i(),"onCancel")},e.theme)},"onPick")})}t(bn,"createModelSelectSubmenu");function kn(e){let n=e.currentModel??null;return te({theme:e.theme,items:ge({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:e.showClear}),onPick:t((o,r,i)=>{if(o==="clear")return he({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(c=>e.onClear(c),"onClear")})("",r);let s=o,l,a=new pe(tt(e.modelOptions,n,e.mergedModels),n,{onSelect:t(c=>{if(c==null){e.onClear(s),i();return}let d=e.offeringFor(c);if(d.kind==="none"){e.onSet(s,c,null),r(c);return}l.activate(vn({theme:e.theme,ctx:e.ctx,offering:d,current:e.currentThinking,onPick:t(u=>e.onSet(s,c,u),"onPick")})("",r))},"onSelect"),onCancel:t(()=>r(),"onCancel")},e.theme);return l=new He(a),l},"onPick")})}t(kn,"createModelThinkingSubmenu");import{getSupportedThinkingLevels as cr}from"@earendil-works/pi-ai";function Ge(e){let{harnessId:n,modelKey:o,entries:r,piModel:i}=e;if(ne(n))return i===void 0?{kind:"advisory",levels:[]}:i.reasoning?{kind:"closed",levels:cr(i)}:{kind:"none"};if(o==="")return dr(r);let s=r.find(l=>l.key===o);return s===void 0?{kind:"advisory",levels:[]}:s.thinkingLevels.kind==="advisory"?{kind:"advisory",levels:s.thinkingLevels.levels}:s.thinkingLevels.levels.length===0?{kind:"none"}:{kind:"closed",levels:s.thinkingLevels.levels}}t(Ge,"thinkingOfferingFor");function dr(e){let n=[...new Set(e.flatMap(r=>r.thinkingLevels.levels))],o=e.length===0||e.some(r=>r.thinkingLevels.kind==="advisory");return n.length===0&&!o?{kind:"none"}:o?{kind:"advisory",levels:n}:{kind:"closed",levels:n}}t(dr,"unionThinkingOffering");function Sn(e){return Ge({harnessId:e.harnessId,modelKey:e.modelKey??"",entries:e.entries.get(e.harnessId)??[],piModel:Se(e.modelKey??"",e.registry,e.parentModel)})}t(Sn,"thinkingOfferingForModel");function Be(e){let n=e.model??"(none)",o=e.thinking??"(none)",r=e.model?e.modelTag:"",i=e.thinking?e.thinkingTag:"";return r!==""&&r===i?`${n} \xB7 ${o}${i}`:`${n}${r} \xB7 ${o}${i}`}t(Be,"pairedRow");function Ue(e,n){return e?" [session]":n?" [project]":""}t(Ue,"layerTag");function lt(e,n){return n===null?"":Ue(e.session,e.project)}t(lt,"thinkingTagOf");function Cn(e,n,o,r){if(o===null){e.mutate.agent.clearHarnessDefaultThinking(n,r);return}r!=="session"&&ne(n)&&!At.safeParse(o).success||e.mutate.agent.setHarnessDefaultThinking(n,o,r)}t(Cn,"writeHarnessDefaultThinking");function mr(e,n,o,r){o===null?e.mutate.agent.clearThinkingOverride(n,r):e.mutate.agent.setThinkingOverride(n,o,r)}t(mr,"writeTypeThinking");function pr(e){return B().runnable(e).filter(n=>!ne(n))}t(pr,"harnessDefaultRowIds");function fr(e){let n=pr(re());return se(gr(e,n))}t(fr,"buildModelSettingsScreen");function gr(e,n){let{ctx:o,store:r,theme:i,harnessModelOptions:s,piDefaultThinking:l,close:a}=e,c,d=t(k=>{let y=[],v=r.isProjectWritable,p=t((h,P)=>o.ui.notify(h,P),"notify"),b=me(),C=b.model??o.model,I=C?`${C.provider}/${C.id}`:null,O=b.thinkingLevel??null,$=r.agentConfigSnapshot(),V=Fe($),H=t(()=>{c?.(d(k))},"refresh"),R=t(h=>P=>Sn({harnessId:h,modelKey:P,entries:s,registry:b.modelRegistry,parentModel:C}),"offeringFor"),D=t(h=>{let P={session:h.modelLevels.session||h.thinkingLevels.session,global:h.modelLevels.global||h.thinkingLevels.global,project:h.modelLevels.project||h.thinkingLevels.project};return kn({modelOptions:h.modelOptions,mergedModels:h.mergedModels,projectOffered:v,theme:k,ctx:o,currentModel:h.model,currentThinking:h.thinking,showClear:P.session||P.global||P.project,availableLevels:P,offeringFor:R(h.harnessId),onSet:t((M,G,N)=>{h.write(M,G,N),p(`${h.label} set to ${G} \xB7 ${N??"(none)"} (${M})`,"info")},"onSet"),onClear:t(M=>{h.clear(M),p(`${h.label} cleared (${M})`,"info"),H()},"onClear")})},"pairSubmenu"),K=$.default,f=r.modelOverrideLevels("default"),m=r.harnessDefaultThinkingLevels("pi"),S=r.defaultThinkingForHarness("pi"),w=r.sessionDefaultModel??K;y.push({id:"defaultModel",label:"Pi Default Model",currentValue:Be({model:w,modelTag:Ue(f.session,r.hasProjectModelKey("default")),thinking:S,thinkingTag:lt(m,S)}),description:"Default model and thinking level applied when no session, per-type, or template override is set.",submenu:D({label:"Pi Default Model",harnessId:"pi",modelOptions:Q(s,"pi"),mergedModels:we("pi",V),model:w,thinking:S,modelLevels:f,thinkingLevels:m,write:t((h,P,M)=>{r.mutate.agent.setModelOverride("default",P,h),Cn(r,"pi",M,h)},"write"),clear:t(h=>{r.mutate.agent.clearModelOverride("default",h),r.mutate.agent.clearHarnessDefaultThinking("pi",h)},"clear")})});for(let h of n){let P=`${B().displayName(h)} Default Model`,M=r.harnessDefaultModelLevels(h),G=r.harnessDefaultThinkingLevels(h),N=r.defaultThinkingForHarness(h);y.push({id:`harness:${h}`,label:P,currentValue:Be({model:r.defaultModelForHarness(h),modelTag:Ue(M.session,M.project),thinking:N,thinkingTag:lt(G,N)}),description:`Default model and thinking level applied to agents launched under ${h} when no session, per-type, or template override is set.`,submenu:D({label:P,harnessId:h,modelOptions:Q(s,h),mergedModels:[],model:r.defaultModelForHarness(h),thinking:N,modelLevels:M,thinkingLevels:G,write:t((J,Ye,tr)=>{r.mutate.agent.setHarnessDefaultModel(h,Ye,J),Cn(r,h,tr,J)},"write"),clear:t(J=>{r.mutate.agent.clearHarnessDefaultModel(h,J),r.mutate.agent.clearHarnessDefaultThinking(h,J)},"clear")})})}let T=Gt(),A={default:r.sessionDefaultModel},x={};for(let h of T)A[h]=r.sessionModelOverride(h),x[h]=U(h);let E={};for(let h of T)E[h]=r.sessionThinkingOverride(h);let F=fn({types:T,agentConfigs:x,config:$,sessionOverrides:A,sessionThinking:E,harnessDefaultFor:t(h=>r.defaultModelForHarness(oe(h)),"harnessDefaultFor"),harnessDefaultThinkingFor:t(h=>{let P=oe(h),M=r.defaultThinkingForHarness(P);return M!==null?M:ne(P)&&O===null?l??null:null},"harnessDefaultThinkingFor"),harnessFamilyFor:t(h=>Ze(oe(h)),"harnessFamilyFor"),hasProjectModelKey:t(h=>r.hasProjectModelKey(h),"hasProjectModelKey"),hasProjectThinkingKey:t(h=>r.hasProjectThinkingKey(h),"hasProjectThinkingKey"),parentModelId:I,parentThinking:O}),z=t((h,P,M,G)=>D({label:h,harnessId:P,modelOptions:Q(s,P),mergedModels:we(P,V),model:M,thinking:G,modelLevels:r.modelOverrideLevels(h),thinkingLevels:r.thinkingOverrideLevels(h),write:t((N,J,Ye)=>{r.mutate.agent.setModelOverride(h,J,N),mr(r,h,Ye,N)},"write"),clear:t(N=>{r.mutate.agent.clearModelOverride(h,N),r.mutate.agent.clearThinkingOverride(h,N)},"clear")}),"typeSubmenu");for(let h of F){y.push({id:q,label:" ",currentValue:""}),y.push(fe(k,h.modelId??"(no model)"));let P=Math.max(...h.rows.map(M=>`${M.thinking??"(none)"}${M.thinkingTag}`.length));for(let M of h.rows){let G=oe(M.type),N=`${M.thinking??"(none)"}${M.thinkingTag}`,J=M.thinking!==null&&M.thinkingTag.trim()===M.tag.trim()?"":M.tag;y.push({id:`type:${M.type}`,label:`${ae(k)}${M.type}`,currentValue:`${N.padEnd(P)} ${J}`.trimEnd(),description:`Model and thinking level for the ${M.type} agent type.`,submenu:z(M.type,G,h.modelId,M.thinking)})}}y.push({id:q,label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",currentValue:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});let Me=T.filter(h=>!ot(A,$,h,E));Me.length>0&&y.push({id:"overrideType",label:"Override another type...",currentValue:"",description:"Configure model and thinking level overrides for an agent type currently using inherited defaults.",submenu:t((h,P)=>_e(Me.map(M=>({value:M,label:`${ae(k)}${M}`})),{onSelect:t(M=>{if(M==null)return P();let G=oe(M),N=U(M),J=r.modelFor(M,I,N,G);return z(M,G,J,it({type:M,agentConfig:N,harnessFamily:Ze(G),config:$,harnessDefault:r.defaultThinkingForHarness(G),parentThinking:O??void 0,sessionThinking:E}).level)("",P)},"onSelect"),onCancel:t(()=>P(),"onCancel")},k),"submenu")}),y.push({id:q,label:" ",currentValue:""});let gt=r.modelSettingsLevels(),Ie={...gt,project:gt.project&&v};return(Ie.session||Ie.global||Ie.project)&&y.push({id:"clearAll",label:"Clear all model and thinking overrides...",currentValue:"",description:"Remove model and thinking level overrides across a selected configuration layer (session, global, project, or all).",submenu:Ke({theme:k,projectOffered:v,availableLevels:Ie,message:t(h=>`Clear all model and thinking overrides at the ${h} level?`,"message"),onConfirm:t(h=>{r.mutate.agent.clearAllModelOverrides(h),p(`Model and thinking overrides cleared (${h})`,"info")},"onConfirm")})}),y},"buildItems"),u=new ur(d(i),15,_(i),(k,y)=>c?.(d(i)),a),g=new j(u,{title:"Model Settings",theme:i,onCancel:a,onRebuild:t(k=>{c=k},"onRebuild")});return se(g)}t(gr,"buildModelSettingsList");function wn(e){let{ctx:n,store:o,theme:r,harnessModelOptions:i,piDefaultThinking:s}=e,l=t(()=>{let a=o.modelOverrideLevels("default"),c=o.harnessDefaultThinkingLevels("pi"),d=o.defaultThinkingForHarness("pi");return Be({model:o.sessionDefaultModel??o.agentConfigSnapshot().default,modelTag:Ue(a.session,o.hasProjectModelKey("default")),thinking:d,thinkingTag:lt(c,d)})},"defaultDisplay");return{id:"modelOverrides",label:"Model overrides",currentValue:l(),description:"Pi's default model and thinking level, plus per-harness and per-type overrides; opens the model settings screen.",submenu:t((a,c)=>fr({ctx:n,store:o,theme:r,harnessModelOptions:i,piDefaultThinking:s,close:t(()=>c(l()),"close")}),"submenu")}}t(wn,"buildModelOverridesRow");import{SettingsList as Tn}from"@earendil-works/pi-tui";function On(e,n){return e==="pi"?n:`${e}:${n}`}t(On,"qualifiedKey");function qe(e){let n=new Map;for(let o of e){let r=$e(o)?.harness??"pi",i=n.get(r);i?i.push(o):n.set(r,[o])}return n}t(qe,"groupKeysByHarness");function yr(e,n){let o=[...e];for(let r of n.keys())o.includes(r)||o.push(r);return o}t(yr,"sectionHarnesses");async function Mn(e,n){let o=[...n.keys()],r=t((s,l)=>{let a=[],c=s.isProjectWritable,d=t((f,m,S)=>m==="default"?f.default!==void 0:S===void 0?!1:m==="harnesses"?f.harnesses?.[S]!==void 0:f[m]?.[S]!==void 0,"layerHas"),u=t((f,m)=>({session:d(s.sessionConcurrency,f,m),global:d(s.globalConcurrency,f,m),project:d(s.projectConcurrency,f,m)}),"entryLevels"),g=t((f,m)=>d(s.sessionConcurrency,f,m)?" [session]":d(s.projectConcurrency,f,m)?" [project]":"","limitTag"),k=t((f,m)=>(S,w)=>We({theme:l,projectOffered:c,onPick:t((T,A)=>at(e,{kind:"optional",min:1,onValid:t(x=>m(T,x),"onValid")})(f,A),"onPick")})(S,w),"targetThenValueSubmenu"),y=t((f,m,S,w)=>(T,A)=>{let x=ge({offered:{session:!0,global:!0,project:c},includeClear:w.session||w.global||w.project});return te({theme:l,items:x,onPick:t((E,F)=>{if(E==="clear")return he({theme:l,projectOffered:c,availableLevels:w,onClear:S})("",F);let z=E;return at(e,{kind:"optional",min:1,onValid:t(Me=>m(z,Me),"onValid")})(String(f),F)},"onPick")})(T,A)},"limitSubmenu"),v=t(f=>(m,S)=>{let w=t(()=>f(),"buildFresh"),T,A=Y(new Tn(w(),15,_(l),(x,E)=>{let F=T,z=w();F.items=z,F.filteredItems=z,F.submenuComponent=null,F.selectedIndex=0},()=>S("closed")));return T=A,je(T),se(A)},"nestedListSubmenu"),p=t(f=>{let m=L(),S=m.concurrency.harnesses[f],w=B().displayName(f),T=`Concurrent agents of every model launched under ${f}.`;if(S===void 0)return{id:`harness:${f}`,label:w,currentValue:"unset",description:T,submenu:k("",(x,E)=>{L().mutate.concurrency.setHarness(f,E,x),e.ui.notify(`${f} concurrency set to ${E} (${x})`,"info")})};let A=d(m.sessionConcurrency,"harnesses",f)?" [session]":d(m.projectConcurrency,"harnesses",f)?" [project]":"";return{id:`harness:${f}`,label:w,currentValue:Ne(S,A),description:T,submenu:y(S,(x,E)=>{L().mutate.concurrency.setHarness(f,E,x),e.ui.notify(`${w} concurrency set to ${E} (${x})`,"info")},x=>{L().mutate.concurrency.removeHarness(f,x),e.ui.notify(`Removed per-harness limit for ${f} (${x})`,"info")},{session:d(m.sessionConcurrency,"harnesses",f),global:d(m.globalConcurrency,"harnesses",f),project:d(m.projectConcurrency,"harnesses",f)})}},"harnessLimitRow"),b=t(()=>{let f=L(),m=[...o];for(let S of Object.keys(f.concurrency.harnesses))S.trim()!==""&&!m.includes(S)&&m.push(S);return m.map(S=>p(S))},"harnessListItems"),C=t(f=>{let m=Q(n,f);return[...new Set(m.map(S=>wt(S)?.provider).filter(S=>S!==void 0))].sort()},"providerOptionsFor"),I=t((f,m)=>{let S=L(),w=S.concurrency.providers[m],T=`Concurrent slots reserved for agents under ${f} using the ${$e(m)?.provider??m} provider.`;if(w===void 0)return{id:`provider:${m}`,label:m,currentValue:"unset",description:T,submenu:k("",(x,E)=>{L().mutate.concurrency.setProvider(m,E,x),e.ui.notify(`${m} concurrency set to ${E} (${x})`,"info")})};let A=d(S.sessionConcurrency,"providers",m)?" [session]":d(S.projectConcurrency,"providers",m)?" [project]":"";return{id:`provider:${m}`,label:m,currentValue:Ne(w,A),description:T,submenu:y(w,(x,E)=>{L().mutate.concurrency.setProvider(m,E,x),e.ui.notify(`${m} concurrency set to ${E} (${x})`,"info")},x=>{L().mutate.concurrency.removeProvider(m,x),e.ui.notify(`Removed per-provider limit for ${m} (${x})`,"info")},{session:d(S.sessionConcurrency,"providers",m),global:d(S.globalConcurrency,"providers",m),project:d(S.projectConcurrency,"providers",m)})}},"providerLimitRow"),O=t(f=>{let m=L(),S=qe(Object.keys(m.concurrency.providers)).get(f)??[],w=C(f).map(A=>On(f,A));return[...new Set([...w,...S])].sort().map(A=>I(f,A))},"providerListItems"),$=t((f,m)=>{let S=L(),w=S.concurrency.models[m],T=$e(m),A=T?.kind==="model"?T.model:m,x=`Concurrent slots reserved for agents under ${f} using the ${A} model.`;if(w===void 0)return{id:`model:${m}`,label:m,currentValue:"unset",description:x,submenu:k("",(F,z)=>{L().mutate.concurrency.setModel(m,z,F),e.ui.notify(`${m} concurrency set to ${z} (${F})`,"info")})};let E=d(S.sessionConcurrency,"models",m)?" [session]":d(S.projectConcurrency,"models",m)?" [project]":"";return{id:`model:${m}`,label:m,currentValue:Ne(w,E),description:x,submenu:y(w,(F,z)=>{L().mutate.concurrency.setModel(m,z,F),e.ui.notify(`${m} concurrency set to ${z} (${F})`,"info")},F=>{L().mutate.concurrency.removeModel(m,F),e.ui.notify(`Removed per-model limit for ${m} (${F})`,"info")},{session:d(S.sessionConcurrency,"models",m),global:d(S.globalConcurrency,"models",m),project:d(S.projectConcurrency,"models",m)})}},"modelLimitRow"),V=t(f=>{let m=L(),S=qe(Object.keys(m.concurrency.models)).get(f)??[],w=Q(n,f).map(A=>On(f,A));return[...new Set([...w,...S])].sort().map(A=>$(f,A))},"modelListItems"),H=t(f=>{let m=L(),S=qe(Object.keys(f==="providers"?m.concurrency.providers:m.concurrency.models));return yr(o,S).filter(w=>{let T=(S.get(w)??[]).length>0;return f==="providers"?T||C(w).length>0:T||Q(n,w).length>0}).map(w=>({id:`${f}-harness:${w}`,label:B().displayName(w),currentValue:"",description:f==="providers"?`Provider limits under ${w}.`:`Model limits under ${w}.`,submenu:v(()=>f==="providers"?O(w):V(w))}))},"harnessPickerItems"),R=s.concurrency.default;a.push({id:"defaultConcurrency",label:"Default concurrency limit",currentValue:`${R}${g("default")}`,description:"Concurrent agents, whatever harness, provider, or model they use.",submenu:y(R,(f,m)=>{s.mutate.concurrency.setDefault(m,f),e.ui.notify(`Default concurrency set to ${m} (${f})`,"info")},f=>{s.mutate.concurrency.removeDefault(f),e.ui.notify(`Removed default concurrency limit (${f})`,"info")},u("default"))}),a.push({id:"harnessLimits",label:"Per-harness limits",currentValue:"",description:"Cap how many agents run at once under a single harness.",submenu:v(b)}),a.push({id:"providerLimits",label:"Per-provider limits",currentValue:"",description:"Cap how many agents run at once for a single provider.",submenu:v(()=>H("providers"))}),a.push({id:"modelLimits",label:"Per-model limits",currentValue:"",description:"Cap how many agents run at once for a single model.",submenu:v(()=>H("models"))});let D=s.concurrencySettingsLevels(),K={...D,project:D.project&&c};return(K.session||K.global||K.project)&&a.push({id:"resetAll",label:"Clear all concurrency limits...",currentValue:"",description:"Remove concurrency overrides at the chosen level (session, global, project, or all).",submenu:Ke({theme:l,projectOffered:c,availableLevels:K,message:t(f=>`Clear all concurrency limits at the ${f} level?`,"message"),onConfirm:t(f=>{s.mutate.concurrency.clearAll(f),e.ui.notify(`Concurrency limits cleared (${f})`,"info")},"onConfirm")})}),a},"buildItems"),i;await new W(e).open(({theme:s,close:l})=>{let a=t(()=>i?.(r(L(),s)),"triggerRebuild"),c=L(),d=r(c,s),u=new Tn(d,15,_(s),(g,k)=>a(),l);return new j(u,{title:"Concurrency Settings",theme:s,onCancel:l,onRebuild:t(g=>{i=g},"onRebuild")})})}t(Mn,"showConcurrencySettingsMenu");import{matchesKey as ce,SelectList as dt,truncateToWidth as Ln,visibleWidth as ze}from"@earendil-works/pi-tui";import{SelectList as vr}from"@earendil-works/pi-tui";async function In(e,n){let o=ee();if(!o)return e.map(i=>({id:i,kind:"error",error:"manager unavailable"}));let r=[];for(let i of e)try{r.push({id:i,kind:"report",report:await o.cleanup(i,n(i))})}catch(s){r.push({id:i,kind:"error",error:ue(s)})}return r}t(In,"runCleanupPass");function ct(e,n){let o=X(e.ui);for(let r of n)r.kind==="report"?o.succeeded(Xt(r.report),et(r.report)?"warning":"info"):o.failed(`Failed to clean up agent ${r.id}`,r.error)}t(ct,"reportCleanupOutcomes");function An(e){return e.outcome.kind==="refused"?e.outcome.reason:void 0}t(An,"refusalReason");function br(e){return e.worktree.kind==="kept"?e.worktree.path??void 0:void 0}t(br,"refusalWorktreePath");function kr(e){switch(e.kind){case"dirty":return"It has uncommitted changes";case"unverifiable":return`Its state could not be verified (${e.detail})`;case"recovered-refusal":return"Herdr still reports it at work";default:return Re(e)}}t(kr,"offerReason");function Sr(e,n){return{invalidate(){},render:t(()=>[` ${e.fg("dim",n)}`],"render")}}t(Sr,"progressBody");function Cr(e,n,o,r){let i=[{value:"force",label:"Force",description:n},{value:"cancel",label:"Cancel",description:"Keep the worktree and its changes"}],s=Y(new vr(i,6,Z(e)));return s.onSelect=l=>l.value==="force"?o():r(),s.onCancel=r,s}t(Cr,"forceOfferList");function xn(e){let{ctx:n,theme:o,view:r,refresh:i,close:s,requestRender:l}=e,a=t(u=>{r.activate(u),l()},"show"),c=t((u,g,k,y)=>{let v=u.length===1;a(Ve({theme:o,message:v?`Force cleanup of agent ${u[0]}?`:`Force cleanup of ${u.length} agents?`,detail:[...k,"",v?"This DELETES its worktree and anything uncommitted in it.":"This DELETES their worktrees and anything uncommitted in them."].join(`
3
3
  `),onNo:y,onYes:t(()=>{s(),X(n.ui).pending(`Forcing cleanup of ${Te(u)}`),(async()=>{let p=await In(u,b=>{let C=g.get(b);return{force:C?{reason:C}:{}}});ct(n,p)})()},"onYes")}))},"askForceConfirm"),d=t(u=>{let g=new Map;for(let{id:I,report:O}of u){let $=An(O);$&&g.set(I,$)}let k=[...g.keys()],y=k.length===1,v=u.map(({id:I,report:O})=>{let $=An(O),V=$?y?Re($):`${I}: ${Re($)}`:`${I}: kept`,H=br(O);return H?`${V} (${H})`:V}),p=g.get(k[0]??""),b=y?`Clean up agent ${k[0]} anyway? ${p?kr(p):"kept"}.`:`Clean up ${k.length} agents anyway?`,C=t(()=>{ct(n,u),i()},"backOut");a(Cr(o,b,()=>c(k,g,v,C),C))},"offerForce");return u=>{a(Sr(o,`Cleaning up ${Te(u)}\u2026`)),(async()=>{let g=await In(u,()=>{}),k=g.filter(p=>p.kind==="report"&&tn(p.report)),y=new Set(k.map(p=>p.id));if(ct(n,g.filter(p=>!y.has(p.id))),k.length>0){d(k);return}g.some(p=>p.kind==="error"||et(p.report))?i():s()})()}}t(xn,"createStatusCleanup");import{SelectList as wr}from"@earendil-works/pi-tui";function $n(e){let{ctx:n,theme:o,view:r,close:i,requestRender:s}=e,l=X(n.ui),a=t(v=>{r.activate(v),s()},"show"),c=t((v,p)=>{i(),l.outcome("warning",`Agent ${v.id} ${p}`)},"refuse"),d=t((v,p)=>{try{an(p.path,p.text)}catch(C){l.failed(`Failed to export agent ${v} to ${p.path}`,C);return}let b=p.loss===void 0?"":Ft(p.loss);l.outcome(nt(p),`Exported handover for agent ${v} to ${p.path}.${b}`)},"writeAndReport"),u=t((v,p)=>{a(Ve({theme:o,message:`Overwrite ${p.path}?`,detail:"An export of this run already exists there. Y replaces it with the current export; Esc keeps the existing file.",onYes:t(()=>{i(),d(v,p)},"onYes"),onNo:t(()=>{i(),l.outcome("warning",`Did not export agent ${v}: kept the existing file at ${p.path}`)},"onNo")}))},"askOverwrite"),g=t(v=>{let p=ee();if(!p){i(),l.failed(`Failed to export agent ${v.id}`,"manager unavailable");return}l.pending(`Exporting handover for agent ${v.id}`),(async()=>{let b=await p.exportHandover(v.id);if(b.kind==="faulted"){i(),l.outcome(nt(b),`Agent ${v.id} ${De(b.fault)}`);return}if(sn(b.path)){u(v.id,b);return}i(),d(v.id,b)})()},"runExport"),k=t((v,p)=>{let b=ee();if(i(),!b){l.failed(`Failed to hand agent ${v.id} over to ${p}`,"manager unavailable");return}l.pending(`Handing agent ${v.id} over to ${p}`),(async()=>{let C=await b.handover(v.id,{harness:p});l.outcome(_t(C),Jt(v.id,C))})()},"runHandover"),y=t((v,p)=>{let b=B(),C=Zt(b,re(),p).map(O=>({value:`harness:${O}`,label:`Hand over to ${b.displayName(O)}`,description:`Launch the next run of this agent under ${b.displayName(O)}`}));C.push({value:"export",label:"Export",description:"Write the handover file to /tmp (nothing is stopped or launched)"});let I=Y(new wr(C,10,Z(o)));I.onSelect=O=>{if(O.value==="export"){g(v);return}k(v,O.value.slice(8))},I.onCancel=()=>i(),a(I)},"openSubmenu");return v=>{let p=v.execution.harness;if(p===void 0){c(v,De({kind:"never-started"}));return}let b=B().get(p);if(b===void 0||!It(b)){c(v,De({kind:"harness-cannot-export-session",harness:p}));return}y(v,p)}}t($n,"createStatusHandover");async function Tr(e,n){let o=n.execution.host;if(!o){e.ui.notify("Agent has no herdr pane yet (still queued)","info");return}let r=Ee();if(!r){e.ui.notify("Agent runtime is not initialized","warning");return}let i=X(e.ui);i.pending(`Focusing agent ${n.id}'s herdr pane`);try{await r.view.focus(o),i.succeeded(`Focused agent ${n.id}'s herdr pane`)}catch(s){i.failed(`Failed to focus agent ${n.id}'s herdr pane`,s)}}t(Tr,"focusHerdrPane");async function En(e,n,o,r){let i=o==="result"?n.id:"Error",s=r.split(`
4
4
  `),l=mn(n.display.type),a=5,c=3,d=70,u=0,g=!0;await new W(e).openOverlay(({tui:k,theme:y,close:v})=>{let p=y.fg("border","\u2502"),b=t(()=>{let C=Math.floor(k.terminal.rows*d/100);return Math.max(c,C-a)},"viewportHeight");return{invalidate(){},render(C){let I=C-4,O=[y.fg("border",`\u256D${"\u2500".repeat(C-2)}\u256E`)],$=y.bold(y.fg("accent",`${l} \xB7 ${i}`)),V=Math.max(0,I-ze($));O.push(`${p} ${Ln($+" ".repeat(V),I,"...",!0)} ${p}`),O.push(`${p} ${y.fg("dim","\u2500".repeat(I))} ${p}`);let H=b(),R=Math.max(0,s.length-H);g&&(u=R);let D=Math.min(u,R),K=s.slice(D,D+H);for(let T=0;T<H;T++){let A=K[T]??"",x=Ln(A,I,"...",!0),E=Math.max(0,I-ze(x));O.push(`${p} ${x}${" ".repeat(E)} ${p}`)}let f=s.length<=H?"100%":`${Math.round((D+H)/s.length*100)}%`,m=y.fg("dim",`${s.length} lines \xB7 ${f}`),S=y.fg("dim","q/Esc close"),w=Math.max(1,I-ze(m)-ze(S));return O.push(`${p} ${m}${" ".repeat(w)}${S} ${p}`),O.push(y.fg("border",`\u2570${"\u2500".repeat(C-2)}\u256F`)),O},handleInput(C){if(ce(C,"q")||ce(C,"escape")){v();return}let I=b(),O=Math.max(0,s.length-I);ce(C,"up")?(u=Math.max(0,u-1),g=u>=O):ce(C,"down")?(u=Math.min(O,u+1),g=u>=O):ce(C,"pageUp")?(u=Math.max(0,u-I),g=!1):ce(C,"pageDown")?(u=Math.min(O,u+I),g=u>=O):ce(C,"home")||C==="g"?(u=0,g=!1):C==="G"&&(u=O,g=!0)}}})}t(En,"showTextViewer");function Pn(e,n){let o=ee(),r=Te(n),i=X(e.ui);if(!o){i.failed(`Failed to stop ${r}`,"manager unavailable");return}(async()=>{let s=0,l=[];for(let c of n)try{await o.abort(c,"user")?s+=1:l.push({id:c,reason:"already settled"})}catch(d){l.push({id:c,reason:ue(d)})}if(l.length===0){i.succeeded(n.length===1?`Stopped ${n[0]}`:`Stopped ${n.length} agent(s)`);return}let a=l.map(({id:c,reason:d})=>n.length===1?d:`${c} (${d})`).join(", ");s>0?i.succeeded(`Stopped ${s} of ${n.length} agent(s); ${a}`,"warning"):i.failed(`Failed to stop ${r}`,a)})()}t(Pn,"stopAgentsOffMenu");function Or(e,n,o,r,i,s,l){let a=[],c=n.id,d=Ce(n.lifecycle.phase),u=n.execution.host!==void 0,g=Et(n.lifecycle),k=xe(n.lifecycle)&&n.lifecycle.status==="error"?n.lifecycle.error:"",y=g.length>0,v=k.length>0;if(u&&a.push({value:"focus-pane",label:"View shell",description:"Focus the subagent's herdr pane"}),y&&a.push({value:"view-result",label:"View result"}),v&&a.push({value:"view-error",label:"View error"}),d?a.push({value:"stop",label:"Stop"}):(n.lifecycle.phase==="settled"&&a.push({value:"handover",label:"Handover",description:"Hand this run's session to another harness, or export it to /tmp"}),a.push({value:"cleanup",label:"Clean up",description:"Close its pane and remove its worktree and merged branch"})),a.length===0)return e.ui.notify(`Agent ${c} \u2014 no actions available`,"info"),r(),new dt([],5,Z(o));let p=Y(new dt(a,10,Z(o)));return p.onSelect=async b=>{b.value==="focus-pane"?await Tr(e,n):b.value==="view-result"?await En(e,n,"result",g):b.value==="view-error"?await En(e,n,"error",k):b.value==="stop"?(X(e.ui).pending(`Stopping agent ${c}`),r(),Pn(e,[n.id])):b.value==="cleanup"?s([n.id]):b.value==="handover"&&l(n)},p.onCancel=()=>r(),p}t(Or,"buildAgentActionsList");async function Rn(e){if((ee()?.listAgents(Ae)??[]).length===0){e.ui.notify("No agents have been spawned this session","info");return}await new W(e).open(({tui:n,theme:o,close:r})=>{let i=ee()?.listAgents(Ae)??[],s=t(()=>i.filter(p=>Ce(p.lifecycle.phase)),"activeAgents"),l=t(()=>i.filter(p=>!Ce(p.lifecycle.phase)),"finishedAgents"),a=t(()=>i.filter(p=>xe(p.lifecycle)&&p.lifecycle.status==="completed"),"completedAgents"),c=t(()=>{let p=Date.now(),b=i.map($=>{let V=Lt($.lifecycle),H=Ce($.lifecycle.phase),R=xe($.lifecycle)?$.lifecycle.completedAt:p,D=rt(R-Pt($.lifecycle)),K=H?"":` ${rt(p-R)} ago`,f=un(V,o),m=$.display.description?$.display.description:"",S=m?` \u2014 ${m}`:"",w=ae(o),T=$.display.worktree?` wt:${$.display.worktree.branch}`:"";return{value:$.id,label:`${f} ${$.id} ${w}${$.display.type} ${V} ${D}${T}${S}${K}`}}),C=s(),I=l(),O=a();return C.length>0&&(b.push({value:q,label:" "}),b.push({value:"__stop-all",label:`Stop ${C.length} active agent(s)`})),I.length>0&&(b.push({value:q,label:" "}),b.push({value:"__cleanup-finished",label:`Clean up ${I.length} settled agent(s)`}),O.length>0&&b.push({value:"__cleanup-completed",label:`Clean up ${O.length} completed agent(s)`})),b},"buildAgentItems"),d=Y(new dt(c(),15,Z(o)));je(d);let u=new He(d),g=t(()=>n.requestRender(),"requestRender"),k=t(p=>{i=ee()?.listAgents(Ae)??[];let b=d,C=c();b.items=C,b.filteredItems=C;let I=p?C.findIndex(O=>O.value===p):-1;d.setSelectedIndex(I>=0?I:0),u.activate(d),g()},"refresh"),y=xn({ctx:e,theme:o,view:u,refresh:k,close:r,requestRender:g}),v=$n({ctx:e,theme:o,view:u,close:r,requestRender:g});return d.onSelect=async p=>{if(p.value==="__stop-all"){let C=s();X(e.ui).pending(`Stopping ${C.length} agent(s)`),r(),Pn(e,C.map(I=>I.id));return}if(p.value==="__cleanup-finished"){y(l().map(C=>C.id));return}if(p.value==="__cleanup-completed"){y(a().map(C=>C.id));return}let b=i.find(C=>C.id===p.value);b&&u.activate(Or(e,b,o,()=>k(b.id),()=>r(),y,v))},d.onCancel=()=>r(),new j(u,{title:"Status",theme:o,passthroughKeys:!0})})}t(Rn,"showAgentStatusMenu");import{SettingsList as Mr,Input as Ir}from"@earendil-works/pi-tui";function Ar(e){let n="Harness that launches agents whose template omits harness_type. pi = the real pi binary; pig and pi-bolt = pi-compatible binaries launched through a shell function in the agent's own pane; opencode and codex = binaries of their own launched as their interactive UIs in the agent's own pane.",o=Ot.filter(l=>l!=="pi"&&!Xe(l,e)),r=o.length===0?n:`${n} Not on PATH: ${o.join(", ")}.`,i=B(),s=Hn().filter(l=>Mt(l)===void 0);return s.length===0?r:`${r} Plugin harnesses: ${s.map(l=>i.displayName(l)).join(", ")}.`}t(Ar,"harnessDescription");function Hn(){return[...ke(B().ids(),re())]}t(Hn,"offerableHarnesses");async function jn(e){let n=L(),o=t(s=>[fe(s,"Spawn defaults"),{id:q,label:" ",currentValue:""},{id:"harnessType",label:"Default harness",currentValue:Vt(),values:Hn(),description:Ar(re())},{id:q,label:" ",currentValue:""},fe(s,"Worktrees"),{id:"worktreeRoot",label:"Worktree root",currentValue:n.agent.worktreeRoot??"(default)",submenu:t((l,a)=>{let c=new Ir;return c.setValue(l==="(default)"?"":l),c.onSubmit=d=>{let u=d.trim();n.mutate.agent.setWorktreeRoot(u||void 0),ln(le()),e.ui.notify(u?`Worktree root set to ${u}`:"Worktree root cleared (default)","info"),a(u||"(default)")},c.onEscape=()=>a(),c},"submenu"),description:`Where worktrees are created. Blank = ${yt()}.`},{id:"worktreeMaterialization",label:"Worktree materialization",currentValue:Le(),values:[...ke(vt,Qe())],description:Xe("copy-on-write",Qe())?"Copy-on-write = clone of the parent working tree (shares node_modules, .env). checkout = git's classic checkout, nothing shared.":"This volume cannot clone, so copy-on-write is unavailable and new worktrees use git's classic checkout."},{id:"worktreeCheckoutType",label:"Worktree checkout",currentValue:n.agent.worktreeCheckoutType,values:[...kt],description:"Where a new worktree's checkout starts when the parent has uncommitted work. clean = the worktree starts at HEAD: under copy-on-write, only ignored files like node_modules and .env are copied in; under checkout, it is git's plain checkout. dirty = the parent's work rides along: copy-on-write clones its edits and untracked files too, while checkout applies only its tracked changes, leaving untracked files behind. A clean parent starts at HEAD either way."},{id:q,label:" ",currentValue:""},fe(s,"Tools"),{id:"disableDefaultAgents",label:"Disable default agents",currentValue:n.agent.disableDefaultAgents?"ON":"OFF",values:["ON","OFF"],description:"Skip auto-loading built-in agent types next session; only .pi/agents types load."}],"buildItems"),r=t((s,l)=>{switch(s){case"worktreeRoot":break;case"worktreeMaterialization":{let a=bt(l);a!==void 0&&(n.mutate.agent.setWorktreeMaterialization(a),e.ui.notify(`Worktree materialization set to ${a}`,"info"));break}case"worktreeCheckoutType":{let a=St(l);a!==void 0&&(n.mutate.agent.setWorktreeCheckoutType(a),e.ui.notify(`Worktree checkout set to ${a}`,"info"));break}case"harnessType":{n.mutate.agent.setHarnessType(l),e.ui.notify(`Default harness set to ${l}`,"info");break}case"disableDefaultAgents":n.mutate.agent.setDisableDefaultAgents(l==="ON"),e.ui.notify(`Disable default agents ${l} (takes effect on next session)`,"info");break}},"onChange"),i;await new W(e).open(({theme:s,close:l})=>{let a=o(s),c=t(()=>i?.(o(s)),"triggerRebuild"),d=new Mr(a,10,_(s),(u,g)=>{r(u,g),a.some(k=>k.id===u&&k.submenu)&&c()},l);return new j(d,{title:"Agent settings",theme:s,onCancel:l,onRebuild:t(u=>{i=u},"onRebuild")})})}t(jn,"showSpawnOptionsMenu");function xr(e,n,o){return(r,i)=>{let s=Pe();s.length===0&&n("No agent types available","error");let l=s.map(a=>({value:a,label:a,provider:U(a)?.description??""}));return new pe(l,e.agent.defaultAgentType,{onSelect:t(a=>{a!=null&&(e.mutate.agent.setDefaultAgentType(a),n(`Agent set to ${a}`,"info")),i(a??void 0)},"onSelect"),onCancel:t(()=>i(),"onCancel")},o)}}t(xr,"createAgentTypeSubmenu");function $r(e,n,o){return(r,i)=>{let s=Ut(),a=(s.length>0?s:Object.keys(Bt)).map(c=>({value:c,label:c}));return new pe(a,e.agent.defaultOrchestrator,{onSelect:t(c=>{c!=null&&(e.mutate.agent.setDefaultOrchestrator(c),n(`Default orchestrator set to ${c}`,"info")),i(c??void 0)},"onSelect"),onCancel:t(()=>i(),"onCancel")},o)}}t($r,"createOrchestratorSubmenu");function Fn(e){return{id:"defaultAgentType",label:"Agent",currentValue:e.store.agent.defaultAgentType,submenu:xr(e.store,e.notify,e.theme),description:`Agent type used when cowboy_agent omits \`agent_type\`. Default: ${xt}.`}}t(Fn,"buildDefaultAgentTypeRow");function _n(e){return{id:"defaultOrchestrator",label:"Default orchestrator",currentValue:e.store.agent.defaultOrchestrator,submenu:$r(e.store,e.notify,e.theme),description:`Orchestration template used for every cowboy_agent spawn; the tool accepts no per-call orchestrator input. Default: ${$t}.`}}t(_n,"buildDefaultOrchestratorRow");import ut from"node:fs";import Lr from"node:path";import{SettingsList as Er}from"@earendil-works/pi-tui";async function Dn(e){let n=L(),o=t(()=>{let l=Je(),a=[{id:"systemPromptMode",label:"System prompt mode",currentValue:n.agent.systemPromptMode,values:["replace","inherit","custom"],description:"How the subagent system prompt is built: replace, inherit, or custom."}];return n.agent.systemPromptMode==="custom"&&!ut.existsSync(l)&&a.push({id:"createPromptFile",label:"Create prompt file",currentValue:l,values:["Create"],description:`Create ${l} with a starter template for custom mode.`}),a.push({id:"includeContextFiles",label:"Include context files",currentValue:n.agent.includeContextFiles?"ON":"OFF",values:["ON","OFF"],description:"Load project and ~/.pi/agent AGENTS.md as shared <project_context>."},{id:"loadSkillsImplicitly",label:"Load skills implicitly",currentValue:n.agent.loadSkillsImplicitly?"ON":"OFF",values:["ON","OFF"],description:"Give new agents all skills when an agent template omits the field."},{id:"loadExtensionsImplicitly",label:"Load extensions implicitly",currentValue:n.agent.loadExtensionsImplicitly?"ON":"OFF",values:["ON","OFF"],description:"Give new agents all extensions when an agent template omits the field."}),a},"buildItems"),r=o(),i=null,s=t((l,a)=>{switch(l){case"systemPromptMode":n.mutate.agent.setSystemPromptMode(a),e.ui.notify(`System prompt mode set to ${a}`,"info"),r=o(),i?.(r);break;case"createPromptFile":try{let c=Je();ut.mkdirSync(Lr.dirname(c),{recursive:!0}),ut.writeFileSync(c,`You are a Pi, an expert coding sub-agent.
@@ -6,4 +6,4 @@ You have been invoked to handle a specific task autonomously`,"utf-8"),e.ui.noti
6
6
  `,1)[0]??"").slice(0,Vr),$=Nt(),V=zt();try{await $.spawn(o,{spawnId:p,type:g.type,requestedHarness:g.harness,prompt:y,description:O,orchestration:V,modelChoice:g.modelChoice,worktree:I,hostRef:b?.hostRef,projectTrusted:b?.projectTrusted,invocation:{...Vn(g.modelChoice),runInBackground:g.runInBackground,fork:g.fork},runInBackground:g.runInBackground,fork:g.fork})}catch(H){let R=`Spawn failed: ${H instanceof Error?H.message:String(H)}`;if(!b){e.ui.notify(R,"error");return}let D=await b.teardown(v);e.ui.notify(`${R}
7
7
 
8
8
  ${rn(D)}`,"error")}},"launch"),a=await Jn(e,n);if(a===void 0)return;let c=new W(e),d;if(a.worktreeChoice.kind==="new"){let g=await Xn(c,(k,y)=>e.ui.notify(k,y));if(g===void 0)return;d={kind:"new",branch:g}}else d=a.worktreeChoice;let u=await c.open(({tui:g,theme:k,keybindings:y,close:v})=>new j(Zn({prefill:"",onDone:t(p=>v(p),"onDone"),onCancel:t(()=>v(),"onCancel"),tui:g,theme:k,keybindings:y}),{title:"Agent Prompt (optional)",theme:k,passthroughKeys:!0}));u!==void 0&&await l(a,d,u)}t(Qn,"showSpawnAgentMenu");async function Wr(e){return await new W(e).open(({theme:n,close:o})=>{let r=t(d=>o(d),"handOff"),i=L(),s=i.agent.showActiveIndicator,l=i.agent.grazingEnabled,a=[be("concurrency","Concurrency Settings","Set per-model slot limits",r),be("spawnoptions","Agent behavior","spawn defaults, results delivery, output, tools, worktrees",r),be("systemprompt","System prompt","Prompt mode, AGENTS.md, skills, extensions",r),{id:"showActiveIndicator",label:"Show cowboy \u{1F920}",currentValue:s?"ON":"OFF",values:["ON","OFF"]},{id:"grazingEnabled",label:"Grazing \u{1F404}",currentValue:l?"ON":"OFF",values:["ON","OFF"]}],c=new er(a,10,_(n),(d,u)=>{d==="showActiveIndicator"?Qt(e.ui,u==="ON"):d==="grazingEnabled"&&i.mutate.agent.setGrazingEnabled(u==="ON")},o);return new j(c,{title:"Settings",theme:n,onCancel:o})})}t(Wr,"showSettingsList");async function Kr(e,n){for(;;){let o=await Wr(e);if(o===void 0)return;switch(o){case"concurrency":await Mn(e,n);break;case"spawnoptions":await jn(e);break;case"systemprompt":await Dn(e);break}}}t(Kr,"showSettingsMenu");async function Gr(e,n,o){switch(n){case"status":await Rn(e);break;case"spawn":await Qn(e,o);break;case"settings":await Kr(e,o);break}}t(Gr,"showAgentsActionMenu");function be(e,n,o,r){return{id:e,label:n,description:o,currentValue:"",submenu:t(()=>(r(e),ie),"submenu")}}t(be,"handOffRow");async function Br(e,n){let o=await dn(e.cwd),r;return await new W(e).open(({theme:i,close:s})=>{let l=t(d=>s(d),"handOff"),a=t(()=>{let d=L(),u=t((y,v)=>e.ui.notify(y,v),"notify"),g=d.agent.extensionEnabled,k={id:"extensionEnabled",label:"Enabled",currentValue:g?"ON":"OFF",values:["ON","OFF"],description:g?"Unload the cowboy tools and stop subagent-result notifications. Persisted; active agents keep working.":"cowboy tools are unloaded and the rest of this menu is hidden. Active agents keep working."};return g?[wn({ctx:e,store:d,theme:i,harnessModelOptions:n,piDefaultThinking:o}),_n({store:d,theme:i,notify:u}),Fn({store:d,theme:i,notify:u}),be("status","Status","List spawned, queued and settled agents",l),be("spawn","Spawn agent","Manually spawn a new agent",l),be("settings","Settings","Concurrency, agent behavior, and system prompt settings",l),k]:[k]},"buildItems"),c=new er(a(),10,_(i),(d,u)=>{let g=d==="extensionEnabled";if(g){let k=u==="ON";cn(e.ui,k),e.ui.notify(k?"pi-cowboy enabled":"pi-cowboy disabled","info")}r?.(a(),g?"extensionEnabled":void 0)},s);return new j(c,{title:"Agents",theme:i,onCancel:s,onRebuild:t(d=>{r=d},"onRebuild")})})}t(Br,"showAgentsMainList");async function ja(e,n){for(;;){let o=await Br(e,n);if(o===void 0)return;await Gr(e,o,n)}}t(ja,"showAgentsMainMenu");export{Gr as showAgentsActionMenu,ja as showAgentsMainMenu,Kr as showSettingsMenu,Qn as showSpawnAgentMenu};
9
- //# sourceMappingURL=menus-QMEWZXAL.js.map
9
+ //# sourceMappingURL=menus-FNRNSUTM.js.map
@@ -1,2 +1,2 @@
1
- import{a as E,b as R,i as A}from"./chunk-ROCBRG4A.js";import{ia as v,ja as u,ma as c,wa as S,xa as k}from"./chunk-GYO352IF.js";import{a as s,e as w,f as m,u as h,v as C}from"./chunk-XXNZAWMK.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
- //# sourceMappingURL=model-picker-I2L5LYS7.js.map
1
+ import{a as E,b as R,i as A}from"./chunk-5Q6BGTTQ.js";import{ia as v,ja as u,ma as c,wa as S,xa as k}from"./chunk-NF3DL7IL.js";import{a as s,e as w,f as m,u as h,v as C}from"./chunk-XXNZAWMK.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
+ //# sourceMappingURL=model-picker-CRQCRAYT.js.map
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "pi-cowboy",
3
- "version": "0.27.0",
3
+ "version": "0.27.3",
4
4
  "type": "module",
5
5
  "packageManager": "pnpm@12.9.1",
6
- "description": "Agent orchestrator for pi: can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",
6
+ "description": "🤠 Agent orchestrator for pi. It can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents and handover sessions in between them. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",
7
7
  "keywords": [
8
8
  "pi-package",
9
9
  "pi",