pi-cowboy 0.18.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/agents/agent-template.d.ts +12 -1
- package/dist/agents/harness/launch-env.d.ts +1 -0
- package/dist/agents/harness/pane-launcher.d.ts +1 -0
- package/dist/agents/harness.d.ts +11 -0
- package/dist/agents/types.d.ts +2 -0
- package/dist/chunk-254PTGN5.js +2 -0
- package/dist/{chunk-UGZYLX24.js → chunk-J525HRTW.js} +2 -2
- package/dist/chunk-JIAP5YBM.js +10 -0
- package/dist/chunk-PYOLHDZJ.js +24 -0
- package/dist/{chunk-HJMJUVTJ.js → chunk-XKS73JKY.js} +2 -2
- package/dist/{chunk-FI6HUFY7.js → chunk-ZLKJYRKY.js} +2 -2
- package/dist/config/config-store.d.ts +2 -1
- package/dist/index.js +20 -18
- package/dist/menu-worktree-command-DYLJ34X3.js +3 -0
- package/dist/menus-RQLX4WC2.js +9 -0
- package/dist/{model-picker-TDKOTEKP.js → model-picker-74J7Z4WJ.js} +2 -2
- package/dist/models/model-groups.d.ts +2 -0
- package/dist/models/model-precedence.d.ts +2 -1
- package/dist/paths.d.ts +1 -0
- package/dist/plugin/index.d.ts +3 -0
- package/dist/plugin/index.js +1 -1
- package/dist/ui/menu/submenus/thinking-select.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-HFCCRB3G.js +0 -10
- package/dist/chunk-OO54ZZLJ.js +0 -2
- package/dist/chunk-UIP66WFU.js +0 -24
- package/dist/menu-worktree-command-WD6LXL6F.js +0 -3
- package/dist/menus-X5WATIRR.js +0 -9
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{b as It,c as Pt,e as Mt,g as Nt,k as Pe,l as $t,p as Bt}from"./chunk-ZLKJYRKY.js";import{F as Ct,I as Ce,K as _t,L as G,M as _e,N as P,O as Se,P as St,R as te,S as _,T as M,V as Et,b as ot,ba as C,ca as ne,da as b,fa as f,ga as N,h as it,ha as Ee,i as st,ia as Oe,j as K,k as at,ka as Ot,l as Ae,m as lt,na as Re,o as dt,oa as re,pa as x,qa as oe,r as ct,sa as j,v as ut,va as Rt,w as pt,x as gt,y as mt,ya as Ie,za as ie}from"./chunk-JIAP5YBM.js";import{a as r,d as ee,f as xe,g as ht,j as ft,k as yt,l as wt,n as kt,o as bt,q as vt,s as Tt,t as At,u as xt}from"./chunk-254PTGN5.js";import{visibleWidth as Be}from"@earendil-works/pi-tui";var Me="\u{1F920}",jt="\u{1F404}",or="\u{1F4A9}",ir=2,sr=1e3,se=Be(jt),ar="76;175;80";function lr(e){return`\x1B[48;2;${ar}m${e}\x1B[49m`}r(lr,"greenBackground");function Ht(e){return e===0?0:Math.max(ir,Math.ceil(Math.sqrt(2*e)))}r(Ht,"pastureEdge");function Lt(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Lt,"emptyPasture");function dr(e,t){let n=Ht(e.cows+e.droppings),o=Lt(n),i=Array.from({length:n*n},(a,l)=>l),s=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let a=0;a<s.length;a+=1){let l=a+Math.floor(t()*(i.length-a)),c=i[l];i[l]=i[a],i[a]=c,o[Math.floor(c/n)][c%n]=s[a]}return o}r(dr,"grazedPasture");function ae(e,t){let n=[];for(let o=0;o<e.length;o+=1)for(let i=0;i<e[o].length;i+=1)e[o][i]===t&&n.push({row:o,col:i});return n}r(ae,"cellsOf");function cr(e,t){return[{row:e.row-1,col:e.col},{row:e.row,col:e.col+1},{row:e.row+1,col:e.col},{row:e.row,col:e.col-1}].filter(({row:o,col:i})=>o>=0&&o<t&&i>=0&&i<t)}r(cr,"neighboursOf");function Dt(e,t){return cr(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Dt,"openNeighboursOf");function ur(e,t){let n=ae(e,"cow").filter(l=>Dt(l,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Dt(o,e),s=i[Math.floor(t()*i.length)],a=e.map(l=>l.slice());return a[o.row][o.col]="empty",a[s.row][s.col]="cow",a}r(ur,"moveHerd");function Ft(e,t,n,o){for(let i=0;i<n;i+=1){let s=ae(e,"empty"),a=s[Math.floor(o()*s.length)];e[a.row][a.col]=t}}r(Ft,"placeAtRandom");function pr(e,t,n,o){let i=ae(e,"cow"),s=ae(e,"dropping"),a=i.length-t,l=s.length-n;for(;a>0&&l<0;){let c=i.pop();e[c.row][c.col]="dropping",a-=1,l+=1}for(;a>0;){let c=i.pop();e[c.row][c.col]="empty",a-=1}for(;l>0;){let c=s.pop();e[c.row][c.col]="empty",l-=1}Ft(e,"cow",-a,o),Ft(e,"dropping",-l,o)}r(pr,"reconcileCounts");function gr(e,t,n){if(e===null)return dr(t,n);let o=Ht(t.cows+t.droppings),i=Lt(o);for(let s=0;s<e.length&&s<o;s+=1)for(let a=0;a<e[s].length&&a<o;a+=1)i[s][a]=e[s][a];return pr(i,t.cows,t.droppings,n),i}r(gr,"reconcilePasture");var mr={anchor:"top-right",width:Be(Me),get offsetX(){return N()?.cowboyOffsetX??0},nonCapturing:!0},hr={anchor:"top-right",offsetY:1,get width(){return N()?.pastureWidth??0},nonCapturing:!0};function fr(e){return e==="cow"?jt:e==="dropping"?or:" ".repeat(se)}r(fr,"cellText");function yr(e,t){return e.map(n=>t(n.map(fr).join("")))}r(yr,"drawnRows");function wr(){return Oe().list(["spawned"]).length}r(wr,"liveAgentCount");function kr(){return Oe().list(St).length}r(kr,"endedAgentCount");function br(){return{live:wr(),ended:kr()}}r(br,"agentCounts");function vr(){return f().agent.grazingEnabled}r(vr,"grazingEnabled");var Ne=class{constructor(t,n,o,i,s){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=s}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return Be(Me)}get pastureWidth(){return this.drawnPasture().length*se}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*se-(t*se-this.cowboyWidth)}render(){return this.frame(),[Me]}pastureRows(){return this.frame(),yr(this.drawnPasture(),this.grass)}invalidate(){}attachCowboy(t){this.cowboyHandle=t}attachPasture(t){this.pastureHandle=t}dispose(){let t=this.drawnPasture().length>0&&(this.cowboyHandle!==null||this.pastureHandle!==null);this.disposed=!0,this.poll!==null&&(clearInterval(this.poll),this.poll=null),this.cowboyHandle?.hide(),this.cowboyHandle=null,this.pastureHandle?.hide(),this.pastureHandle=null,t&&this.tui.requestRender(!0)}drawnPasture(){return this.herd===null||!this.isGrazing()?[]:this.herd.pasture}frame(){if(this.disposed)return;let t=this.isGrazing();this.herd===null?(this.herd=this.place(this.countAgents()),this.grazing=t):t!==this.grazing&&this.recount(),this.pollWhile(t)}pollWhile(t){!t&&this.poll!==null?(clearInterval(this.poll),this.poll=null):t&&this.poll===null&&(this.poll=setInterval(()=>this.recount(),sr))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,s=(this.grazing??o)&&(this.herd?.pasture.length??0)>0;if(this.herd===null||t!==this.herd.liveAgents||n!==this.herd.endedAgents)this.herd=this.place({live:t,ended:n});else if(o&&!i)this.herd={...this.herd,pasture:ur(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let a=s&&this.drawnPasture().length===0;this.tui.requestRender(a)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:gr(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},$e=class{static{r(this,"PastureView")}render(){return N()?.pastureRows()??[]}invalidate(){}};function Ut(e){De(),e.custom(t=>{let n=new Ne(t,br,vr,lr,Math.random);return Ee(n),n},{overlay:!0,overlayOptions:mr,onHandle:r(t=>N()?.attachCowboy(t),"onHandle")}),e.custom(()=>new $e,{overlay:!0,overlayOptions:hr,onHandle:r(t=>N()?.attachPasture(t),"onHandle")})}r(Ut,"showExtensionIndicator");function De(){let e=N();Ee(null),e?.dispose()}r(De,"hideExtensionIndicator");function le(){return f().agent.extensionEnabled}r(le,"isExtensionEnabled");function Tr(){return le()&&f().agent.showActiveIndicator}r(Tr,"isActiveIndicatorShown");function de(e){Tr()?Ut(e):De()}r(de,"syncExtensionIndicator");function gi(e,t){f().mutate.agent.setShowActiveIndicator(t),de(e)}r(gi,"setShowActiveIndicator");import{Type as D}from"typebox";import{Text as Dn}from"@earendil-works/pi-tui";import{Type as y}from"typebox";var Ar="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",xr=`REQUIRED. Short 2-3 word task name (e.g. "fix login flow"). This single value names the agent's branch/tab/worktree/agent so you can recognize it at a glance, and the extension appends a unique spawn id so parallel spawns \u2014 and every entry in a batch \u2014 are always distinct. Limits: 3 words, 19 characters when slugged (lowercase, dashes). A longer name throws with the exact overshoot \u2014 retry with a shorter name. Missing name throws too. The same name twice in one call is rejected before anything spawns.`,Cr=`Optional model for THIS agent as "provider/model-id". Omit it, or pass null, to leave it unset and use the configured default for this session and agent type \u2014 the usual case, and never a value to guess at. Pass it when the user asked for a specific model for this task. When a previous attempt failed with a provider/model error, pass a different model here and instruct the agent in plain text to continue where the failed attempt left off. A model that is not in this session's registry fails the call before anything is spawned.`,_r=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${yt.join(", ")}) and any harness a plugin registered in this session. Omit it, or pass null, to leave it unset and use the agent template's harness_type, then the configured default \u2014 never pass a harness the user did not ask for. A harness this session did not register, or this machine cannot launch, fails the call before anything is spawned \u2014 unlike the configured default, an explicit request never falls back to pi.`,Sr=y.Object({prompt:y.String({description:Ar}),task_name:y.String({description:xr}),agent_type:y.Optional(y.Union([y.String(),y.Null()])),model:y.Optional(y.Union([y.String(),y.Null()],{description:Cr})),harness_type:y.Optional(y.Union([y.String(),y.Null()],{description:_r}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=y.Object({agents:y.Array(Sr,{minItems:1}),run_in_background:y.Optional(y.Boolean())},{additionalProperties:!1,required:["agents"]});import{Type as Fe}from"typebox";var Er="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Wt=Fe.Object({agent_ids:Fe.Array(Fe.String({minLength:1}),{minItems:1,description:Er})},{additionalProperties:!1,required:["agent_ids"]});import{Type as je}from"typebox";var Or="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",qt=je.Object({agent_ids:je.Array(je.String({minLength:1}),{minItems:1,description:Or})},{additionalProperties:!1,required:["agent_ids"]});import{Type as $}from"typebox";var Rr="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",Ir="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",Pr="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",Kt=$.Object({branches:$.Array($.String({minLength:1}),{minItems:1,description:Rr}),target:$.Optional($.String({description:Ir})),repo:$.Optional($.String({description:Pr}))},{additionalProperties:!1,required:["branches"]});import{Type as ce}from"typebox";var Mr="REQUIRED. One or more agent ids to steer (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A settled agent is revived by the delivery. A repeated id is rejected before anything is delivered \u2014 pass each id once.",Nr="REQUIRED. The single message delivered verbatim to every id in `agent_ids`. Plain instructions work best (e.g. \"stop refactoring; just fix the failing test and report\"). Delivery is fire-and-forget: nothing here waits for an agent to act on it. Because the text is entered into the agent's pi session, a command prefixed with `!` runs and adds its output to that agent's context, while `!!` runs it without adding the output to its context.",Gt=ce.Object({agent_ids:ce.Array(ce.String({minLength:1}),{minItems:1,description:Mr}),message:ce.String({description:Nr})},{additionalProperties:!1,required:["agent_ids","message"]});import*as ue from"node:fs";import*as Vt from"node:path";import{parse as $r,TomlError as Br}from"smol-toml";import{z as Dr}from"zod";var Fr=".toml";function pe(e){return $r(e.replace(/^\uFEFF/,""))}r(pe,"parseTemplateToml");function T(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0))}r(T,"compactDefined");function jr(e){let t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}r(jr,"describeZodIssue");function Hr(e){if(e instanceof Dr.ZodError)return e.issues.map(jr).join("; ").replace(/\s+/g," ").trim();if(e instanceof Br){let[n]=e.message.split(`
|
|
2
|
+
|
|
3
|
+
`);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}r(Hr,"describeParseError");var Lr={label:"File",problem:"was skipped"};async function ge(e,t,n,o,i=Lr,s){try{await ue.promises.access(e)}catch{return[]}let l=(await ue.promises.readdir(e,{withFileTypes:!0})).filter(d=>d.isFile()&&d.name.endsWith(Fr)),c=[];for(let d of l){let h=Vt.join(e,d.name),g;try{g=await ue.promises.readFile(h,"utf-8")}catch{continue}try{let p=t(g),m=s?.(p);if(m!==void 0)throw new Error(m);n(p)&&c.push(p)}catch(p){o?.(`[cowboy] ${i.label} file ${h} ${i.problem}: ${Hr(p)}`,"warning")}}return c}r(ge,"scanTemplateFilesInDir");import{z as u}from"zod";var zt=u.union([u.boolean(),u.array(u.string())]);function Ur(e,t,n){if(!kt(e))return"is not a valid environment variable name";if(vt(e,n))return"is a reserved environment variable and cannot be overridden";if(bt(t))return"contains a control character"}r(Ur,"envProblem");function he(e){let t=Tt[e];return u.record(u.string(),u.string()).superRefine((n,o)=>{for(let[i,s]of Object.entries(n)){let a=Ur(i,s,t);a!==void 0&&o.addIssue({code:"custom",path:[i],message:a})}})}r(he,"envTable");var Yt={model:u.string().optional(),thinking:G.optional(),extensions:zt.optional(),skills:zt.optional(),inlined_skills:u.array(u.string()).optional(),fork:u.boolean().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:he("pi").optional()},Wr=u.strictObject(Yt),qr=u.strictObject({model:u.string().optional(),variant:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:he("opencode").optional()}),Kr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),env:he("codex").optional()}),Gr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:he("claude").optional()});function He(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}r(He,"toToolFilter");function Vr(e,t){return t===void 0?e:e===void 0?t:{...t,...e}}r(Vr,"mergeEnv");function me(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}r(me,"nonEmptyEnv");var zr=u.strictObject({include_context_files:u.boolean().optional(),pi:Wr.optional(),opencode:qr.optional(),codex:Kr.optional(),claude:Gr.optional(),...Yt}).transform(({pi:e,opencode:t,codex:n,claude:o,...i})=>{let{model:s,thinking:a,tools:l,exclude_tools:c,env:d,...h}=i,{model:g,thinking:p,tools:m,exclude_tools:w,env:k,...v}=T(e??{}),{model:F,variant:q,tools:Te,exclude_tools:Gn,env:Vn,...zn}=T(t??{}),{model:Yn,thinking:Qn,env:Xn,...Zn}=T(n??{}),{model:Jn,thinking:er,tools:tr,exclude_tools:nr,env:rr}=T(o??{}),et=T({pi:g??s,opencode:F,codex:Yn,claude:Jn}),tt=T({pi:He(m??l,w??c),opencode:He(Te,Gn),claude:He(tr,nr)}),nt=T({pi:p??a,opencode:q,codex:Qn,claude:er}),rt=T({pi:me(Vr(k,d)),opencode:me(Vn),codex:me(Xn),claude:me(rr)});return{...h,...v,...zn,...Zn,...Object.keys(et).length>0?{modelsByFamily:et}:{},...Object.keys(tt).length>0?{toolsByFamily:tt}:{},...Object.keys(nt).length>0?{thinkingByFamily:nt}:{},...Object.keys(rt).length>0?{envByFamily:rt}:{}}}),Qt=u.strictObject({name:u.string().optional(),display_name:u.string().optional(),description:u.string().optional(),hidden:u.boolean().optional(),worktree_checkout_type:u.enum(ct).optional(),system_prompt:u.string().optional(),harness_type:u.string().min(1).optional(),harness:zr.optional()});function Yr(e){return Qt.parse(pe(e))}r(Yr,"parseAgentFile");var Qr={label:"Agent",problem:"is not a valid agent template and was skipped"};async function L(e,t,n){return ge(e,Yr,o=>o.name,t,Qr,n)}r(L,"scanAgentFilesInDir");function fe(e,t,n,o){let i=new Map;for(let[s,a]of e)i.set(s,{...a});return Le(i,t),Le(i,n),Le(i,o),i}r(fe,"mergeAgents");function Le(e,t){for(let n of t){if(!n.name)continue;let o=e.get(n.name);if(o){let i={displayName:n.display_name,description:n.description??""},s=Xt(n),a=Xr(o.modelsByFamily,s.modelsByFamily),l=Zr(o.toolsByFamily,s.toolsByFamily),c=Jr(o.thinkingByFamily,s.thinkingByFamily),d=eo(o.envByFamily,s.envByFamily);e.set(n.name,{...o,...s,...a?{modelsByFamily:a}:{},...l?{toolsByFamily:l}:{},...c?{thinkingByFamily:c}:{},...d?{envByFamily:d}:{},...i})}else e.set(n.name,{...to,...Xt(n)})}}r(Le,"mergeAgentOverrides");function Xr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Xr,"mergeModelsByFamily");function Zr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Zr,"mergeToolsByFamily");function Jr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Jr,"mergeThinkingByFamily");function eo(e,t){let n={...e};for(let[o,i]of Object.entries(t??{})){let s=o;n[s]={...n[s],...i}}return Object.keys(n).length>0?n:void 0}r(eo,"mergeEnvByFamily");function Xt(e){let{harness:t}=e,n={name:e.name,displayName:e.display_name,description:e.description,harnessType:e.harness_type,toolsByFamily:t?.toolsByFamily,extensions:t?.extensions,skills:t?.skills,inlinedSkills:t?.inlined_skills,modelsByFamily:t?.modelsByFamily,thinkingByFamily:t?.thinkingByFamily,envByFamily:t?.envByFamily,hidden:e.hidden,fork:t?.fork,includeContextFiles:t?.include_context_files,worktreeCheckoutType:e.worktree_checkout_type,systemPrompt:e.system_prompt};return T(n)}r(Xt,"fromTemplate");var to={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Ue=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return ie().agents}r(S,"registry");function V(e){let t=e.harness_type;if(t===void 0)return;let n=x();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}r(V,"unregisteredHarness");function Vi(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[o,i]of Ue)n.set(o,i);for(let[o,i]of e)n.set(o,i);S().agents=n}r(Vi,"registerAgents");function zi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}r(zi,"setAgentScanDirs");async function no(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,o=S().scanDirs,[i,s,a,l]=await Promise.all([t?Promise.resolve([]):L(it,n,V),L(o.user,n,V),L(o.shared,n,V),L(o.project,n,V)]),d=fe(t?new Map:Ue,i,[],[]);return fe(d,s,a,l)}r(no,"scanAndMerge");async function ro(e,t){let n=await no(t),{agents:o}=S(),i=0;for(let[s,a]of n)o.has(s)||(o.set(s,a),i++);if(e){let s=await L(e,t?.notify,V),a=fe(new Map,[],[],s);for(let[l,c]of a)o.has(l)||(o.set(l,c),i++)}return i}r(ro,"discoverNewAgents");function z(e){let{agents:t}=S();if(!e)return{kind:"not-found"};if(t.has(e))return{kind:"resolved",key:e};let n=e.toLowerCase(),o=[];for(let i of t.keys())i.toLowerCase()===n&&o.push(i);return o.length===1?{kind:"resolved",key:o[0]}:o.length>1?{kind:"ambiguous",candidates:o}:{kind:"not-found"}}r(z,"resolveType");async function Jt(e,t,n){let o=z(e);return o.kind==="not-found"&&(await ro(t,{notify:n}),o=z(e)),o}r(Jt,"resolveTypeOrDiscover");function E(e){let t=z(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}r(E,"getAgentConfig");function en(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}r(en,"getAvailableTypes");function Yi(){return[...S().agents.keys()]}r(Yi,"getAllTypes");function Zt(e,t,n,o){return{skills:e??n,extensions:t??o}}r(Zt,"applyGlobalDefaults");function Qi(e,t=!0,n=!0){let o=E(e);if(o){let{skills:s,extensions:a,...l}=o,c=Zt(s,a,t,n);return{displayName:l.displayName??l.name,description:l.description,...c}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Zt(void 0,void 0,t,n)}}r(Qi,"getConfig");var We="_configuredModel",qe="_configuredThinking";function U(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(U,"readModelKey");function tn(e){return U(e.thinking)??U(e[qe])}r(tn,"readThinkingRequest");function nn(e){let t=U(e.model);if(t)return{source:"call",key:t};let n=U(e[We]);if(n)return{source:"configured",key:n}}r(nn,"readModelRequest");function Y(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(Y,"withoutModel");function rn(e){switch(e.kind){case"resolved":return{model:e.model,key:e.modelKey,thinking:e.thinking};case"foreign":return{harness:e.harness,key:e.modelKey,name:e.modelName,thinking:e.thinking};case"level":return{levelOnly:!0,thinking:e.thinking};case"none":return}}r(rn,"modelChoiceFor");function Q(e){return`${e.provider}/${e.id}`}r(Q,"modelKey");function oo(e,t){if(t!==void 0&&!G.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${G.options.join(", ")}); launching "${Q(e)}" with "${t}".`}r(oo,"undeclaredLevelWarning");function on(e,t){let n=oo(e,t);return{resolved:{kind:"resolved",model:e,modelKey:Q(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(on,"resolvedModel");function io(e){return`No API key found for "${e}"`}r(io,"missingCredential");function sn(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:ee(o)}}return!Ct(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:io(t.provider)}}r(sn,"probeCredentials");function Ke(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ke,"refusal");function Ge(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return Y(i);let l=sn(n,o);if(l.verdict!=="unusable")return on(o,i);throw new Error(Ke(`The parent session's model "${Q(o)}" did not resolve credentials in this session`,l.reason))}let s=e.source==="call"?xe(e.key,n,void 0):xe(e.key,n,o);if(!s){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return Y(i)}let a=sn(n,s);if(a.verdict!=="unusable")return on(s,i);throw e.source==="call"?new Error(Ke(`Model "${Q(s)}" cannot authenticate in this session`,a.reason)):new Error(Ke(`The subagent model "${Q(s)}" for this configured default cannot authenticate in this session`,a.reason))}r(Ge,"resolvePiModel");async function so(e){try{return await e.listModels(e.harness)}catch{return[]}}r(so,"harnessModels");function ao(e,t,n){if(t===void 0||t.thinkingLevels.kind!=="closed")return;let{levels:o}=t.thinkingLevels;if(!o.includes(n))return o.length===0?`Model "${t.key}" (${e}) does not support thinking levels; launching with "${n}".`:`Thinking level "${n}" is not declared by ${e} model "${t.key}" (supported: ${o.join(", ")}); proceeding with "${n}".`}r(ao,"undeclaredLevelWarning");async function an(e,t){if(!e)return Y(t.thinking);let n=await so(t),o=n.find(s=>s.key===e.key),i=[];if(n.length>0&&!o&&i.push(`The ${t.harness} model list does not include "${e.key}"; launching with that key anyway.`),t.thinking!==void 0){let s=ao(t.harness,o,t.thinking);s!==void 0&&i.push(s)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(an,"resolveForeignModel");async function ln(e,t){let{harness:n}=t;if(wt(n))return Ge(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return an(e,o)}r(ln,"resolveSpawnModel");function ye(e,t){return{content:[{type:"text",text:e}],details:t}}r(ye,"successResult");var Ve=`
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
`,lo={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function O(e){let{items:t}=e;uo(t,e),await e.prepare?.();let n=co(e),o=[],i=[],s=r(({outcome:l,text:c})=>{o.push(l),i.push(c)},"record"),a;for(let l of t){let c=n.halt;if(c!==void 0&&a!==void 0){s(c.skip(l,a));continue}let d=await n.handle(l);s(d),c!==void 0&&c.halts(d.outcome)&&(a=l)}return ye(i.join(Ve),{[e.detailsKey]:o})}r(O,"runBatch");function co(e){if("render"in e){let n=e.render,o=e.halt;return{handle:r(async i=>{let s=await e.handleItem(i);return{outcome:s,text:n(s)}},"handle"),halt:o===void 0?void 0:{halts:r(i=>o.on(i),"halts"),skip:r((i,s)=>{let a=o.skip(i,s);return{outcome:a,text:n(a)}},"skip")}}}let t=e.halt;return{handle:e.handleItem,halt:t===void 0?void 0:{halts:r(n=>t.on(n),"halts"),skip:t.skip}}}r(co,"batchSteps");function uo(e,{toolName:t,param:n}){let o=e.map(a=>a.trim()),i=o.filter((a,l)=>o.indexOf(a)!==l);if(i.length===0)return;let s=lo[n];throw new Error(`${t} received duplicate ${s.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(uo,"rejectRepeatedKeys");var dn={user:"STOPPED BY THE USER before completion \u2014 output is partial; the task was NOT finished",agent:"STOPPED BY YOU before completion \u2014 output is partial; the task was NOT finished"},po={user:"STOPPED BY THE USER before the agent started \u2014 the task was NOT attempted",agent:"STOPPED BY YOU before the agent started \u2014 the task was NOT attempted"};function go(e){if(!_(e)||e.status!=="stopped")return dn.agent;let{stop:t}=e;return e.phase==="never-started"?po[t.initiator]:dn[t.initiator]}r(go,"stopNote");function cn(e){return!_(e)||e.status!=="stopped"?"":` (${go(e)})`}r(cn,"getStatusNote");var mo=`Success! You delegated to an agent. A notification will arrive when done - USER: do not poll, don't check status and don't duplicate the delegated work!{{#has_worktree}}
|
|
8
|
+
(Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
|
|
9
|
+
|
|
10
|
+
Agent ID: {{agent_id}}`,ho=`Agent QUEUED \u2014 the concurrency limit is reached ({{queue_running}} {{queue_running_label}} already spawned), so this task is waiting for a slot. It is NOT spawned yet: the process has not started. It will start automatically when another agent settles; you'll get a message when it starts and when it settles. Do NOT re-delegate \u2014 this task IS in flight.{{#has_worktree}}
|
|
11
|
+
(Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
|
|
12
|
+
|
|
13
|
+
Agent ID: {{agent_id}}`,fo=`{{result}}{{#error}}
|
|
14
|
+
|
|
15
|
+
Error: {{error}}{{/error}}{{#has_worktree}}
|
|
16
|
+
(Worktree: {{worktree_path}} (branch {{worktree_branch}}){{#retention}} \u2014 KEPT: {{retention}}{{/retention}}.{{#process_alive}} The agent process and its {{multiplexer_id}} pane stay until you call cleanup_cowboy_agent \u2014 its pane is closed, which ends that process.{{/process_alive}} {{#retention}}Clean the worktree up, then call cleanup_cowboy_agent to remove it.{{/retention}}{{^retention}}The worktree stays until you call cleanup_cowboy_agent to remove it \u2014 call it once the branch is merged or rejected.{{/retention}}){{/has_worktree}}{{status_note}}`,R={default:{name:"default",displayName:"Default",guidance:"Update your report file each time you make a commit",cues:{spawned:mo,queued:ho,settled:fo}}};import{z as I}from"zod";import hn from"mustache";function un(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}r(un,"worktreeVariables");function yo(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}r(yo,"outcomeVariables");function wo(e){return e?{...un(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}r(wo,"settledWorktreeVariables");function ze(e){return e.worktree?{agent_id:e.agentId,...un(e.worktree)}:{agent_id:e.agentId}}r(ze,"spawnCueContext");function pn(e){return{...ze(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}r(pn,"queuedCueContext");function gn(e){let{outcome:t,statusNote:n,worktree:o,multiplexerId:i}=e;return{...yo(t),...n?{status_note:n}:{},...wo(o),...i!=null?{multiplexer_id:i}:{}}}r(gn,"settledCueContext");var ko={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},bo={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},vo={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},To=Object.keys(ko),Ao=Object.keys(bo),xo=Object.keys(vo);function mn(e){switch(e){case"spawned":return To;case"queued":return Ao;case"settled":return xo;default:return}}r(mn,"cueVariables");var Co={ok:!0},_o="&",So=new Set(["name",_o,"#","^"]);function we(e,t,n){return hn.render(e[t],n,void 0,{escape:r(o=>o==null?"":String(o),"escape")})}r(we,"renderCue");function Eo(e){let t=e[4];return Array.isArray(t)?t:void 0}r(Eo,"spanChildren");function fn(e,t,n){for(let o of e){let[i,s]=o;if(i===">")return`partials are not supported: "{{>${s}}}"`;if(i==="=")return`delimiter changes are not supported: "{{=${s}=}}"`;if(So.has(i)&&!t.includes(s))return`unknown variable "{{${s}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let a=Eo(o);if(a){let l=fn(a,t,n);if(l)return l}}}r(fn,"findTemplateProblem");function yn(e,t){let n=mn(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let o;try{o=hn.parse(t)}catch(s){return{ok:!1,reason:`unparsable template: ${(s instanceof Error?s.message:String(s)).replace(/\s+/g," ").trim()}`}}let i=fn(o,n,e);return i?{ok:!1,reason:i}:Co}r(yn,"validateCueTemplate");var Oo=["spawned","queued","settled"],Ro=I.strictObject({spawned:I.string().optional(),queued:I.string().optional(),settled:I.string().optional()}).superRefine((e,t)=>{for(let n of Oo){let o=e[n];if(o===void 0)continue;let i=yn(n,o);i.ok||t.addIssue({code:"custom",message:i.reason,path:[n]})}}),wn=I.strictObject({name:I.string().optional(),display_name:I.string().optional(),guidance:I.string().optional(),cues:Ro.optional()});var Io={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function Po(e){return wn.parse(pe(e))}r(Po,"parseOrchestratorFile");async function X(e,t){return ge(e,Po,n=>n.name,t,Io)}r(X,"scanOrchestratorFilesInDir");function Ye(e,t,n,o){let i=new Map(e instanceof Map?e:Object.entries(e)),s=i.get("default")??R.default;for(let a of[t,n,o])for(let l of a)l.name&&i.set(l.name,No(i.get(l.name)??Mo(l.name,s),l));return i}r(Ye,"mergeOrchestrators");function Mo(e,t){return{...t,name:e,displayName:e}}r(Mo,"namedBase");function No(e,t){return{...e,name:t.name??e.name,displayName:t.display_name??e.displayName,cues:{...e.cues,...t.cues},guidance:t.guidance??e.guidance}}r(No,"applyOverride");function Z(){return ie().orchestrators}r(Z,"registry");function qs(e,t){let n=new Map;if(!t?.disableDefaultOrchestrators)for(let[o,i]of Object.entries(R))n.set(o,i);for(let[o,i]of e)n.set(o,i);Z().orchestrators=n}r(qs,"registerOrchestrators");function Ks(e,t,n){Z().scanDirs={user:e,project:t,shared:n??""}}r(Ks,"setOrchestratorScanDirs");async function Gs(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,o=Z().scanDirs,[i,s,a,l]=await Promise.all([t?Promise.resolve([]):X(st,n),X(o.user,n),X(o.shared,n),X(o.project,n)]),d=Ye(t?new Map:R,i,[],[]);return Ye(d,s,a,l)}r(Gs,"scanAndMergeOrchestrators");function Qe(e){let{orchestrators:t}=Z();if(!e)return;let n=t.get(e);if(n)return n;let o=e.toLowerCase(),i=[];for(let[s,a]of t)s.toLowerCase()===o&&i.push(a);return i.length===1?i[0]:void 0}r(Qe,"resolveOrchestrator");function Vs(){return[...Z().orchestrators.values()].map(e=>e.name)}r(Vs,"getAvailableOrchestrators");function kn(e){return typeof e=="string"&&e!==""?e:void 0}r(kn,"configuredString");function $o(){let e=kn(f().agent.defaultAgentType);if(e===void 0)return _e;let t=z(e);return t.kind==="resolved"?t.key:_e}r($o,"resolveDefaultAgentType");function Bo(){let e=kn(f().agent.defaultOrchestrator);return e===void 0?P:e===P||Qe(e)?e:P}r(Bo,"resolveDefaultOrchestratorName");function ke(e){return typeof e=="string"&&e!==""?e:$o()}r(ke,"resolveAgentTypeParam");function bn(){let e=Bo();return Qe(e)??(e===P?R[P]:void 0)??R[P]}r(bn,"resolveDefaultOrchestrator");function na(e){return E(e)?.worktreeCheckoutType??f().agent.worktreeCheckoutType}r(na,"resolveWorktreeCheckoutType");function vn(e){return typeof e=="string"&&e.trim()!==""?e:void 0}r(vn,"harnessParam");function Tn(e){let t=vn(e);if(t!==void 0&&x().get(t)!==void 0)return Ae(t,j())?t:void 0}r(Tn,"requestedHarnessId");function An(e){let t=vn(e);if(t===void 0)return;let n=x();if(n.get(t)===void 0)throw new Error(`Unknown harness_type "${t}": valid harnesses are ${n.ids().join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);let o=j();if(!Ae(t,o))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${lt(n.ids(),o).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}r(An,"resolveRequestedHarness");function be(e,t){if(t!==void 0)return t;let n=E(e)?.harnessType??f().agent.harnessType;return x().resolve(n,j())}r(be,"resolveHarnessType");function B(e=b()){let t=e.listAgents(Se).filter(n=>te(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(B,"formatActiveAgents");function Xe(e,t){let n={type:e.display.type,description:e.display.description};e.display.taskSlug&&(n.taskSlug=e.display.taskSlug),e.display.worktree&&(n.worktreePath=e.display.worktree.path,n.worktreeBranch=e.display.worktree.branch),e.display.worktree?.kind==="owned"&&(n.worktreeManaged=!0);let o=e.execution.host;if(o&&(n.herdrAgent=o.name,n.herdrPane=o.paneId,n.herdrTab=o.tabId),t?.includeStatus&&(n.status=M(e.lifecycle)),t?.includeRunInfo){let i=_(e.lifecycle)?e.lifecycle.completedAt-Et(e.lifecycle):0;n.durationMs=i,n.modelName=e.display.invocation?.modelName,n.modelId=e.display.invocation?.modelName,n.thinkingLevel=e.display.invocation?.thinkingLevel}return n}r(Xe,"buildAgentDetails");function Do(e){if(!_(e))return{kind:"stopped"};switch(e.status){case"completed":return{kind:"completed",result:e.result};case"error":return{kind:"failed",error:e.error};case"stopped":return{kind:"stopped"};default:return ft(e)}}r(Do,"settledOutcome");function Fo(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${M(e.lifecycle)}]`}r(Fo,"settledHeadline");function jo(e){let t=e.lifecycle,n=_(t)?t.worktreeRetentionReason:void 0,o=e.display.orchestration,i=e.display.worktree?.kind==="owned"?e.display.worktree:void 0;return we(o.cues,"settled",gn({outcome:Do(t),statusNote:cn(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?Bt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:f().multiplexer||_t}))}r(jo,"formatResultContent");var Ze=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=ke(t.agent_type),s=t.prompt,a=typeof t.task_name=="string"?t.task_name.trim():"";if(!a)throw new Error('cowboy_agent requires a short 2-3 word task name (e.g. "fix login flow") via the `task_name` parameter \u2014 it names the agent\'s branch/tab/worktree/agent so you can recognize it at a glance.');let l=ut(a),c=bn(),d=await Jt(i,void 0,(k,v)=>{n.ui.notify(k,v)});if(d.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${i}. Candidates: ${d.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(d.kind==="not-found")throw new Error(`Unknown agent type: ${i} \u2014 nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);let h=An(t.harness_type),g=be(d.key,h),p=tn(t),m=await ln(nn(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:p,listModels:r(async k=>{let v=await x().require(k).listModels({pi:C(),modelCatalog:oe(n.modelRegistry)}),F=xt(v);return F!==void 0&&n.hasUI&&n.ui.notify(F,"warning"),At(v)},"listModels")});for(let k of m.notices)n.ui.notify(k,"warning");let w=t.run_in_background!==!1;return new e({ctx:n,toolCallId:o,taskSlug:l,prompt:s,description:s.split(`
|
|
17
|
+
`)[0].slice(0,80)||s.slice(0,80),agentType:i,resolvedType:d.key,orchestrator:c,fork:E(i)?.fork??!1,modelChoice:rn(m.resolved),requestedHarness:h,isBackground:w})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:s}=this.intent,a=C(),l=b().mintSpawnId(),c=await this.expectedWorktree(a,l),d=this.intent.modelChoice?.thinking??void 0,h=ht(this.intent.modelChoice),{agentId:g,spawn:p}=await Ot().spawn(n,{spawnId:l,type:s,prompt:this.intent.prompt,description:this.intent.description,taskSlug:i,orchestration:this.intent.orchestrator,modelChoice:this.intent.modelChoice,requestedHarness:this.intent.requestedHarness,fork:this.intent.fork,worktree:c,invocation:{modelName:h,thinkingLevel:d,fork:this.intent.fork},runInBackground:o,signal:o?void 0:t});if(this.intent.toolCallId&&(p.display.toolCallId=this.intent.toolCallId),!o){let v=Xe(p,{includeRunInfo:!0});if(v.agentId=g,_(p.lifecycle)&&p.lifecycle.status==="error")throw new Error(`agent ${g} stopped with an error: ${p.lifecycle.error||"no error message was recorded"}`);return{message:`${Fo(p)}
|
|
18
|
+
|
|
19
|
+
${jo(p)}`,details:v}}let m=c;if(p.lifecycle.phase==="queued"){let v=b().listAgents(Se).filter(Te=>Te.lifecycle.phase==="spawned").length,F=we(this.intent.orchestrator.cues,"queued",pn({agentId:g,worktree:m,queueRunning:v})),q=Xe(p);return q.agentId=g,q.status="queued",{message:`[Agent queued] ${F}`,details:q}}let w=we(this.intent.orchestrator.cues,"spawned",ze({agentId:g,worktree:m})),k=Xe(p);return k.agentId=g,k.status="spawned",{message:`[Agent spawned] ${w}`,details:k}}async expectedWorktree(t,n){let o=await Nt(t,ne().cwd).catch(()=>{});if(o===void 0)return;let i=mt(f().agent.worktreeRoot,o);return{kind:"owned",path:gt(i,this.intent.taskSlug,n),branch:pt(this.intent.taskSlug,n)}}};async function xn(e,t,n,o){if(e.agents.length>1&&e.run_in_background===!1)throw new Error("run_in_background: false requires exactly one agent");let i=e.agents.map(d=>({...d,run_in_background:e.run_in_background})),s=await Promise.all(i.map(d=>Ze.parse(d,t,n)));Ho(s);let a=await Promise.all(s.map(d=>d.run(o))),l=a.map(d=>d.message).join(Ve),c={agents:a.map(d=>d.details)};return{message:l,details:c}}r(xn,"runDelegationBatch");function Ho(e){let t=e.map(o=>o.intent.taskSlug),n=t.filter((o,i)=>t.indexOf(o)!==i);if(n.length!==0)throw new Error(`cowboy_agent received the same task_name more than once: ${[...new Set(n)].join(", ")} \u2014 nothing was spawned. Give every item in \`agents\` its own task_name.`)}r(Ho,"rejectRepeatedTaskSlugs");async function Cn(e,t,n,o,i){let{message:s,details:a}=await xn(t,i,e,n);return ye(s,a)}r(Cn,"executeAgentTool");function Lo(e){switch(e.kind){case"stopped":return`Stopped agent ${e.agentId}`;case"already-settled":return`Agent ${e.agentId} is already ${e.status}. Active agents: ${e.activeAgents}`;case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`;case"failed":return`Failed to stop agent ${e.agentId}: ${e.error}`}}r(Lo,"renderStopOutcome");async function _n(e,t,n,o,i){let s=t.agent_ids;return O({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:s,render:Lo,handleItem:r(async a=>{let l=b().getSpawn(a);if(!l)return{kind:"unknown",agentId:a,activeAgents:B()};if(!te(l.lifecycle.phase))return{kind:"already-settled",agentId:a,status:M(l.lifecycle),activeAgents:B()};try{return await b().abort(a,"agent")?{kind:"stopped",agentId:a}:{kind:"failed",agentId:a,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:a,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}r(_n,"executeStopAgentTool");async function Oa(e,t){if(e.toolName!=="cowboy_agent")return;let o=e.input.agents??[],i=t.model?`${t.model.provider}/${t.model.id}`:null;for(let s of o){let a=s.agent_type,l=ke(a),c=E(l),d=Tn(s.harness_type),h=be(l,d),g=U(s.model),p=g??f().modelFor(l,i,c,h);if(p&&!g&&(s[We]=p),s.thinking===void 0){let m=f().thinkingFor(l,c,h,t.thinkingLevel);m!==void 0&&(s[qe]=m)}}}r(Oa,"toolCallListener");function Sn(e){switch(e.kind){case"pane-absent":return"pane-absent";case"pane-not-working":return`pane-not-working: ${e.state}`;case"forced":return"forced";case"pane-working":return"pane-working";case"pane-unreadable":return`pane-unreadable: ${e.detail}`;case"artifacts-ambiguous":return"artifacts-ambiguous"}}r(Sn,"formatBasis");function Uo(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${Sn(e.basis)})`}r(Uo,"formatSettlement");function En(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`;case"agent-active":return`the agent is still ${e.phase} and has not reported a result \u2014 stop it with stop_cowboy_agent, then clean up`;case"recovered-refusal":return`no settlement was recorded and herdr still reports the agent at work (${Sn(e.basis)}) \u2014 stop it before retrying`;case"ambiguous-artifacts":return`two artifacts answer to this id (${e.candidates.join(", ")}) \u2014 nothing was removed; work out which run owns the id before removing either by hand`}}r(En,"formatKeptReason");function Wo(e){switch(e.kind){case"closed":return"closed";case"open":return"open";case"gone":return"gone (herdr has no such pane)";case"unknown":return"unknown (the pane was not read)";case"none":return"none"}}r(Wo,"paneText");function On(e){switch(e.kind){case"removed":return`removed (${e.path})`;case"removal-failed":return`NOT removed \u2014 ${e.detail} (${e.path})`;case"kept":return`kept${e.path?` (${e.path})`:" (worktree path not recorded)"}`;case"absent":return`already gone (${e.path})`;case"none":return"none (agent ran without a worktree)"}}r(On,"worktreeText");function Rn(e){let t=e.branch;return`${t.kind==="deleted"?"deleted":t.kind==="kept"?`kept (${t.reason})`:t.kind==="delete-failed"?`NOT deleted \u2014 ${t.detail}`:"not applicable"}${e.branchName?` (${e.branchName})`:""}`}r(Rn,"branchText");function qo(e){return e?` forced${e.reason?` \u2014 ${En(e.reason)}`:""}`:""}r(qo,"forcedClause");function Je(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${En(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${qo(e.outcome.forced)}:`}r(Je,"headline");function In(e){let t=[Je(e),` agent status: ${Uo(e.settlement)}`,` pane: ${Wo(e.pane)}`,` worktree: ${On(e.worktree)}`,` branch: ${Rn(e)}`];if(e.source==="recovered"&&t.push(" recovered: no spawn record survived \u2014 this verdict rests on discovery (herdr's live read plus the worktree on disk)"),e.settlement.kind==="discovered"){let{path:n,present:o}=e.settlement.deliverable;t.push(o?` deliverable: UNREAD at ${n} \u2014 read it before deleting the directory`:` deliverable: none written (${n} does not exist)`)}return t.join(`
|
|
20
|
+
`)}r(In,"renderCleanupReport");function Pa(e){let t=e.pane.kind==="closed"?"pane closed":e.pane.kind==="open"?"pane left open":e.pane.kind==="gone"?"pane already gone":e.pane.kind==="unknown"?"pane state unknown":"no pane";return e.outcome.kind==="refused"?`${Je(e)} ${t}`:`${Je(e)} ${t}, worktree ${On(e.worktree)}, branch ${Rn(e)}`}r(Pa,"summarizeCleanupReport");function Ma(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Ma,"cleanupNeedsAttention");function Ko(e){switch(e.kind){case"cleaned":return In(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(Ko,"renderCleanupOutcome");async function Pn(e,t,n,o,i){let s=t.agent_ids;return O({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:s,render:Ko,handleItem:r(async a=>{let l=b();if(!l.getSpawn(a)&&(await l.locate(a)).kind==="not-found")return{kind:"unknown",agentId:a,activeAgents:B(l)};let c=await l.cleanup(a);return{kind:"cleaned",agentId:a,report:c}},"handleItem")})}r(Pn,"executeCleanupAgentTool");import*as Nn from"node:fs";import*as W from"node:path";function Mn(e){let t=W.normalize(e),{root:n}=W.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Mn,"normalizeRepoRoot");function Go(e,t){return Mn(e)===Mn(t)}r(Go,"isSameRepoRoot");function Vo(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(Vo,"formatOutsideRepoWarning");async function zo(e,t){let n=new Pt(e),o=await n.probe(["rev-parse","--show-toplevel"],t);if(o===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: ${t} is not inside a git repository (git rev-parse --show-toplevel failed). Refusing to merge without a repo-scope check \u2014 run the session from inside a git checkout or pass an explicit \`repo\` inside one.`);let i=await n.probe(["rev-parse","--git-common-dir"],o);if(i===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: could not resolve the git directory for ${t}. Refusing to merge without a repo-scope check.`);let{mainRoot:s}=Mt(i,o);if(!Nn.existsSync(W.join(s,".git")))throw new Error(`merge_cowboy_branch cannot verify the session repo: no main checkout found for ${t} (unsupported repo layout). Refusing to merge without a repo-scope check.`);return s}r(zo,"resolveSessionMainRoot");var Yo="has conflicts in:";function Qo(e){return e.includes(Yo)}r(Qo,"isConflictError");function Xo(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
|
|
21
|
+
`).map(n=>n.trim()).filter(n=>n!==""):[]}r(Xo,"parseConflictFiles");function Zo(e,t){return e.includes(`branch "${t}" does not exist`)}r(Zo,"isUnknownBranchError");async function $n(e,t,n,o,i){let s=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",a=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,l,c=r(()=>(l??=(async()=>{let d=ne().cwd;if(typeof d!="string"||d.trim()==="")throw new Error("merge_cowboy_branch cannot verify the session repo: the session working directory is unavailable, so the repo-scope check is impossible. Refusing to merge without a repo-scope check.");return{sessionRoot:await zo(C(),d),cwd:a??d}})(),l),"mergeScope");return O({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,prepare:r(async()=>{Pe(s,"target");for(let d of t.branches)Pe(d.trim(),"branch");await c()},"prepare"),halt:{on:r(d=>d.kind==="conflict","on"),skip:r((d,h)=>{let g=d.trim(),p=`not attempted \u2014 the merge of "${h.trim()}" conflicted and is still in progress`;return{outcome:{kind:"not-attempted",branch:g,reason:p},text:`"${g}" ${p}.`}},"skip")},handleItem:r(async d=>{let{sessionRoot:h,cwd:g}=await c(),p=d.trim();try{let m=await $t(C(),{cwd:g,branch:p,target:s}),w=Go(m.mainRoot,h)?void 0:Vo(m.mainRoot,h);if(w!==void 0)try{i.ui.notify(w,"warning")}catch{}let k=w!==void 0?`${w}
|
|
22
|
+
`:"";return m.alreadyMerged?{outcome:{kind:"already-merged",branch:p,target:s},text:`${k}"${p}" is already merged into "${m.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:p,target:m.target,output:m.output},text:`${k}Merged "${p}" into "${m.target}" in ${m.mainRoot}.`+(m.output?`
|
|
23
|
+
${m.output}`:"")}}catch(m){let w=m instanceof Error?m.message:String(m);return Qo(w)?{outcome:{kind:"conflict",branch:p,target:s,files:Xo(w)},text:`"${p}": ${w}`}:Zo(w,p)?{outcome:{kind:"unknown",branch:p},text:`"${p}": ${w}`}:{outcome:{kind:"failed",branch:p,error:w},text:`"${p}": ${w}`}}},"handleItem")})}r($n,"executeMergeBranchTool");async function Bn(e,t,n,o,i){let s=t.message.trim();return O({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,prepare:r(()=>{if(s==="")throw new Error("message is required")},"prepare"),handleItem:r(async a=>{let l=b().getSpawn(a);if(!l){let g=`not found. Active agents: ${B()}`;return{outcome:{kind:"refused",agentId:a,reason:g},text:`Agent ${a} was not steered: ${g}`}}let c=M(l.lifecycle),d;try{d=await b().steer(a,s)}catch(g){d={kind:"refused",reason:`steering failed: ${ee(g)}`}}if(d.kind==="refused")return{outcome:{kind:"refused",agentId:a,reason:d.reason},text:`Agent ${a} was not steered (${c}): ${d.reason}`};if(d.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:a,reason:d.reason},text:`Agent ${a} had settled (${c}) and the message reached its pane, but it was not revived: ${d.reason}`};let h=c!=="spawned"&&l.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:a},text:h?`Agent ${a} had settled (${c}) \u2014 revived: the message was delivered to its pane and the agent is spawned again. Merge nothing yet; a new completion message will arrive when it settles again.`:c==="spawned"?`Message delivered to spawned agent ${a}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${a} was delivered to (${c}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r(Bn,"executeSteerAgentTool");var A={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},jn=Object.values(A),J={type:"json_schema",strict:"prefer"};function Jo(e){let t=D.Object({prompt:H.properties.agents.items.properties.prompt,task_name:H.properties.agents.items.properties.task_name,agent_type:D.Optional(D.Union([D.String(),D.Null()],{description:`Optional agent type. Omit it, or pass null, to use the configured default agent type \u2014 never pass a type the user did not ask for. An unknown or ambiguous name is rejected before any agent in the batch spawns.${e.length>0?` Available: ${e.join(",")}`:""}`})),model:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type},{additionalProperties:!1,required:["prompt","task_name"]});return D.Object({agents:D.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Jo,"cowboyAgentsSchemaWithTypes");function Hn(e){let t=Jo(en()),n={name:A.agent,label:A.agent,description:"Delegate one or more tasks to agents. Each agent gets an isolated worktree and a fresh pi process \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. When an agent settles, the completion message names its `cow-` branch and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.",parameters:t,execute:Cn,constrainedSampling:J};e.registerTool(n)}r(Hn,"registerAgentTool");function ei(e,t){f().mutate.agent.setExtensionEnabled(t),t?ti(e):ni(e)}r(ei,"setExtensionEnabled");function ti(e){let t=C();Hn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...jn])]),de(e)}r(ti,"activateExtension");function ni(e){let t=C();t.setActiveTools(t.getActiveTools().filter(n=>!jn.includes(n))),de(e)}r(ni,"deactivateExtension");function fl(e){Hn(e);let t={name:A.stopAgent,label:A.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping interrupts the pi process (its pane is left in place) and settles the agent as stopped. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Wt,execute:_n,constrainedSampling:J,renderResult:r((s,a,l,c)=>{let d=c.isError??!1,h=s.content.at(0),g=h?.type==="text"?h.text:"",p=d?l.fg("error","\u2717"):l.fg("success","\u2713");return new Dn(`${p} ${g}`,0,0)},"renderResult")};e.registerTool(t);let n={name:A.mergeBranch,label:A.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:Kt,execute:$n,constrainedSampling:J};e.registerTool(n);let o={name:A.steerAgent,label:A.steerAgent,description:"Send one message to one or more agents in one call: pass every id in `agent_ids` and the single `message` delivered to each. Each id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A repeated id in `agent_ids` is rejected before anything is delivered \u2014 pass each id once. A spawned agent receives the message before its next model call; a SETTLED one is REVIVED \u2014 spawned again, given the message, and it sends you another completion message when it settles again. That second result arrives only as that completion message: the spawn's result promise closed with the first turn and never opens again. Delivery is fire-and-forget: nothing here waits for an agent to act on it, so do not poll for a reply. The message is entered into the agent's pi session, so it can also be a bash command: `!command` runs the command and sends its output to the agent's context; `!!command` runs it without adding the output to the agent's context. A QUEUED agent cannot be steered \u2014 it has no pane yet; wait for a concurrency slot first. An agent whose pane is gone (cleaned up) cannot be steered either, and neither can an agent being TORN DOWN \u2014 wait for its report. Every refusal states its reason and what to do about it.",parameters:Gt,execute:Bn,constrainedSampling:J};e.registerTool(o);let i={name:A.cleanupAgent,label:A.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:qt,execute:Pn,constrainedSampling:J};e.registerTool(i),e.registerMessageRenderer("subagent-result",(s,a,l)=>{let c=typeof s=="object"&&typeof s.content=="string"?s.content:"",d=/\b(error|stopped)\b/.test(c.slice(0,200)),h=l.fg(d?"error":"success",d?"\u2717":"\u2713");return new Dn(`${h} ${c}`,0,0)})}r(fl,"registerTools");async function Fn(e,t){let n=await x().listModelOptions({pi:e,modelCatalog:oe(t.modelRegistry)},j());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Fn,"harnessModelOptions");var Ln="cowboy",ri={wt:"worktree",sp:"spawn",st:"status"};function yl(e,t){e.registerCommand(Ln,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(yl,"registerUnavailableCowboyCommand");function wl(e){e.registerCommand(Ln,{description:"Manage agents: status, spawn, settings. `status` lists spawned, queued and settled agents; `spawn` opens the spawn wizard; `worktree` creates one git worktree with no agent attached to it. `status`, `spawn` and `worktree` also answer to `st`, `sp` and `wt`. `enable`/`disable` load or unload the cowboy tools. Pass `model` (optionally a provider/model-id) to set the model agents use for this session \u2014 opens pi's model picker.",getArgumentCompletions:r(async t=>(await import("./model-picker-74J7Z4WJ.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{Rt(n);let[o,...i]=t.trim().split(/\s+/),s=ri[o]??o,a=[s,...i].join(" ");if(a==="enable"||a==="disable"){let d=a==="enable";if(d&&Ie()===null){n.ui.notify(Ce,"warning");return}if(le()===d){n.ui.notify(`pi-cowboy is already ${d?"enabled":"disabled"}`,"info");return}ei(n.ui,d),n.ui.notify(d?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(Ie()===null){n.ui.notify(Ce,"warning");return}if(s==="worktree"){let{showWorktreeCommandMenu:d}=await import("./menu-worktree-command-DYLJ34X3.js");await d(n,i.join(" "));return}if((s==="model"||a==="spawn"||a==="status")&&!le()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(s==="model"){let{handleModelArg:d}=await import("./model-picker-74J7Z4WJ.js");await d(i.join(" "),n);return}if(a==="spawn"||a==="status"){let{showAgentsActionMenu:d}=await import("./menus-RQLX4WC2.js");await d(n,a,await Fn(e,n));return}if(a!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-RQLX4WC2.js");await c(n,await Fn(e,n))},"handler")})}r(wl,"registerCowboyCommand");import*as Un from"node:fs";import{tmpdir as oi}from"node:os";import*as ve from"node:path";async function Wn(e,t){try{return await It(e).probe(t),K(dt)}catch{return K(["checkout"])}}r(Wn,"detectCowAvailability");function qn(e){let t=ve.resolve(e??ot());for(;;){try{if(Un.statSync(t).isDirectory())return t}catch{}let n=ve.dirname(t);if(n===t)return oi();t=n}}r(qn,"probeTargetFor");function ii(e){return(t,n,o)=>e.exec(t,n,o)}r(ii,"execOf");function Il(e){return Kn(e,Re())}r(Il,"startCowSupportProbe");function Pl(e){let t=Re();return re(t,at()),Kn(e,t)}r(Pl,"refreshCowSupportProbe");function Kn(e,t){let n=qn(f().agent.worktreeRoot);return Wn(ii(e),n).then(o=>{re(t,o)},()=>{re(t,K(["checkout"]))})}r(Kn,"probe");export{Ue as a,Vi as b,zi as c,no as d,E as e,en as f,Yi as g,Qi as h,R as i,qs as j,Ks as k,Gs as l,Vs as m,$o as n,bn as o,na as p,be as q,Xe as r,Fo as s,jo as t,Oa as u,En as v,Pa as w,Ma as x,De as y,le as z,gi as A,Il as B,Pl as C,ei as D,ti as E,ni as F,fl as G,yl as H,wl as I};
|
|
24
|
+
//# sourceMappingURL=chunk-PYOLHDZJ.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as l,n as h}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{h as l,n as h}from"./chunk-J525HRTW.js";import{a as r}from"./chunk-254PTGN5.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
|
|
2
|
+
//# sourceMappingURL=chunk-XKS73JKY.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as
|
|
1
|
+
import{B as ue,C as D,J as le,S as pe,ja as fe,n as se,q as I,w as ce,y as de}from"./chunk-JIAP5YBM.js";import{a as i,d as A,i as G,j as M}from"./chunk-254PTGN5.js";import*as v from"node:fs";import*as k from"node:path";var qe=`import ctypes, sys
|
|
2
2
|
libc = ctypes.CDLL(None, use_errno=True)
|
|
3
3
|
# CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
|
|
4
4
|
if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
|
|
@@ -12,4 +12,4 @@ ${n}`;return`merge of "${r}" into "${e}" ${o}
|
|
|
12
12
|
The merge is still in progress in ${t}. No conflict was resolved automatically.`}i(Ae,"conflictMessage");var Z=class{constructor(e){this.runner=e}runner;static{i(this,"BranchCleaner")}async delete(e,t){let{branch:n,worktreePath:o,repoCwd:a}=e;if(!n.startsWith("cow-"))return{kind:"not-applicable"};try{if(!await q(this.runner,n,a))return{kind:"not-applicable"};let s=await this.runner.run(["merge-base","--is-ancestor","--",n,"HEAD"],a);if(s===void 0)throw new h(`git merge-base --is-ancestor -- ${n} HEAD could not run in ${a}`);return s.code!==0?{kind:"kept",reason:"unmerged"}:t&&await t(o)?{kind:"kept",reason:"checked-out"}:await V(this.runner,n,a)}catch(s){return{kind:"delete-failed",detail:s instanceof Error?s.message:String(s)}}}};async function tr(r,e){return new X(new y(r)).merge(e)}i(tr,"mergeBranchIntoTarget");async function Se(r,e,t){return new Z(new y(r)).delete(e,t)}i(Se,"deleteWorktreeBranch");function Ie(r,e){return new S(new y(r),e)}i(Ie,"worktree");async function Me(r,e){return Ie(r,e).isDirty()}i(Me,"isWorktreeDirty");async function ar(r,e){let t=await Ie(r,e).isDirty();return t===void 0?{kind:"unverifiable",detail:"git status probe failed"}:t?{kind:"dirty"}:null}i(ar,"worktreeRetentionReason");function De(r){switch(r.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${r.detail})`}}i(De,"formatRetentionClause");import*as P from"node:fs";import*as W from"node:path";function Q(r){return{kind:"recorded",phase:r.lifecycle.phase}}i(Q,"recordedSettlement");function Le(r){let e=r.pane?{paneId:r.pane.paneId,origin:r.paneCreated?"self-created":"adopted"}:null,t=r.worktree;return t!==null&&t.repoCwd!==void 0?{kind:"worktree",worktree:{workspaceId:t.workspaceId,worktreePath:t.path,repoCwd:t.repoCwd,branchName:r.branch},pane:e}:r.worktreeManaged?{kind:"worktree-unlocatable",branchName:r.branch,worktreePath:t?.path??null,pane:e}:{kind:"no-worktree",pane:e}}i(Le,"planRecovered");async function ee(r,e,t){if(e?.force!==void 0)return{kind:"removable"};let n=await r(t.worktreePath);return n===void 0?{kind:"kept",reason:{kind:"unverifiable",detail:"git status probe failed"}}:n?{kind:"kept",reason:{kind:"dirty"}}:{kind:"removable"}}i(ee,"assessRemovability");function ze(r){if(r===void 0)return{kind:"allow",basis:{kind:"pane-absent"}};switch(r.state){case"working":return{kind:"refuse",basis:{kind:"pane-working"}};case"idle":case"blocked":case"done":case"unknown":return{kind:"allow",basis:{kind:"pane-not-working",state:r.state}};default:return M(r.state)}}i(ze,"recoveryGate");function te(r){switch(r.kind){case"pane-working":return{kind:"recovered-refusal",basis:r};case"pane-unreadable":return{kind:"unverifiable",detail:`the pane state could not be read (${r.detail})`};case"pane-absent":case"pane-not-working":case"forced":case"artifacts-ambiguous":return{kind:"unverifiable",detail:"the run's end could not be established"}}}i(te,"recoveryRefusalReason");function B(r,e,t,n,o){let a=t.kind==="worktree"?{kind:"kept",path:t.worktree.worktreePath}:t.kind==="worktree-unlocatable"?{kind:"kept",path:t.worktreePath}:{kind:"none"};return{agentId:r,source:e,outcome:{kind:"refused",reason:o.reason,forceable:o.forceable},branchName:t.kind==="worktree"?t.worktree.branchName:t.kind==="worktree-unlocatable"?t.branchName:void 0,settlement:n,pane:t.pane?{kind:"open",paneId:t.pane.paneId}:{kind:"none"},worktree:a,branch:{kind:"not-applicable"}}}i(B,"keptReport");function Be(r,e,t,n){return{agentId:r,source:e,outcome:{kind:"refused",reason:{kind:"ambiguous-artifacts",candidates:n},forceable:!1},settlement:t,pane:{kind:"none"},worktree:{kind:"kept",path:null},branch:{kind:"not-applicable"}}}i(Be,"ambiguousReport");function re(r){return r?.force!==void 0?{forced:r.force}:{}}i(re,"forcedFields");function _e(r,e,t,n,o,a){return{agentId:r,source:e,outcome:{kind:"torn-down",...re(a)},branchName:t.kind==="worktree"?t.worktree.branchName:void 0,settlement:n,pane:o.pane,worktree:o.worktree,branch:o.branch}}i(_e,"assembleReport");function wr(r){return r.outcome.kind==="refused"&&r.outcome.forceable}i(wr,"isForceableRefusal");function ne(r){return r.worktree.kind==="removed"||r.worktree.kind==="absent"?!0:r.worktree.kind==="none"?r.pane.kind==="none"||r.pane.kind==="closed":!1}i(ne,"shouldDropSpawn");function _(r){return r.workspaceId!==void 0?"multiplexer":"git"}i(_,"removalMechanismOf");function Ne(r,e,t){if(r===null)return{kind:"none"};if(!t)return{kind:"leave-open"};switch(e){case"multiplexer":return{kind:"closed-with-workspace"};case"git":case null:switch(r.origin){case"self-created":return{kind:"close"};case"adopted":return{kind:"leave-open"};default:return M(r.origin)}default:return M(e)}}i(Ne,"paneDispositionFor");var Ct=le("cleanup");function Rt(r,e){let t=r.pane,n=t?.workspaceId??r.worktree?.workspaceId;if(!(t===null||n===void 0))return{multiplexer:e,name:r.branch,paneId:t.paneId,tabId:t.tabId,workspaceId:n,paneCreated:r.paneCreated}}i(Rt,"hostRefFor");async function xt(r,e,t){if(!t)throw new Error(`cleanup has a pane (${e.paneId}) with no host address`);return await r.closePane(t),{kind:"closed",paneId:e.paneId}}i(xt,"closeOwnedPane");async function Ge(r,e,t){let n=t!==void 0&&e.workspaceId!==void 0;return(n?await r.removeWorktree(t):await r.removeGitWorktree(e.worktreePath,e.repoCwd))?{kind:"removed",path:e.worktreePath}:{kind:"removal-failed",path:e.worktreePath,detail:n?"herdr did not confirm the worktree removal":"git did not confirm the worktree removal"}}i(Ge,"removeOwnedTree");async function N(r,e,t,n,o){if(e===null)return{kind:"none"};switch(Ne(e,t,n).kind){case"none":return{kind:"none"};case"closed-with-workspace":return{kind:"closed",paneId:e.paneId};case"close":return xt(r,e,o);case"leave-open":return{kind:"open",paneId:e.paneId}}}i(N,"paneOutcomeFor");async function Pt(r,e){if(e===null)return{kind:"none"};let t;try{t=await r.observe(e)}catch{return{kind:"unknown",paneId:e.paneId}}return t===void 0?{kind:"gone",paneId:e.paneId}:{kind:"open",paneId:e.paneId}}i(Pt,"paneOutcomeForAbsentTree");async function Et(r,e,t){if(e.kind==="no-worktree")return{pane:await N(r,e.pane,null,!0,t),worktree:{kind:"none"},branch:{kind:"not-applicable"}};let{worktree:n,pane:o}=e,a=await Ge(r,n,t);return a.kind==="removed"?{pane:await N(r,o,_(n),!0,t),worktree:a,branch:await r.deleteBranch({branch:n.branchName,worktreePath:n.worktreePath,repoCwd:n.repoCwd})}:{pane:await N(r,o,_(n),!1,t),worktree:a,branch:{kind:"not-applicable"}}}i(Et,"removeResources");function oe(r){return{async removeWorktree(e,t){let n=e.worktree,o=e.pane,a=e.kind==="detached"?void 0:e.ref;try{if(!await r.worktreeExists(n.worktreePath))return{kind:"absent",path:n.worktreePath};let s=await ee(r.isWorktreeDirty,t,n);if(s.kind==="kept")return{kind:"kept",path:n.worktreePath,reason:s.reason};let c=await Ge(r,n,a);if(c.kind==="removal-failed")return c;let u=_(n);await N(r,o,u,!0,a);let d=await r.deleteBranch({branch:n.branchName,worktreePath:n.worktreePath,repoCwd:n.repoCwd});return{kind:"removed",path:n.worktreePath,branchName:n.branchName,via:u,branch:d}}catch(s){return{kind:"removal-failed",path:n.worktreePath,detail:A(s)}}}}}i(oe,"createWorktreeTeardown");function Pr(r){let e=oe(r);function t(a,s){return{kind:"discovered",basis:s,deliverable:r.deliverable(a)}}i(t,"recovered");async function n(a,s,c,u){if(c!==void 0){let p=Q(c);return pe(c.lifecycle)?{kind:"torn-down",settlement:p}:{kind:"refused",settlement:p,reason:{kind:"agent-active",phase:c.lifecycle.phase},forceable:!1}}if(u?.force!==void 0)return{kind:"torn-down",settlement:t(a,{kind:"forced"})};let d;if(s.pane!==null)try{d=await r.observe(s.pane)}catch(p){let m={kind:"pane-unreadable",detail:A(p)};return{kind:"refused",settlement:t(a,m),reason:te(m),forceable:!0}}let l=ze(d);return l.kind==="allow"?{kind:"torn-down",settlement:t(a,l.basis)}:{kind:"refused",settlement:t(a,l.basis),reason:te(l.basis),forceable:!0}}i(n,"verdictFor");async function o(a,s,c){let u=s.getSpawn(a),d=await r.locate(a,u);if(d.kind==="not-found")throw new Error(`Agent ${a} not found.`);if(d.kind==="ambiguous")return Be(a,u===void 0?"recovered":"tracked",u===void 0?t(a,{kind:"artifacts-ambiguous"}):Q(u),d.candidates.map(x=>x.worktreePath));let l=Le(d),p=await n(a,d,u,c);if(p.kind==="refused")return B(a,d.source,l,p.settlement,{reason:p.reason,forceable:p.forceable});let m=u?.execution.harness;if(m!==void 0)try{await r.harnessTeardown(m,{paneId:d.pane?.paneId??null,cwd:d.worktree?.path??null,subagentId:a})}catch(x){Ct.warn("harness teardown failed during cleanup",{spawnId:a,harness:m,error:A(x)})}if(l.kind==="worktree-unlocatable"){if(l.worktreePath!==null&&!await r.worktreeExists(l.worktreePath)){let x={agentId:a,source:d.source,outcome:{kind:"torn-down",...re(c)},branchName:l.branchName,settlement:p.settlement,pane:await Pt(r,d.pane),worktree:{kind:"absent",path:l.worktreePath},branch:{kind:"not-applicable"}};return ne(x)&&u!==void 0&&s.dropSpawn(u),x}return B(a,d.source,l,p.settlement,{reason:{kind:"unverifiable",detail:"missing worktree path or repo cwd"},forceable:!1})}if(l.kind==="worktree"){let x=await ee(r.isWorktreeDirty,c,l.worktree);if(x.kind==="kept")return B(a,d.source,l,p.settlement,{reason:x.reason,forceable:!0})}let T=await Et(r,l,Rt(d,r.multiplexer)),ae=_e(a,d.source,l,p.settlement,T,c);return ne(ae)&&u!==void 0&&s.dropSpawn(u),ae}return i(o,"cleanupAgent"),{...e,cleanupAgent:o}}i(Pr,"createCleanup");import*as He from"node:path";async function Wt(r,e,t){let n=await U(r,["rev-parse","--verify","--quiet",`refs/heads/${t}`],e,R);return n===void 0?!0:n.code===0}i(Wt,"branchExisted");async function je(r,e){let t=e.branch.trim();if(t==="")throw new h("worktree checkout requires a branch name");let n=await z(r,e.repoCwd),o=He.resolve(e.path),a=e.materialization??se,s=e.dirtyCheckout??I,c=await Wt(r,n,t),u=await U(r,["worktree","add",...Ee(a),"-b",t,o,e.base??"HEAD"],n,R);if(u===void 0||u.code!==0)throw await E(r,n,o),c||await O(r,t,n),new h(u===void 0?`git worktree add for "${t}" could not run (worktree removed)`:`git worktree add for "${t}" failed (worktree removed): ${(u.stderr||u.stdout||`exit ${u.code}`).slice(0,300)}`);let d=await xe(r,["branch","--show-current"],o);if(d!==t)throw await E(r,n,o),await O(r,t,n),new h(d===void 0?`worktree created at ${o} but its branch could not be verified (worktree removed)`:`worktree created at ${o} is on branch "${d||"(detached)"}", not the requested "${t}" (worktree removed). The branch "${d}" still exists.`);let l;try{l=await We(r,o,a,s)}catch(p){await E(r,n,o),await O(r,t,n);let m=p instanceof Error?p.message:String(p);throw new h(`worktree created but ${a} materialization failed (worktree removed): ${m}`)}if(l.kind==="cow-fallback"){let p=s==="dirty"?" The parent's uncommitted work was not carried over.":"";e.notify?.(`[cowboy] ${l.reason}${p} Nothing is shared with the parent checkout.`,"warning")}return{path:o,branch:t,repoCwd:n,materialization:l}}i(je,"createWorktreeCheckout");function Tt(r){try{let e=P.statSync(r,{bigint:!0});return`${e.dev}:${e.ino}`}catch{return W.resolve(r)}}i(Tt,"canonicalRepoKey");var Fe=class r{static{i(this,"AgentSandbox")}branch;projectTrusted;host;placement;current={kind:"bound"};constructor(e,t,n,o){this.host=e,this.placement=t,this.branch=n,this.projectTrusted=o}static async allocate(e,t){let{naming:n,parentCwd:o,worktreeRoot:a,materialization:s,dirtyCheckout:c,notify:u,host:d}=t,l=n.kind==="generated"?ce(n.taskSlug,n.id):n.branch.trim();if(n.kind==="explicit"&&l==="")throw new Error("explicit worktree naming requires a branch name");let p;try{p=await z(e,o)}catch{return u?.("[cowboy] Parent is not inside a git repository \u2014 spawning in the parent cwd without a worktree","warning"),new r(d,{kind:"parent-cwd"},l,!0)}let m=await Ot(e,{repoCwd:p,path:W.join(de(a,p),l),branch:l,materialization:s,dirtyCheckout:c,notify:u,host:d});return new r(d,{kind:"worktree",checkout:{path:m.path,branch:m.branch,repoCwd:m.repoCwd},ref:m.ref},l,!0)}get state(){return this.current}get worktree(){return this.placement.kind==="worktree"?{path:this.placement.checkout.path,branch:this.placement.checkout.branch}:void 0}get hostRef(){return this.placement.kind==="worktree"?this.placement.ref:void 0}async teardown(e,t){let n=this.placement;if(n.kind==="parent-cwd")return this.current={kind:"destroyed"},{kind:"absent"};if(this.current.kind==="destroyed")return{kind:"absent",path:n.checkout.path};let o=await oe(St(e,this.host)).removeWorktree({kind:"adopted",worktree:{workspaceId:n.ref.workspaceId,worktreePath:n.checkout.path,repoCwd:n.checkout.repoCwd,branchName:n.checkout.branch},pane:{paneId:n.ref.paneId,origin:n.ref.paneCreated===!0?"self-created":"adopted"},ref:n.ref},t);return this.current=At(o),o}};function At(r){switch(r.kind){case"kept":return{kind:"preserved",reason:r.reason};case"removed":case"absent":return{kind:"destroyed"};case"removal-failed":return{kind:"teardown-failed",detail:r.detail}}}i(At,"stateAfterTeardown");async function Ot(r,e){let t=W.resolve(e.path);return P.mkdirSync(W.dirname(t),{recursive:!0}),fe().run(Tt(e.repoCwd),()=>$t(r,e.host,{...e,path:t}))}i(Ot,"createAdoptedWorktree");async function $t(r,e,t){let{repoCwd:n,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:u}=t,d;try{d=await je(r,{repoCwd:n,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:u})}catch(p){throw Ue(p,await Ke(r,n,o))}let l;try{l=await e.hostAt({unit:"pane",cwd:d.path,label:a,name:a,checkout:{path:d.path,repoCwd:n,branch:d.branch}})}catch(p){let m=await Ke(r,n,d.path),T=await O(r,d.branch,n);throw Ue(p,`${m}. ${ie(d.branch,T)}`)}return{path:d.path,branch:d.branch,repoCwd:n,materialization:d.materialization,ref:l}}i($t,"adoptWorktree");function St(r,e){return{isWorktreeDirty:i(t=>Me(r,t),"isWorktreeDirty"),worktreeExists:i(async t=>P.existsSync(t),"worktreeExists"),removeWorktree:i(t=>e.release(t,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(t,n)=>(await E(r,n,t),!P.existsSync(t)),"removeGitWorktree"),deleteBranch:i(t=>Se(r,t,n=>e.isAttached(n,{repoCwd:t.repoCwd})),"deleteBranch"),closePane:i(async t=>{await e.release(t,"placement")},"closePane"),harnessTeardown:i(async()=>{},"harnessTeardown")}}i(St,"cleanupDeps");async function Ke(r,e,t){return await E(r,e,t),P.existsSync(t)?`worktree ${t} NOT removed \u2014 inspect it manually`:`worktree ${t} removed`}i(Ke,"removeFailedCheckout");function Ue(r,e){return new Error(`could not create the herdr worktree: ${A(r)}
|
|
13
13
|
|
|
14
14
|
Launch-failure cleanup: ${e}.`)}i(Ue,"createFailureMessage");function ie(r,e){switch(e.kind){case"deleted":return`branch ${r} deleted`;case"kept":return`branch ${r} kept (${e.reason})`;case"delete-failed":return`branch ${r} NOT deleted \u2014 ${e.detail}`;case"not-applicable":return`branch ${r} already gone`}}i(ie,"formatLaunchedBranchOutcome");function Br(r){switch(r.kind){case"removed":return r.via==="multiplexer"?`Launch-failure cleanup: worktree ${r.path} removed \u2014 its workspace, tab, and pane were closed with it. ${ie(r.branchName,r.branch)}.`:`Launch-failure cleanup: worktree ${r.path} removed. ${ie(r.branchName,r.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${r.path} KEPT \u2014 ${De(r.reason)}. No agent spawn exists for it, so extension cleanup cannot see it \u2014 inspect and remove it manually.`;case"removal-failed":return`Launch-failure cleanup FAILED for worktree ${r.path}: ${r.detail} \u2014 it may still exist, and no agent spawn exists for it, so inspect it manually.`;case"absent":return"Launch-failure cleanup: no worktree residue was left behind."}}i(Br,"formatLaunchCleanupNote");export{Mt as a,Ce as b,y as c,xe as d,$ as e,Bt as f,z as g,E as h,Ht as i,jt as j,Te as k,tr as l,Se as m,Me as n,ar as o,De as p,wr as q,Pr as r,Fe as s,Ot as t,Br as u};
|
|
15
|
-
//# sourceMappingURL=chunk-
|
|
15
|
+
//# sourceMappingURL=chunk-ZLKJYRKY.js.map
|
|
@@ -46,6 +46,7 @@ export declare class ConfigStore {
|
|
|
46
46
|
global: Record<string, Record<string, unknown>>;
|
|
47
47
|
project: Record<string, Record<string, unknown>>;
|
|
48
48
|
};
|
|
49
|
+
harnessEnv(harnessId: AnyHarnessId): Readonly<Record<string, string>>;
|
|
49
50
|
reportHarnessConfigIssue(id: AnyHarnessId, issue: HarnessConfigIssue): void;
|
|
50
51
|
get concurrency(): ConcurrencyConfig;
|
|
51
52
|
get sessionDefaultModel(): string | null;
|
|
@@ -55,7 +56,7 @@ export declare class ConfigStore {
|
|
|
55
56
|
defaultThinkingForHarness(harness: AnyHarnessId): string | null;
|
|
56
57
|
thinkingFor(type: string, agentConfig: {
|
|
57
58
|
thinkingByFamily?: ThinkingByFamily;
|
|
58
|
-
} | undefined, harnessId: AnyHarnessId): string | undefined;
|
|
59
|
+
} | undefined, harnessId: AnyHarnessId, parentThinking?: string): string | undefined;
|
|
59
60
|
configuredHarnessIds(): AnyHarnessId[];
|
|
60
61
|
modelOverrideLevels(type: string): ConfigLayerPresence;
|
|
61
62
|
harnessDefaultModelLevels(harness: AnyHarnessId): ConfigLayerPresence;
|
package/dist/index.js
CHANGED
|
@@ -1,33 +1,35 @@
|
|
|
1
|
-
import{B as bt,E as At,F as Se,G as xt,H as Rt,I as It,a as st,b as ot,c as at,d as lt,e as ut,h as dt,j as ct,k as pt,l as gt,p as mt,q as ht,r as ve,s as ft,t as yt,u as wt,y as vt,z as $}from"./chunk-UIP66WFU.js";import{a as Ze,f as et,g as we,h as tt,m as nt,n as rt,o as it,r as kt,s as Pt}from"./chunk-FI6HUFY7.js";import{$ as Ne,A as je,Aa as Qe,B as f,Ba as ze,F as j,Fa as _,G as He,Ha as Ye,Ia as Ve,Ja as fe,K as z,Ka as ye,L as pe,La as Z,Ma as Xe,N as $e,Na as Je,Oa as St,P as ge,Q as H,V as Y,X as We,Y as qe,Z as N,_ as V,a as C,aa as me,c as Te,d as I,e as Le,f as Fe,fa as _e,ga as Ue,ha as Be,i as Me,ia as b,ja as X,la as he,ma as P,pa as L,sa as J,t as G,v as K,wa as R,x as De,y as Q,ya as Ge,z as Oe,za as Ke}from"./chunk-HFCCRB3G.js";import{a as s}from"./chunk-OO54ZZLJ.js";import*as F from"node:path";function te(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(te,"findTaskDedup");var M=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?V(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}},ee=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(h=>h.display.taskSlug===e.taskSlug&&qe(h.lifecycle.phase)),g=te(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},u=this.deps.spawn(r,n,a);return this.deps.getSpawn(u)?.lifecycle.phase==="queued"?{status:"queued",agentId:u,queuePosition:this.deps.queuePosition(u)}:{status:"admitted",agentId:u}}};import Ct from"node:fs";var ne=class{constructor(e){this.resultFile=e}resultFile;static{s(this,"FileDeliverable")}async readDeliverable(){try{let e=Ct.statSync(this.resultFile).mtimeMs,r=Ct.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import In from"node:fs";import*as Et from"node:path";function U(t){try{In.rmSync(Et.dirname(t),{recursive:!0,force:!0})}catch{}}s(U,"removeResultArtifacts");import*as W from"node:fs";import*as re from"node:path";async function Tt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}s(Tt,"probeList");function Cn(t,e,r){let n=r(e);return t?.find(i=>r(i.path)===n)}s(Cn,"matchWorktree");function Ft(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}s(Ft,"paneOf");function Lt(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:Ft(i)}s(Lt,"paneInWorktree");function En(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:Ft(r)}s(En,"paneInWorkspace");function Tn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}s(e,"root");async function r(a,u){let d=await e(),c=[],g=new Set,h=s(p=>{let y=t.canonicalizePath(p.path);g.has(y)||(g.add(y),c.push(p))},"push");for(let p of u??[]){let y=re.basename(p.path);Q(y,a)&&(d!==void 0&&!Oe(p.path,d)||h({path:p.path,branch:p.branch!==void 0&&Q(p.branch,a)?p.branch:y,workspaceId:p.workspaceId}))}if(c.length>0||d===void 0)return c;for(let p of await t.listRootEntries(d))Q(p,a)&&h({path:re.join(d,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,u,d,c){let g=u.execution.host,h=u.display.worktree,p=h?.kind==="owned",y=g?{paneId:g.paneId,tabId:g.tabId,workspaceId:g.workspaceId}:null,m="tracked",v=h?.kind==="owned"?h.path:void 0,w=g?.workspaceId;if(v!==void 0){let x=Cn(d,v,t.canonicalizePath);x!==void 0&&(w=x.workspaceId)}let k=v===void 0?y:Lt(c,v,t.canonicalizePath)??y,A=v===void 0?null:{path:v,workspaceId:w,repoCwd:await t.resolveRepoCwd(v)};return{kind:"located",source:m,id:a,branch:h?.branch??K(u.display.taskSlug??G(u.display.type),u.id),worktreeManaged:p||A!==null,paneCreated:g?.paneCreated===!0,worktree:A,pane:k}}s(i,"locateTracked");async function o(a,u,d){let c=await r(a,u);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],h=Lt(d,g.path,t.canonicalizePath)??En(d,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:h}}s(o,"locateDiscovered");async function l(a,u){let d=await Tt(t.listWorktrees),c=await Tt(t.listPlacements),g=d.ok?d.entries:void 0,h=c.ok?c.entries:void 0;return u===void 0?o(a,g,h):i(a,u,g,h)}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(Tn,"createAgentAssets");function Mt(t,e,r){return Tn({multiplexer:r.multiplexer,canonicalizePath:s(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:s(n=>{let i=I(n);return{path:i,present:W.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=X().cwd;if(!n)return;let i=await we(t,n).catch(()=>{});return i===void 0?void 0:De(P().agent.worktreeRoot,i)},"worktreeRoot"),listRootEntries:s(async n=>{try{return await W.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:s(async n=>{try{return await we(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:s(n=>rt(t,n),"isWorktreeDirty"),worktreeExists:s(async n=>W.existsSync(n),"worktreeExists"),removeWorktree:s(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:s(async(n,i)=>(await tt(t,i,n),!W.existsSync(n)),"removeGitWorktree"),deleteBranch:s(n=>nt(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 R().get(n)?.teardown({pi:t,...i})},"harnessTeardown")})}s(Mt,"createMultiplexerAgentAssets");var T=H("supervisor"),Ln=2e3;function Fn(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}s(Fn,"deferred");var ie=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??Ln,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp}host;deliverable;static{s(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;phase={kind:"idle"};outcome=null;settlement=Fn();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},T.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(),T.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{T.error("poll loop failed",{errorMessage:f(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=>(T.debug("host stop failed",{errorMessage:f(o)}),!1));return T.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"&&(T.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,T.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||!Mn(this.held,e)){this.held=e,T.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 T.debug("readDeliverable failed",{errorMessage:f(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Mn(t,e){return t.content===e.content&&t.mtime===e.mtime}s(Mn,"sameReport");function se(t){let e=t.transport.createDeliverable(t.resultFile);return new ie(t.host,e,t.supervisorOptions)}s(se,"createPaneSupervisor");import be from"node:fs";import O from"node:path";import{SettingsManager as Zn}from"@earendil-works/pi-coding-agent";import Bn from"node:fs";import{loadProjectContextFiles as Gn}from"@earendil-works/pi-coding-agent";function Dt(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
|
|
2
|
-
`):""}s(
|
|
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(Bt,"buildOrchestrationGuidance");import{formatSkillsForPrompt as Qn}from"@earendil-works/pi-coding-agent";function Kn(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,
|
|
8
|
+
`),e.trim()}s(Kn,"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=Qn(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
|
-
${["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>",...
|
|
12
|
-
`)}`}let
|
|
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
|
+
`)}`}let u=`
|
|
13
13
|
<agent_instructions>
|
|
14
14
|
${t.systemPrompt}
|
|
15
|
-
</agent_instructions>`,c="";if(n?.contextFiles?.length){let
|
|
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
|
-
${
|
|
18
|
-
`)}`}let g=
|
|
17
|
+
${f.join(`
|
|
18
|
+
`)}`}let g=zn(t),m=i==="inherit"?n?.parentSystemPrompt:i==="custom"?n?.customSystemPrompt:void 0,p=m&&Kn(m);return{prefix:`${p?`${p}
|
|
19
19
|
|
|
20
20
|
${l}`:l}${c}`,identity:`${g}
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
</active_agent>`:`<active_agent ${n}/>`}s(
|
|
21
|
+
${u}`,skills:d}}s(Pe,"buildAgentPrompt");function zn(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
|
+
${M(i)}
|
|
23
|
+
</active_agent>`:`<active_agent ${n}/>`}s(zn,"buildActiveAgentTag");function M(t){return t.replace(/</g,"<").replace(/>/g,">")}s(M,"escapeXml");import{existsSync as Vn,readFileSync as Yn,realpathSync as Xn}from"node:fs";import{homedir as be}from"node:os";import{join as G,resolve as W}from"node:path";import{loadSkills as Jn,loadSkillsFromDir as Gt}from"@earendil-works/pi-coding-agent";function Qt(t){let e=W(t),r=Zn(e,Gt),n=Gt({dir:G(be(),".agents","skills"),source:"agents"}),i=Kt(n.skills,G(be(),".agents","skills")),o=Jn({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=tr(u.filePath);a.has(c)||l.has(u.name)||(l.add(u.name),a.add(c),d.push(u))}return d}s(Qt,"loadAllSkills");function Zn(t,e){let r=er(t),n=[],i=t;for(;;){let o=G(i,".agents","skills"),l=e({dir:o,source:"agents"});if(n.push(...Kt(l.skills,o)),i===r)break;let a=W(i,"..");if(a===i)break;i=a}return n}s(Zn,"loadAncestorAgentsSkills");function Kt(t,e){let r=W(e);return t.filter(n=>W(n.filePath,"..")!==r)}s(Kt,"filterRootMdFiles");function er(t){let e=W(t);for(;;){if(Vn(G(e,".git")))return e;let r=W(e,"..");if(r===e)return e;e=r}}s(er,"findGitRoot");function tr(t){try{return Xn(t)}catch{return t}}s(tr,"canonicalizePath");async function zt(t,e){let r=Qt(e);return t.map(n=>{if(Ne(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(zt,"inlineSkills");async function Vt(t,e){let r=Qt(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(Vt,"loadSkillMeta");async function Yt(t,e,r){try{let n=await t.exec("git",e,{cwd:r,timeout:_e});return n.code===0?n.stdout.trim():null}catch{return null}}s(Yt,"execGit");async function ir(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(ir,"detectEnv");async function sr(t,e,r,n,i,o){let l=Ze(),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=nr.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=rr({cwd:e,agentDir:E()})}catch{}return d}s(sr,"resolveSystemPromptSources");async function or(t,e,r,n,i,o,l){let a={...l},d=e?.inlinedSkills??[];if(d.length>0&&(a.inlinedSkills=await zt(d,n)),Array.isArray(r.skills)&&(a.skillMetas=await Vt(r.skills,n)),e)return await Pe(e,n,i,a,o);let u=ft.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(or,"buildPrompt");function ar(t){return t.filter(e=>!!e?.trim()).join(`
|
|
24
24
|
|
|
25
|
-
`)}s(
|
|
26
|
-
`):""}s(
|
|
27
|
-
`)}s(
|
|
28
|
-
`)}s(Jn,"buildResultInstruction");async function _t(t){let{pi:e,ctx:r,cwd:n,notify:i}=t,o=await Kn(e,n),l=await Qn(r,n,i,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),a=await zn(t.type,t.agentConfig,t.config,n,o,t.globalSystemPromptMode,l);return Yn([a.prefix,a.identity,a.skills,Nt(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),Xn(),Jn(t.resultFile),Dt(t.agentGuidance)])}s(_t,"buildSubagentSystemPrompt");function er(t,e){let r=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||r.length>0?{kind:"none"}:{kind:"default"}}s(er,"resolveSkillMode");function tr(t,e,r){let n=new Map,i=s((o,l)=>{let a=o.toLowerCase(),u=n.get(a);u===void 0?n.set(a,l):u!==l&&n.set(a,null)},"addSource");for(let o of e.packages){let l=typeof o=="string"?o:o.source,a=Ut(l);a&&i(a,l)}for(let o of e.extensionPaths){let l=Ut(o);l&&i(l,o)}return t.map(o=>{if(nr(o)||rr(o,r))return o;let l=ir(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(tr,"resolveExtensionSources");function nr(t){return t.startsWith("npm:")||t.startsWith("git:")}s(nr,"isPiExtensionSource");function rr(t,e){return O.isAbsolute(t)?be.existsSync(t):be.existsSync(O.resolve(e,t))}s(rr,"isExistingPath");function ir(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}s(ir,"extensionEntryName");function Ut(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=O.basename(r),i=O.basename(n,O.extname(n));return i==="index"?O.basename(O.dirname(r))||void 0:i||void 0}s(Ut,"extensionSourceName");function Bt(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}s(Bt,"notifyLaunchConfigurationError");function sr(t){let e=t,r=e.sessionFile??e.sessionManager?.getSessionFile?.();if(r)return r}s(sr,"resolveParentSessionFile");function Gt(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(Gt,"resolveToolCliEntries");function or(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(R().get(t)===void 0)throw new Error(`no harness registered for "${t}"`);return{...e,family:"plugin"}}}}s(or,"buildLaunchRequest");function ar(t,e){return R().require(t).buildArgs(e)}s(ar,"buildHarnessArgs");async function Kt(t,e,r,n,i){let o=P(),l=i.cwd??e.cwd,a=dt(r,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),u=ut(r),d=i.harness,c=er(a.skills,u),g=[],h=s(S=>{g.push(S)},"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 S=Zn.create(l,C(),{projectTrusted:i.projectTrusted!==!1});p={kind:"paths",paths:tr(a.extensions,{packages:S.getPackages(),extensionPaths:S.getExtensionPaths()},l)}}catch(S){let E=S instanceof Error?S.message:String(S);Bt(e,E)}let y={kind:"default"};try{let S=$e(d),E=S===void 0?void 0:u?.toolsByFamily?.[S];E?.tools===!1?y={kind:"none"}:Array.isArray(E?.tools)?y={kind:"include",names:Gt(E.tools,"tools")}:E?.excludeTools?.length&&(y={kind:"exclude",names:Gt(E.excludeTools,"excludeTools")})}catch(S){let E=S instanceof Error?S.message:String(S);Bt(e,E)}let m=i.agentId??"unknown",v=Te(m);z(v);let w=I(m),k=Le(m),A=Fe(m),x=await _t({pi:t,ctx:e,type:r,agentConfig:u,config:a,cwd:l,globalSystemPromptMode:o.agent.systemPromptMode,globalIncludeContextFiles:o.agent.includeContextFiles,worktreePath:i.worktree?.path,expectedBranch:i.worktree?.branch,agentGuidance:i.agentGuidance,resultFile:w,notify:h});try{pe(k,x)}catch(S){throw new Error(`cannot write the system prompt file ${k}: ${f(S)}. The agent did not start.`,{cause:S})}if(!be.existsSync(k))throw new Error(`the system prompt file is missing after the write: ${k}. The agent did not start.`);pe(A,n);let Ce=i.fork?sr(e):void 0;i.fork&&Ce===void 0&&h("Fork session is enabled, but no parent session file is available; launching without --fork");let bn={subagentId:m,systemPromptFile:k,taskFile:A,resultFile:w,modelKey:j(i.modelChoice)??null,thinking:i.modelChoice?.thinking??null,toolSelection:y},An={forkSessionFile:Ce??null,skills:c,extensions:p,projectTrusted:i.projectTrusted!==!1},xn={projectTrusted:i.projectTrusted!==!1},Ee=or(d,bn,An,xn),Rn=ar(d,Ee);for(let S of g)e.ui.notify(`[cowboy] ${S}`,"warning");return{name:m,cwd:l,systemPrompt:x,piArgs:Rn,launch:Ee,harness:d}}s(Kt,"buildLaunchPlan");var Ae="Agent manager disposed before the queued agent could start.";function zt(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}s(zt,"createRun");function Yt(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(Yt,"startRun");function Vt(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(Vt,"activateRun");function Xt(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(Xt,"abortQueuedRun");function Jt(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(Jt,"failStart");function oe(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(oe,"enterSettling");function Zt(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(Zt,"finishSettling");function en(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(en,"reviveRun");function tn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:Ae},completedAt:e},shell:t.shell}}s(tn,"disposeQueuedRun");function nn(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}s(nn,"disposeLiveRun");function xe(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:Re(t,e)}}s(xe,"dropRun");function Qt(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(Qt,"settledStartedOutcome");function lr(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(lr,"settledNeverStartedOutcome");function ur(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 Qt(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?Qt(t.startedAt,t.terminal,t.completedAt,e):lr(t.queuedAt,t.terminal,t.completedAt,e)}}s(ur,"projectProcess");function Re(t,e){return t.shell==="dropped"?t.lifecycle:ur(t.process,e)}s(Re,"projectLifecycle");import*as rn from"node:fs";import*as sn from"node:path";function on(t){let{spawn:e,hostRef:r,transport:n}=t,i=dr(e),o=sn.dirname(i.resultFile);z(o),rn.rmSync(i.resultFile,{force:!0});let l=se({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(on,"reviveSettledRun");function dr(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??I(t.id)}}s(dr,"resumeLaunch");var ae=H("session");function cr(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(cr,"buildAgentSpawn");var Ie=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))}},le=class{static{s(this,"SubagentSession")}id;args;deps;gate=new Ie;stableSpawn;run;launchState;retention;supervisor;parentBinding;constructor({id:e,args:r,deps:n}){this.id=e,this.args=r,this.deps=n,this.stableSpawn=cr(r,this.gate.promise),this.stableSpawn.id=e;let i=this.stableSpawn.lifecycle;this.run=zt(i.phase==="queued"?i.queuedAt:Date.now()),L().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=Re(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(Yt(this.run,Date.now())),this.launch())}rollbackStart(){this.commit(xe(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(Jt(this.run,f(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:f(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: ${f(o)}. No completion message will arrive \u2014 read the pane for the result.`}}return{kind:"delivered"}}revive(e){let r=Date.now();on({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:j(this.args.options.modelChoice)}),this.supervisor=n,this.launchState=i,this.retention=void 0,this.commit(en(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 ae.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(Xt(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(oe(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}drop(){this.commit(xe(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,U(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit(tn(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(nn(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:u,prompt:d,options:c}=this.args,g=c.hostRef;if(!g&&c.worktree?.kind==="owned"){let k;try{k=await Pt.allocate(l,{naming:{kind:"generated",taskSlug:c.taskSlug??u,id:this.spawn.id},parentCwd:a.cwd,worktreeRoot:P().agent.worktreeRoot,materialization:ze(),dirtyCheckout:mt(u),notify:s((A,x)=>a.ui.notify(A,x),"notify"),host:i})}catch(A){throw c.worktree=void 0,this.spawn.display.worktree=void 0,A}k.worktree?(c.worktree={kind:"owned",...k.worktree},this.spawn.display.worktree=c.worktree):(c.worktree=void 0,this.spawn.display.worktree=void 0),g=k.hostRef}let h=c.worktree?.branch??K(c.taskSlug??G(u),this.id),p=await Kt(l,a,u,d,{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}),y={resultFile:p.launch.resultFile};this.launchState=y,n=p.cwd;let m=R(),v=m.require(p.harness);if(g=g??await i.hostAt({unit:"pane",cwd:p.cwd,label:c.taskSlug??u,name:h}),e={kind:"held",host:i,ref:g},!this.isLaunching())return;this.spawn.execution.host=g,this.spawn.execution.harness=p.harness,await v.prepare({pi:l,pane:o,paneId:g.paneId,cwd:p.cwd,launch:p.launch,config:m.config(p.harness)});let w=se({host:i,resultFile:y.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=w,await w.start({name:h,cwd:p.cwd,piArgs:p.piArgs,agentMultiplexerKind:v.agentMultiplexerKind,taskSlug:c.taskSlug},g),e={kind:"committed"},!this.isLaunching())return;this.commit(Vt(this.run)),w.watch().then(k=>this.applySupervisorOutcome(w,k))}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 R().require(i).teardown({pi:this.args.pi,paneId:this.spawn.execution.host?.paneId??null,cwd:n??null,subagentId:this.spawn.id})}catch(o){ae.warn("harness teardown failed after a failed launch",{spawnId:this.spawn.id,harness:i,error:f(o)})}this.commit(oe(this.run,{kind:"failed",error:f(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(ae.debug("outcome mapped",{kind:r.kind}),r.kind){case"completed":{this.commit(oe(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=Ne(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(Zt(this.run)))}async readWorktreeRetention(){let e=this.spawn.display.worktree;return e?.kind!=="owned"?null:it(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(()=>{ae.debug("parent signal fired",{initiator:"user"}),this.abort("user")},"handler");e.addEventListener("abort",r,{once:!0}),this.parentBinding={signal:e,handler:r}}};function ln(t){return{createHost:s(()=>t.host,"createHost"),createPane:s(()=>t.pane,"createPane"),createPlacements:s(()=>t.placements,"createPlacements"),createDeliverable:s(e=>new ne(e),"createDeliverable")}}s(ln,"createAgentManagerTransport");var an=H("manager");function pr(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(pr,"retentionForReport");var ue=class{constructor(e,r){this.transport=r;this.pools=e,this.registry=new ee({listAgents:s(()=>this.listAgents(Y),"listAgents"),spawn:s((n,i,o)=>this.spawn(b(),X(),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 L().mint()}spawn(e,r,n,i,o){let l=o.spawnId,{requestedHarness:a,...u}=o,d={...u,harness:ht(n,a)},c={pi:e,ctx:r,type:n,prompt:i,options:d},g=this.pools.admitSpawn({harness:d.harness,modelKey:j(d.modelChoice)},{id:l,start:s(p=>this.startSession(l,c,p),"start")}),h;try{h=new le({id:l,args:c,deps:{transport:this.transport,pools:this.pools,onRunEnded:s(p=>this.notifyComplete(p),"onRunEnded"),onFollowUpResult:s((p,y)=>this.notifyFollowUp(p,y),"onFollowUpResult")}})}catch(p){throw this.pools.release(l),p}if(this.sessions.set(l,h),d.signal?.aborted)return h.abort("user"),l;if(g.kind==="queue")return l;try{h.start(g.reservation)}catch(p){throw h.rollbackStart(),this.pools.release(l),this.sessions.delete(l),L().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 L().get(e)}assets(){let e=b();return Mt(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=We){return L().list(e).sort((r,n)=>me(n.lifecycle)-me(r.lifecycle))}async abort(e,r){return await this.sessions.get(e)?.abort(r)??!1}notifyComplete(e){try{this.onComplete?.(e)}catch(r){an.warn("completion notification failed",{spawnId:e.id,detail:f(r)})}}notifyFollowUp(e,r){try{this.onFollowUp?.(e,r)}catch(n){an.warn("follow-up notification failed",{spawnId:e.id,detail:f(n)})}}recordRetention(e,r){let n=e.lifecycle;N(n)&&(n.worktreeRetentionReason=r)}dropSpawn(e){this.sessions.get(e.id)?.drop(),this.sessions.delete(e.id),U(I(e.id)),L().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(()=>{}),J()?.dropNudge(e);let i=this.getSpawn(e)!==void 0,o=await kt(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=pr(o);a!==void 0&&this.recordRetention(l,a)}return i&&o.outcome.kind==="torn-down"&&U(I(e)),o}dispose(){this.pools.clearQueue();for(let e of this.sessions.values())e.settleForDispose();this.sessions.clear()}};var gr=200,de=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(N(n))return;let i=n.phase==="queued"?"Queued":"Spawned";St(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 M({kind:"spawn",spawn:n},e);let i=await _().host.findAttempts(e),o=te([],i);if(o.kind!=="none")return new M(o,e);let l={name:r.conflictingId};return new M({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)},gr))}onAgentComplete(e){this.backgroundAgentIds.has(e.id)&&(mr(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=ve(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}
|
|
25
|
+
`)}s(ar,"joinPromptSections");function lr(t,e){return t!==null&&t!==""?t:e}s(lr,"branchName");function Xt(t,e,r,n){let i=t&&e?lr(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(Xt,"buildWorktreeBranchSection");function dr(){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(dr,"buildSteeringInstructions");function ur(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(ur,"buildResultInstruction");async function Jt(t){let{pi:e,ctx:r,cwd:n,notify:i}=t,o=await ir(e,n),l=await sr(r,n,i,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),a=await or(t.type,t.agentConfig,t.config,n,o,t.globalSystemPromptMode,l);return ar([a.prefix,a.identity,a.skills,Xt(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),dr(),ur(t.resultFile),Bt(t.agentGuidance)])}s(Jt,"buildSubagentSystemPrompt");function Zt(t,e){let r=Object.entries(e);return r.length===0?null:(_(t,`${r.map(([n,i])=>`export ${n}=${Ke(i)}`).join(`
|
|
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}
|
|
29
31
|
|
|
30
|
-
${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||!$())return;let r=b(),n=this.manager.getSpawn(e);if(!n)return;let i=
|
|
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||!$())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:`${Rt(n)}
|
|
31
33
|
|
|
32
|
-
${
|
|
34
|
+
${It(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 Er(t){let e=t.lifecycle;return q(e)&&e.status==="stopped"&&e.stop.initiator==="user"}s(Er,"stoppedByUser");import*as Rn from"node:fs";import{pathToFileURL as Dr}from"node:url";import*as An from"node:path";import{DefaultPackageManager as Lr,SettingsManager as Fr}from"@earendil-works/pi-coding-agent";import*as Sn from"node:fs";import*as kn from"node:path";import{z as pe}from"zod";var Pn="pi-cowboy",Cr="pi-cowboy-",Tr=pe.object({name:pe.string().startsWith(Cr),[Pn]:pe.object({plugin:pe.string().min(1)})});function bn(t){let e;try{e=Sn.readFileSync(kn.join(t,"package.json"),"utf-8")}catch{return}let r;try{r=JSON.parse(e)}catch{return}let n=Tr.safeParse(r);if(n.success)return{name:n.data.name,entry:n.data[Pn].plugin}}s(bn,"readPluginManifest");function Mr(t){let e=new Map;for(let r of t){if(r.installedPath===void 0)continue;let n=bn(r.installedPath);n!==void 0&&(e.has(n.name)||e.set(n.name,{name:n.name,source:r.source,root:r.installedPath,entry:An.resolve(r.installedPath,n.entry)}))}return[...e.values()].sort((r,n)=>r.name.localeCompare(n.name))}s(Mr,"pluginsAmong");async function xn(t){let e=new Lr({cwd:t,agentDir:E(),settingsManager:Fr.create(t,E())});return Mr(e.listConfiguredPackages())}s(xn,"discoverPluginPackages");function In(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 xn(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 $r(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(In,"createPluginLoader");function Or(t){try{return`?v=${Rn.statSync(t).mtimeMs}`}catch{return""}}s(Or,"cacheBust");function jr(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(jr,"pluginApi");async function $r(t,e,r,n,i){let o=jr(e,r,n,i),a=(await import(`${Dr(t.entry).href}${Or(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($r,"loadOne");function Hr(){let t=[],e=[];for(let r of A().ids()){let n=Wr(r);n.status==="available"?t.push(r):n.notice!==void 0&&e.push(n.notice)}return{availability:$e(t),notices:e}}s(Hr,"probeHarnessAvailability");function Wr(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(Wr,"askAvailability");function En(){let t=Hr();return rt(t.availability),t}s(En,"startHarnessAvailabilityProbe");function Cn(t){let e=nt(),r=A();for(let n of r.runnable(e))try{r.require(n).prefetchModels(t)}catch{}}s(Cn,"prefetchHarnessModels");async function Tn(t,e){let r=tt(),n=await In(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)),Nr(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=En();if(e.hasUI)for(let d of a.notices)e.ui.notify(d,"warning");return Cn(t),{kind:"hosted",plugins:n,runtime:l}}s(Tn,"startSessionRuntime");function Nr(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(Nr,"reportUnregisteredConfig");function _r(t){if(!he()){let e=new ue(new Je(P().concurrency),vn(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 qr(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"):"";yt(r,o,i);let l=P().agent.disableDefaultAgents,a=await wt({disableDefaultAgents:l,notify:s((d,u)=>{t.ui.notify(d,u)},"notify")});ht(a,{disableDefaultAgents:l})}s(qr,"scanAndRegisterAgents");async function Ur(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"):"";Pt(r,o,i);let l=await bt({notify:s((a,d)=>{t.ui.notify(a,d)},"notify")});kt(l)}s(Ur,"scanAndRegisterOrchestrators");async function Br(t){at(et());let e=t.isProjectTrusted()?L.join(t.cwd,".pi"):void 0;P().setProjectDir(e),P().reload()}s(Br,"loadSessionConfig");async function Gr(t){await qr(t),await Ur(t)}s(Gr,"scanSessionTemplates");function Ln(t){t.on("tool_call",Et);let e=null;t.on("session_start",async(r,n)=>{ot(n),await Br(n);let i=await Tn(t,n);if(e=i.plugins,i.kind==="unhosted"){ke(n.ui),n.hasUI&&$()&&n.ui.notify(i.reason,"warning");return}await Gr(n),_r(i.runtime),await Mt(t),$()?Dt(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(Y);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),Ct();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(Ln,"setupEventListeners");var Fn="pi-cowboy needs a git repository: this directory is not inside one, so pi-cowboy stays inactive";function Mn(t,e){t.on("session_start",async(r,n)=>{n.hasUI&&n.ui.notify(e,"warning")})}s(Mn,"reportInactive");function Qr(t){if(lt()!==void 0)return;let e=dt();if(e!==void 0){Mn(t,e);return}if(!ut(process.cwd())){Mn(t,Fn),jt(t,Fn);return}st(t),Ot(t),$t(t),Ln(t)}s(Qr,"default");export{Qr as default};
|
|
33
35
|
//# sourceMappingURL=index.js.map
|