pi-cowboy 0.22.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +0,0 @@
1
- import{b as It,c as Pt,e as Mt,g as Nt,k as Pe,l as $t,p as Bt}from"./chunk-ZLKJYRKY.js";import{F as Ct,I as Ce,K as _t,L as G,M as _e,N as P,O as Se,P as St,R as te,S as _,T as M,V as Et,b as ot,ba as C,ca as ne,da as b,fa as f,ga as N,h as it,ha as Ee,i as st,ia as Oe,j as K,k as at,ka as Ot,l as Ae,m as lt,na as Re,o as dt,oa as re,pa as x,qa as oe,r as ct,sa as j,v as ut,va as Rt,w as pt,x as gt,y as mt,ya as Ie,za as ie}from"./chunk-JIAP5YBM.js";import{a as r,d as ee,f as xe,g as ht,j as ft,k as yt,l as wt,n as kt,o as bt,q as vt,s as Tt,t as At,u as xt}from"./chunk-254PTGN5.js";import{visibleWidth as Be}from"@earendil-works/pi-tui";var Me="\u{1F920}",jt="\u{1F404}",or="\u{1F4A9}",ir=2,sr=1e3,se=Be(jt),ar="76;175;80";function lr(e){return`\x1B[48;2;${ar}m${e}\x1B[49m`}r(lr,"greenBackground");function Ht(e){return e===0?0:Math.max(ir,Math.ceil(Math.sqrt(2*e)))}r(Ht,"pastureEdge");function Lt(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Lt,"emptyPasture");function dr(e,t){let n=Ht(e.cows+e.droppings),o=Lt(n),i=Array.from({length:n*n},(a,l)=>l),s=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let a=0;a<s.length;a+=1){let l=a+Math.floor(t()*(i.length-a)),c=i[l];i[l]=i[a],i[a]=c,o[Math.floor(c/n)][c%n]=s[a]}return o}r(dr,"grazedPasture");function ae(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(ae,"cellsOf");function cr(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(cr,"neighboursOf");function Dt(e,t){return cr(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Dt,"openNeighboursOf");function ur(e,t){let n=ae(e,"cow").filter(l=>Dt(l,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Dt(o,e),s=i[Math.floor(t()*i.length)],a=e.map(l=>l.slice());return a[o.row][o.col]="empty",a[s.row][s.col]="cow",a}r(ur,"moveHerd");function Ft(e,t,n,o){for(let i=0;i<n;i+=1){let s=ae(e,"empty"),a=s[Math.floor(o()*s.length)];e[a.row][a.col]=t}}r(Ft,"placeAtRandom");function pr(e,t,n,o){let i=ae(e,"cow"),s=ae(e,"dropping"),a=i.length-t,l=s.length-n;for(;a>0&&l<0;){let c=i.pop();e[c.row][c.col]="dropping",a-=1,l+=1}for(;a>0;){let c=i.pop();e[c.row][c.col]="empty",a-=1}for(;l>0;){let c=s.pop();e[c.row][c.col]="empty",l-=1}Ft(e,"cow",-a,o),Ft(e,"dropping",-l,o)}r(pr,"reconcileCounts");function gr(e,t,n){if(e===null)return dr(t,n);let o=Ht(t.cows+t.droppings),i=Lt(o);for(let s=0;s<e.length&&s<o;s+=1)for(let a=0;a<e[s].length&&a<o;a+=1)i[s][a]=e[s][a];return pr(i,t.cows,t.droppings,n),i}r(gr,"reconcilePasture");var mr={anchor:"top-right",width:Be(Me),get offsetX(){return N()?.cowboyOffsetX??0},nonCapturing:!0},hr={anchor:"top-right",offsetY:1,get width(){return N()?.pastureWidth??0},nonCapturing:!0};function fr(e){return e==="cow"?jt:e==="dropping"?or:" ".repeat(se)}r(fr,"cellText");function yr(e,t){return e.map(n=>t(n.map(fr).join("")))}r(yr,"drawnRows");function wr(){return Oe().list(["spawned"]).length}r(wr,"liveAgentCount");function kr(){return Oe().list(St).length}r(kr,"endedAgentCount");function br(){return{live:wr(),ended:kr()}}r(br,"agentCounts");function vr(){return f().agent.grazingEnabled}r(vr,"grazingEnabled");var Ne=class{constructor(t,n,o,i,s){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=s}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return Be(Me)}get pastureWidth(){return this.drawnPasture().length*se}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*se-(t*se-this.cowboyWidth)}render(){return this.frame(),[Me]}pastureRows(){return this.frame(),yr(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(),sr))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,s=(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:ur(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let a=s&&this.drawnPasture().length===0;this.tui.requestRender(a)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:gr(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},$e=class{static{r(this,"PastureView")}render(){return N()?.pastureRows()??[]}invalidate(){}};function Ut(e){De(),e.custom(t=>{let n=new Ne(t,br,vr,lr,Math.random);return Ee(n),n},{overlay:!0,overlayOptions:mr,onHandle:r(t=>N()?.attachCowboy(t),"onHandle")}),e.custom(()=>new $e,{overlay:!0,overlayOptions:hr,onHandle:r(t=>N()?.attachPasture(t),"onHandle")})}r(Ut,"showExtensionIndicator");function De(){let e=N();Ee(null),e?.dispose()}r(De,"hideExtensionIndicator");function le(){return f().agent.extensionEnabled}r(le,"isExtensionEnabled");function Tr(){return le()&&f().agent.showActiveIndicator}r(Tr,"isActiveIndicatorShown");function de(e){Tr()?Ut(e):De()}r(de,"syncExtensionIndicator");function gi(e,t){f().mutate.agent.setShowActiveIndicator(t),de(e)}r(gi,"setShowActiveIndicator");import{Type as D}from"typebox";import{Text as Dn}from"@earendil-works/pi-tui";import{Type as y}from"typebox";var Ar="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.",xr=`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.`,Cr=`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.`,_r=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${yt.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.`,Sr=y.Object({prompt:y.String({description:Ar}),task_name:y.String({description:xr}),agent_type:y.Optional(y.Union([y.String(),y.Null()])),model:y.Optional(y.Union([y.String(),y.Null()],{description:Cr})),harness_type:y.Optional(y.Union([y.String(),y.Null()],{description:_r}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=y.Object({agents:y.Array(Sr,{minItems:1}),run_in_background:y.Optional(y.Boolean())},{additionalProperties:!1,required:["agents"]});import{Type as Fe}from"typebox";var Er="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Wt=Fe.Object({agent_ids:Fe.Array(Fe.String({minLength:1}),{minItems:1,description:Er})},{additionalProperties:!1,required:["agent_ids"]});import{Type as je}from"typebox";var Or="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",qt=je.Object({agent_ids:je.Array(je.String({minLength:1}),{minItems:1,description:Or})},{additionalProperties:!1,required:["agent_ids"]});import{Type as $}from"typebox";var Rr="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",Ir="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",Pr="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",Kt=$.Object({branches:$.Array($.String({minLength:1}),{minItems:1,description:Rr}),target:$.Optional($.String({description:Ir})),repo:$.Optional($.String({description:Pr}))},{additionalProperties:!1,required:["branches"]});import{Type as ce}from"typebox";var Mr="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.",Nr="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.",Gt=ce.Object({agent_ids:ce.Array(ce.String({minLength:1}),{minItems:1,description:Mr}),message:ce.String({description:Nr})},{additionalProperties:!1,required:["agent_ids","message"]});import*as ue from"node:fs";import*as Vt from"node:path";import{parse as $r,TomlError as Br}from"smol-toml";import{z as Dr}from"zod";var Fr=".toml";function pe(e){return $r(e.replace(/^\uFEFF/,""))}r(pe,"parseTemplateToml");function T(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0))}r(T,"compactDefined");function jr(e){let t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}r(jr,"describeZodIssue");function Hr(e){if(e instanceof Dr.ZodError)return e.issues.map(jr).join("; ").replace(/\s+/g," ").trim();if(e instanceof Br){let[n]=e.message.split(`
2
-
3
- `);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}r(Hr,"describeParseError");var Lr={label:"File",problem:"was skipped"};async function ge(e,t,n,o,i=Lr,s){try{await ue.promises.access(e)}catch{return[]}let l=(await ue.promises.readdir(e,{withFileTypes:!0})).filter(d=>d.isFile()&&d.name.endsWith(Fr)),c=[];for(let d of l){let h=Vt.join(e,d.name),g;try{g=await ue.promises.readFile(h,"utf-8")}catch{continue}try{let p=t(g),m=s?.(p);if(m!==void 0)throw new Error(m);n(p)&&c.push(p)}catch(p){o?.(`[cowboy] ${i.label} file ${h} ${i.problem}: ${Hr(p)}`,"warning")}}return c}r(ge,"scanTemplateFilesInDir");import{z as u}from"zod";var zt=u.union([u.boolean(),u.array(u.string())]);function Ur(e,t,n){if(!kt(e))return"is not a valid environment variable name";if(vt(e,n))return"is a reserved environment variable and cannot be overridden";if(bt(t))return"contains a control character"}r(Ur,"envProblem");function he(e){let t=Tt[e];return u.record(u.string(),u.string()).superRefine((n,o)=>{for(let[i,s]of Object.entries(n)){let a=Ur(i,s,t);a!==void 0&&o.addIssue({code:"custom",path:[i],message:a})}})}r(he,"envTable");var Yt={model:u.string().optional(),thinking:G.optional(),extensions:zt.optional(),skills:zt.optional(),inlined_skills:u.array(u.string()).optional(),fork:u.boolean().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:he("pi").optional()},Wr=u.strictObject(Yt),qr=u.strictObject({model:u.string().optional(),variant:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:he("opencode").optional()}),Kr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),env:he("codex").optional()}),Gr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:he("claude").optional()});function He(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}r(He,"toToolFilter");function Vr(e,t){return t===void 0?e:e===void 0?t:{...t,...e}}r(Vr,"mergeEnv");function me(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}r(me,"nonEmptyEnv");var zr=u.strictObject({include_context_files:u.boolean().optional(),pi:Wr.optional(),opencode:qr.optional(),codex:Kr.optional(),claude:Gr.optional(),...Yt}).transform(({pi:e,opencode:t,codex:n,claude:o,...i})=>{let{model:s,thinking:a,tools:l,exclude_tools:c,env:d,...h}=i,{model:g,thinking:p,tools:m,exclude_tools:w,env:k,...v}=T(e??{}),{model:F,variant:q,tools:Te,exclude_tools:Gn,env:Vn,...zn}=T(t??{}),{model:Yn,thinking:Qn,env:Xn,...Zn}=T(n??{}),{model:Jn,thinking:er,tools:tr,exclude_tools:nr,env:rr}=T(o??{}),et=T({pi:g??s,opencode:F,codex:Yn,claude:Jn}),tt=T({pi:He(m??l,w??c),opencode:He(Te,Gn),claude:He(tr,nr)}),nt=T({pi:p??a,opencode:q,codex:Qn,claude:er}),rt=T({pi:me(Vr(k,d)),opencode:me(Vn),codex:me(Xn),claude:me(rr)});return{...h,...v,...zn,...Zn,...Object.keys(et).length>0?{modelsByFamily:et}:{},...Object.keys(tt).length>0?{toolsByFamily:tt}:{},...Object.keys(nt).length>0?{thinkingByFamily:nt}:{},...Object.keys(rt).length>0?{envByFamily:rt}:{}}}),Qt=u.strictObject({name:u.string().optional(),display_name:u.string().optional(),description:u.string().optional(),hidden:u.boolean().optional(),worktree_checkout_type:u.enum(ct).optional(),system_prompt:u.string().optional(),harness_type:u.string().min(1).optional(),harness:zr.optional()});function Yr(e){return Qt.parse(pe(e))}r(Yr,"parseAgentFile");var Qr={label:"Agent",problem:"is not a valid agent template and was skipped"};async function L(e,t,n){return ge(e,Yr,o=>o.name,t,Qr,n)}r(L,"scanAgentFilesInDir");function fe(e,t,n,o){let i=new Map;for(let[s,a]of e)i.set(s,{...a});return Le(i,t),Le(i,n),Le(i,o),i}r(fe,"mergeAgents");function Le(e,t){for(let n of t){if(!n.name)continue;let o=e.get(n.name);if(o){let i={displayName:n.display_name,description:n.description??""},s=Xt(n),a=Xr(o.modelsByFamily,s.modelsByFamily),l=Zr(o.toolsByFamily,s.toolsByFamily),c=Jr(o.thinkingByFamily,s.thinkingByFamily),d=eo(o.envByFamily,s.envByFamily);e.set(n.name,{...o,...s,...a?{modelsByFamily:a}:{},...l?{toolsByFamily:l}:{},...c?{thinkingByFamily:c}:{},...d?{envByFamily:d}:{},...i})}else e.set(n.name,{...to,...Xt(n)})}}r(Le,"mergeAgentOverrides");function Xr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Xr,"mergeModelsByFamily");function Zr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Zr,"mergeToolsByFamily");function Jr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Jr,"mergeThinkingByFamily");function eo(e,t){let n={...e};for(let[o,i]of Object.entries(t??{})){let s=o;n[s]={...n[s],...i}}return Object.keys(n).length>0?n:void 0}r(eo,"mergeEnvByFamily");function Xt(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 T(n)}r(Xt,"fromTemplate");var to={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Ue=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return ie().agents}r(S,"registry");function V(e){let t=e.harness_type;if(t===void 0)return;let n=x();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}r(V,"unregisteredHarness");function Vi(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[o,i]of Ue)n.set(o,i);for(let[o,i]of e)n.set(o,i);S().agents=n}r(Vi,"registerAgents");function zi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}r(zi,"setAgentScanDirs");async function no(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,o=S().scanDirs,[i,s,a,l]=await Promise.all([t?Promise.resolve([]):L(it,n,V),L(o.user,n,V),L(o.shared,n,V),L(o.project,n,V)]),d=fe(t?new Map:Ue,i,[],[]);return fe(d,s,a,l)}r(no,"scanAndMerge");async function ro(e,t){let n=await no(t),{agents:o}=S(),i=0;for(let[s,a]of n)o.has(s)||(o.set(s,a),i++);if(e){let s=await L(e,t?.notify,V),a=fe(new Map,[],[],s);for(let[l,c]of a)o.has(l)||(o.set(l,c),i++)}return i}r(ro,"discoverNewAgents");function z(e){let{agents:t}=S();if(!e)return{kind:"not-found"};if(t.has(e))return{kind:"resolved",key:e};let n=e.toLowerCase(),o=[];for(let i of t.keys())i.toLowerCase()===n&&o.push(i);return o.length===1?{kind:"resolved",key:o[0]}:o.length>1?{kind:"ambiguous",candidates:o}:{kind:"not-found"}}r(z,"resolveType");async function Jt(e,t,n){let o=z(e);return o.kind==="not-found"&&(await ro(t,{notify:n}),o=z(e)),o}r(Jt,"resolveTypeOrDiscover");function E(e){let t=z(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}r(E,"getAgentConfig");function en(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}r(en,"getAvailableTypes");function Yi(){return[...S().agents.keys()]}r(Yi,"getAllTypes");function Zt(e,t,n,o){return{skills:e??n,extensions:t??o}}r(Zt,"applyGlobalDefaults");function Qi(e,t=!0,n=!0){let o=E(e);if(o){let{skills:s,extensions:a,...l}=o,c=Zt(s,a,t,n);return{displayName:l.displayName??l.name,description:l.description,...c}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Zt(void 0,void 0,t,n)}}r(Qi,"getConfig");var We="_configuredModel",qe="_configuredThinking";function U(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(U,"readModelKey");function tn(e){return U(e.thinking)??U(e[qe])}r(tn,"readThinkingRequest");function nn(e){let t=U(e.model);if(t)return{source:"call",key:t};let n=U(e[We]);if(n)return{source:"configured",key:n}}r(nn,"readModelRequest");function Y(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(Y,"withoutModel");function rn(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(rn,"modelChoiceFor");function Q(e){return`${e.provider}/${e.id}`}r(Q,"modelKey");function oo(e,t){if(t!==void 0&&!G.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${G.options.join(", ")}); launching "${Q(e)}" with "${t}".`}r(oo,"undeclaredLevelWarning");function on(e,t){let n=oo(e,t);return{resolved:{kind:"resolved",model:e,modelKey:Q(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(on,"resolvedModel");function io(e){return`No API key found for "${e}"`}r(io,"missingCredential");function sn(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:ee(o)}}return!Ct(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:io(t.provider)}}r(sn,"probeCredentials");function Ke(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ke,"refusal");function Ge(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return Y(i);let l=sn(n,o);if(l.verdict!=="unusable")return on(o,i);throw new Error(Ke(`The parent session's model "${Q(o)}" did not resolve credentials in this session`,l.reason))}let s=e.source==="call"?xe(e.key,n,void 0):xe(e.key,n,o);if(!s){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return Y(i)}let a=sn(n,s);if(a.verdict!=="unusable")return on(s,i);throw e.source==="call"?new Error(Ke(`Model "${Q(s)}" cannot authenticate in this session`,a.reason)):new Error(Ke(`The subagent model "${Q(s)}" for this configured default cannot authenticate in this session`,a.reason))}r(Ge,"resolvePiModel");async function so(e){try{return await e.listModels(e.harness)}catch{return[]}}r(so,"harnessModels");function ao(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(ao,"undeclaredLevelWarning");async function an(e,t){if(!e)return Y(t.thinking);let n=await so(t),o=n.find(s=>s.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 s=ao(t.harness,o,t.thinking);s!==void 0&&i.push(s)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(an,"resolveForeignModel");async function ln(e,t){let{harness:n}=t;if(wt(n))return Ge(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return an(e,o)}r(ln,"resolveSpawnModel");function ye(e,t){return{content:[{type:"text",text:e}],details:t}}r(ye,"successResult");var Ve=`
4
-
5
- ---
6
-
7
- `,lo={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function O(e){let{items:t}=e;uo(t,e),await e.prepare?.();let n=co(e),o=[],i=[],s=r(({outcome:l,text:c})=>{o.push(l),i.push(c)},"record"),a;for(let l of t){let c=n.halt;if(c!==void 0&&a!==void 0){s(c.skip(l,a));continue}let d=await n.handle(l);s(d),c!==void 0&&c.halts(d.outcome)&&(a=l)}return ye(i.join(Ve),{[e.detailsKey]:o})}r(O,"runBatch");function co(e){if("render"in e){let n=e.render,o=e.halt;return{handle:r(async i=>{let s=await e.handleItem(i);return{outcome:s,text:n(s)}},"handle"),halt:o===void 0?void 0:{halts:r(i=>o.on(i),"halts"),skip:r((i,s)=>{let a=o.skip(i,s);return{outcome:a,text:n(a)}},"skip")}}}let t=e.halt;return{handle:e.handleItem,halt:t===void 0?void 0:{halts:r(n=>t.on(n),"halts"),skip:t.skip}}}r(co,"batchSteps");function uo(e,{toolName:t,param:n}){let o=e.map(a=>a.trim()),i=o.filter((a,l)=>o.indexOf(a)!==l);if(i.length===0)return;let s=lo[n];throw new Error(`${t} received duplicate ${s.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(uo,"rejectRepeatedKeys");var dn={user:"STOPPED BY THE USER before completion \u2014 output is partial; the task was NOT finished",agent:"STOPPED BY YOU before completion \u2014 output is partial; the task was NOT finished"},po={user:"STOPPED BY THE USER before the agent started \u2014 the task was NOT attempted",agent:"STOPPED BY YOU before the agent started \u2014 the task was NOT attempted"};function go(e){if(!_(e)||e.status!=="stopped")return dn.agent;let{stop:t}=e;return e.phase==="never-started"?po[t.initiator]:dn[t.initiator]}r(go,"stopNote");function cn(e){return!_(e)||e.status!=="stopped"?"":` (${go(e)})`}r(cn,"getStatusNote");var mo=`Success! You delegated to an agent. A notification will arrive when done - USER: do not poll, don't check status and don't duplicate the delegated work!{{#has_worktree}}
8
- (Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
9
-
10
- Agent ID: {{agent_id}}`,ho=`Agent QUEUED \u2014 the concurrency limit is reached ({{queue_running}} {{queue_running_label}} already spawned), so this task is waiting for a slot. It is NOT spawned yet: the process has not started. It will start automatically when another agent settles; you'll get a message when it starts and when it settles. Do NOT re-delegate \u2014 this task IS in flight.{{#has_worktree}}
11
- (Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
12
-
13
- Agent ID: {{agent_id}}`,fo=`{{result}}{{#error}}
14
-
15
- Error: {{error}}{{/error}}{{#has_worktree}}
16
- (Worktree: {{worktree_path}} (branch {{worktree_branch}}){{#retention}} \u2014 KEPT: {{retention}}{{/retention}}.{{#process_alive}} The agent process and its {{multiplexer_id}} pane stay until you call cleanup_cowboy_agent \u2014 its pane is closed, which ends that process.{{/process_alive}} {{#retention}}Clean the worktree up, then call cleanup_cowboy_agent to remove it.{{/retention}}{{^retention}}The worktree stays until you call cleanup_cowboy_agent to remove it \u2014 call it once the branch is merged or rejected.{{/retention}}){{/has_worktree}}{{status_note}}`,R={default:{name:"default",displayName:"Default",guidance:"Update your report file each time you make a commit",cues:{spawned:mo,queued:ho,settled:fo}}};import{z as I}from"zod";import hn from"mustache";function un(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}r(un,"worktreeVariables");function yo(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}r(yo,"outcomeVariables");function wo(e){return e?{...un(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}r(wo,"settledWorktreeVariables");function ze(e){return e.worktree?{agent_id:e.agentId,...un(e.worktree)}:{agent_id:e.agentId}}r(ze,"spawnCueContext");function pn(e){return{...ze(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}r(pn,"queuedCueContext");function gn(e){let{outcome:t,statusNote:n,worktree:o,multiplexerId:i}=e;return{...yo(t),...n?{status_note:n}:{},...wo(o),...i!=null?{multiplexer_id:i}:{}}}r(gn,"settledCueContext");var ko={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},bo={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},vo={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},To=Object.keys(ko),Ao=Object.keys(bo),xo=Object.keys(vo);function mn(e){switch(e){case"spawned":return To;case"queued":return Ao;case"settled":return xo;default:return}}r(mn,"cueVariables");var Co={ok:!0},_o="&",So=new Set(["name",_o,"#","^"]);function we(e,t,n){return hn.render(e[t],n,void 0,{escape:r(o=>o==null?"":String(o),"escape")})}r(we,"renderCue");function Eo(e){let t=e[4];return Array.isArray(t)?t:void 0}r(Eo,"spanChildren");function fn(e,t,n){for(let o of e){let[i,s]=o;if(i===">")return`partials are not supported: "{{>${s}}}"`;if(i==="=")return`delimiter changes are not supported: "{{=${s}=}}"`;if(So.has(i)&&!t.includes(s))return`unknown variable "{{${s}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let a=Eo(o);if(a){let l=fn(a,t,n);if(l)return l}}}r(fn,"findTemplateProblem");function yn(e,t){let n=mn(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let o;try{o=hn.parse(t)}catch(s){return{ok:!1,reason:`unparsable template: ${(s instanceof Error?s.message:String(s)).replace(/\s+/g," ").trim()}`}}let i=fn(o,n,e);return i?{ok:!1,reason:i}:Co}r(yn,"validateCueTemplate");var Oo=["spawned","queued","settled"],Ro=I.strictObject({spawned:I.string().optional(),queued:I.string().optional(),settled:I.string().optional()}).superRefine((e,t)=>{for(let n of Oo){let o=e[n];if(o===void 0)continue;let i=yn(n,o);i.ok||t.addIssue({code:"custom",message:i.reason,path:[n]})}}),wn=I.strictObject({name:I.string().optional(),display_name:I.string().optional(),guidance:I.string().optional(),cues:Ro.optional()});var Io={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function Po(e){return wn.parse(pe(e))}r(Po,"parseOrchestratorFile");async function X(e,t){return ge(e,Po,n=>n.name,t,Io)}r(X,"scanOrchestratorFilesInDir");function Ye(e,t,n,o){let i=new Map(e instanceof Map?e:Object.entries(e)),s=i.get("default")??R.default;for(let a of[t,n,o])for(let l of a)l.name&&i.set(l.name,No(i.get(l.name)??Mo(l.name,s),l));return i}r(Ye,"mergeOrchestrators");function Mo(e,t){return{...t,name:e,displayName:e}}r(Mo,"namedBase");function No(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}}r(No,"applyOverride");function Z(){return ie().orchestrators}r(Z,"registry");function qs(e,t){let n=new Map;if(!t?.disableDefaultOrchestrators)for(let[o,i]of Object.entries(R))n.set(o,i);for(let[o,i]of e)n.set(o,i);Z().orchestrators=n}r(qs,"registerOrchestrators");function Ks(e,t,n){Z().scanDirs={user:e,project:t,shared:n??""}}r(Ks,"setOrchestratorScanDirs");async function Gs(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,o=Z().scanDirs,[i,s,a,l]=await Promise.all([t?Promise.resolve([]):X(st,n),X(o.user,n),X(o.shared,n),X(o.project,n)]),d=Ye(t?new Map:R,i,[],[]);return Ye(d,s,a,l)}r(Gs,"scanAndMergeOrchestrators");function Qe(e){let{orchestrators:t}=Z();if(!e)return;let n=t.get(e);if(n)return n;let o=e.toLowerCase(),i=[];for(let[s,a]of t)s.toLowerCase()===o&&i.push(a);return i.length===1?i[0]:void 0}r(Qe,"resolveOrchestrator");function Vs(){return[...Z().orchestrators.values()].map(e=>e.name)}r(Vs,"getAvailableOrchestrators");function kn(e){return typeof e=="string"&&e!==""?e:void 0}r(kn,"configuredString");function $o(){let e=kn(f().agent.defaultAgentType);if(e===void 0)return _e;let t=z(e);return t.kind==="resolved"?t.key:_e}r($o,"resolveDefaultAgentType");function Bo(){let e=kn(f().agent.defaultOrchestrator);return e===void 0?P:e===P||Qe(e)?e:P}r(Bo,"resolveDefaultOrchestratorName");function ke(e){return typeof e=="string"&&e!==""?e:$o()}r(ke,"resolveAgentTypeParam");function bn(){let e=Bo();return Qe(e)??(e===P?R[P]:void 0)??R[P]}r(bn,"resolveDefaultOrchestrator");function na(e){return E(e)?.worktreeCheckoutType??f().agent.worktreeCheckoutType}r(na,"resolveWorktreeCheckoutType");function vn(e){return typeof e=="string"&&e.trim()!==""?e:void 0}r(vn,"harnessParam");function Tn(e){let t=vn(e);if(t!==void 0&&x().get(t)!==void 0)return Ae(t,j())?t:void 0}r(Tn,"requestedHarnessId");function An(e){let t=vn(e);if(t===void 0)return;let n=x();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 o=j();if(!Ae(t,o))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${lt(n.ids(),o).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}r(An,"resolveRequestedHarness");function be(e,t){if(t!==void 0)return t;let n=E(e)?.harnessType??f().agent.harnessType;return x().resolve(n,j())}r(be,"resolveHarnessType");function B(e=b()){let t=e.listAgents(Se).filter(n=>te(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(B,"formatActiveAgents");function Xe(e,t){let n={type:e.display.type,description:e.display.description};e.display.taskSlug&&(n.taskSlug=e.display.taskSlug),e.display.worktree&&(n.worktreePath=e.display.worktree.path,n.worktreeBranch=e.display.worktree.branch),e.display.worktree?.kind==="owned"&&(n.worktreeManaged=!0);let o=e.execution.host;if(o&&(n.herdrAgent=o.name,n.herdrPane=o.paneId,n.herdrTab=o.tabId),t?.includeStatus&&(n.status=M(e.lifecycle)),t?.includeRunInfo){let i=_(e.lifecycle)?e.lifecycle.completedAt-Et(e.lifecycle):0;n.durationMs=i,n.modelName=e.display.invocation?.modelName,n.modelId=e.display.invocation?.modelName,n.thinkingLevel=e.display.invocation?.thinkingLevel}return n}r(Xe,"buildAgentDetails");function Do(e){if(!_(e))return{kind:"stopped"};switch(e.status){case"completed":return{kind:"completed",result:e.result};case"error":return{kind:"failed",error:e.error};case"stopped":return{kind:"stopped"};default:return ft(e)}}r(Do,"settledOutcome");function Fo(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${M(e.lifecycle)}]`}r(Fo,"settledHeadline");function jo(e){let t=e.lifecycle,n=_(t)?t.worktreeRetentionReason:void 0,o=e.display.orchestration,i=e.display.worktree?.kind==="owned"?e.display.worktree:void 0;return we(o.cues,"settled",gn({outcome:Do(t),statusNote:cn(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?Bt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:f().multiplexer||_t}))}r(jo,"formatResultContent");var Ze=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=ke(t.agent_type),s=t.prompt,a=typeof t.task_name=="string"?t.task_name.trim():"";if(!a)throw new Error('cowboy_agent requires a short 2-3 word task name (e.g. "fix login flow") via the `task_name` parameter \u2014 it names the agent\'s branch/tab/worktree/agent so you can recognize it at a glance.');let l=ut(a),c=bn(),d=await Jt(i,void 0,(k,v)=>{n.ui.notify(k,v)});if(d.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${i}. Candidates: ${d.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(d.kind==="not-found")throw new Error(`Unknown agent type: ${i} \u2014 nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);let h=An(t.harness_type),g=be(d.key,h),p=tn(t),m=await ln(nn(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:p,listModels:r(async k=>{let v=await x().require(k).listModels({pi:C(),modelCatalog:oe(n.modelRegistry)}),F=xt(v);return F!==void 0&&n.hasUI&&n.ui.notify(F,"warning"),At(v)},"listModels")});for(let k of m.notices)n.ui.notify(k,"warning");let w=t.run_in_background!==!1;return new e({ctx:n,toolCallId:o,taskSlug:l,prompt:s,description:s.split(`
17
- `)[0].slice(0,80)||s.slice(0,80),agentType:i,resolvedType:d.key,orchestrator:c,fork:E(i)?.fork??!1,modelChoice:rn(m.resolved),requestedHarness:h,isBackground:w})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:s}=this.intent,a=C(),l=b().mintSpawnId(),c=await this.expectedWorktree(a,l),d=this.intent.modelChoice?.thinking??void 0,h=ht(this.intent.modelChoice),{agentId:g,spawn:p}=await Ot().spawn(n,{spawnId:l,type:s,prompt:this.intent.prompt,description:this.intent.description,taskSlug:i,orchestration:this.intent.orchestrator,modelChoice:this.intent.modelChoice,requestedHarness:this.intent.requestedHarness,fork:this.intent.fork,worktree:c,invocation:{modelName:h,thinkingLevel:d,fork:this.intent.fork},runInBackground:o,signal:o?void 0:t});if(this.intent.toolCallId&&(p.display.toolCallId=this.intent.toolCallId),!o){let v=Xe(p,{includeRunInfo:!0});if(v.agentId=g,_(p.lifecycle)&&p.lifecycle.status==="error")throw new Error(`agent ${g} stopped with an error: ${p.lifecycle.error||"no error message was recorded"}`);return{message:`${Fo(p)}
18
-
19
- ${jo(p)}`,details:v}}let m=c;if(p.lifecycle.phase==="queued"){let v=b().listAgents(Se).filter(Te=>Te.lifecycle.phase==="spawned").length,F=we(this.intent.orchestrator.cues,"queued",pn({agentId:g,worktree:m,queueRunning:v})),q=Xe(p);return q.agentId=g,q.status="queued",{message:`[Agent queued] ${F}`,details:q}}let w=we(this.intent.orchestrator.cues,"spawned",ze({agentId:g,worktree:m})),k=Xe(p);return k.agentId=g,k.status="spawned",{message:`[Agent spawned] ${w}`,details:k}}async expectedWorktree(t,n){let o=await Nt(t,ne().cwd).catch(()=>{});if(o===void 0)return;let i=mt(f().agent.worktreeRoot,o);return{kind:"owned",path:gt(i,this.intent.taskSlug,n),branch:pt(this.intent.taskSlug,n)}}};async function xn(e,t,n,o){if(e.agents.length>1&&e.run_in_background===!1)throw new Error("run_in_background: false requires exactly one agent");let i=e.agents.map(d=>({...d,run_in_background:e.run_in_background})),s=await Promise.all(i.map(d=>Ze.parse(d,t,n)));Ho(s);let a=await Promise.all(s.map(d=>d.run(o))),l=a.map(d=>d.message).join(Ve),c={agents:a.map(d=>d.details)};return{message:l,details:c}}r(xn,"runDelegationBatch");function Ho(e){let t=e.map(o=>o.intent.taskSlug),n=t.filter((o,i)=>t.indexOf(o)!==i);if(n.length!==0)throw new Error(`cowboy_agent received the same task_name more than once: ${[...new Set(n)].join(", ")} \u2014 nothing was spawned. Give every item in \`agents\` its own task_name.`)}r(Ho,"rejectRepeatedTaskSlugs");async function Cn(e,t,n,o,i){let{message:s,details:a}=await xn(t,i,e,n);return ye(s,a)}r(Cn,"executeAgentTool");function Lo(e){switch(e.kind){case"stopped":return`Stopped agent ${e.agentId}`;case"already-settled":return`Agent ${e.agentId} is already ${e.status}. Active agents: ${e.activeAgents}`;case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`;case"failed":return`Failed to stop agent ${e.agentId}: ${e.error}`}}r(Lo,"renderStopOutcome");async function _n(e,t,n,o,i){let s=t.agent_ids;return O({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:s,render:Lo,handleItem:r(async a=>{let l=b().getSpawn(a);if(!l)return{kind:"unknown",agentId:a,activeAgents:B()};if(!te(l.lifecycle.phase))return{kind:"already-settled",agentId:a,status:M(l.lifecycle),activeAgents:B()};try{return await b().abort(a,"agent")?{kind:"stopped",agentId:a}:{kind:"failed",agentId:a,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:a,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}r(_n,"executeStopAgentTool");async function Oa(e,t){if(e.toolName!=="cowboy_agent")return;let o=e.input.agents??[],i=t.model?`${t.model.provider}/${t.model.id}`:null;for(let s of o){let a=s.agent_type,l=ke(a),c=E(l),d=Tn(s.harness_type),h=be(l,d),g=U(s.model),p=g??f().modelFor(l,i,c,h);if(p&&!g&&(s[We]=p),s.thinking===void 0){let m=f().thinkingFor(l,c,h,t.thinkingLevel);m!==void 0&&(s[qe]=m)}}}r(Oa,"toolCallListener");function Sn(e){switch(e.kind){case"pane-absent":return"pane-absent";case"pane-not-working":return`pane-not-working: ${e.state}`;case"forced":return"forced";case"pane-working":return"pane-working";case"pane-unreadable":return`pane-unreadable: ${e.detail}`;case"artifacts-ambiguous":return"artifacts-ambiguous"}}r(Sn,"formatBasis");function Uo(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${Sn(e.basis)})`}r(Uo,"formatSettlement");function En(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`;case"agent-active":return`the agent is still ${e.phase} and has not reported a result \u2014 stop it with stop_cowboy_agent, then clean up`;case"recovered-refusal":return`no settlement was recorded and herdr still reports the agent at work (${Sn(e.basis)}) \u2014 stop it before retrying`;case"ambiguous-artifacts":return`two artifacts answer to this id (${e.candidates.join(", ")}) \u2014 nothing was removed; work out which run owns the id before removing either by hand`}}r(En,"formatKeptReason");function Wo(e){switch(e.kind){case"closed":return"closed";case"open":return"open";case"gone":return"gone (herdr has no such pane)";case"unknown":return"unknown (the pane was not read)";case"none":return"none"}}r(Wo,"paneText");function On(e){switch(e.kind){case"removed":return`removed (${e.path})`;case"removal-failed":return`NOT removed \u2014 ${e.detail} (${e.path})`;case"kept":return`kept${e.path?` (${e.path})`:" (worktree path not recorded)"}`;case"absent":return`already gone (${e.path})`;case"none":return"none (agent ran without a worktree)"}}r(On,"worktreeText");function Rn(e){let t=e.branch;return`${t.kind==="deleted"?"deleted":t.kind==="kept"?`kept (${t.reason})`:t.kind==="delete-failed"?`NOT deleted \u2014 ${t.detail}`:"not applicable"}${e.branchName?` (${e.branchName})`:""}`}r(Rn,"branchText");function qo(e){return e?` forced${e.reason?` \u2014 ${En(e.reason)}`:""}`:""}r(qo,"forcedClause");function Je(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${En(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${qo(e.outcome.forced)}:`}r(Je,"headline");function In(e){let t=[Je(e),` agent status: ${Uo(e.settlement)}`,` pane: ${Wo(e.pane)}`,` worktree: ${On(e.worktree)}`,` branch: ${Rn(e)}`];if(e.source==="recovered"&&t.push(" recovered: no spawn record survived \u2014 this verdict rests on discovery (herdr's live read plus the worktree on disk)"),e.settlement.kind==="discovered"){let{path:n,present:o}=e.settlement.deliverable;t.push(o?` deliverable: UNREAD at ${n} \u2014 read it before deleting the directory`:` deliverable: none written (${n} does not exist)`)}return t.join(`
20
- `)}r(In,"renderCleanupReport");function Pa(e){let t=e.pane.kind==="closed"?"pane closed":e.pane.kind==="open"?"pane left open":e.pane.kind==="gone"?"pane already gone":e.pane.kind==="unknown"?"pane state unknown":"no pane";return e.outcome.kind==="refused"?`${Je(e)} ${t}`:`${Je(e)} ${t}, worktree ${On(e.worktree)}, branch ${Rn(e)}`}r(Pa,"summarizeCleanupReport");function Ma(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Ma,"cleanupNeedsAttention");function Ko(e){switch(e.kind){case"cleaned":return In(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(Ko,"renderCleanupOutcome");async function Pn(e,t,n,o,i){let s=t.agent_ids;return O({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:s,render:Ko,handleItem:r(async a=>{let l=b();if(!l.getSpawn(a)&&(await l.locate(a)).kind==="not-found")return{kind:"unknown",agentId:a,activeAgents:B(l)};let c=await l.cleanup(a);return{kind:"cleaned",agentId:a,report:c}},"handleItem")})}r(Pn,"executeCleanupAgentTool");import*as Nn from"node:fs";import*as W from"node:path";function Mn(e){let t=W.normalize(e),{root:n}=W.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Mn,"normalizeRepoRoot");function Go(e,t){return Mn(e)===Mn(t)}r(Go,"isSameRepoRoot");function Vo(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(Vo,"formatOutsideRepoWarning");async function zo(e,t){let n=new Pt(e),o=await n.probe(["rev-parse","--show-toplevel"],t);if(o===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: ${t} is not inside a git repository (git rev-parse --show-toplevel failed). Refusing to merge without a repo-scope check \u2014 run the session from inside a git checkout or pass an explicit \`repo\` inside one.`);let i=await n.probe(["rev-parse","--git-common-dir"],o);if(i===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: could not resolve the git directory for ${t}. Refusing to merge without a repo-scope check.`);let{mainRoot:s}=Mt(i,o);if(!Nn.existsSync(W.join(s,".git")))throw new Error(`merge_cowboy_branch cannot verify the session repo: no main checkout found for ${t} (unsupported repo layout). Refusing to merge without a repo-scope check.`);return s}r(zo,"resolveSessionMainRoot");var Yo="has conflicts in:";function Qo(e){return e.includes(Yo)}r(Qo,"isConflictError");function Xo(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
21
- `).map(n=>n.trim()).filter(n=>n!==""):[]}r(Xo,"parseConflictFiles");function Zo(e,t){return e.includes(`branch "${t}" does not exist`)}r(Zo,"isUnknownBranchError");async function $n(e,t,n,o,i){let s=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",a=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,l,c=r(()=>(l??=(async()=>{let d=ne().cwd;if(typeof d!="string"||d.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 zo(C(),d),cwd:a??d}})(),l),"mergeScope");return O({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,prepare:r(async()=>{Pe(s,"target");for(let d of t.branches)Pe(d.trim(),"branch");await c()},"prepare"),halt:{on:r(d=>d.kind==="conflict","on"),skip:r((d,h)=>{let g=d.trim(),p=`not attempted \u2014 the merge of "${h.trim()}" conflicted and is still in progress`;return{outcome:{kind:"not-attempted",branch:g,reason:p},text:`"${g}" ${p}.`}},"skip")},handleItem:r(async d=>{let{sessionRoot:h,cwd:g}=await c(),p=d.trim();try{let m=await $t(C(),{cwd:g,branch:p,target:s}),w=Go(m.mainRoot,h)?void 0:Vo(m.mainRoot,h);if(w!==void 0)try{i.ui.notify(w,"warning")}catch{}let k=w!==void 0?`${w}
22
- `:"";return m.alreadyMerged?{outcome:{kind:"already-merged",branch:p,target:s},text:`${k}"${p}" is already merged into "${m.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:p,target:m.target,output:m.output},text:`${k}Merged "${p}" into "${m.target}" in ${m.mainRoot}.`+(m.output?`
23
- ${m.output}`:"")}}catch(m){let w=m instanceof Error?m.message:String(m);return Qo(w)?{outcome:{kind:"conflict",branch:p,target:s,files:Xo(w)},text:`"${p}": ${w}`}:Zo(w,p)?{outcome:{kind:"unknown",branch:p},text:`"${p}": ${w}`}:{outcome:{kind:"failed",branch:p,error:w},text:`"${p}": ${w}`}}},"handleItem")})}r($n,"executeMergeBranchTool");async function Bn(e,t,n,o,i){let s=t.message.trim();return O({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,prepare:r(()=>{if(s==="")throw new Error("message is required")},"prepare"),handleItem:r(async a=>{let l=b().getSpawn(a);if(!l){let g=`not found. Active agents: ${B()}`;return{outcome:{kind:"refused",agentId:a,reason:g},text:`Agent ${a} was not steered: ${g}`}}let c=M(l.lifecycle),d;try{d=await b().steer(a,s)}catch(g){d={kind:"refused",reason:`steering failed: ${ee(g)}`}}if(d.kind==="refused")return{outcome:{kind:"refused",agentId:a,reason:d.reason},text:`Agent ${a} was not steered (${c}): ${d.reason}`};if(d.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:a,reason:d.reason},text:`Agent ${a} had settled (${c}) and the message reached its pane, but it was not revived: ${d.reason}`};let h=c!=="spawned"&&l.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:a},text:h?`Agent ${a} 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 ${a}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${a} was delivered to (${c}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r(Bn,"executeSteerAgentTool");var A={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},jn=Object.values(A),J={type:"json_schema",strict:"prefer"};function Jo(e){let t=D.Object({prompt:H.properties.agents.items.properties.prompt,task_name:H.properties.agents.items.properties.task_name,agent_type:D.Optional(D.Union([D.String(),D.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 D.Object({agents:D.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Jo,"cowboyAgentsSchemaWithTypes");function Hn(e){let t=Jo(en()),n={name:A.agent,label:A.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:Cn,constrainedSampling:J};e.registerTool(n)}r(Hn,"registerAgentTool");function ei(e,t){f().mutate.agent.setExtensionEnabled(t),t?ti(e):ni(e)}r(ei,"setExtensionEnabled");function ti(e){let t=C();Hn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...jn])]),de(e)}r(ti,"activateExtension");function ni(e){let t=C();t.setActiveTools(t.getActiveTools().filter(n=>!jn.includes(n))),de(e)}r(ni,"deactivateExtension");function fl(e){Hn(e);let t={name:A.stopAgent,label:A.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping interrupts the pi process (its pane is left in place) and settles the agent as stopped. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Wt,execute:_n,constrainedSampling:J,renderResult:r((s,a,l,c)=>{let d=c.isError??!1,h=s.content.at(0),g=h?.type==="text"?h.text:"",p=d?l.fg("error","\u2717"):l.fg("success","\u2713");return new Dn(`${p} ${g}`,0,0)},"renderResult")};e.registerTool(t);let n={name:A.mergeBranch,label:A.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:Kt,execute:$n,constrainedSampling:J};e.registerTool(n);let o={name:A.steerAgent,label:A.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 \u2014 wait for its report. Every refusal states its reason and what to do about it.",parameters:Gt,execute:Bn,constrainedSampling:J};e.registerTool(o);let i={name:A.cleanupAgent,label:A.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:qt,execute:Pn,constrainedSampling:J};e.registerTool(i),e.registerMessageRenderer("subagent-result",(s,a,l)=>{let c=typeof s=="object"&&typeof s.content=="string"?s.content:"",d=/\b(error|stopped)\b/.test(c.slice(0,200)),h=l.fg(d?"error":"success",d?"\u2717":"\u2713");return new Dn(`${h} ${c}`,0,0)})}r(fl,"registerTools");async function Fn(e,t){let n=await x().listModelOptions({pi:e,modelCatalog:oe(t.modelRegistry)},j());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Fn,"harnessModelOptions");var Ln="cowboy",ri={wt:"worktree",sp:"spawn",st:"status"};function yl(e,t){e.registerCommand(Ln,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(yl,"registerUnavailableCowboyCommand");function wl(e){e.registerCommand(Ln,{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-74J7Z4WJ.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{Rt(n);let[o,...i]=t.trim().split(/\s+/),s=ri[o]??o,a=[s,...i].join(" ");if(a==="enable"||a==="disable"){let d=a==="enable";if(d&&Ie()===null){n.ui.notify(Ce,"warning");return}if(le()===d){n.ui.notify(`pi-cowboy is already ${d?"enabled":"disabled"}`,"info");return}ei(n.ui,d),n.ui.notify(d?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(Ie()===null){n.ui.notify(Ce,"warning");return}if(s==="worktree"){let{showWorktreeCommandMenu:d}=await import("./menu-worktree-command-DYLJ34X3.js");await d(n,i.join(" "));return}if((s==="model"||a==="spawn"||a==="status")&&!le()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(s==="model"){let{handleModelArg:d}=await import("./model-picker-74J7Z4WJ.js");await d(i.join(" "),n);return}if(a==="spawn"||a==="status"){let{showAgentsActionMenu:d}=await import("./menus-RQLX4WC2.js");await d(n,a,await Fn(e,n));return}if(a!==""){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-RQLX4WC2.js");await c(n,await Fn(e,n))},"handler")})}r(wl,"registerCowboyCommand");import*as Un from"node:fs";import{tmpdir as oi}from"node:os";import*as ve from"node:path";async function Wn(e,t){try{return await It(e).probe(t),K(dt)}catch{return K(["checkout"])}}r(Wn,"detectCowAvailability");function qn(e){let t=ve.resolve(e??ot());for(;;){try{if(Un.statSync(t).isDirectory())return t}catch{}let n=ve.dirname(t);if(n===t)return oi();t=n}}r(qn,"probeTargetFor");function ii(e){return(t,n,o)=>e.exec(t,n,o)}r(ii,"execOf");function Il(e){return Kn(e,Re())}r(Il,"startCowSupportProbe");function Pl(e){let t=Re();return re(t,at()),Kn(e,t)}r(Pl,"refreshCowSupportProbe");function Kn(e,t){let n=qn(f().agent.worktreeRoot);return Wn(ii(e),n).then(o=>{re(t,o)},()=>{re(t,K(["checkout"]))})}r(Kn,"probe");export{Ue as a,Vi as b,zi as c,no as d,E as e,en as f,Yi as g,Qi as h,R as i,qs as j,Ks as k,Gs as l,Vs as m,$o as n,bn as o,na as p,be as q,Xe as r,Fo as s,jo as t,Oa as u,En as v,Pa as w,Ma as x,De as y,le as z,gi as A,Il as B,Pl as C,ei as D,ti as E,ni as F,fl as G,yl as H,wl as I};
24
- //# sourceMappingURL=chunk-PYOLHDZJ.js.map