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.
- package/README.md +14 -14
- package/agents/explore.toml +9 -11
- package/dist/agents/agent-template.d.ts +12 -11
- package/dist/agents/harness/env-overrides.d.ts +12 -0
- package/dist/agents/harness/launch-env.d.ts +2 -1
- package/dist/agents/types.d.ts +2 -1
- package/dist/chunk-CTBFJWEE.js +10 -0
- package/dist/{chunk-XKS73JKY.js → chunk-F526OOT6.js} +2 -2
- package/dist/{chunk-ZLKJYRKY.js → chunk-KMXT7XW7.js} +2 -2
- package/dist/chunk-PDV4AFO7.js +24 -0
- package/dist/{chunk-J525HRTW.js → chunk-WL3QYM2F.js} +2 -2
- package/dist/config/config-store.d.ts +2 -1
- package/dist/index.js +14 -14
- package/dist/{menu-worktree-command-DYLJ34X3.js → menu-worktree-command-SXLBWK4D.js} +2 -2
- package/dist/{menus-RQLX4WC2.js → menus-Q3TEDIPV.js} +2 -2
- package/dist/{model-picker-74J7Z4WJ.js → model-picker-IIXU4GJP.js} +2 -2
- package/package.json +3 -2
- package/dist/chunk-JIAP5YBM.js +0 -10
- package/dist/chunk-PYOLHDZJ.js +0 -24
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{b as Rt,c as It,e as Pt,g as Mt,k as Me,l as Nt,p as $t}from"./chunk-KMXT7XW7.js";import{$ as St,Ba as Pe,Ca as se,F as At,I as _e,K as xt,L as G,M as Se,N as P,O as Ee,P as Ct,R as te,S as _,T as M,V as _t,aa as ne,b as it,ea as C,fa as re,ga as b,h as st,i as at,ia as f,j as K,ja as N,k as lt,ka as Oe,l as xe,la as Re,m as ct,na as Et,o as dt,qa as Ie,r as ut,ra as oe,sa as x,ta as ie,v as pt,va as j,w as gt,x as mt,y as ht,ya as Ot}from"./chunk-CTBFJWEE.js";import{a as r,d as ee,f as Ce,g as ft,j as yt,k as wt,l as kt,s as bt,t as vt,u as Tt}from"./chunk-254PTGN5.js";import{visibleWidth as De}from"@earendil-works/pi-tui";var Ne="\u{1F920}",Ft="\u{1F404}",rr="\u{1F4A9}",or=2,ir=1e3,ae=De(Ft),sr="76;175;80";function ar(e){return`\x1B[48;2;${sr}m${e}\x1B[49m`}r(ar,"greenBackground");function jt(e){return e===0?0:Math.max(or,Math.ceil(Math.sqrt(2*e)))}r(jt,"pastureEdge");function Ht(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Ht,"emptyPasture");function lr(e,t){let n=jt(e.cows+e.droppings),o=Ht(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)),d=i[l];i[l]=i[a],i[a]=d,o[Math.floor(d/n)][d%n]=s[a]}return o}r(lr,"grazedPasture");function le(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(le,"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 Bt(e,t){return cr(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Bt,"openNeighboursOf");function dr(e,t){let n=le(e,"cow").filter(l=>Bt(l,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Bt(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(dr,"moveHerd");function Dt(e,t,n,o){for(let i=0;i<n;i+=1){let s=le(e,"empty"),a=s[Math.floor(o()*s.length)];e[a.row][a.col]=t}}r(Dt,"placeAtRandom");function ur(e,t,n,o){let i=le(e,"cow"),s=le(e,"dropping"),a=i.length-t,l=s.length-n;for(;a>0&&l<0;){let d=i.pop();e[d.row][d.col]="dropping",a-=1,l+=1}for(;a>0;){let d=i.pop();e[d.row][d.col]="empty",a-=1}for(;l>0;){let d=s.pop();e[d.row][d.col]="empty",l-=1}Dt(e,"cow",-a,o),Dt(e,"dropping",-l,o)}r(ur,"reconcileCounts");function pr(e,t,n){if(e===null)return lr(t,n);let o=jt(t.cows+t.droppings),i=Ht(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 ur(i,t.cows,t.droppings,n),i}r(pr,"reconcilePasture");var gr={anchor:"top-right",width:De(Ne),get offsetX(){return N()?.cowboyOffsetX??0},nonCapturing:!0},mr={anchor:"top-right",offsetY:1,get width(){return N()?.pastureWidth??0},nonCapturing:!0};function hr(e){return e==="cow"?Ft:e==="dropping"?rr:" ".repeat(ae)}r(hr,"cellText");function fr(e,t){return e.map(n=>t(n.map(hr).join("")))}r(fr,"drawnRows");function yr(){return Re().list(["spawned"]).length}r(yr,"liveAgentCount");function wr(){return Re().list(Ct).length}r(wr,"endedAgentCount");function kr(){return{live:yr(),ended:wr()}}r(kr,"agentCounts");function br(){return f().agent.grazingEnabled}r(br,"grazingEnabled");var $e=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 De(Ne)}get pastureWidth(){return this.drawnPasture().length*ae}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*ae-(t*ae-this.cowboyWidth)}render(){return this.frame(),[Ne]}pastureRows(){return this.frame(),fr(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(),ir))}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:dr(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:pr(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Be=class{static{r(this,"PastureView")}render(){return N()?.pastureRows()??[]}invalidate(){}};function Lt(e){Fe(),e.custom(t=>{let n=new $e(t,kr,br,ar,Math.random);return Oe(n),n},{overlay:!0,overlayOptions:gr,onHandle:r(t=>N()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Be,{overlay:!0,overlayOptions:mr,onHandle:r(t=>N()?.attachPasture(t),"onHandle")})}r(Lt,"showExtensionIndicator");function Fe(){let e=N();Oe(null),e?.dispose()}r(Fe,"hideExtensionIndicator");function ce(){return f().agent.extensionEnabled}r(ce,"isExtensionEnabled");function vr(){return ce()&&f().agent.showActiveIndicator}r(vr,"isActiveIndicatorShown");function de(e){vr()?Lt(e):Fe()}r(de,"syncExtensionIndicator");function ui(e,t){f().mutate.agent.setShowActiveIndicator(t),de(e)}r(ui,"setShowActiveIndicator");import{Type as D}from"typebox";import{Text as Bn}from"@earendil-works/pi-tui";import{Type as y}from"typebox";var Tr="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.",Ar=`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.`,xr=`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.`,Cr=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${wt.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.`,_r=y.Object({prompt:y.String({description:Tr}),task_name:y.String({description:Ar}),agent_type:y.Optional(y.Union([y.String(),y.Null()])),model:y.Optional(y.Union([y.String(),y.Null()],{description:xr})),harness_type:y.Optional(y.Union([y.String(),y.Null()],{description:Cr}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=y.Object({agents:y.Array(_r,{minItems:1}),run_in_background:y.Optional(y.Boolean())},{additionalProperties:!1,required:["agents"]});import{Type as je}from"typebox";var Sr="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).",Ut=je.Object({agent_ids:je.Array(je.String({minLength:1}),{minItems:1,description:Sr})},{additionalProperties:!1,required:["agent_ids"]});import{Type as He}from"typebox";var Er="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).",Wt=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:Er})},{additionalProperties:!1,required:["agent_ids"]});import{Type as $}from"typebox";var Or="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.",Rr="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",Ir="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.",qt=$.Object({branches:$.Array($.String({minLength:1}),{minItems:1,description:Or}),target:$.Optional($.String({description:Rr})),repo:$.Optional($.String({description:Ir}))},{additionalProperties:!1,required:["branches"]});import{Type as ue}from"typebox";var Pr="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.",Mr="REQUIRED. The single message delivered verbatim to every id in `agent_ids`. Plain instructions work best (e.g. \"stop refactoring; just fix the failing test and report\"). Delivery is fire-and-forget: nothing here waits for an agent to act on it. Because the text is entered into the agent's pi session, a command prefixed with `!` runs and adds its output to that agent's context, while `!!` runs it without adding the output to its context.",Kt=ue.Object({agent_ids:ue.Array(ue.String({minLength:1}),{minItems:1,description:Pr}),message:ue.String({description:Mr})},{additionalProperties:!1,required:["agent_ids","message"]});import*as pe from"node:fs";import*as Gt from"node:path";import{parse as Nr,TomlError as $r}from"smol-toml";import{z as Br}from"zod";var Dr=".toml";function ge(e){return Nr(e.replace(/^\uFEFF/,""))}r(ge,"parseTemplateToml");function T(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0))}r(T,"compactDefined");function Fr(e){let t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}r(Fr,"describeZodIssue");function jr(e){if(e instanceof Br.ZodError)return e.issues.map(Fr).join("; ").replace(/\s+/g," ").trim();if(e instanceof $r){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(jr,"describeParseError");var Hr={label:"File",problem:"was skipped"};async function me(e,t,n,o,i=Hr,s){try{await pe.promises.access(e)}catch{return[]}let l=(await pe.promises.readdir(e,{withFileTypes:!0})).filter(c=>c.isFile()&&c.name.endsWith(Dr)),d=[];for(let c of l){let h=Gt.join(e,c.name),g;try{g=await pe.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)&&d.push(p)}catch(p){o?.(`[cowboy] ${i.label} file ${h} ${i.problem}: ${jr(p)}`,"warning")}}return d}r(me,"scanTemplateFilesInDir");import{z as u}from"zod";var Vt=u.union([u.boolean(),u.array(u.string())]),Lr={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 fe(e){return u.record(u.string(),u.unknown()).transform((t,n)=>St(t,{reserved:bt[e],report:r((o,i)=>n.addIssue({code:"custom",path:[o],message:Lr[i]}),"report")}))}r(fe,"envTable");var zt={model:u.string().optional(),thinking:G.optional(),extensions:Vt.optional(),skills:Vt.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:fe("pi").optional()},Ur=u.strictObject(zt),Wr=u.strictObject({model:u.string().optional(),variant:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:fe("opencode").optional()}),qr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),env:fe("codex").optional()}),Kr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:fe("claude").optional()});function Le(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}r(Le,"toToolFilter");function he(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}r(he,"nonEmptyEnv");var Gr=u.strictObject({include_context_files:u.boolean().optional(),pi:Ur.optional(),opencode:Wr.optional(),codex:qr.optional(),claude:Kr.optional(),...zt}).transform(({pi:e,opencode:t,codex:n,claude:o,...i})=>{let{model:s,thinking:a,tools:l,exclude_tools:d,env:c,...h}=i,{model:g,thinking:p,tools:m,exclude_tools:w,env:k,...v}=T(e??{}),{model:F,variant:q,tools:Ae,exclude_tools:Kn,env:Gn,...Vn}=T(t??{}),{model:zn,thinking:Yn,env:Qn,...Xn}=T(n??{}),{model:Zn,thinking:Jn,tools:er,exclude_tools:tr,env:nr}=T(o??{}),tt=T({pi:g??s,opencode:F,codex:zn,claude:Zn}),nt=T({pi:Le(m??l,w??d),opencode:Le(Ae,Kn),claude:Le(er,tr)}),rt=T({pi:p??a,opencode:q,codex:Yn,claude:Jn}),ot=T({pi:he(ne(c,k)),opencode:he(Gn),codex:he(Qn),claude:he(nr)});return{...h,...v,...Vn,...Xn,...Object.keys(tt).length>0?{modelsByFamily:tt}:{},...Object.keys(nt).length>0?{toolsByFamily:nt}:{},...Object.keys(rt).length>0?{thinkingByFamily:rt}:{},...Object.keys(ot).length>0?{envByFamily:ot}:{}}}),Yt=u.strictObject({name:u.string().optional(),display_name:u.string().optional(),description:u.string().optional(),hidden:u.boolean().optional(),worktree_checkout_type:u.enum(ut).optional(),system_prompt:u.string().optional(),harness_type:u.string().min(1).optional(),harness:Gr.optional()});function Vr(e){return Yt.parse(ge(e))}r(Vr,"parseAgentFile");var zr={label:"Agent",problem:"is not a valid agent template and was skipped"};async function L(e,t,n){return me(e,Vr,o=>o.name,t,zr,n)}r(L,"scanAgentFilesInDir");function ye(e,t,n,o){let i=new Map;for(let[s,a]of e)i.set(s,{...a});return Ue(i,t),Ue(i,n),Ue(i,o),i}r(ye,"mergeAgents");function Ue(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=Qt(n),a=Yr(o.modelsByFamily,s.modelsByFamily),l=Qr(o.toolsByFamily,s.toolsByFamily),d=Xr(o.thinkingByFamily,s.thinkingByFamily),c=Zr(o.envByFamily,s.envByFamily);e.set(n.name,{...o,...s,...a?{modelsByFamily:a}:{},...l?{toolsByFamily:l}:{},...d?{thinkingByFamily:d}:{},...c?{envByFamily:c}:{},...i})}else e.set(n.name,{...Jr,...Qt(n)})}}r(Ue,"mergeAgentOverrides");function Yr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Yr,"mergeModelsByFamily");function Qr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Qr,"mergeToolsByFamily");function Xr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Xr,"mergeThinkingByFamily");function Zr(e,t){let n={...e};for(let[o,i]of Object.entries(t??{})){let s=o;n[s]=ne(n[s],i)}return Object.keys(n).length>0?n:void 0}r(Zr,"mergeEnvByFamily");function Qt(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(Qt,"fromTemplate");var Jr={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var We=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return se().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 We)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 eo(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,o=S().scanDirs,[i,s,a,l]=await Promise.all([t?Promise.resolve([]):L(st,n,V),L(o.user,n,V),L(o.shared,n,V),L(o.project,n,V)]),c=ye(t?new Map:We,i,[],[]);return ye(c,s,a,l)}r(eo,"scanAndMerge");async function to(e,t){let n=await eo(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=ye(new Map,[],[],s);for(let[l,d]of a)o.has(l)||(o.set(l,d),i++)}return i}r(to,"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 Zt(e,t,n){let o=z(e);return o.kind==="not-found"&&(await to(t,{notify:n}),o=z(e)),o}r(Zt,"resolveTypeOrDiscover");function E(e){let t=z(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}r(E,"getAgentConfig");function Jt(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}r(Jt,"getAvailableTypes");function Yi(){return[...S().agents.keys()]}r(Yi,"getAllTypes");function Xt(e,t,n,o){return{skills:e??n,extensions:t??o}}r(Xt,"applyGlobalDefaults");function Qi(e,t=!0,n=!0){let o=E(e);if(o){let{skills:s,extensions:a,...l}=o,d=Xt(s,a,t,n);return{displayName:l.displayName??l.name,description:l.description,...d}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Xt(void 0,void 0,t,n)}}r(Qi,"getConfig");var qe="_configuredModel",Ke="_configuredThinking";function U(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(U,"readModelKey");function en(e){return U(e.thinking)??U(e[Ke])}r(en,"readThinkingRequest");function tn(e){let t=U(e.model);if(t)return{source:"call",key:t};let n=U(e[qe]);if(n)return{source:"configured",key:n}}r(tn,"readModelRequest");function Y(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(Y,"withoutModel");function nn(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(nn,"modelChoiceFor");function Q(e){return`${e.provider}/${e.id}`}r(Q,"modelKey");function no(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(no,"undeclaredLevelWarning");function rn(e,t){let n=no(e,t);return{resolved:{kind:"resolved",model:e,modelKey:Q(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(rn,"resolvedModel");function ro(e){return`No API key found for "${e}"`}r(ro,"missingCredential");function on(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:ee(o)}}return!At(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:ro(t.provider)}}r(on,"probeCredentials");function Ge(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ge,"refusal");function Ve(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return Y(i);let l=on(n,o);if(l.verdict!=="unusable")return rn(o,i);throw new Error(Ge(`The parent session's model "${Q(o)}" did not resolve credentials in this session`,l.reason))}let s=e.source==="call"?Ce(e.key,n,void 0):Ce(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=on(n,s);if(a.verdict!=="unusable")return rn(s,i);throw e.source==="call"?new Error(Ge(`Model "${Q(s)}" cannot authenticate in this session`,a.reason)):new Error(Ge(`The subagent model "${Q(s)}" for this configured default cannot authenticate in this session`,a.reason))}r(Ve,"resolvePiModel");async function oo(e){try{return await e.listModels(e.harness)}catch{return[]}}r(oo,"harnessModels");function io(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(io,"undeclaredLevelWarning");async function sn(e,t){if(!e)return Y(t.thinking);let n=await oo(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=io(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(sn,"resolveForeignModel");async function an(e,t){let{harness:n}=t;if(kt(n))return Ve(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return sn(e,o)}r(an,"resolveSpawnModel");function we(e,t){return{content:[{type:"text",text:e}],details:t}}r(we,"successResult");var ze=`
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
`,so={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function O(e){let{items:t}=e;lo(t,e),await e.prepare?.();let n=ao(e),o=[],i=[],s=r(({outcome:l,text:d})=>{o.push(l),i.push(d)},"record"),a;for(let l of t){let d=n.halt;if(d!==void 0&&a!==void 0){s(d.skip(l,a));continue}let c=await n.handle(l);s(c),d!==void 0&&d.halts(c.outcome)&&(a=l)}return we(i.join(ze),{[e.detailsKey]:o})}r(O,"runBatch");function ao(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(ao,"batchSteps");function lo(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=so[n];throw new Error(`${t} received duplicate ${s.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(lo,"rejectRepeatedKeys");var ln={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"},co={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 uo(e){if(!_(e)||e.status!=="stopped")return ln.agent;let{stop:t}=e;return e.phase==="never-started"?co[t.initiator]:ln[t.initiator]}r(uo,"stopNote");function cn(e){return!_(e)||e.status!=="stopped"?"":` (${uo(e)})`}r(cn,"getStatusNote");var po=`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}}`,go=`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}}`,mo=`{{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:po,queued:go,settled:mo}}};import{z as I}from"zod";import mn from"mustache";function dn(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}r(dn,"worktreeVariables");function ho(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}r(ho,"outcomeVariables");function fo(e){return e?{...dn(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}r(fo,"settledWorktreeVariables");function Ye(e){return e.worktree?{agent_id:e.agentId,...dn(e.worktree)}:{agent_id:e.agentId}}r(Ye,"spawnCueContext");function un(e){return{...Ye(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}r(un,"queuedCueContext");function pn(e){let{outcome:t,statusNote:n,worktree:o,multiplexerId:i}=e;return{...ho(t),...n?{status_note:n}:{},...fo(o),...i!=null?{multiplexer_id:i}:{}}}r(pn,"settledCueContext");var yo={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},wo={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},ko={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},bo=Object.keys(yo),vo=Object.keys(wo),To=Object.keys(ko);function gn(e){switch(e){case"spawned":return bo;case"queued":return vo;case"settled":return To;default:return}}r(gn,"cueVariables");var Ao={ok:!0},xo="&",Co=new Set(["name",xo,"#","^"]);function ke(e,t,n){return mn.render(e[t],n,void 0,{escape:r(o=>o==null?"":String(o),"escape")})}r(ke,"renderCue");function _o(e){let t=e[4];return Array.isArray(t)?t:void 0}r(_o,"spanChildren");function hn(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(Co.has(i)&&!t.includes(s))return`unknown variable "{{${s}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let a=_o(o);if(a){let l=hn(a,t,n);if(l)return l}}}r(hn,"findTemplateProblem");function fn(e,t){let n=gn(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let o;try{o=mn.parse(t)}catch(s){return{ok:!1,reason:`unparsable template: ${(s instanceof Error?s.message:String(s)).replace(/\s+/g," ").trim()}`}}let i=hn(o,n,e);return i?{ok:!1,reason:i}:Ao}r(fn,"validateCueTemplate");var So=["spawned","queued","settled"],Eo=I.strictObject({spawned:I.string().optional(),queued:I.string().optional(),settled:I.string().optional()}).superRefine((e,t)=>{for(let n of So){let o=e[n];if(o===void 0)continue;let i=fn(n,o);i.ok||t.addIssue({code:"custom",message:i.reason,path:[n]})}}),yn=I.strictObject({name:I.string().optional(),display_name:I.string().optional(),guidance:I.string().optional(),cues:Eo.optional()});var Oo={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function Ro(e){return yn.parse(ge(e))}r(Ro,"parseOrchestratorFile");async function X(e,t){return me(e,Ro,n=>n.name,t,Oo)}r(X,"scanOrchestratorFilesInDir");function Qe(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,Po(i.get(l.name)??Io(l.name,s),l));return i}r(Qe,"mergeOrchestrators");function Io(e,t){return{...t,name:e,displayName:e}}r(Io,"namedBase");function Po(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(Po,"applyOverride");function Z(){return se().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(at,n),X(o.user,n),X(o.shared,n),X(o.project,n)]),c=Qe(t?new Map:R,i,[],[]);return Qe(c,s,a,l)}r(Gs,"scanAndMergeOrchestrators");function Xe(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(Xe,"resolveOrchestrator");function Vs(){return[...Z().orchestrators.values()].map(e=>e.name)}r(Vs,"getAvailableOrchestrators");function wn(e){return typeof e=="string"&&e!==""?e:void 0}r(wn,"configuredString");function Mo(){let e=wn(f().agent.defaultAgentType);if(e===void 0)return Se;let t=z(e);return t.kind==="resolved"?t.key:Se}r(Mo,"resolveDefaultAgentType");function No(){let e=wn(f().agent.defaultOrchestrator);return e===void 0?P:e===P||Xe(e)?e:P}r(No,"resolveDefaultOrchestratorName");function be(e){return typeof e=="string"&&e!==""?e:Mo()}r(be,"resolveAgentTypeParam");function kn(){let e=No();return Xe(e)??(e===P?R[P]:void 0)??R[P]}r(kn,"resolveDefaultOrchestrator");function na(e){return E(e)?.worktreeCheckoutType??f().agent.worktreeCheckoutType}r(na,"resolveWorktreeCheckoutType");function bn(e){return typeof e=="string"&&e.trim()!==""?e:void 0}r(bn,"harnessParam");function vn(e){let t=bn(e);if(t!==void 0&&x().get(t)!==void 0)return xe(t,j())?t:void 0}r(vn,"requestedHarnessId");function Tn(e){let t=bn(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(!xe(t,o))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${ct(n.ids(),o).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}r(Tn,"resolveRequestedHarness");function ve(e,t){if(t!==void 0)return t;let n=E(e)?.harnessType??f().agent.harnessType;return x().resolve(n,j())}r(ve,"resolveHarnessType");function B(e=b()){let t=e.listAgents(Ee).filter(n=>te(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(B,"formatActiveAgents");function Ze(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-_t(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(Ze,"buildAgentDetails");function $o(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 yt(e)}}r($o,"settledOutcome");function Bo(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${M(e.lifecycle)}]`}r(Bo,"settledHeadline");function Do(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 ke(o.cues,"settled",pn({outcome:$o(t),statusNote:cn(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?$t(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:f().multiplexer||xt}))}r(Do,"formatResultContent");var Je=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=be(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=pt(a),d=kn(),c=await Zt(i,void 0,(k,v)=>{n.ui.notify(k,v)});if(c.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${i}. Candidates: ${c.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(c.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=Tn(t.harness_type),g=ve(c.key,h),p=en(t),m=await an(tn(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:ie(n.modelRegistry)}),F=Tt(v);return F!==void 0&&n.hasUI&&n.ui.notify(F,"warning"),vt(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:c.key,orchestrator:d,fork:E(i)?.fork??!1,modelChoice:nn(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(),d=await this.expectedWorktree(a,l),c=this.intent.modelChoice?.thinking??void 0,h=ft(this.intent.modelChoice),{agentId:g,spawn:p}=await Et().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:d,invocation:{modelName:h,thinkingLevel:c,fork:this.intent.fork},runInBackground:o,signal:o?void 0:t});if(this.intent.toolCallId&&(p.display.toolCallId=this.intent.toolCallId),!o){let v=Ze(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:`${Bo(p)}
|
|
18
|
+
|
|
19
|
+
${Do(p)}`,details:v}}let m=d;if(p.lifecycle.phase==="queued"){let v=b().listAgents(Ee).filter(Ae=>Ae.lifecycle.phase==="spawned").length,F=ke(this.intent.orchestrator.cues,"queued",un({agentId:g,worktree:m,queueRunning:v})),q=Ze(p);return q.agentId=g,q.status="queued",{message:`[Agent queued] ${F}`,details:q}}let w=ke(this.intent.orchestrator.cues,"spawned",Ye({agentId:g,worktree:m})),k=Ze(p);return k.agentId=g,k.status="spawned",{message:`[Agent spawned] ${w}`,details:k}}async expectedWorktree(t,n){let o=await Mt(t,re().cwd).catch(()=>{});if(o===void 0)return;let i=ht(f().agent.worktreeRoot,o);return{kind:"owned",path:mt(i,this.intent.taskSlug,n),branch:gt(this.intent.taskSlug,n)}}};async function An(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(c=>({...c,run_in_background:e.run_in_background})),s=await Promise.all(i.map(c=>Je.parse(c,t,n)));Fo(s);let a=await Promise.all(s.map(c=>c.run(o))),l=a.map(c=>c.message).join(ze),d={agents:a.map(c=>c.details)};return{message:l,details:d}}r(An,"runDelegationBatch");function Fo(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(Fo,"rejectRepeatedTaskSlugs");async function xn(e,t,n,o,i){let{message:s,details:a}=await An(t,i,e,n);return we(s,a)}r(xn,"executeAgentTool");function jo(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(jo,"renderStopOutcome");async function Cn(e,t,n,o,i){let s=t.agent_ids;return O({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:s,render:jo,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(d){return{kind:"failed",agentId:a,error:d instanceof Error?d.message:String(d)}}},"handleItem")})}r(Cn,"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=be(a),d=E(l),c=vn(s.harness_type),h=ve(l,c),g=U(s.model),p=g??f().modelFor(l,i,d,h);if(p&&!g&&(s[qe]=p),s.thinking===void 0){let m=f().thinkingFor(l,d,h,t.thinkingLevel);m!==void 0&&(s[Ke]=m)}}}r(Oa,"toolCallListener");function _n(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(_n,"formatBasis");function Ho(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${_n(e.basis)})`}r(Ho,"formatSettlement");function Sn(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 (${_n(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(Sn,"formatKeptReason");function Lo(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(Lo,"paneText");function En(e){switch(e.kind){case"removed":return`removed (${e.path})`;case"removal-failed":return`NOT removed \u2014 ${e.detail} (${e.path})`;case"kept":return`kept${e.path?` (${e.path})`:" (worktree path not recorded)"}`;case"absent":return`already gone (${e.path})`;case"none":return"none (agent ran without a worktree)"}}r(En,"worktreeText");function On(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(On,"branchText");function Uo(e){return e?` forced${e.reason?` \u2014 ${Sn(e.reason)}`:""}`:""}r(Uo,"forcedClause");function et(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Sn(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${Uo(e.outcome.forced)}:`}r(et,"headline");function Rn(e){let t=[et(e),` agent status: ${Ho(e.settlement)}`,` pane: ${Lo(e.pane)}`,` worktree: ${En(e.worktree)}`,` branch: ${On(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(Rn,"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"?`${et(e)} ${t}`:`${et(e)} ${t}, worktree ${En(e.worktree)}, branch ${On(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 Wo(e){switch(e.kind){case"cleaned":return Rn(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(Wo,"renderCleanupOutcome");async function In(e,t,n,o,i){let s=t.agent_ids;return O({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:s,render:Wo,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 d=await l.cleanup(a);return{kind:"cleaned",agentId:a,report:d}},"handleItem")})}r(In,"executeCleanupAgentTool");import*as Mn from"node:fs";import*as W from"node:path";function Pn(e){let t=W.normalize(e),{root:n}=W.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Pn,"normalizeRepoRoot");function qo(e,t){return Pn(e)===Pn(t)}r(qo,"isSameRepoRoot");function Ko(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(Ko,"formatOutsideRepoWarning");async function Go(e,t){let n=new It(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}=Pt(i,o);if(!Mn.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(Go,"resolveSessionMainRoot");var Vo="has conflicts in:";function zo(e){return e.includes(Vo)}r(zo,"isConflictError");function Yo(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(Yo,"parseConflictFiles");function Qo(e,t){return e.includes(`branch "${t}" does not exist`)}r(Qo,"isUnknownBranchError");async function Nn(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,d=r(()=>(l??=(async()=>{let c=re().cwd;if(typeof c!="string"||c.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 Go(C(),c),cwd:a??c}})(),l),"mergeScope");return O({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,prepare:r(async()=>{Me(s,"target");for(let c of t.branches)Me(c.trim(),"branch");await d()},"prepare"),halt:{on:r(c=>c.kind==="conflict","on"),skip:r((c,h)=>{let g=c.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 c=>{let{sessionRoot:h,cwd:g}=await d(),p=c.trim();try{let m=await Nt(C(),{cwd:g,branch:p,target:s}),w=qo(m.mainRoot,h)?void 0:Ko(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 zo(w)?{outcome:{kind:"conflict",branch:p,target:s,files:Yo(w)},text:`"${p}": ${w}`}:Qo(w,p)?{outcome:{kind:"unknown",branch:p},text:`"${p}": ${w}`}:{outcome:{kind:"failed",branch:p,error:w},text:`"${p}": ${w}`}}},"handleItem")})}r(Nn,"executeMergeBranchTool");async function $n(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 d=M(l.lifecycle),c;try{c=await b().steer(a,s)}catch(g){c={kind:"refused",reason:`steering failed: ${ee(g)}`}}if(c.kind==="refused")return{outcome:{kind:"refused",agentId:a,reason:c.reason},text:`Agent ${a} was not steered (${d}): ${c.reason}`};if(c.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:a,reason:c.reason},text:`Agent ${a} had settled (${d}) and the message reached its pane, but it was not revived: ${c.reason}`};let h=d!=="spawned"&&l.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:a},text:h?`Agent ${a} had settled (${d}) \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.`:d==="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 (${d}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r($n,"executeSteerAgentTool");var A={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Fn=Object.values(A),J={type:"json_schema",strict:"prefer"};function Xo(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(Xo,"cowboyAgentsSchemaWithTypes");function jn(e){let t=Xo(Jt()),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:xn,constrainedSampling:J};e.registerTool(n)}r(jn,"registerAgentTool");function Zo(e,t){f().mutate.agent.setExtensionEnabled(t),t?Jo(e):ei(e)}r(Zo,"setExtensionEnabled");function Jo(e){let t=C();jn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Fn])]),de(e)}r(Jo,"activateExtension");function ei(e){let t=C();t.setActiveTools(t.getActiveTools().filter(n=>!Fn.includes(n))),de(e)}r(ei,"deactivateExtension");function fl(e){jn(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:Ut,execute:Cn,constrainedSampling:J,renderResult:r((s,a,l,d)=>{let c=d.isError??!1,h=s.content.at(0),g=h?.type==="text"?h.text:"",p=c?l.fg("error","\u2717"):l.fg("success","\u2713");return new Bn(`${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:qt,execute:Nn,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:Kt,execute:$n,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:Wt,execute:In,constrainedSampling:J};e.registerTool(i),e.registerMessageRenderer("subagent-result",(s,a,l)=>{let d=typeof s=="object"&&typeof s.content=="string"?s.content:"",c=/\b(error|stopped)\b/.test(d.slice(0,200)),h=l.fg(c?"error":"success",c?"\u2717":"\u2713");return new Bn(`${h} ${d}`,0,0)})}r(fl,"registerTools");async function Dn(e,t){let n=await x().listModelOptions({pi:e,modelCatalog:ie(t.modelRegistry)},j());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Dn,"harnessModelOptions");var Hn="cowboy",ti={wt:"worktree",sp:"spawn",st:"status"};function yl(e,t){e.registerCommand(Hn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(yl,"registerUnavailableCowboyCommand");function wl(e){e.registerCommand(Hn,{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-IIXU4GJP.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{Ot(n);let[o,...i]=t.trim().split(/\s+/),s=ti[o]??o,a=[s,...i].join(" ");if(a==="enable"||a==="disable"){let c=a==="enable";if(c&&Pe()===null){n.ui.notify(_e,"warning");return}if(ce()===c){n.ui.notify(`pi-cowboy is already ${c?"enabled":"disabled"}`,"info");return}Zo(n.ui,c),n.ui.notify(c?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(Pe()===null){n.ui.notify(_e,"warning");return}if(s==="worktree"){let{showWorktreeCommandMenu:c}=await import("./menu-worktree-command-SXLBWK4D.js");await c(n,i.join(" "));return}if((s==="model"||a==="spawn"||a==="status")&&!ce()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(s==="model"){let{handleModelArg:c}=await import("./model-picker-IIXU4GJP.js");await c(i.join(" "),n);return}if(a==="spawn"||a==="status"){let{showAgentsActionMenu:c}=await import("./menus-Q3TEDIPV.js");await c(n,a,await Dn(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:d}=await import("./menus-Q3TEDIPV.js");await d(n,await Dn(e,n))},"handler")})}r(wl,"registerCowboyCommand");import*as Ln from"node:fs";import{tmpdir as ni}from"node:os";import*as Te from"node:path";async function Un(e,t){try{return await Rt(e).probe(t),K(dt)}catch{return K(["checkout"])}}r(Un,"detectCowAvailability");function Wn(e){let t=Te.resolve(e??it());for(;;){try{if(Ln.statSync(t).isDirectory())return t}catch{}let n=Te.dirname(t);if(n===t)return ni();t=n}}r(Wn,"probeTargetFor");function ri(e){return(t,n,o)=>e.exec(t,n,o)}r(ri,"execOf");function Il(e){return qn(e,Ie())}r(Il,"startCowSupportProbe");function Pl(e){let t=Ie();return oe(t,lt()),qn(e,t)}r(Pl,"refreshCowSupportProbe");function qn(e,t){let n=Wn(f().agent.worktreeRoot);return Un(ri(e),n).then(o=>{oe(t,o)},()=>{oe(t,K(["checkout"]))})}r(qn,"probe");export{We as a,Vi as b,zi as c,eo as d,E as e,Jt as f,Yi as g,Qi as h,R as i,qs as j,Ks as k,Gs as l,Vs as m,Mo as n,kn as o,na as p,ve as q,Ze as r,Bo as s,Do as t,Oa as u,Sn as v,Pa as w,Ma as x,Fe as y,ce as z,ui as A,Il as B,Pl as C,Zo as D,Jo as E,ei as F,fl as G,yl as H,wl as I};
|
|
24
|
+
//# sourceMappingURL=chunk-PDV4AFO7.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{za as x}from"./chunk-CTBFJWEE.js";import{a as s,e as f,l as C}from"./chunk-254PTGN5.js";import{Container as y,fuzzyFilter as M,getKeybindings as N,Input as k,Spacer as v,Text as b}from"@earendil-works/pi-tui";import{DynamicBorder as w}from"@earendil-works/pi-coding-agent";var h=10,g=class extends y{static{s(this,"SearchableSelectDialog")}searchInput;listContainer;items;filteredItems;selectedIndex;currentValue;callbacks;theme;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}constructor(e,n,r,l){super(),this.items=e,this.currentValue=n,this.callbacks=r,this.theme=l,this.filteredItems=[...e];let a=e.findIndex(o=>o.value===n);this.selectedIndex=a>=0?a:0,this.addChild(new w),this.addChild(new v(1)),this.searchInput=new k,this.searchInput.onSubmit=()=>{this.filteredItems[this.selectedIndex]&&this.callbacks.onSelect(this.filteredItems[this.selectedIndex].value)},this.addChild(this.searchInput),this.addChild(new v(1)),this.listContainer=new y,this.addChild(this.listContainer),this.addChild(new v(1)),this.addChild(new w),this.updateList()}handleInput(e){let n=N();if(!(this.filteredItems.length===0&&(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")||n.matches(e,"tui.select.pageUp")||n.matches(e,"tui.select.pageDown")))){if(n.matches(e,"tui.select.up")){this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(n.matches(e,"tui.select.down")){this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}if(n.matches(e,"tui.select.pageUp")){this.selectedIndex=Math.max(0,this.selectedIndex-h),this.updateList();return}if(n.matches(e,"tui.select.pageDown")){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+h),this.updateList();return}if(n.matches(e,"tui.select.confirm")){let r=this.filteredItems.at(this.selectedIndex);r&&this.callbacks.onSelect(r.value);return}if(n.matches(e,"tui.select.cancel")){this.callbacks.onCancel();return}this.searchInput.handleInput(e),this.filterItems()}}invalidate(){}filterItems(){let e=this.searchInput.getValue();e?this.filteredItems=M(this.items,e,n=>`${n.label} ${n.provider} ${n.value??""}`):this.filteredItems=[...this.items],this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList()}updateList(){this.listContainer.clear();let{filteredItems:e}=this;if(e.length===0){this.listContainer.addChild(new b(this.theme.fg("muted"," No matching items"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(h/2),e.length-h)),r=Math.min(n+h,e.length);for(let l=n;l<r;l++){let a=e.at(l);if(!a)continue;let o=l===this.selectedIndex,d=a.value===this.currentValue,c=o?this.theme.fg("accent","\u2192 ")+this.theme.fg("accent",a.label):` ${a.label}`,i=a.provider?this.theme.fg("muted",`[${a.provider}]`):"",u=d?this.theme.fg("success"," \u2713"):"",m=`${c} ${i}${u}`;this.listContainer.addChild(new b(m,0,0))}if(n>0||r<e.length){let l=this.theme.fg("muted",` (${this.selectedIndex+1}/${e.length})`);this.listContainer.addChild(new b(l,0,0))}}};import{isFocusable as L}from"@earendil-works/pi-tui";var O=class{constructor(e){this.ctx=e}ctx;static{s(this,"ScreenHost")}async open(e){return await this.show(e,!1)}async openOverlay(e){return await this.show(e,!0)}async show(e,n){if(x(this.ctx))return await new Promise(r=>{this.ctx.ui.custom((l,a,o,d)=>e({tui:l,theme:a,keybindings:o,close:s(c=>{x(this.ctx)&&d(c),r(c)},"close")}),n?{overlay:!0}:void 0).then(r)})}},j=void 0;function K(t){return Object.assign(t,{focused:!0})}s(K,"asSubmenuComponent");var I=class{static{s(this,"SwappableView")}active;constructor(e){this.active=e}activate(e){this.active=e}invalidate(){this.active.invalidate()}render(e){return this.active.render(e)}handleInput(e){this.active.handleInput?.(e)}get focused(){return L(this.active)?this.active.focused:!1}set focused(e){L(this.active)&&(this.active.focused=e)}};var F="group-header";function q(t,e){return{id:T,kind:F,label:t.bold(t.fg("accent",e)),currentValue:""}}s(q,"headerItem");var T="__sep__",p=new WeakMap;function X(t){if(!Array.isArray(t.items))return;let e=s(o=>o?.value===T||o?.id===T,"isSep"),n=s((o,d,c)=>{let i=d+c;for(;i>=0&&i<o.length&&e(o[i]);)i+=c;return i},"firstNonSepFrom"),r=s((o,d)=>d>=0&&d<o.length,"inBounds"),l=s((o,d)=>{let c=Math.max(0,Math.min(d,o.length-1));for(let i=c;i<o.length;i+=1)if(!e(o[i]))return i;for(let i=c-1;i>=0;i-=1)if(!e(o[i]))return i;return 0},"seedIndex"),a=t.selectedIndex??0;Object.defineProperty(t,"selectedIndex",{get(){return p.get(t)},set(o){let d=t.items,c=p.get(t)??0,i=Math.max(0,Math.min(o,d.length-1));if(!e(d[i])){p.set(t,i);return}let u=o>c?1:-1,m=n(d,i,u),S=n(d,i,-u);r(d,m)?p.set(t,m):r(d,S)?p.set(t,S):p.set(t,i)},configurable:!0}),p.set(t,l(t.items,a))}s(X,"installSeparatorSkip");function J(t,e,n){let r=[{value:null,label:"(none)",provider:""}],l=[];for(let i of t){let u=f(i);u&&l.push({value:i,label:u.modelId,provider:u.provider})}if(e===null&&n.length===0)return r.push(...l),r;let a=[],o=[],d=[],c=new Set;if(e){let i=f(e);i&&(a.push({value:e,label:i.modelId,provider:i.provider}),c.add(e))}for(let i of n){if(c.has(i))continue;let u=f(i);u&&(o.push({value:i,label:u.modelId,provider:u.provider}),c.add(i))}for(let i of l)i.value!=null&&!c.has(i.value)&&d.push(i);return r.push(...a,...o,...d),r}s(J,"buildModelOptions");function Q(t){let e=[];t.default&&typeof t.default=="string"&&e.push(t.default);for(let[n,r]of Object.entries(t))n!=="default"&&typeof r=="string"&&r.includes("/")&&e.push(r);return[...new Set(e)]}s(Q,"extractConfiguredModels");function Y(t,e){return C(t)?e:[]}s(Y,"mergedModelsForHarness");function Z(t){return{label:s((e,n)=>n?t.fg("accent",e):e,"label"),value:s((e,n)=>n?t.fg("accent",e):t.fg("muted",e),"value"),description:s(e=>t.fg("dim",e),"description"),cursor:t.fg("accent","\u2192 "),hint:s(e=>t.fg("dim",e),"hint")}}s(Z,"buildSettingsListTheme");function ee(t,e){let n=t.trim();if(!/^\d*\.?\d+$/.test(n))return;let r=parseFloat(n);if(!(r<e))return r}s(ee,"validateNumeric");var _=new Map([["k","\x1B[A"],["j","\x1B[B"]]);function te(t){let e=t,n=e.handleInput?.bind(e);return n&&(e.handleInput=r=>{let l=e.submenuComponent?void 0:_.get(r);n(l??r)}),t}s(te,"withVimKeys");function ne(t){return{selectedPrefix:s(()=>t.fg("accent","\u2192 "),"selectedPrefix"),selectedText:s(e=>t.fg("accent",e),"selectedText"),description:s(e=>t.fg("muted",e),"description"),scrollInfo:s(e=>t.fg("dim",e),"scrollInfo"),noMatch:s(e=>t.fg("dim",e),"noMatch")}}s(ne,"buildSelectListTheme");function ie(t,e,n){let r,l=new g(t,null,{onSelect:s(a=>{let o=e.onSelect(a);o&&r.activate(o)},"onSelect"),onCancel:e.onCancel},n);return r=new I(l),r}s(ie,"createSearchableSelect");function se(t){return t.length===1?`agent ${t[0]}`:`${t.length} agent(s)`}s(se,"agentSubject");export{g as a,O as b,j as c,K as d,I as e,q as f,T as g,X as h,J as i,Q as j,Y as k,Z as l,ee as m,te as n,ne as o,ie as p,se as q};
|
|
2
|
+
//# sourceMappingURL=chunk-WL3QYM2F.js.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { SubagentsConfig } from "../models/model-precedence.js";
|
|
2
2
|
import type { AgentManager } from "../agents/agent-manager.js";
|
|
3
3
|
import { type AnyHarnessId, type HarnessConfigIssue } from "../agents/harness.js";
|
|
4
|
+
import type { EnvOverrides } from "../agents/harness/env-overrides.js";
|
|
4
5
|
import type { ModelsByFamily, SystemPromptMode, ThinkingByFamily } from "../agents/types.js";
|
|
5
6
|
import { type WorktreeCheckoutType, type WorktreeMaterialization } from "../spawn/worktree-policy.js";
|
|
6
7
|
import { type ThinkingLevel } from "../types.js";
|
|
@@ -46,7 +47,7 @@ export declare class ConfigStore {
|
|
|
46
47
|
global: Record<string, Record<string, unknown>>;
|
|
47
48
|
project: Record<string, Record<string, unknown>>;
|
|
48
49
|
};
|
|
49
|
-
harnessEnv(harnessId: AnyHarnessId):
|
|
50
|
+
harnessEnv(harnessId: AnyHarnessId): EnvOverrides | undefined;
|
|
50
51
|
reportHarnessConfigIssue(id: AnyHarnessId, issue: HarnessConfigIssue): void;
|
|
51
52
|
get concurrency(): ConcurrencyConfig;
|
|
52
53
|
get sessionDefaultModel(): string | null;
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{B as Mt,E as Dt,F as ke,G as Ot,H as jt,I as $t,a as ft,b as ht,c as yt,d as wt,e as vt,h as St,j as kt,k as Pt,l as bt,p as At,q as xt,r as Se,s as Rt,t as It,u as Et,y as Ct,z as $}from"./chunk-PYOLHDZJ.js";import{a as dt,f as ut,g as ve,h as ct,m as pt,n as gt,o as mt,r as Lt,s as Ft}from"./chunk-ZLKJYRKY.js";import{$ as Ze,A as We,Aa as st,Ba as ot,Ca as ye,D as V,Da as we,E as _,Ea as ee,Fa as at,G as ze,Ga as lt,Ha as Tt,I as me,J as j,O as Y,Q as Ve,R as Ye,S as q,T as X,U as Xe,V as fe,_ as Je,a as E,aa as et,ba as b,c as Me,ca as J,d as I,e as De,ea as he,f as Oe,fa as P,g as je,ia as T,j as $e,la as Z,pa as A,ra as tt,sa as nt,ta as rt,u as Q,ua as it,w as K,y as He,ya as U,z}from"./chunk-JIAP5YBM.js";import{a as s,b as Ne,d as y,h as O,i as _e,n as qe,o as Ue,p as Be,r as Ge,s as Qe,v as Ke}from"./chunk-254PTGN5.js";import*as L from"node:path";function ne(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"}}s(ne,"findTaskDedup");var F=class extends Error{static{s(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",i=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?X(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${i} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},te=class{constructor(e){this.deps=e}deps;static{s(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let i=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,i);try{return await i}finally{this.admissionBySlug.get(r)===i&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let c=this.deps.listAgents().filter(m=>m.display.taskSlug===e.taskSlug&&Ye(m.lifecycle.phase)),g=ne(c,await this.deps.findTaskAttempts(e.taskSlug));if(g.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:g.kind==="spawn"?g.spawn.id:g.attempt.name}}let{type:r,prompt:n,runInBackground:i,signal:o,...l}=e,a={...l,isBackground:i,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 Ht from"node:fs";var re=class{constructor(e){this.resultFile=e}resultFile;static{s(this,"FileDeliverable")}async readDeliverable(){try{let e=Ht.statSync(this.resultFile).mtimeMs,r=Ht.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import Wn from"node:fs";import*as Wt from"node:path";function B(t){try{Wn.rmSync(Wt.dirname(t),{recursive:!0,force:!0})}catch{}}s(B,"removeResultArtifacts");import*as H from"node:fs";import*as ie from"node:path";async function Nt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}s(Nt,"probeList");function Nn(t,e,r){let n=r(e);return t?.find(i=>r(i.path)===n)}s(Nn,"matchWorktree");function qt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}s(qt,"paneOf");function _t(t,e,r){let n=r(e),i=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return i===void 0?void 0:qt(i)}s(_t,"paneInWorktree");function _n(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:qt(r)}s(_n,"paneInWorkspace");function qn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}s(e,"root");async function r(a,d){let u=await e(),c=[],g=new Set,m=s(p=>{let h=t.canonicalizePath(p.path);g.has(h)||(g.add(h),c.push(p))},"push");for(let p of d??[]){let h=ie.basename(p.path);z(h,a)&&(u!==void 0&&!We(p.path,u)||m({path:p.path,branch:p.branch!==void 0&&z(p.branch,a)?p.branch:h,workspaceId:p.workspaceId}))}if(c.length>0||u===void 0)return c;for(let p of await t.listRootEntries(u))z(p,a)&&m({path:ie.join(u,p),branch:p});return c}s(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}s(n,"candidateSummary");async function i(a,d,u,c){let g=d.execution.host,m=d.display.worktree,p=m?.kind==="owned",h=g?{paneId:g.paneId,tabId:g.tabId,workspaceId:g.workspaceId}:null,f="tracked",S=m?.kind==="owned"?m.path:void 0,k=g?.workspaceId;if(S!==void 0){let x=Nn(u,S,t.canonicalizePath);x!==void 0&&(k=x.workspaceId)}let v=S===void 0?h:_t(c,S,t.canonicalizePath)??h,R=S===void 0?null:{path:S,workspaceId:k,repoCwd:await t.resolveRepoCwd(S)};return{kind:"located",source:f,id:a,branch:m?.branch??K(d.display.taskSlug??Q(d.display.type),d.id),worktreeManaged:p||R!==null,paneCreated:g?.paneCreated===!0,worktree:R,pane:v}}s(i,"locateTracked");async function o(a,d,u){let c=await r(a,d);if(c.length===0)return{kind:"not-found",id:a};if(c.length>1)return{kind:"ambiguous",id:a,candidates:c.map(n)};let g=c[0],m=_t(u,g.path,t.canonicalizePath)??_n(u,g.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:g.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:g.path,workspaceId:g.workspaceId,repoCwd:await t.resolveRepoCwd(g.path)},pane:m}}s(o,"locateDiscovered");async function l(a,d){let u=await Nt(t.listWorktrees),c=await Nt(t.listPlacements),g=u.ok?u.entries:void 0,m=c.ok?c.entries:void 0;return d===void 0?o(a,g,m):i(a,d,g,m)}return s(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:s(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,harnessTeardown:t.harnessTeardown}}s(qn,"createAgentAssets");function Ut(t,e,r){return qn({multiplexer:r.multiplexer,canonicalizePath:s(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:s(n=>{let i=I(n);return{path:i,present:H.existsSync(i)}},"deliverable"),listWorktrees:s(()=>r.listWorktrees(),"listWorktrees"),listPlacements:s(()=>r.listPlacements(),"listPlacements"),readPane:s(n=>r.observePane(n),"readPane"),worktreeRoot:s(async()=>{let n=J().cwd;if(!n)return;let i=await ve(t,n).catch(()=>{});return i===void 0?void 0:He(P().agent.worktreeRoot,i)},"worktreeRoot"),listRootEntries:s(async n=>{try{return await H.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:s(async n=>{try{return await ve(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:s(n=>gt(t,n),"isWorktreeDirty"),worktreeExists:s(async n=>H.existsSync(n),"worktreeExists"),removeWorktree:s(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:s(async(n,i)=>(await ct(t,i,n),!H.existsSync(n)),"removeGitWorktree"),deleteBranch:s(n=>pt(t,n,i=>e.isAttached(i,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:s(async n=>{await e.release(n,"placement")},"closePane"),harnessTeardown:s(async(n,i)=>{await A().get(n)?.teardown({pi:t,...i})},"harnessTeardown")})}s(Ut,"createMultiplexerAgentAssets");var C=j("supervisor"),Un=2e3;function Bn(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}s(Bn,"deferred");var se=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??Un,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp}host;deliverable;static{s(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;phase={kind:"idle"};outcome=null;settlement=Bn();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,i=await this.host.stop(n,{interruptGraceMs:e,confirmMs:0}).catch(o=>(C.debug("host stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:i,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),i}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||!Gn(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 Gn(t,e){return t.content===e.content&&t.mtime===e.mtime}s(Gn,"sameReport");function oe(t){let e=t.transport.createDeliverable(t.resultFile);return new se(t.host,e,t.supervisorOptions)}s(oe,"createPaneSupervisor");import Ae from"node:fs";import D from"node:path";import{SettingsManager as cr}from"@earendil-works/pi-coding-agent";import nr from"node:fs";import{loadProjectContextFiles as rr}from"@earendil-works/pi-coding-agent";function Bt(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
|
|
2
|
-
`):""}s(
|
|
1
|
+
import{B as Ft,E as Mt,F as ke,G as Dt,H as Ot,I as jt,a as mt,b as ft,c as ht,d as yt,e as wt,h as vt,j as St,k as kt,l as Pt,p as bt,q as At,r as Se,s as xt,t as Rt,u as It,y as Et,z as H}from"./chunk-PDV4AFO7.js";import{a as lt,f as dt,g as ve,h as ut,m as ct,n as pt,o as gt,r as Tt,s as Lt}from"./chunk-KMXT7XW7.js";import{A as We,Ba as U,D as Y,Da as it,E as N,Ea as st,Fa as ye,G as Ge,Ga as we,Ha as ee,I as me,Ia as ot,J as j,Ja as at,Ka as Ct,O as V,Q as Qe,R as Ke,S as q,T as X,U as ze,V as fe,_ as Ye,a as E,aa as Ve,ba as Xe,c as Me,ca as Je,d as I,da as Ze,e as De,ea as b,f as Oe,fa as J,g as je,ha as he,ia as P,j as He,la as T,oa as Z,sa as A,u as Q,ua as et,va as tt,w as K,wa as nt,xa as rt,y as $e,z}from"./chunk-CTBFJWEE.js";import{a as s,b as _e,d as y,h as O,i as Ne,r as qe,s as Ue,v as Be}from"./chunk-254PTGN5.js";import*as L from"node:path";function ne(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"}}s(ne,"findTaskDedup");var F=class extends Error{static{s(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",i=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?X(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${i} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},te=class{constructor(e){this.deps=e}deps;static{s(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let i=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,i);try{return await i}finally{this.admissionBySlug.get(r)===i&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let c=this.deps.listAgents().filter(m=>m.display.taskSlug===e.taskSlug&&Ke(m.lifecycle.phase)),g=ne(c,await this.deps.findTaskAttempts(e.taskSlug));if(g.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:g.kind==="spawn"?g.spawn.id:g.attempt.name}}let{type:r,prompt:n,runInBackground:i,signal:o,...l}=e,a={...l,isBackground:i,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 Ht from"node:fs";var re=class{constructor(e){this.resultFile=e}resultFile;static{s(this,"FileDeliverable")}async readDeliverable(){try{let e=Ht.statSync(this.resultFile).mtimeMs,r=Ht.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import $n from"node:fs";import*as $t from"node:path";function B(t){try{$n.rmSync($t.dirname(t),{recursive:!0,force:!0})}catch{}}s(B,"removeResultArtifacts");import*as $ from"node:fs";import*as ie from"node:path";async function Wt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}s(Wt,"probeList");function Wn(t,e,r){let n=r(e);return t?.find(i=>r(i.path)===n)}s(Wn,"matchWorktree");function Nt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}s(Nt,"paneOf");function _t(t,e,r){let n=r(e),i=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return i===void 0?void 0:Nt(i)}s(_t,"paneInWorktree");function _n(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:Nt(r)}s(_n,"paneInWorkspace");function Nn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}s(e,"root");async function r(a,d){let u=await e(),c=[],g=new Set,m=s(p=>{let h=t.canonicalizePath(p.path);g.has(h)||(g.add(h),c.push(p))},"push");for(let p of d??[]){let h=ie.basename(p.path);z(h,a)&&(u!==void 0&&!We(p.path,u)||m({path:p.path,branch:p.branch!==void 0&&z(p.branch,a)?p.branch:h,workspaceId:p.workspaceId}))}if(c.length>0||u===void 0)return c;for(let p of await t.listRootEntries(u))z(p,a)&&m({path:ie.join(u,p),branch:p});return c}s(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}s(n,"candidateSummary");async function i(a,d,u,c){let g=d.execution.host,m=d.display.worktree,p=m?.kind==="owned",h=g?{paneId:g.paneId,tabId:g.tabId,workspaceId:g.workspaceId}:null,f="tracked",S=m?.kind==="owned"?m.path:void 0,k=g?.workspaceId;if(S!==void 0){let x=Wn(u,S,t.canonicalizePath);x!==void 0&&(k=x.workspaceId)}let v=S===void 0?h:_t(c,S,t.canonicalizePath)??h,R=S===void 0?null:{path:S,workspaceId:k,repoCwd:await t.resolveRepoCwd(S)};return{kind:"located",source:f,id:a,branch:m?.branch??K(d.display.taskSlug??Q(d.display.type),d.id),worktreeManaged:p||R!==null,paneCreated:g?.paneCreated===!0,worktree:R,pane:v}}s(i,"locateTracked");async function o(a,d,u){let c=await r(a,d);if(c.length===0)return{kind:"not-found",id:a};if(c.length>1)return{kind:"ambiguous",id:a,candidates:c.map(n)};let g=c[0],m=_t(u,g.path,t.canonicalizePath)??_n(u,g.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:g.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:g.path,workspaceId:g.workspaceId,repoCwd:await t.resolveRepoCwd(g.path)},pane:m}}s(o,"locateDiscovered");async function l(a,d){let u=await Wt(t.listWorktrees),c=await Wt(t.listPlacements),g=u.ok?u.entries:void 0,m=c.ok?c.entries:void 0;return d===void 0?o(a,g,m):i(a,d,g,m)}return s(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:s(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,harnessTeardown:t.harnessTeardown}}s(Nn,"createAgentAssets");function qt(t,e,r){return Nn({multiplexer:r.multiplexer,canonicalizePath:s(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:s(n=>{let i=I(n);return{path:i,present:$.existsSync(i)}},"deliverable"),listWorktrees:s(()=>r.listWorktrees(),"listWorktrees"),listPlacements:s(()=>r.listPlacements(),"listPlacements"),readPane:s(n=>r.observePane(n),"readPane"),worktreeRoot:s(async()=>{let n=J().cwd;if(!n)return;let i=await ve(t,n).catch(()=>{});return i===void 0?void 0:$e(P().agent.worktreeRoot,i)},"worktreeRoot"),listRootEntries:s(async n=>{try{return await $.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:s(async n=>{try{return await ve(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:s(n=>pt(t,n),"isWorktreeDirty"),worktreeExists:s(async n=>$.existsSync(n),"worktreeExists"),removeWorktree:s(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:s(async(n,i)=>(await ut(t,i,n),!$.existsSync(n)),"removeGitWorktree"),deleteBranch:s(n=>ct(t,n,i=>e.isAttached(i,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:s(async n=>{await e.release(n,"placement")},"closePane"),harnessTeardown:s(async(n,i)=>{await A().get(n)?.teardown({pi:t,...i})},"harnessTeardown")})}s(qt,"createMultiplexerAgentAssets");var C=j("supervisor"),qn=2e3;function Un(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}s(Un,"deferred");var se=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??qn,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp}host;deliverable;static{s(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;phase={kind:"idle"};outcome=null;settlement=Un();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,i=await this.host.stop(n,{interruptGraceMs:e,confirmMs:0}).catch(o=>(C.debug("host stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:i,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),i}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||!Bn(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 Bn(t,e){return t.content===e.content&&t.mtime===e.mtime}s(Bn,"sameReport");function oe(t){let e=t.transport.createDeliverable(t.resultFile);return new se(t.host,e,t.supervisorOptions)}s(oe,"createPaneSupervisor");import Ae from"node:fs";import D from"node:path";import{SettingsManager as ur}from"@earendil-works/pi-coding-agent";import tr from"node:fs";import{loadProjectContextFiles as nr}from"@earendil-works/pi-coding-agent";function Ut(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
|
|
2
|
+
`):""}s(Ut,"buildOrchestrationGuidance");import{formatSkillsForPrompt as Gn}from"@earendil-works/pi-coding-agent";function Qn(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,`
|
|
5
5
|
`),e=e.replace(/\n?Current working directory:.*\n?/g,`
|
|
6
6
|
`),e=e.replace(/\n{3,}/g,`
|
|
7
7
|
|
|
8
|
-
`),e.trim()}s(
|
|
9
|
-
`),a=!!n?.skillMetas?.length||!!n?.inlinedSkills?.length,d="";if(a){let f=[];if(n?.skillMetas?.length){let k=n.skillMetas.map(x=>({name:x.name,description:x.description,filePath:x.location,baseDir:"",sourceInfo:{},disableModelInvocation:x.disableModelInvocation})),R=
|
|
8
|
+
`),e.trim()}s(Qn,"stripScaffolding");async function Pe(t,e,r,n,i="replace"){let o=["# Environment",`Working directory: ${e}`,r.isGitRepo?"Git repository: yes":"Not a git repository"];r.isGitRepo&&r.branch&&o.push(`Branch: ${r.branch}`),o.push(`Platform: ${r.platform}`);let l=o.join(`
|
|
9
|
+
`),a=!!n?.skillMetas?.length||!!n?.inlinedSkills?.length,d="";if(a){let f=[];if(n?.skillMetas?.length){let k=n.skillMetas.map(x=>({name:x.name,description:x.description,filePath:x.location,baseDir:"",sourceInfo:{},disableModelInvocation:x.disableModelInvocation})),R=Gn(k).match(/<skill>[\s\S]*?<\/skill>/g);R&&f.push(...R)}for(let k of n?.inlinedSkills??[])f.push(`<skill><name>${M(k.name)}</name><description>${M(k.description)}</description><content>${M(k.content)}</content></skill>`);d=`
|
|
10
10
|
|
|
11
11
|
${["The following skills provide specialized instructions for specific tasks.","Use the read tool to load a skill's file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>",...f,"</available_skills>"].join(`
|
|
12
12
|
`)}`}let u=`
|
|
@@ -15,21 +15,21 @@ ${t.systemPrompt}
|
|
|
15
15
|
</agent_instructions>`,c="";if(n?.contextFiles?.length){let f=["<project_context>","","Project-specific instructions and guidelines:",""];for(let S of n.contextFiles)f.push(`<project_instructions path="${M(S.path)}">`),f.push(S.content),f.push("</project_instructions>"),f.push("");f.push("</project_context>"),c=`
|
|
16
16
|
|
|
17
17
|
${f.join(`
|
|
18
|
-
`)}`}let g=
|
|
18
|
+
`)}`}let g=Kn(t),m=i==="inherit"?n?.parentSystemPrompt:i==="custom"?n?.customSystemPrompt:void 0,p=m&&Qn(m);return{prefix:`${p?`${p}
|
|
19
19
|
|
|
20
20
|
${l}`:l}${c}`,identity:`${g}
|
|
21
|
-
${u}`,skills:d}}s(Pe,"buildAgentPrompt");function
|
|
21
|
+
${u}`,skills:d}}s(Pe,"buildAgentPrompt");function Kn(t){let e=t.displayName?.trim(),r=e?` display_name="${M(e)}"`:"",n=`name="${M(t.name)}"${r}`,i=t.description.trim();return i?`<active_agent ${n}>
|
|
22
22
|
${M(i)}
|
|
23
|
-
</active_agent>`:`<active_agent ${n}/>`}s(
|
|
23
|
+
</active_agent>`:`<active_agent ${n}/>`}s(Kn,"buildActiveAgentTag");function M(t){return t.replace(/</g,"<").replace(/>/g,">")}s(M,"escapeXml");import{existsSync as zn,readFileSync as Yn,realpathSync as Vn}from"node:fs";import{homedir as be}from"node:os";import{join as G,resolve as W}from"node:path";import{loadSkills as Xn,loadSkillsFromDir as Bt}from"@earendil-works/pi-coding-agent";function Gt(t){let e=W(t),r=Jn(e,Bt),n=Bt({dir:G(be(),".agents","skills"),source:"agents"}),i=Qt(n.skills,G(be(),".agents","skills")),o=Xn({cwd:e,agentDir:G(be(),".pi","agent"),skillPaths:[],includeDefaults:!0}),l=new Set,a=new Set,d=[];for(let u of[...r,...i,...o.skills]){let c=er(u.filePath);a.has(c)||l.has(u.name)||(l.add(u.name),a.add(c),d.push(u))}return d}s(Gt,"loadAllSkills");function Jn(t,e){let r=Zn(t),n=[],i=t;for(;;){let o=G(i,".agents","skills"),l=e({dir:o,source:"agents"});if(n.push(...Qt(l.skills,o)),i===r)break;let a=W(i,"..");if(a===i)break;i=a}return n}s(Jn,"loadAncestorAgentsSkills");function Qt(t,e){let r=W(e);return t.filter(n=>W(n.filePath,"..")!==r)}s(Qt,"filterRootMdFiles");function Zn(t){let e=W(t);for(;;){if(zn(G(e,".git")))return e;let r=W(e,"..");if(r===e)return e;e=r}}s(Zn,"findGitRoot");function er(t){try{return Vn(t)}catch{return t}}s(er,"canonicalizePath");async function Kt(t,e){let r=Gt(e);return t.map(n=>{if(_e(n))return{name:n,description:"",content:`(Skill "${n}" skipped: name contains path traversal characters)`};let i=r.find(o=>o.name===n);if(!i)return{name:n,description:"",content:`(Skill "${n}" not found in .pi/skills/, .agents/skills/, or global skill locations)`};try{return{name:n,description:i.description,content:Yn(i.filePath,"utf-8").trim()}}catch{return{name:n,description:"",content:`(Skill "${n}" not found in .pi/skills/, .agents/skills/, or global skill locations)`}}})}s(Kt,"inlineSkills");async function zt(t,e){let r=Gt(e);return t.map(n=>{let i=r.find(o=>o.name===n);return i?{name:n,description:i.description,location:i.filePath,disableModelInvocation:i.disableModelInvocation}:{name:n,description:`(Skill "${n}" not found)`,location:"",disableModelInvocation:!1}})}s(zt,"loadSkillMeta");async function Yt(t,e,r){try{let n=await t.exec("git",e,{cwd:r,timeout:Ne});return n.code===0?n.stdout.trim():null}catch{return null}}s(Yt,"execGit");async function rr(t,e){let n=await Yt(t,["rev-parse","--is-inside-work-tree"],e)==="true",i=n?await Yt(t,["branch","--show-current"],e):null;return{isGitRepo:n,branch:i,platform:process.platform}}s(rr,"detectEnv");async function ir(t,e,r,n,i,o){let l=Je(),a=n?.includeContextFiles??o,d={};if(i==="inherit")try{d.parentSystemPrompt=t.getSystemPrompt()}catch(u){r(`Failed to get parent system prompt: ${y(u)}. Falling back to replace mode.`)}if(i==="custom")try{let u=tr.readFileSync(l,"utf-8").trim();u?d.customSystemPrompt=u:r(`Custom prompt file is empty: ${l}. Falling back to replace mode.`)}catch(u){u?.code==="ENOENT"?r(`Custom prompt file not found: ${l}. Falling back to replace mode.`):r(`Failed to read custom prompt file: ${y(u)}. Falling back to replace mode.`)}if(a)try{d.contextFiles=nr({cwd:e,agentDir:E()})}catch{}return d}s(ir,"resolveSystemPromptSources");async function sr(t,e,r,n,i,o,l){let a={...l},d=e?.inlinedSkills??[];if(d.length>0&&(a.inlinedSkills=await Kt(d,n)),Array.isArray(r.skills)&&(a.skillMetas=await zt(r.skills,n)),e)return await Pe(e,n,i,a,o);let u=mt.get("general-purpose");if(!u)throw new Error(`No fallback config available for unknown type "${t}"`);return await Pe({...u,name:t},n,i,a,o)}s(sr,"buildPrompt");function or(t){return t.filter(e=>!!e?.trim()).join(`
|
|
24
24
|
|
|
25
|
-
`)}s(
|
|
26
|
-
`):""}s(
|
|
27
|
-
`)}s(
|
|
28
|
-
`)}s(
|
|
25
|
+
`)}s(or,"joinPromptSections");function ar(t,e){return t!==null&&t!==""?t:e}s(ar,"branchName");function Vt(t,e,r,n){let i=t&&e?ar(r,n):void 0;return i?["","## Worktree branch","",`You are working in a git worktree on branch \`${i}\`.`,"Every commit you make and every merge you run lands on THIS branch \u2014 never on `main` or any other branch.","Do NOT switch branches and do NOT merge into `main` yourself. Report the branch name in your final response so the orchestrator can merge it with the merge_cowboy_branch tool."].join(`
|
|
26
|
+
`):""}s(Vt,"buildWorktreeBranchSection");function lr(){return["## Steering & Mid-Run Instructions","- You may receive additional instructions or steering messages while working (from the user or the orchestrator).","- Always treat mid-run steering and follow-up instructions as having higher priority than your original initial prompt.","- In your final report (written to the result file), you MUST explicitly disclose any steering or direction changes you received during implementation.","- If steering or code review comments caused you to diverge from, modify, or abandon parts of the original goal, clearly explain what changed and why, so the orchestrator understands that the divergence was intentional and requested."].join(`
|
|
27
|
+
`)}s(lr,"buildSteeringInstructions");function dr(t){return["","## Your report","","When the task is done \u2014 every change committed, every check run \u2014 write your complete final answer, once, to the file:",t,"","That write is your last action. The parent session reads the file as your deliverable as soon as it stops changing, so an edit or a rewrite after it is announced to the parent as a separate report. Verify before you write, not after; then reply with a one-line confirmation."].join(`
|
|
28
|
+
`)}s(dr,"buildResultInstruction");async function Xt(t){let{pi:e,ctx:r,cwd:n,notify:i}=t,o=await rr(e,n),l=await ir(r,n,i,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),a=await sr(t.type,t.agentConfig,t.config,n,o,t.globalSystemPromptMode,l);return or([a.prefix,a.identity,a.skills,Vt(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),lr(),dr(t.resultFile),Ut(t.agentGuidance)])}s(Xt,"buildSubagentSystemPrompt");function Jt(t,e){let r=Object.entries(e??{});return r.length===0?null:(N(t,`${r.map(([n,i])=>`export ${n}=${Be(i)}`).join(`
|
|
29
29
|
`)}
|
|
30
|
-
`),t)}s(Zt,"stageLaunchEnv");function pr(t,e){let r=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||r.length>0?{kind:"none"}:{kind:"default"}}s(pr,"resolveSkillMode");function gr(t,e,r){let n=new Map,i=s((o,l)=>{let a=o.toLowerCase(),d=n.get(a);d===void 0?n.set(a,l):d!==l&&n.set(a,null)},"addSource");for(let o of e.packages){let l=typeof o=="string"?o:o.source,a=en(l);a&&i(a,l)}for(let o of e.extensionPaths){let l=en(o);l&&i(l,o)}return t.map(o=>{if(mr(o)||fr(o,r))return o;let l=hr(o),a=n.get(l.toLowerCase());if(a===null)throw new Error(`Extension entry "${o}" is ambiguous in pi settings; more than one source matches its name. The agent did not start.`);if(a===void 0)throw new Error(`Extension entry "${o}" is not in the pi settings and is not an npm:, git:, or path source. The agent did not start.`);return a})}s(gr,"resolveExtensionSources");function mr(t){return t.startsWith("npm:")||t.startsWith("git:")}s(mr,"isPiExtensionSource");function fr(t,e){return D.isAbsolute(t)?Ae.existsSync(t):Ae.existsSync(D.resolve(e,t))}s(fr,"isExistingPath");function hr(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}s(hr,"extensionEntryName");function en(t){let e=t.split("#",1)[0].replace(/[\\/]$/,"");if(!e)return;if(e.startsWith("npm:")){let o=e.slice(4);return(o.startsWith("@")?o.split("/",2).at(1)?.split("@",1)[0]:o.split("@",1)[0])?.toLowerCase()}let r=e.startsWith("git:")?e.slice(4):e,n=D.basename(r),i=D.basename(n,D.extname(n));return i==="index"?D.basename(D.dirname(r))||void 0:i||void 0}s(en,"extensionSourceName");function tn(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}s(tn,"notifyLaunchConfigurationError");function yr(t){let e=t,r=e.sessionFile??e.sessionManager?.getSessionFile?.();if(r)return r}s(yr,"resolveParentSessionFile");function nn(t,e){let r=new Set;for(let n of t){if(!n)throw new Error(`Empty entry in ${e} is not supported`);r.add(n)}return[...r]}s(nn,"resolveToolCliEntries");function wr(t,e,r,n){switch(t){case"pi":case"pig":case"pi-bolt":return{...e,family:"pi",...r};case"opencode":return{...e,family:"opencode"};case"codex":return{...e,family:"codex",...n};case"claude":return{...e,family:"claude"};default:{if(A().get(t)===void 0)throw new Error(`no harness registered for "${t}"`);return{...e,family:"plugin"}}}}s(wr,"buildLaunchRequest");function vr(t,e){return A().require(t).buildArgs(e)}s(vr,"buildHarnessArgs");function Sr(t,e,r,n,i){let o={};for(let[l,a]of Object.entries({...t,...e})){if(!qe(l)){n(`Ignoring environment variable "${l}" for ${i}: not a valid variable name`);continue}if(Be(l)){n(`Ignoring environment variable ${l} for ${i}: it is reserved and cannot be overridden`);continue}if(r.includes(l)){n(`Ignoring environment variable ${l} for ${i}: it is reserved by the ${i} harness and cannot be overridden`);continue}if(Ue(a)){n(`Ignoring environment variable ${l} for ${i}: its value contains a control character`);continue}o[l]=a}return o}s(Sr,"resolveLaunchEnv");function kr(t,e){return[...t===void 0?[]:Qe[t],...e===void 0?[]:Ge(e)]}s(kr,"familyReservations");async function rn(t,e,r,n,i){let o=P(),l=i.cwd??e.cwd,a=St(r,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),d=vt(r),u=i.harness,c=pr(a.skills,d),g=[],m=s(w=>{g.push(w)},"bufferNotify"),p={kind:"default"};if(a.extensions===!1)p={kind:"none"};else if(Array.isArray(a.extensions))if(a.extensions.length===0)p={kind:"none"};else try{let w=cr.create(l,E(),{projectTrusted:i.projectTrusted!==!1});p={kind:"paths",paths:gr(a.extensions,{packages:w.getPackages(),extensionPaths:w.getExtensionPaths()},l)}}catch(w){let ge=w instanceof Error?w.message:String(w);tn(e,ge)}let h=ze(u),f={kind:"default"};try{let w=h===void 0?void 0:d?.toolsByFamily?.[h];w?.tools===!1?f={kind:"none"}:Array.isArray(w?.tools)?f={kind:"include",names:nn(w.tools,"tools")}:w?.excludeTools?.length&&(f={kind:"exclude",names:nn(w.excludeTools,"excludeTools")})}catch(w){let ge=w instanceof Error?w.message:String(w);tn(e,ge)}let S=A().get(u),k=Sr(o.harnessEnv(u),h===void 0?void 0:d?.envByFamily?.[h],kr(h,S),m,u),v=i.agentId??"unknown",R=Me(v);V(R);let x=I(v),N=De(v),Ce=je(v),Dn=Zt(Oe(v),k),Te=await Jt({pi:t,ctx:e,type:r,agentConfig:d,config:a,cwd:l,globalSystemPromptMode:o.agent.systemPromptMode,globalIncludeContextFiles:o.agent.includeContextFiles,worktreePath:i.worktree?.path,expectedBranch:i.worktree?.branch,agentGuidance:i.agentGuidance,resultFile:x,notify:m});try{_(N,Te)}catch(w){throw new Error(`cannot write the system prompt file ${N}: ${y(w)}. The agent did not start.`,{cause:w})}if(!Ae.existsSync(N))throw new Error(`the system prompt file is missing after the write: ${N}. The agent did not start.`);_(Ce,n);let Le=i.fork?yr(e):void 0;i.fork&&Le===void 0&&m("Fork session is enabled, but no parent session file is available; launching without --fork");let On={subagentId:v,systemPromptFile:N,taskFile:Ce,resultFile:x,modelKey:O(i.modelChoice)??null,thinking:i.modelChoice?.thinking??null,toolSelection:f,envFile:Dn},jn={forkSessionFile:Le??null,skills:c,extensions:p,projectTrusted:i.projectTrusted!==!1},$n={projectTrusted:i.projectTrusted!==!1},Fe=wr(u,On,jn,$n),Hn=vr(u,Fe);for(let w of g)e.ui.notify(`[cowboy] ${w}`,"warning");return{name:v,cwd:l,systemPrompt:Te,piArgs:Hn,launch:Fe,harness:u}}s(rn,"buildLaunchPlan");var xe="Agent manager disposed before the queued agent could start.";function on(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}s(on,"createRun");function an(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(an,"startRun");function ln(t){return t.shell==="dropped"||t.process.kind!=="launching"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt},shell:t.shell}}s(ln,"activateRun");function dn(t,e,r){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"stopped",initiator:e},completedAt:r},shell:t.shell}}s(dn,"abortQueuedRun");function un(t,e,r){return t.shell!=="held"?t:t.process.kind==="queued"?{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:e},completedAt:r},shell:t.shell}:t.process.kind==="launching"?{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:{kind:"failed",error:e},completedAt:r},shell:t.shell}:t}s(un,"failStart");function ae(t,e,r){return t.shell==="dropped"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:{kind:"settling",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,terminal:e,completedAt:r},shell:"held"}}s(ae,"enterSettling");function cn(t){return t.shell!=="held"||t.process.kind!=="settling"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:t.process.terminal,completedAt:t.process.completedAt},shell:t.shell}}s(cn,"finishSettling");function pn(t,e){return t.shell!=="held"||t.process.kind!=="settling"&&t.process.kind!=="settled"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(pn,"reviveRun");function gn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:xe},completedAt:e},shell:t.shell}}s(gn,"disposeQueuedRun");function mn(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}s(mn,"disposeLiveRun");function Re(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:Ie(t,e)}}s(Re,"dropRun");function sn(t,e,r,{launch:n,retention:i}){let o={phase:"settled",startedAt:t,...n===void 0?{}:{launch:n},...i===void 0?{}:{worktreeRetentionReason:i}};switch(e.kind){case"completed":return{...o,status:"completed",result:e.result,completedAt:r};case"failed":return{...o,status:"error",error:e.error,completedAt:r};case"stopped":return{...o,status:"stopped",completedAt:r,stop:{initiator:e.initiator}}}}s(sn,"settledStartedOutcome");function Pr(t,e,r,{retention:n}){let i={phase:"never-started",queuedAt:t,...n===void 0?{}:{worktreeRetentionReason:n}};switch(e.kind){case"failed":return{...i,status:"error",error:e.error,completedAt:r};case"stopped":return{...i,status:"stopped",completedAt:r,stop:{initiator:e.initiator}}}}s(Pr,"settledNeverStartedOutcome");function br(t,e){switch(t.kind){case"queued":return{phase:"queued",queuedAt:t.queuedAt};case"launching":case"active":return{phase:"spawned",startedAt:t.startedAt,...e.launch===void 0?{}:{launch:e.launch}};case"settling":return sn(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?sn(t.startedAt,t.terminal,t.completedAt,e):Pr(t.queuedAt,t.terminal,t.completedAt,e)}}s(br,"projectProcess");function Ie(t,e){return t.shell==="dropped"?t.lifecycle:br(t.process,e)}s(Ie,"projectLifecycle");import*as fn from"node:fs";import*as hn from"node:path";function yn(t){let{spawn:e,hostRef:r,transport:n}=t,i=Ar(e),o=hn.dirname(i.resultFile);V(o),fn.rmSync(i.resultFile,{force:!0});let l=oe({host:n.createHost(b()),resultFile:i.resultFile,supervisorOptions:t.supervisorOptions,transport:n});l.adopt(r),t.attachSupervisor(l,i),t.rebindParentSignal(),l.watch().then(a=>t.reportOutcome(l,a))}s(yn,"reviveSettledRun");function Ar(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??I(t.id)}}s(Ar,"resumeLaunch");var le=j("session");function xr(t,e){let{type:r,options:n}=t;return{id:"",lifecycle:{phase:"queued",queuedAt:Date.now()},display:{type:r,description:n.description,taskSlug:n.taskSlug,invocation:n.invocation,orchestration:n.orchestration,worktree:n.worktree},execution:{promise:e,abortController:new AbortController,host:n.hostRef}}}s(xr,"buildAgentSpawn");var Ee=class{static{s(this,"CompletionGate")}resolve;promise;constructor(){this.promise=new Promise(e=>{this.resolve=e})}open(e){let r=this.resolve;r&&(this.resolve=void 0,r(e))}},de=class{static{s(this,"SubagentSession")}id;args;deps;gate=new Ee;stableSpawn;run;launchState;retention;supervisor;parentBinding;constructor({id:e,args:r,deps:n}){this.id=e,this.args=r,this.deps=n,this.stableSpawn=xr(r,this.gate.promise),this.stableSpawn.id=e;let i=this.stableSpawn.lifecycle;this.run=on(i.phase==="queued"?i.queuedAt:Date.now()),T().add(this.stableSpawn),this.bindParentSignal()}get spawn(){return this.stableSpawn}get promise(){return this.gate.promise}isQueued(){return this.run.shell==="held"&&this.run.process.kind==="queued"}isLaunching(){return this.run.shell!=="dropped"&&this.run.process.kind==="launching"}isActive(){return this.run.shell!=="dropped"&&this.run.process.kind==="active"}isSettled(){return this.run.shell==="held"&&(this.run.process.kind==="settling"||this.run.process.kind==="settled")}commit(e){this.run=e,this.spawn.lifecycle=Ie(e,this.artifacts)}get artifacts(){return{launch:this.launchState,retention:this.retention}}start(e){this.isQueued()&&(e&&this.deps.pools.reserve(this.id,e),this.commit(an(this.run,Date.now())),this.launch())}rollbackStart(){this.commit(Re(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(un(this.run,y(e),Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn)}async steer(e){if(this.isQueued())return{kind:"refused",reason:`agent ${this.id} is queued \u2014 it has no pane yet, so it cannot receive a message. Wait for a concurrency slot (or stop it).`};let r=this.spawn.execution.host;if(!r)return{kind:"refused",reason:this.isLaunching()?`agent ${this.id} is still starting up \u2014 its pane does not exist yet, so it cannot receive a message. Retry in a moment.`:this.spawn.lifecycle.phase==="never-started"?`agent ${this.id} never started, so it has no pane and there is nobody to receive the message.`:`agent ${this.id} has no pane (it was cleaned up), so there is nobody to receive the message.`};let n=this.isSettled(),i;try{i=await this.deps.transport.createHost(b()).deliver(r,e)}catch(o){i={kind:"not-submitted",detail:y(o)}}if(i.kind==="not-submitted")return{kind:"refused",reason:`the message could not be delivered to agent ${this.id} \u2014 ${i.detail}`};if(n)try{this.revive(r)}catch(o){return{kind:"delivered-not-revived",reason:`the message reached its pane, but the agent could not be revived: ${y(o)}. No completion message will arrive \u2014 read the pane for the result.`}}return{kind:"delivered"}}revive(e){let r=Date.now();yn({spawn:this.spawn,hostRef:e,transport:this.deps.transport,supervisorOptions:this.supervisorOptions(),attachSupervisor:s((n,i)=>{this.supervisor?.detach(),this.deps.pools.reacquire(this.id,{harness:this.args.options.harness,modelKey:O(this.args.options.modelChoice)}),this.supervisor=n,this.launchState=i,this.retention=void 0,this.commit(pn(this.run,r))},"attachSupervisor"),rebindParentSignal:s(()=>this.bindParentSignal(),"rebindParentSignal"),reportOutcome:s((n,i)=>{this.applySupervisorOutcome(n,i)},"reportOutcome")})}async abort(e){let r=this.isLaunching()||this.isActive(),n=this.run;return le.debug("abort requested",{initiator:e,process:n.shell==="dropped"?"dropped":n.process.kind,shell:n.shell,stopIssued:r}),this.isQueued()?(this.deps.pools.cancelQueued(this.id),this.commit(dn(this.run,e??"agent",Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn),!0):!this.isLaunching()&&!this.isActive()||(this.spawn.execution.abortController.abort(),await this.stopPaneProcess(),!this.isLaunching()&&!this.isActive())?!1:(this.commit(ae(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}drop(){this.commit(Re(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,B(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit(gn(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(mn(this.run)),this.gate.open("")),this.supervisor?.abandon(),this.supervisor=void 0,this.detachParentBinding()}async launch(){let e={kind:"none"},r={kind:"none"},n;try{let i=this.deps.transport.createHost(this.args.pi),o=this.deps.transport.createPane(this.args.pi),{pi:l,ctx:a,type:d,prompt:u,options:c}=this.args,g=c.hostRef;if(!g&&c.worktree?.kind==="owned"){let v;try{v=await Ft.allocate(l,{naming:{kind:"generated",taskSlug:c.taskSlug??d,id:this.spawn.id},parentCwd:a.cwd,worktreeRoot:P().agent.worktreeRoot,materialization:it(),dirtyCheckout:At(d),notify:s((R,x)=>a.ui.notify(R,x),"notify"),host:i})}catch(R){throw c.worktree=void 0,this.spawn.display.worktree=void 0,R}v.worktree?(c.worktree={kind:"owned",...v.worktree},this.spawn.display.worktree=c.worktree):(c.worktree=void 0,this.spawn.display.worktree=void 0),g=v.hostRef}let m=c.worktree?.branch??K(c.taskSlug??Q(d),this.id),p=await rn(l,a,d,u,{agentId:this.id,harness:c.harness,modelChoice:c.modelChoice,fork:c.fork,cwd:c.worktree?.path,projectTrusted:c.projectTrusted,description:c.description,worktree:c.worktree,agentGuidance:c.orchestration.guidance}),h={resultFile:p.launch.resultFile};this.launchState=h,n=p.cwd;let f=A(),S=f.require(p.harness);if(g=g??await i.hostAt({unit:"pane",cwd:p.cwd,label:c.taskSlug??d,name:m}),e={kind:"held",host:i,ref:g},!this.isLaunching())return;this.spawn.execution.host=g,this.spawn.execution.harness=p.harness,await S.prepare({pi:l,pane:o,paneId:g.paneId,cwd:p.cwd,launch:p.launch,config:f.config(p.harness)});let k=oe({host:i,resultFile:h.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=k,await k.start({name:m,cwd:p.cwd,piArgs:p.piArgs,agentMultiplexerKind:S.agentMultiplexerKind,taskSlug:c.taskSlug},g),e={kind:"committed"},!this.isLaunching())return;this.commit(ln(this.run)),k.watch().then(v=>this.applySupervisorOutcome(k,v))}catch(i){r={kind:"failed",error:i}}finally{e.kind==="held"&&await e.host.release(e.ref,"placement").catch(()=>{})}if(r.kind==="failed"&&this.isLaunching()){let i=this.spawn.execution.harness;if(i!==void 0)try{await A().require(i).teardown({pi:this.args.pi,paneId:this.spawn.execution.host?.paneId??null,cwd:n??null,subagentId:this.spawn.id})}catch(o){le.warn("harness teardown failed after a failed launch",{spawnId:this.spawn.id,harness:i,error:y(o)})}this.commit(ae(this.run,{kind:"failed",error:y(r.error)},Date.now())),await this.settle()}}supervisorOptions(){return{stopInitiator:"agent",onFollowUp:s(e=>this.deps.onFollowUpResult(this.spawn,e),"onFollowUp")}}resultFilePath(){return this.launchState?.resultFile??I(this.id)}async applySupervisorOutcome(e,r){if(!(!this.isActive()||this.supervisor!==e))switch(le.debug("outcome mapped",{kind:r.kind}),r.kind){case"completed":{this.commit(ae(this.run,{kind:"completed",result:r.deliverable||""},Date.now())),await this.settle();return}case"stopped":await this.abort(r.initiator)}}async stopPaneProcess(){let e=this.supervisor;if(e){this.supervisor=void 0,await e.stop(2e3);return}let r=this.spawn.execution.host;r&&await this.deps.transport.createHost(b()).stop(r,{interruptGraceMs:2e3,confirmMs:1e4})}settleChain=Promise.resolve();async settle(){if(this.run.shell!=="held"||this.run.process.kind!=="settling")return;let e=this.settleChain,r,n=new Promise(i=>{r=i});this.settleChain=n,await e;try{await this.runSettlePass()}finally{r()}}async runSettlePass(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settling")return;let r=Xe(this.spawn.lifecycle),n=await this.readWorktreeRetention();this.deps.pools.release(this.id),this.deps.onRunEnded(this.spawn),this.run===e&&this.detachParentBinding(),this.gate.open(r),this.run===e&&(this.retention=n??void 0,this.commit(cn(this.run)))}async readWorktreeRetention(){let e=this.spawn.display.worktree;return e?.kind!=="owned"?null:mt(b(),e.path)}detachParentBinding(){let e=this.parentBinding;e&&(this.parentBinding=void 0,e.signal.removeEventListener("abort",e.handler))}bindParentSignal(){if(this.parentBinding)return;let e=this.args.options.signal;if(!e||e.aborted)return;let r=s(()=>{le.debug("parent signal fired",{initiator:"user"}),this.abort("user")},"handler");e.addEventListener("abort",r,{once:!0}),this.parentBinding={signal:e,handler:r}}};function vn(t){return{createHost:s(()=>t.host,"createHost"),createPane:s(()=>t.pane,"createPane"),createPlacements:s(()=>t.placements,"createPlacements"),createDeliverable:s(e=>new re(e),"createDeliverable")}}s(vn,"createAgentManagerTransport");var wn=j("manager");function Rr(t){if(t.outcome.kind==="refused"){let e=t.outcome.reason;return e.kind==="dirty"||e.kind==="unverifiable"?e:void 0}if(t.worktree.kind==="removal-failed")return{kind:"unverifiable",detail:`the removal was not confirmed (${t.worktree.detail})`}}s(Rr,"retentionForReport");var ue=class{constructor(e,r){this.transport=r;this.pools=e,this.registry=new te({listAgents:s(()=>this.listAgents(Y),"listAgents"),spawn:s((n,i,o)=>this.spawn(b(),J(),n,i,o),"spawn"),getSpawn:s(n=>this.getSpawn(n),"getSpawn"),findTaskAttempts:s(n=>this.transport.createHost(b()).findAttempts(n),"findTaskAttempts"),queuePosition:s(n=>this.pools.queuePosition(n),"queuePosition")})}transport;static{s(this,"AgentManager")}sessions=new Map;onComplete;onFollowUp;teardowns=new Map;pools;registry;getRegistry(){return this.registry}setConcurrency(e){this.pools.setConcurrency(e)}setOnComplete(e){this.onComplete=e}setOnFollowUp(e){this.onFollowUp=e}mintSpawnId(){return T().mint()}spawn(e,r,n,i,o){let l=o.spawnId,{requestedHarness:a,...d}=o,u={...d,harness:xt(n,a)},c={pi:e,ctx:r,type:n,prompt:i,options:u},g=this.pools.admitSpawn({harness:u.harness,modelKey:O(u.modelChoice)},{id:l,start:s(p=>this.startSession(l,c,p),"start")}),m;try{m=new de({id:l,args:c,deps:{transport:this.transport,pools:this.pools,onRunEnded:s(p=>this.notifyComplete(p),"onRunEnded"),onFollowUpResult:s((p,h)=>this.notifyFollowUp(p,h),"onFollowUpResult")}})}catch(p){throw this.pools.release(l),p}if(this.sessions.set(l,m),u.signal?.aborted)return m.abort("user"),l;if(g.kind==="queue")return l;try{m.start(g.reservation)}catch(p){throw m.rollbackStart(),this.pools.release(l),this.sessions.delete(l),T().drop(l),p}return l}startSession(e,r,n){let i=this.sessions.get(e);if(!i||!i.isQueued())return!1;try{i.start(n)}catch(o){i.settleStartFailure(o)}return!0}async steer(e,r){if(this.teardowns.has(e))return{kind:"refused",reason:`agent ${e} is being cleaned up, so its worktree is on its way out \u2014 wait for the report before steering it.`};let n=this.sessions.get(e);return n?n.steer(r):{kind:"refused",reason:`no live session tracks agent ${e} \u2014 check the id from its spawn or completion result (a cleaned-up agent is gone for good).`}}getSpawn(e){return T().get(e)}assets(){let e=b();return Ut(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=Ve){return T().list(e).sort((r,n)=>fe(n.lifecycle)-fe(r.lifecycle))}async abort(e,r){return await this.sessions.get(e)?.abort(r)??!1}notifyComplete(e){try{this.onComplete?.(e)}catch(r){wn.warn("completion notification failed",{spawnId:e.id,detail:y(r)})}}notifyFollowUp(e,r){try{this.onFollowUp?.(e,r)}catch(n){wn.warn("follow-up notification failed",{spawnId:e.id,detail:y(n)})}}recordRetention(e,r){let n=e.lifecycle;q(n)&&(n.worktreeRetentionReason=r)}dropSpawn(e){this.sessions.get(e.id)?.drop(),this.sessions.delete(e.id),B(I(e.id)),T().drop(e.id)}async cleanup(e,r){let n=this.runCleanup(e,this.teardowns.get(e),r);this.teardowns.set(e,n);try{return await n}finally{this.teardowns.get(e)===n&&this.teardowns.delete(e)}}async runCleanup(e,r,n){await r?.catch(()=>{}),Z()?.dropNudge(e);let i=this.getSpawn(e)!==void 0,o=await Lt(this.assets()).cleanupAgent(e,{getSpawn:s(a=>this.getSpawn(a),"getSpawn"),dropSpawn:s(a=>this.dropSpawn(a),"dropSpawn")},n),l=this.getSpawn(e);if(l!==void 0){let a=Rr(o);a!==void 0&&this.recordRetention(l,a)}return i&&o.outcome.kind==="torn-down"&&B(I(e)),o}dispose(){this.pools.clearQueue();for(let e of this.sessions.values())e.settleForDispose();this.sessions.clear()}};var Ir=200,ce=class{static{s(this,"SpawnCoordinator")}manager;backgroundAgentIds=new Set;pendingNudges=new Set;pendingFollowUps=new Map;nudgeTimer=null;disposed=!1;registry;constructor(e){this.manager=e,this.registry=e.getRegistry()}async spawn(e,r){let n=await this.registry.admit(r);if(n.status==="rejected")throw await this.inFlightError(r.taskSlug,n);let i=n.agentId,o=this.manager.getSpawn(i);return o.execution.spawnCtx=e,this.announceSpawn(e,o),r.runInBackground?this.backgroundAgentIds.add(i):await o.execution.promise,{agentId:i,spawn:o}}announceSpawn(e,r){if(!e.hasUI)return;let n=r.lifecycle;if(q(n))return;let i=n.phase==="queued"?"Queued":"Spawned";Tt(e.ui).succeeded(`${i} agent ${r.id} (${r.display.type})`)}async inFlightError(e,r){let n=this.manager.getSpawn(r.conflictingId);if(n)return new F({kind:"spawn",spawn:n},e);let i=await U().host.findAttempts(e),o=ne([],i);if(o.kind!=="none")return new F(o,e);let l={name:r.conflictingId};return new F({kind:"multiplexer",attempt:l},e)}dropNudge(e){this.pendingNudges.delete(e),this.pendingFollowUps.delete(e)}scheduleNudge(e){this.pendingNudges.add(e),this.ensureNudgeTimer()}onAgentFollowUp(e,r){this.backgroundAgentIds.has(e.id)&&(this.pendingFollowUps.set(e.id,r),this.ensureNudgeTimer())}ensureNudgeTimer(){this.nudgeTimer||(this.nudgeTimer=setTimeout(()=>{this.nudgeTimer=null;let e=[...this.pendingNudges];this.pendingNudges.clear();let r=[...this.pendingFollowUps];this.pendingFollowUps.clear();for(let n of e)this.emitIndividualNudge(n);for(let[n,i]of r)this.emitFollowUp(n,i)},Ir))}onAgentComplete(e){this.backgroundAgentIds.has(e.id)&&(Er(e)||this.scheduleNudge(e.id))}dispose(){this.nudgeTimer&&(clearTimeout(this.nudgeTimer),this.nudgeTimer=null),this.pendingNudges.clear(),this.pendingFollowUps.clear(),this.backgroundAgentIds.clear(),this.disposed=!0}emitFollowUp(e,r){if(this.disposed||!$())return;let n=b(),i=this.manager.getSpawn(e);if(!i)return;let o=Se(i,{includeRunInfo:!0,includeStatus:!0}),l=`[Cowboy agent "${i.display.type}" ${i.id} reported again after settling]`;try{n.sendMessage({customType:"subagent-result",content:`${l}
|
|
30
|
+
`),t)}s(Jt,"stageLaunchEnv");function cr(t,e){let r=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||r.length>0?{kind:"none"}:{kind:"default"}}s(cr,"resolveSkillMode");function pr(t,e,r){let n=new Map,i=s((o,l)=>{let a=o.toLowerCase(),d=n.get(a);d===void 0?n.set(a,l):d!==l&&n.set(a,null)},"addSource");for(let o of e.packages){let l=typeof o=="string"?o:o.source,a=Zt(l);a&&i(a,l)}for(let o of e.extensionPaths){let l=Zt(o);l&&i(l,o)}return t.map(o=>{if(gr(o)||mr(o,r))return o;let l=fr(o),a=n.get(l.toLowerCase());if(a===null)throw new Error(`Extension entry "${o}" is ambiguous in pi settings; more than one source matches its name. The agent did not start.`);if(a===void 0)throw new Error(`Extension entry "${o}" is not in the pi settings and is not an npm:, git:, or path source. The agent did not start.`);return a})}s(pr,"resolveExtensionSources");function gr(t){return t.startsWith("npm:")||t.startsWith("git:")}s(gr,"isPiExtensionSource");function mr(t,e){return D.isAbsolute(t)?Ae.existsSync(t):Ae.existsSync(D.resolve(e,t))}s(mr,"isExistingPath");function fr(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}s(fr,"extensionEntryName");function Zt(t){let e=t.split("#",1)[0].replace(/[\\/]$/,"");if(!e)return;if(e.startsWith("npm:")){let o=e.slice(4);return(o.startsWith("@")?o.split("/",2).at(1)?.split("@",1)[0]:o.split("@",1)[0])?.toLowerCase()}let r=e.startsWith("git:")?e.slice(4):e,n=D.basename(r),i=D.basename(n,D.extname(n));return i==="index"?D.basename(D.dirname(r))||void 0:i||void 0}s(Zt,"extensionSourceName");function en(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}s(en,"notifyLaunchConfigurationError");function hr(t){let e=t,r=e.sessionFile??e.sessionManager?.getSessionFile?.();if(r)return r}s(hr,"resolveParentSessionFile");function tn(t,e){let r=new Set;for(let n of t){if(!n)throw new Error(`Empty entry in ${e} is not supported`);r.add(n)}return[...r]}s(tn,"resolveToolCliEntries");function yr(t,e,r,n){switch(t){case"pi":case"pig":case"pi-bolt":return{...e,family:"pi",...r};case"opencode":return{...e,family:"opencode"};case"codex":return{...e,family:"codex",...n};case"claude":return{...e,family:"claude"};default:{if(A().get(t)===void 0)throw new Error(`no harness registered for "${t}"`);return{...e,family:"plugin"}}}}s(yr,"buildLaunchRequest");function wr(t,e){return A().require(t).buildArgs(e)}s(wr,"buildHarnessArgs");function vr(t,e,r,n,i){let o=Ve(t,e);if(o===void 0)return;let l={};for(let[a,d]of Object.entries(o)){if(!r.includes(a)){l[a]=d;continue}n(`Ignoring environment variable ${a} for ${i}: it is reserved by the ${i} harness and cannot be overridden`)}return Xe(l)}s(vr,"resolveLaunchEnv");function Sr(t,e){return[...t===void 0?[]:Ue[t],...e===void 0?[]:qe(e)]}s(Sr,"familyReservations");async function nn(t,e,r,n,i){let o=P(),l=i.cwd??e.cwd,a=vt(r,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),d=wt(r),u=i.harness,c=cr(a.skills,d),g=[],m=s(w=>{g.push(w)},"bufferNotify"),p={kind:"default"};if(a.extensions===!1)p={kind:"none"};else if(Array.isArray(a.extensions))if(a.extensions.length===0)p={kind:"none"};else try{let w=ur.create(l,E(),{projectTrusted:i.projectTrusted!==!1});p={kind:"paths",paths:pr(a.extensions,{packages:w.getPackages(),extensionPaths:w.getExtensionPaths()},l)}}catch(w){let ge=w instanceof Error?w.message:String(w);en(e,ge)}let h=Ge(u),f={kind:"default"};try{let w=h===void 0?void 0:d?.toolsByFamily?.[h];w?.tools===!1?f={kind:"none"}:Array.isArray(w?.tools)?f={kind:"include",names:tn(w.tools,"tools")}:w?.excludeTools?.length&&(f={kind:"exclude",names:tn(w.excludeTools,"excludeTools")})}catch(w){let ge=w instanceof Error?w.message:String(w);en(e,ge)}let S=A().get(u),k=vr(o.harnessEnv(u),h===void 0?void 0:d?.envByFamily?.[h],Sr(h,S),m,u),v=i.agentId??"unknown",R=Me(v);Y(R);let x=I(v),_=De(v),Ce=je(v),Mn=Jt(Oe(v),k),Te=await Xt({pi:t,ctx:e,type:r,agentConfig:d,config:a,cwd:l,globalSystemPromptMode:o.agent.systemPromptMode,globalIncludeContextFiles:o.agent.includeContextFiles,worktreePath:i.worktree?.path,expectedBranch:i.worktree?.branch,agentGuidance:i.agentGuidance,resultFile:x,notify:m});try{N(_,Te)}catch(w){throw new Error(`cannot write the system prompt file ${_}: ${y(w)}. The agent did not start.`,{cause:w})}if(!Ae.existsSync(_))throw new Error(`the system prompt file is missing after the write: ${_}. The agent did not start.`);N(Ce,n);let Le=i.fork?hr(e):void 0;i.fork&&Le===void 0&&m("Fork session is enabled, but no parent session file is available; launching without --fork");let Dn={subagentId:v,systemPromptFile:_,taskFile:Ce,resultFile:x,modelKey:O(i.modelChoice)??null,thinking:i.modelChoice?.thinking??null,toolSelection:f,envFile:Mn},On={forkSessionFile:Le??null,skills:c,extensions:p,projectTrusted:i.projectTrusted!==!1},jn={projectTrusted:i.projectTrusted!==!1},Fe=yr(u,Dn,On,jn),Hn=wr(u,Fe);for(let w of g)e.ui.notify(`[cowboy] ${w}`,"warning");return{name:v,cwd:l,systemPrompt:Te,piArgs:Hn,launch:Fe,harness:u}}s(nn,"buildLaunchPlan");var xe="Agent manager disposed before the queued agent could start.";function sn(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}s(sn,"createRun");function on(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(on,"startRun");function an(t){return t.shell==="dropped"||t.process.kind!=="launching"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt},shell:t.shell}}s(an,"activateRun");function ln(t,e,r){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"stopped",initiator:e},completedAt:r},shell:t.shell}}s(ln,"abortQueuedRun");function dn(t,e,r){return t.shell!=="held"?t:t.process.kind==="queued"?{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:e},completedAt:r},shell:t.shell}:t.process.kind==="launching"?{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:{kind:"failed",error:e},completedAt:r},shell:t.shell}:t}s(dn,"failStart");function ae(t,e,r){return t.shell==="dropped"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:{kind:"settling",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,terminal:e,completedAt:r},shell:"held"}}s(ae,"enterSettling");function un(t){return t.shell!=="held"||t.process.kind!=="settling"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:t.process.terminal,completedAt:t.process.completedAt},shell:t.shell}}s(un,"finishSettling");function cn(t,e){return t.shell!=="held"||t.process.kind!=="settling"&&t.process.kind!=="settled"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(cn,"reviveRun");function pn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:xe},completedAt:e},shell:t.shell}}s(pn,"disposeQueuedRun");function gn(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}s(gn,"disposeLiveRun");function Re(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:Ie(t,e)}}s(Re,"dropRun");function rn(t,e,r,{launch:n,retention:i}){let o={phase:"settled",startedAt:t,...n===void 0?{}:{launch:n},...i===void 0?{}:{worktreeRetentionReason:i}};switch(e.kind){case"completed":return{...o,status:"completed",result:e.result,completedAt:r};case"failed":return{...o,status:"error",error:e.error,completedAt:r};case"stopped":return{...o,status:"stopped",completedAt:r,stop:{initiator:e.initiator}}}}s(rn,"settledStartedOutcome");function kr(t,e,r,{retention:n}){let i={phase:"never-started",queuedAt:t,...n===void 0?{}:{worktreeRetentionReason:n}};switch(e.kind){case"failed":return{...i,status:"error",error:e.error,completedAt:r};case"stopped":return{...i,status:"stopped",completedAt:r,stop:{initiator:e.initiator}}}}s(kr,"settledNeverStartedOutcome");function Pr(t,e){switch(t.kind){case"queued":return{phase:"queued",queuedAt:t.queuedAt};case"launching":case"active":return{phase:"spawned",startedAt:t.startedAt,...e.launch===void 0?{}:{launch:e.launch}};case"settling":return rn(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?rn(t.startedAt,t.terminal,t.completedAt,e):kr(t.queuedAt,t.terminal,t.completedAt,e)}}s(Pr,"projectProcess");function Ie(t,e){return t.shell==="dropped"?t.lifecycle:Pr(t.process,e)}s(Ie,"projectLifecycle");import*as mn from"node:fs";import*as fn from"node:path";function hn(t){let{spawn:e,hostRef:r,transport:n}=t,i=br(e),o=fn.dirname(i.resultFile);Y(o),mn.rmSync(i.resultFile,{force:!0});let l=oe({host:n.createHost(b()),resultFile:i.resultFile,supervisorOptions:t.supervisorOptions,transport:n});l.adopt(r),t.attachSupervisor(l,i),t.rebindParentSignal(),l.watch().then(a=>t.reportOutcome(l,a))}s(hn,"reviveSettledRun");function br(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??I(t.id)}}s(br,"resumeLaunch");var le=j("session");function Ar(t,e){let{type:r,options:n}=t;return{id:"",lifecycle:{phase:"queued",queuedAt:Date.now()},display:{type:r,description:n.description,taskSlug:n.taskSlug,invocation:n.invocation,orchestration:n.orchestration,worktree:n.worktree},execution:{promise:e,abortController:new AbortController,host:n.hostRef}}}s(Ar,"buildAgentSpawn");var Ee=class{static{s(this,"CompletionGate")}resolve;promise;constructor(){this.promise=new Promise(e=>{this.resolve=e})}open(e){let r=this.resolve;r&&(this.resolve=void 0,r(e))}},de=class{static{s(this,"SubagentSession")}id;args;deps;gate=new Ee;stableSpawn;run;launchState;retention;supervisor;parentBinding;constructor({id:e,args:r,deps:n}){this.id=e,this.args=r,this.deps=n,this.stableSpawn=Ar(r,this.gate.promise),this.stableSpawn.id=e;let i=this.stableSpawn.lifecycle;this.run=sn(i.phase==="queued"?i.queuedAt:Date.now()),T().add(this.stableSpawn),this.bindParentSignal()}get spawn(){return this.stableSpawn}get promise(){return this.gate.promise}isQueued(){return this.run.shell==="held"&&this.run.process.kind==="queued"}isLaunching(){return this.run.shell!=="dropped"&&this.run.process.kind==="launching"}isActive(){return this.run.shell!=="dropped"&&this.run.process.kind==="active"}isSettled(){return this.run.shell==="held"&&(this.run.process.kind==="settling"||this.run.process.kind==="settled")}commit(e){this.run=e,this.spawn.lifecycle=Ie(e,this.artifacts)}get artifacts(){return{launch:this.launchState,retention:this.retention}}start(e){this.isQueued()&&(e&&this.deps.pools.reserve(this.id,e),this.commit(on(this.run,Date.now())),this.launch())}rollbackStart(){this.commit(Re(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(dn(this.run,y(e),Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn)}async steer(e){if(this.isQueued())return{kind:"refused",reason:`agent ${this.id} is queued \u2014 it has no pane yet, so it cannot receive a message. Wait for a concurrency slot (or stop it).`};let r=this.spawn.execution.host;if(!r)return{kind:"refused",reason:this.isLaunching()?`agent ${this.id} is still starting up \u2014 its pane does not exist yet, so it cannot receive a message. Retry in a moment.`:this.spawn.lifecycle.phase==="never-started"?`agent ${this.id} never started, so it has no pane and there is nobody to receive the message.`:`agent ${this.id} has no pane (it was cleaned up), so there is nobody to receive the message.`};let n=this.isSettled(),i;try{i=await this.deps.transport.createHost(b()).deliver(r,e)}catch(o){i={kind:"not-submitted",detail:y(o)}}if(i.kind==="not-submitted")return{kind:"refused",reason:`the message could not be delivered to agent ${this.id} \u2014 ${i.detail}`};if(n)try{this.revive(r)}catch(o){return{kind:"delivered-not-revived",reason:`the message reached its pane, but the agent could not be revived: ${y(o)}. No completion message will arrive \u2014 read the pane for the result.`}}return{kind:"delivered"}}revive(e){let r=Date.now();hn({spawn:this.spawn,hostRef:e,transport:this.deps.transport,supervisorOptions:this.supervisorOptions(),attachSupervisor:s((n,i)=>{this.supervisor?.detach(),this.deps.pools.reacquire(this.id,{harness:this.args.options.harness,modelKey:O(this.args.options.modelChoice)}),this.supervisor=n,this.launchState=i,this.retention=void 0,this.commit(cn(this.run,r))},"attachSupervisor"),rebindParentSignal:s(()=>this.bindParentSignal(),"rebindParentSignal"),reportOutcome:s((n,i)=>{this.applySupervisorOutcome(n,i)},"reportOutcome")})}async abort(e){let r=this.isLaunching()||this.isActive(),n=this.run;return le.debug("abort requested",{initiator:e,process:n.shell==="dropped"?"dropped":n.process.kind,shell:n.shell,stopIssued:r}),this.isQueued()?(this.deps.pools.cancelQueued(this.id),this.commit(ln(this.run,e??"agent",Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn),!0):!this.isLaunching()&&!this.isActive()||(this.spawn.execution.abortController.abort(),await this.stopPaneProcess(),!this.isLaunching()&&!this.isActive())?!1:(this.commit(ae(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}drop(){this.commit(Re(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,B(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit(pn(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(gn(this.run)),this.gate.open("")),this.supervisor?.abandon(),this.supervisor=void 0,this.detachParentBinding()}async launch(){let e={kind:"none"},r={kind:"none"},n;try{let i=this.deps.transport.createHost(this.args.pi),o=this.deps.transport.createPane(this.args.pi),{pi:l,ctx:a,type:d,prompt:u,options:c}=this.args,g=c.hostRef;if(!g&&c.worktree?.kind==="owned"){let v;try{v=await Lt.allocate(l,{naming:{kind:"generated",taskSlug:c.taskSlug??d,id:this.spawn.id},parentCwd:a.cwd,worktreeRoot:P().agent.worktreeRoot,materialization:rt(),dirtyCheckout:bt(d),notify:s((R,x)=>a.ui.notify(R,x),"notify"),host:i})}catch(R){throw c.worktree=void 0,this.spawn.display.worktree=void 0,R}v.worktree?(c.worktree={kind:"owned",...v.worktree},this.spawn.display.worktree=c.worktree):(c.worktree=void 0,this.spawn.display.worktree=void 0),g=v.hostRef}let m=c.worktree?.branch??K(c.taskSlug??Q(d),this.id),p=await nn(l,a,d,u,{agentId:this.id,harness:c.harness,modelChoice:c.modelChoice,fork:c.fork,cwd:c.worktree?.path,projectTrusted:c.projectTrusted,description:c.description,worktree:c.worktree,agentGuidance:c.orchestration.guidance}),h={resultFile:p.launch.resultFile};this.launchState=h,n=p.cwd;let f=A(),S=f.require(p.harness);if(g=g??await i.hostAt({unit:"pane",cwd:p.cwd,label:c.taskSlug??d,name:m}),e={kind:"held",host:i,ref:g},!this.isLaunching())return;this.spawn.execution.host=g,this.spawn.execution.harness=p.harness,await S.prepare({pi:l,pane:o,paneId:g.paneId,cwd:p.cwd,launch:p.launch,config:f.config(p.harness)});let k=oe({host:i,resultFile:h.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=k,await k.start({name:m,cwd:p.cwd,piArgs:p.piArgs,agentMultiplexerKind:S.agentMultiplexerKind,taskSlug:c.taskSlug},g),e={kind:"committed"},!this.isLaunching())return;this.commit(an(this.run)),k.watch().then(v=>this.applySupervisorOutcome(k,v))}catch(i){r={kind:"failed",error:i}}finally{e.kind==="held"&&await e.host.release(e.ref,"placement").catch(()=>{})}if(r.kind==="failed"&&this.isLaunching()){let i=this.spawn.execution.harness;if(i!==void 0)try{await A().require(i).teardown({pi:this.args.pi,paneId:this.spawn.execution.host?.paneId??null,cwd:n??null,subagentId:this.spawn.id})}catch(o){le.warn("harness teardown failed after a failed launch",{spawnId:this.spawn.id,harness:i,error:y(o)})}this.commit(ae(this.run,{kind:"failed",error:y(r.error)},Date.now())),await this.settle()}}supervisorOptions(){return{stopInitiator:"agent",onFollowUp:s(e=>this.deps.onFollowUpResult(this.spawn,e),"onFollowUp")}}resultFilePath(){return this.launchState?.resultFile??I(this.id)}async applySupervisorOutcome(e,r){if(!(!this.isActive()||this.supervisor!==e))switch(le.debug("outcome mapped",{kind:r.kind}),r.kind){case"completed":{this.commit(ae(this.run,{kind:"completed",result:r.deliverable||""},Date.now())),await this.settle();return}case"stopped":await this.abort(r.initiator)}}async stopPaneProcess(){let e=this.supervisor;if(e){this.supervisor=void 0,await e.stop(2e3);return}let r=this.spawn.execution.host;r&&await this.deps.transport.createHost(b()).stop(r,{interruptGraceMs:2e3,confirmMs:1e4})}settleChain=Promise.resolve();async settle(){if(this.run.shell!=="held"||this.run.process.kind!=="settling")return;let e=this.settleChain,r,n=new Promise(i=>{r=i});this.settleChain=n,await e;try{await this.runSettlePass()}finally{r()}}async runSettlePass(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settling")return;let r=ze(this.spawn.lifecycle),n=await this.readWorktreeRetention();this.deps.pools.release(this.id),this.deps.onRunEnded(this.spawn),this.run===e&&this.detachParentBinding(),this.gate.open(r),this.run===e&&(this.retention=n??void 0,this.commit(un(this.run)))}async readWorktreeRetention(){let e=this.spawn.display.worktree;return e?.kind!=="owned"?null:gt(b(),e.path)}detachParentBinding(){let e=this.parentBinding;e&&(this.parentBinding=void 0,e.signal.removeEventListener("abort",e.handler))}bindParentSignal(){if(this.parentBinding)return;let e=this.args.options.signal;if(!e||e.aborted)return;let r=s(()=>{le.debug("parent signal fired",{initiator:"user"}),this.abort("user")},"handler");e.addEventListener("abort",r,{once:!0}),this.parentBinding={signal:e,handler:r}}};function wn(t){return{createHost:s(()=>t.host,"createHost"),createPane:s(()=>t.pane,"createPane"),createPlacements:s(()=>t.placements,"createPlacements"),createDeliverable:s(e=>new re(e),"createDeliverable")}}s(wn,"createAgentManagerTransport");var yn=j("manager");function xr(t){if(t.outcome.kind==="refused"){let e=t.outcome.reason;return e.kind==="dirty"||e.kind==="unverifiable"?e:void 0}if(t.worktree.kind==="removal-failed")return{kind:"unverifiable",detail:`the removal was not confirmed (${t.worktree.detail})`}}s(xr,"retentionForReport");var ue=class{constructor(e,r){this.transport=r;this.pools=e,this.registry=new te({listAgents:s(()=>this.listAgents(V),"listAgents"),spawn:s((n,i,o)=>this.spawn(b(),J(),n,i,o),"spawn"),getSpawn:s(n=>this.getSpawn(n),"getSpawn"),findTaskAttempts:s(n=>this.transport.createHost(b()).findAttempts(n),"findTaskAttempts"),queuePosition:s(n=>this.pools.queuePosition(n),"queuePosition")})}transport;static{s(this,"AgentManager")}sessions=new Map;onComplete;onFollowUp;teardowns=new Map;pools;registry;getRegistry(){return this.registry}setConcurrency(e){this.pools.setConcurrency(e)}setOnComplete(e){this.onComplete=e}setOnFollowUp(e){this.onFollowUp=e}mintSpawnId(){return T().mint()}spawn(e,r,n,i,o){let l=o.spawnId,{requestedHarness:a,...d}=o,u={...d,harness:At(n,a)},c={pi:e,ctx:r,type:n,prompt:i,options:u},g=this.pools.admitSpawn({harness:u.harness,modelKey:O(u.modelChoice)},{id:l,start:s(p=>this.startSession(l,c,p),"start")}),m;try{m=new de({id:l,args:c,deps:{transport:this.transport,pools:this.pools,onRunEnded:s(p=>this.notifyComplete(p),"onRunEnded"),onFollowUpResult:s((p,h)=>this.notifyFollowUp(p,h),"onFollowUpResult")}})}catch(p){throw this.pools.release(l),p}if(this.sessions.set(l,m),u.signal?.aborted)return m.abort("user"),l;if(g.kind==="queue")return l;try{m.start(g.reservation)}catch(p){throw m.rollbackStart(),this.pools.release(l),this.sessions.delete(l),T().drop(l),p}return l}startSession(e,r,n){let i=this.sessions.get(e);if(!i||!i.isQueued())return!1;try{i.start(n)}catch(o){i.settleStartFailure(o)}return!0}async steer(e,r){if(this.teardowns.has(e))return{kind:"refused",reason:`agent ${e} is being cleaned up, so its worktree is on its way out \u2014 wait for the report before steering it.`};let n=this.sessions.get(e);return n?n.steer(r):{kind:"refused",reason:`no live session tracks agent ${e} \u2014 check the id from its spawn or completion result (a cleaned-up agent is gone for good).`}}getSpawn(e){return T().get(e)}assets(){let e=b();return qt(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=Qe){return T().list(e).sort((r,n)=>fe(n.lifecycle)-fe(r.lifecycle))}async abort(e,r){return await this.sessions.get(e)?.abort(r)??!1}notifyComplete(e){try{this.onComplete?.(e)}catch(r){yn.warn("completion notification failed",{spawnId:e.id,detail:y(r)})}}notifyFollowUp(e,r){try{this.onFollowUp?.(e,r)}catch(n){yn.warn("follow-up notification failed",{spawnId:e.id,detail:y(n)})}}recordRetention(e,r){let n=e.lifecycle;q(n)&&(n.worktreeRetentionReason=r)}dropSpawn(e){this.sessions.get(e.id)?.drop(),this.sessions.delete(e.id),B(I(e.id)),T().drop(e.id)}async cleanup(e,r){let n=this.runCleanup(e,this.teardowns.get(e),r);this.teardowns.set(e,n);try{return await n}finally{this.teardowns.get(e)===n&&this.teardowns.delete(e)}}async runCleanup(e,r,n){await r?.catch(()=>{}),Z()?.dropNudge(e);let i=this.getSpawn(e)!==void 0,o=await Tt(this.assets()).cleanupAgent(e,{getSpawn:s(a=>this.getSpawn(a),"getSpawn"),dropSpawn:s(a=>this.dropSpawn(a),"dropSpawn")},n),l=this.getSpawn(e);if(l!==void 0){let a=xr(o);a!==void 0&&this.recordRetention(l,a)}return i&&o.outcome.kind==="torn-down"&&B(I(e)),o}dispose(){this.pools.clearQueue();for(let e of this.sessions.values())e.settleForDispose();this.sessions.clear()}};var Rr=200,ce=class{static{s(this,"SpawnCoordinator")}manager;backgroundAgentIds=new Set;pendingNudges=new Set;pendingFollowUps=new Map;nudgeTimer=null;disposed=!1;registry;constructor(e){this.manager=e,this.registry=e.getRegistry()}async spawn(e,r){let n=await this.registry.admit(r);if(n.status==="rejected")throw await this.inFlightError(r.taskSlug,n);let i=n.agentId,o=this.manager.getSpawn(i);return o.execution.spawnCtx=e,this.announceSpawn(e,o),r.runInBackground?this.backgroundAgentIds.add(i):await o.execution.promise,{agentId:i,spawn:o}}announceSpawn(e,r){if(!e.hasUI)return;let n=r.lifecycle;if(q(n))return;let i=n.phase==="queued"?"Queued":"Spawned";Ct(e.ui).succeeded(`${i} agent ${r.id} (${r.display.type})`)}async inFlightError(e,r){let n=this.manager.getSpawn(r.conflictingId);if(n)return new F({kind:"spawn",spawn:n},e);let i=await U().host.findAttempts(e),o=ne([],i);if(o.kind!=="none")return new F(o,e);let l={name:r.conflictingId};return new F({kind:"multiplexer",attempt:l},e)}dropNudge(e){this.pendingNudges.delete(e),this.pendingFollowUps.delete(e)}scheduleNudge(e){this.pendingNudges.add(e),this.ensureNudgeTimer()}onAgentFollowUp(e,r){this.backgroundAgentIds.has(e.id)&&(this.pendingFollowUps.set(e.id,r),this.ensureNudgeTimer())}ensureNudgeTimer(){this.nudgeTimer||(this.nudgeTimer=setTimeout(()=>{this.nudgeTimer=null;let e=[...this.pendingNudges];this.pendingNudges.clear();let r=[...this.pendingFollowUps];this.pendingFollowUps.clear();for(let n of e)this.emitIndividualNudge(n);for(let[n,i]of r)this.emitFollowUp(n,i)},Rr))}onAgentComplete(e){this.backgroundAgentIds.has(e.id)&&(Ir(e)||this.scheduleNudge(e.id))}dispose(){this.nudgeTimer&&(clearTimeout(this.nudgeTimer),this.nudgeTimer=null),this.pendingNudges.clear(),this.pendingFollowUps.clear(),this.backgroundAgentIds.clear(),this.disposed=!0}emitFollowUp(e,r){if(this.disposed||!H())return;let n=b(),i=this.manager.getSpawn(e);if(!i)return;let o=Se(i,{includeRunInfo:!0,includeStatus:!0}),l=`[Cowboy agent "${i.display.type}" ${i.id} reported again after settling]`;try{n.sendMessage({customType:"subagent-result",content:`${l}
|
|
31
31
|
|
|
32
|
-
${r}`,details:o,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let a=i.execution.spawnCtx;if(a)try{a.ui.notify(`${l} New report available`,"info")}catch{}}}emitIndividualNudge(e){if(this.disposed
|
|
32
|
+
${r}`,details:o,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let a=i.execution.spawnCtx;if(a)try{a.ui.notify(`${l} New report available`,"info")}catch{}}}emitIndividualNudge(e){if(this.disposed||!H())return;let r=b(),n=this.manager.getSpawn(e);if(!n)return;let i=Se(n,{includeRunInfo:!0,includeStatus:!0});try{r.sendMessage({customType:"subagent-result",content:`${xt(n)}
|
|
33
33
|
|
|
34
|
-
${
|
|
34
|
+
${Rt(n)}`,details:i,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let o=n.execution.spawnCtx;if(o)try{o.ui.notify(`[Cowboy agent "${n.display.type}" ${X(n.lifecycle)}] Result available`,"info")}catch{}}}};function Ir(t){let e=t.lifecycle;return q(e)&&e.status==="stopped"&&e.stop.initiator==="user"}s(Ir,"stoppedByUser");import*as xn from"node:fs";import{pathToFileURL as Mr}from"node:url";import*as bn from"node:path";import{DefaultPackageManager as Tr,SettingsManager as Lr}from"@earendil-works/pi-coding-agent";import*as vn from"node:fs";import*as Sn from"node:path";import{z as pe}from"zod";var kn="pi-cowboy",Er="pi-cowboy-",Cr=pe.object({name:pe.string().startsWith(Er),[kn]:pe.object({plugin:pe.string().min(1)})});function Pn(t){let e;try{e=vn.readFileSync(Sn.join(t,"package.json"),"utf-8")}catch{return}let r;try{r=JSON.parse(e)}catch{return}let n=Cr.safeParse(r);if(n.success)return{name:n.data.name,entry:n.data[kn].plugin}}s(Pn,"readPluginManifest");function Fr(t){let e=new Map;for(let r of t){if(r.installedPath===void 0)continue;let n=Pn(r.installedPath);n!==void 0&&(e.has(n.name)||e.set(n.name,{name:n.name,source:r.source,root:r.installedPath,entry:bn.resolve(r.installedPath,n.entry)}))}return[...e.values()].sort((r,n)=>r.name.localeCompare(n.name))}s(Fr,"pluginsAmong");async function An(t){let e=new Tr({cwd:t,agentDir:E(),settingsManager:Lr.create(t,E())});return Fr(e.listConfiguredPackages())}s(An,"discoverPluginPackages");function Rn(t){let e=null,r=null,n=null;async function i(o,l,a){let d=n;d!==null&&(await d,n===d&&(n=null));let u=[],c=[],g=[],m;try{m=await An(l)}catch(f){a(`[cowboy] installed plugins could not be discovered and were skipped: ${y(f)}`,"warning"),m=[]}for(let f of m){let S=c.length;try{let k=await jr(f,o,l,t,v=>c.push(v));k!==void 0&&u.push(k),g.push(f.name)}catch(k){for(let v of c.splice(S).reverse())v();a(`[cowboy] plugin "${f.name}" (${f.source}) could not load and was skipped: ${y(k)}`,"warning")}}let p,h={loaded:g,dispose:s(()=>(p??=(async()=>{e===h&&(e=null);for(let f=u.pop();f!==void 0;f=u.pop())try{await f()}catch(S){a(`[cowboy] a plugin disposer failed: ${y(S)}`,"warning")}for(let f=c.pop();f!==void 0;f=c.pop())f()})(),n=p,p),"dispose")};return e=h,r=null,h}return s(i,"startLoad"),{load(o,l,a){return e!==null?Promise.resolve(e):(r??=i(o,l,a),r)}}}s(Rn,"createPluginLoader");function Dr(t){try{return`?v=${xn.statSync(t).mtimeMs}`}catch{return""}}s(Dr,"cacheBust");function Or(t,e,r,n){return{pi:t,cwd:e,registerHarness:s(i=>{let o=r.harnesses.register(i);return o&&n(()=>r.harnesses.unregister(i.id)),o},"registerHarness"),registerMultiplexer:s(i=>{let o=r.multiplexers.register(i);return o&&n(()=>r.multiplexers.unregister(i.id)),o},"registerMultiplexer")}}s(Or,"pluginApi");async function jr(t,e,r,n,i){let o=Or(e,r,n,i),a=(await import(`${Mr(t.entry).href}${Dr(t.entry)}`)).default;if(typeof a!="function")throw new Error(`entry module ${t.entry} has no default-export factory`);let d=await a(o);return typeof d=="function"?d:void 0}s(jr,"loadOne");function Hr(){let t=[],e=[];for(let r of A().ids()){let n=$r(r);n.status==="available"?t.push(r):n.notice!==void 0&&e.push(n.notice)}return{availability:He(t),notices:e}}s(Hr,"probeHarnessAvailability");function $r(t){try{return A().require(t).availability()}catch(e){return{status:"unavailable",notice:`[cowboy] the "${t}" harness could not answer for itself and is not offered: ${y(e)}`}}}s($r,"askAvailability");function In(){let t=Hr();return nt(t.availability),t}s(In,"startHarnessAvailabilityProbe");function En(t){let e=tt(),r=A();for(let n of r.runnable(e))try{r.require(n).prefetchModels(t)}catch{}}s(En,"prefetchHarnessModels");async function Cn(t,e){let r=et(),n=await Rn(r).load(t,e.cwd,(d,u)=>{e.hasUI&&e.ui.notify(d,u)}),i=P();r.harnesses.validateConfigs(i.harnessConfigLayers(),(d,u)=>i.reportHarnessConfigIssue(d,u)),Wr(e,r);let o=r.multiplexers.hosting();if(o.length===0)return{kind:"unhosted",plugins:n,reason:me};let l=r.multiplexers.runtime(t,P().multiplexer);if(!o.includes(l.multiplexer))return{kind:"unhosted",plugins:n,reason:me};ee(l);let a=In();if(e.hasUI)for(let d of a.notices)e.ui.notify(d,"warning");return En(t),{kind:"hosted",plugins:n,runtime:l}}s(Cn,"startSessionRuntime");function Wr(t,e){if(!t.hasUI)return;let r=P(),n=new Set(e.harnesses.ids()),i=r.configuredHarnessIds().filter(o=>!n.has(o)).map(o=>`harness "${o}"`);e.multiplexers.has(r.multiplexer)||i.push(`multiplexer "${r.multiplexer}"`),i.length!==0&&t.ui.notify(`[cowboy] nothing registered for ${i.join(", ")}; those settings are ignored and the launch falls back to the default.`,"warning")}s(Wr,"reportUnregisteredConfig");function _r(t){if(!he()){let e=new ue(new Ye(P().concurrency),wn(t));ye(e),P().setDeps({manager:e});let r=new ce(e);we(r),e.setOnComplete(n=>{r.onAgentComplete(n)}),e.setOnFollowUp((n,i)=>{r.onAgentFollowUp(n,i)})}}s(_r,"wireManagerAndCoordinator");async function Nr(t){let e=E(),r=L.join(e,"agents"),n=t.isProjectTrusted(),i=n?L.join(t.cwd,".agents","agents"):"",o=n?L.join(t.cwd,".pi","agents"):"";ht(r,o,i);let l=P().agent.disableDefaultAgents,a=await yt({disableDefaultAgents:l,notify:s((d,u)=>{t.ui.notify(d,u)},"notify")});ft(a,{disableDefaultAgents:l})}s(Nr,"scanAndRegisterAgents");async function qr(t){let e=E(),r=L.join(e,"orchestrators"),n=t.isProjectTrusted(),i=n?L.join(t.cwd,".agents","orchestrators"):"",o=n?L.join(t.cwd,".pi","orchestrators"):"";kt(r,o,i);let l=await Pt({notify:s((a,d)=>{t.ui.notify(a,d)},"notify")});St(l)}s(qr,"scanAndRegisterOrchestrators");async function Ur(t){ot(Ze());let e=t.isProjectTrusted()?L.join(t.cwd,".pi"):void 0;P().setProjectDir(e),P().reload()}s(Ur,"loadSessionConfig");async function Br(t){await Nr(t),await qr(t)}s(Br,"scanSessionTemplates");function Tn(t){t.on("tool_call",It);let e=null;t.on("session_start",async(r,n)=>{st(n),await Ur(n);let i=await Cn(t,n);if(e=i.plugins,i.kind==="unhosted"){ke(n.ui),n.hasUI&&H()&&n.ui.notify(i.reason,"warning");return}await Br(n),_r(i.runtime),await Ft(t),H()?Mt(n.ui):(ke(n.ui),n.hasUI&&n.ui.notify("Cowboy extension is disabled \u2014 its tools are not loaded. Run /cowboy enable to turn it back on.","info"))}),t.on("session_shutdown",async(r,n)=>{let i=he();if(i){let a=i.listAgents(V);a.length>0&&n.hasUI&&n.ui.notify(`${a.length} subagent pane(s) left running in their panes (tracking stopped for the previous session)`,"warning")}Z()?.dispose(),we(null),P().dispose(),i?.dispose(),ye(null),Et();let o=e;e=null;let l=U();await o?.dispose(),U()===l&&ee(null)}),process.on("exit",()=>{try{process.stderr.write("\x1B[?2026l\x1B[?25h\x1B[0m")}catch{}})}s(Tn,"setupEventListeners");var Ln="pi-cowboy needs a git repository: this directory is not inside one, so pi-cowboy stays inactive";function Fn(t,e){t.on("session_start",async(r,n)=>{n.hasUI&&n.ui.notify(e,"warning")})}s(Fn,"reportInactive");function Gr(t){if(at()!==void 0)return;let e=lt();if(e!==void 0){Fn(t,e);return}if(!dt(process.cwd())){Fn(t,Ln),Ot(t,Ln);return}it(t),Dt(t),jt(t),Tn(t)}s(Gr,"default");export{Gr as default};
|
|
35
35
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as M,b as y}from"./chunk-
|
|
1
|
+
import{a as M,b as y}from"./chunk-F526OOT6.js";import{d as g,g as R,j as P,t as H}from"./chunk-KMXT7XW7.js";import{b as S,o as D}from"./chunk-WL3QYM2F.js";import{Ba as x,Ka as _,ea as I,ia as T,r as p,s as b,t as E,xa as v,y as A}from"./chunk-CTBFJWEE.js";import{a as t,d as N}from"./chunk-254PTGN5.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-
|
|
3
|
+
//# sourceMappingURL=menu-worktree-command-SXLBWK4D.js.map
|