pi-cowboy 0.22.2 → 0.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +16 -1
  2. package/dist/agents/agent-assets.d.ts +11 -2
  3. package/dist/agents/agent-cleanup.d.ts +6 -22
  4. package/dist/agents/agent-environment.d.ts +6 -0
  5. package/dist/agents/agent-host.d.ts +3 -3
  6. package/dist/agents/agent-manager.d.ts +5 -1
  7. package/dist/agents/batch.d.ts +2 -1
  8. package/dist/agents/cleanup-policy.d.ts +15 -16
  9. package/dist/agents/handover.d.ts +71 -0
  10. package/dist/agents/harness/claude/session-export.d.ts +7 -0
  11. package/dist/agents/harness/claude/staging.d.ts +9 -1
  12. package/dist/agents/harness/codex-session-schema.d.ts +90 -0
  13. package/dist/agents/harness/codex-session.d.ts +17 -0
  14. package/dist/agents/harness/opencode/session-export.d.ts +39 -0
  15. package/dist/agents/harness/pi-compatible.d.ts +3 -1
  16. package/dist/agents/harness/pi-session.d.ts +12 -0
  17. package/dist/agents/harness/pi-store.d.ts +8 -0
  18. package/dist/agents/harness/pi.d.ts +2 -0
  19. package/dist/agents/harness/pig-store.d.ts +7 -0
  20. package/dist/agents/harness/stop-keys.d.ts +2 -0
  21. package/dist/agents/harness.d.ts +53 -0
  22. package/dist/agents/run-state.d.ts +1 -0
  23. package/dist/agents/schemas/handover.schema.d.ts +8 -0
  24. package/dist/agents/subagent-session.d.ts +8 -1
  25. package/dist/agents/tool-cleanup.d.ts +16 -2
  26. package/dist/agents/tool-execution.d.ts +21 -2
  27. package/dist/agents/tool-handover.d.ts +28 -0
  28. package/dist/agents/tool-merge.d.ts +18 -2
  29. package/dist/agents/tool-renderer.d.ts +21 -0
  30. package/dist/agents/tool-result.d.ts +9 -2
  31. package/dist/agents/tool-steer.d.ts +17 -2
  32. package/dist/{chunk-F526OOT6.js → chunk-277WT5MT.js} +2 -2
  33. package/dist/chunk-J5TU3AFX.js +2 -0
  34. package/dist/chunk-M42XWVYW.js +45 -0
  35. package/dist/{chunk-WL3QYM2F.js → chunk-MZROKRT4.js} +2 -2
  36. package/dist/chunk-S4BS2R6G.js +26 -0
  37. package/dist/chunk-TFQCH2TO.js +14 -0
  38. package/dist/config/config-store.d.ts +1 -0
  39. package/dist/config/layered-config.d.ts +2 -3
  40. package/dist/cowboy-tools.d.ts +13 -0
  41. package/dist/dev-mode.d.ts +1 -0
  42. package/dist/index.js +18 -18
  43. package/dist/infrastructure/herdr/agent-exit.d.ts +12 -0
  44. package/dist/infrastructure/herdr/agents.d.ts +0 -1
  45. package/dist/infrastructure/herdr/index.d.ts +1 -1
  46. package/dist/{menu-worktree-command-SXLBWK4D.js → menu-worktree-command-THJ3VSWU.js} +2 -2
  47. package/dist/{menus-Q3TEDIPV.js → menus-KXKDXZRN.js} +3 -3
  48. package/dist/{model-picker-IIXU4GJP.js → model-picker-FMMQY4KI.js} +2 -2
  49. package/dist/models/model-precedence.d.ts +1 -0
  50. package/dist/models/model-request-types.d.ts +8 -2
  51. package/dist/plugin/index.d.ts +1 -1
  52. package/dist/plugin/index.js +1 -1
  53. package/dist/predicates.d.ts +1 -0
  54. package/dist/registration.d.ts +3 -8
  55. package/dist/spawn/sandbox.d.ts +22 -0
  56. package/dist/subagent/result-artifacts.d.ts +1 -0
  57. package/dist/subagent/supervisor.d.ts +2 -0
  58. package/dist/types.d.ts +11 -0
  59. package/package.json +2 -2
  60. package/dist/chunk-254PTGN5.js +0 -2
  61. package/dist/chunk-CTBFJWEE.js +0 -10
  62. package/dist/chunk-KMXT7XW7.js +0 -15
  63. package/dist/chunk-PDV4AFO7.js +0 -24
  64. package/dist/infrastructure/herdr/agent-stopper.d.ts +0 -14
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
- import{B as Ft,E as Mt,F as ke,G as Dt,H as Ot,I as jt,a as mt,b as ft,c as ht,d as yt,e as wt,h as vt,j as St,k as kt,l as Pt,p as bt,q as At,r as Se,s as xt,t as Rt,u as It,y as Et,z as H}from"./chunk-PDV4AFO7.js";import{a as lt,f as dt,g as ve,h as ut,m as ct,n as pt,o as gt,r as Tt,s as Lt}from"./chunk-KMXT7XW7.js";import{A as We,Ba as U,D as Y,Da as it,E as N,Ea as st,Fa as ye,G as Ge,Ga as we,Ha as ee,I as me,Ia as ot,J as j,Ja as at,Ka as Ct,O as V,Q as Qe,R as Ke,S as q,T as X,U as ze,V as fe,_ as Ye,a as E,aa as Ve,ba as Xe,c as Me,ca as Je,d as I,da as Ze,e as De,ea as b,f as Oe,fa as J,g as je,ha as he,ia as P,j as He,la as T,oa as Z,sa as A,u as Q,ua as et,va as tt,w as K,wa as nt,xa as rt,y as $e,z}from"./chunk-CTBFJWEE.js";import{a as s,b as _e,d as y,h as O,i as Ne,r as qe,s as Ue,v as Be}from"./chunk-254PTGN5.js";import*as L from"node:path";function ne(t,e){let r=t.at(0);if(r)return{kind:"spawn",spawn:r};let n=e.at(0);return n?{kind:"multiplexer",attempt:n}:{kind:"none"}}s(ne,"findTaskDedup");var F=class extends Error{static{s(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",i=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?X(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${i} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},te=class{constructor(e){this.deps=e}deps;static{s(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let i=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,i);try{return await i}finally{this.admissionBySlug.get(r)===i&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let c=this.deps.listAgents().filter(m=>m.display.taskSlug===e.taskSlug&&Ke(m.lifecycle.phase)),g=ne(c,await this.deps.findTaskAttempts(e.taskSlug));if(g.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:g.kind==="spawn"?g.spawn.id:g.attempt.name}}let{type:r,prompt:n,runInBackground:i,signal:o,...l}=e,a={...l,isBackground:i,signal:o},d=this.deps.spawn(r,n,a);return this.deps.getSpawn(d)?.lifecycle.phase==="queued"?{status:"queued",agentId:d,queuePosition:this.deps.queuePosition(d)}:{status:"admitted",agentId:d}}};import Ht from"node:fs";var re=class{constructor(e){this.resultFile=e}resultFile;static{s(this,"FileDeliverable")}async readDeliverable(){try{let e=Ht.statSync(this.resultFile).mtimeMs,r=Ht.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import $n from"node:fs";import*as $t from"node:path";function B(t){try{$n.rmSync($t.dirname(t),{recursive:!0,force:!0})}catch{}}s(B,"removeResultArtifacts");import*as $ from"node:fs";import*as ie from"node:path";async function Wt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}s(Wt,"probeList");function Wn(t,e,r){let n=r(e);return t?.find(i=>r(i.path)===n)}s(Wn,"matchWorktree");function Nt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}s(Nt,"paneOf");function _t(t,e,r){let n=r(e),i=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return i===void 0?void 0:Nt(i)}s(_t,"paneInWorktree");function _n(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:Nt(r)}s(_n,"paneInWorkspace");function Nn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}s(e,"root");async function r(a,d){let u=await e(),c=[],g=new Set,m=s(p=>{let h=t.canonicalizePath(p.path);g.has(h)||(g.add(h),c.push(p))},"push");for(let p of d??[]){let h=ie.basename(p.path);z(h,a)&&(u!==void 0&&!We(p.path,u)||m({path:p.path,branch:p.branch!==void 0&&z(p.branch,a)?p.branch:h,workspaceId:p.workspaceId}))}if(c.length>0||u===void 0)return c;for(let p of await t.listRootEntries(u))z(p,a)&&m({path:ie.join(u,p),branch:p});return c}s(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}s(n,"candidateSummary");async function i(a,d,u,c){let g=d.execution.host,m=d.display.worktree,p=m?.kind==="owned",h=g?{paneId:g.paneId,tabId:g.tabId,workspaceId:g.workspaceId}:null,f="tracked",S=m?.kind==="owned"?m.path:void 0,k=g?.workspaceId;if(S!==void 0){let x=Wn(u,S,t.canonicalizePath);x!==void 0&&(k=x.workspaceId)}let v=S===void 0?h:_t(c,S,t.canonicalizePath)??h,R=S===void 0?null:{path:S,workspaceId:k,repoCwd:await t.resolveRepoCwd(S)};return{kind:"located",source:f,id:a,branch:m?.branch??K(d.display.taskSlug??Q(d.display.type),d.id),worktreeManaged:p||R!==null,paneCreated:g?.paneCreated===!0,worktree:R,pane:v}}s(i,"locateTracked");async function o(a,d,u){let c=await r(a,d);if(c.length===0)return{kind:"not-found",id:a};if(c.length>1)return{kind:"ambiguous",id:a,candidates:c.map(n)};let g=c[0],m=_t(u,g.path,t.canonicalizePath)??_n(u,g.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:g.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:g.path,workspaceId:g.workspaceId,repoCwd:await t.resolveRepoCwd(g.path)},pane:m}}s(o,"locateDiscovered");async function l(a,d){let u=await Wt(t.listWorktrees),c=await Wt(t.listPlacements),g=u.ok?u.entries:void 0,m=c.ok?c.entries:void 0;return d===void 0?o(a,g,m):i(a,d,g,m)}return s(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:s(a=>t.readPane(a.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,harnessTeardown:t.harnessTeardown}}s(Nn,"createAgentAssets");function qt(t,e,r){return Nn({multiplexer:r.multiplexer,canonicalizePath:s(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:s(n=>{let i=I(n);return{path:i,present:$.existsSync(i)}},"deliverable"),listWorktrees:s(()=>r.listWorktrees(),"listWorktrees"),listPlacements:s(()=>r.listPlacements(),"listPlacements"),readPane:s(n=>r.observePane(n),"readPane"),worktreeRoot:s(async()=>{let n=J().cwd;if(!n)return;let i=await ve(t,n).catch(()=>{});return i===void 0?void 0:$e(P().agent.worktreeRoot,i)},"worktreeRoot"),listRootEntries:s(async n=>{try{return await $.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:s(async n=>{try{return await ve(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:s(n=>pt(t,n),"isWorktreeDirty"),worktreeExists:s(async n=>$.existsSync(n),"worktreeExists"),removeWorktree:s(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:s(async(n,i)=>(await ut(t,i,n),!$.existsSync(n)),"removeGitWorktree"),deleteBranch:s(n=>ct(t,n,i=>e.isAttached(i,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:s(async n=>{await e.release(n,"placement")},"closePane"),harnessTeardown:s(async(n,i)=>{await A().get(n)?.teardown({pi:t,...i})},"harnessTeardown")})}s(qt,"createMultiplexerAgentAssets");var C=j("supervisor"),qn=2e3;function Un(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}s(Un,"deferred");var se=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??qn,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp}host;deliverable;static{s(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;phase={kind:"idle"};outcome=null;settlement=Un();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,r){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:r};try{await this.host.start(r,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(n){throw this.isWatching()&&(this.phase={kind:"idle"}),n}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},C.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),C.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{C.error("poll loop failed",{errorMessage:y(r)})}),this.settlement.promise}async stop(e){let r=this.phase;if(r.kind!=="watching"||this.outcome!==null)return!1;let{ref:n}=r,i=await this.host.stop(n,{interruptGraceMs:e,confirmMs:0}).catch(o=>(C.debug("host stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:i,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),i}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let r=this.phase;r.kind==="watching"&&(C.debug(e,{paneId:r.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,C.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let r=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);r.unref(),this.wakeLoop=()=>{clearTimeout(r),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!Bn(this.held,e)){this.held=e,C.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return C.debug("readDeliverable failed",{errorMessage:y(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Bn(t,e){return t.content===e.content&&t.mtime===e.mtime}s(Bn,"sameReport");function oe(t){let e=t.transport.createDeliverable(t.resultFile);return new se(t.host,e,t.supervisorOptions)}s(oe,"createPaneSupervisor");import Ae from"node:fs";import D from"node:path";import{SettingsManager as ur}from"@earendil-works/pi-coding-agent";import tr from"node:fs";import{loadProjectContextFiles as nr}from"@earendil-works/pi-coding-agent";function Ut(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
2
- `):""}s(Ut,"buildOrchestrationGuidance");import{formatSkillsForPrompt as Gn}from"@earendil-works/pi-coding-agent";function Qn(t){let e=t;return e=e.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g,`
1
+ import{a as Pe,b as Et,c as Ct,d as Tt,h as Lt,i as W,k as Dt,n as Ht,o as be,p as jt,q as $t,r as Wt}from"./chunk-TFQCH2TO.js";import{E as At,F as xt,G as Rt,O as It,Q as Ot,R as Mt,a as pt,f as gt,g as K,h as ht,m as ft,n as mt,o as yt,q as vt,r as wt,s as kt,t as St,v as Pt,y as bt}from"./chunk-S4BS2R6G.js";import{$ as Je,A as Ne,Aa as at,E as Z,Ea as G,F as U,G as Qe,Ga as lt,Ha as dt,I as me,Ia as ke,J as T,Ja as Se,Ka as re,La as ut,Ma as ct,Na as Ft,O as ee,Q as ze,R as Ve,S as B,T as D,U as Ye,V as ye,_ as Xe,a as E,ba as Ze,c as De,ca as et,d as I,da as ve,e as He,ea as tt,f as je,fa as nt,g as $e,ga as rt,ha as R,ia as te,j as We,ka as we,la as b,oa as L,ra as ne,u as Y,va as A,w as X,xa as st,y as qe,ya as it,z as J,za as ot}from"./chunk-M42XWVYW.js";import{a as i,b as _e,d as y,h as M,i as Ue,r as Be,s as Ge,x as Ke}from"./chunk-J5TU3AFX.js";import*as F from"node:path";function ie(t,e){let r=t.at(0);if(r)return{kind:"spawn",spawn:r};let n=e.at(0);return n?{kind:"multiplexer",attempt:n}:{kind:"none"}}i(ie,"findTaskDedup");var H=class extends Error{static{i(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",s=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?D(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${s} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},se=class{constructor(e){this.deps=e}deps;static{i(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let s=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,s);try{return await s}finally{this.admissionBySlug.get(r)===s&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let h=this.deps.listAgents().filter(p=>p.display.taskSlug===e.taskSlug&&Ve(p.lifecycle.phase)),c=ie(h,await this.deps.findTaskAttempts(e.taskSlug));if(c.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:c.kind==="spawn"?c.spawn.id:c.attempt.name}}let{type:r,prompt:n,runInBackground:s,signal:o,...l}=e,a={...l,isBackground:s,signal:o},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 qt from"node:fs";var oe=class{constructor(e){this.resultFile=e}resultFile;static{i(this,"FileDeliverable")}async readDeliverable(){try{let e=qt.statSync(this.resultFile).mtimeMs,r=qt.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import Nt from"node:fs";import*as _t from"node:path";function Q(t){try{Nt.rmSync(_t.dirname(t),{recursive:!0,force:!0})}catch{}}i(Q,"removeResultArtifacts");function Ut(t){try{Nt.rmSync(t,{force:!0})}catch{}}i(Ut,"removeResultFile");import*as q from"node:fs";import*as ae from"node:path";var zn=T("assets");async function Bt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}i(Bt,"probeList");function Vn(t,e,r){let n=r(e);return t?.find(s=>r(s.path)===n)}i(Vn,"matchWorktree");function Kt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}i(Kt,"paneOf");function Gt(t,e,r){let n=r(e),s=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return s===void 0?void 0:Kt(s)}i(Gt,"paneInWorktree");function Yn(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:Kt(r)}i(Yn,"paneInWorkspace");function Xn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}i(e,"root");async function r(a,u){let d=await e(),h=[],c=new Set,p=i(g=>{let m=t.canonicalizePath(g.path);c.has(m)||(c.add(m),h.push(g))},"push");for(let g of u??[]){let m=ae.basename(g.path);J(m,a)&&(d!==void 0&&!Ne(g.path,d)||p({path:g.path,branch:g.branch!==void 0&&J(g.branch,a)?g.branch:m,workspaceId:g.workspaceId}))}if(h.length>0||d===void 0)return h;for(let g of await t.listRootEntries(d))J(g,a)&&p({path:ae.join(d,g),branch:g});return h}i(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}i(n,"candidateSummary");async function s(a,u,d,h){let c=u.execution.host,p=u.display.worktree,g=p?.kind==="owned",m=c?{paneId:c.paneId,tabId:c.tabId,workspaceId:c.workspaceId}:null,f="tracked",w=p?.kind==="owned"?p.path:void 0,P=c?.workspaceId;if(w!==void 0){let x=Vn(d,w,t.canonicalizePath);x!==void 0&&(P=x.workspaceId)}let S=w===void 0?m:Gt(h,w,t.canonicalizePath)??m,k=w===void 0?null:{path:w,workspaceId:P,repoCwd:await t.resolveRepoCwd(w)};return{kind:"located",source:f,id:a,branch:p?.branch??X(u.display.taskSlug??Y(u.display.type),u.id),worktreeManaged:g||k!==null,paneCreated:c?.paneCreated===!0,worktree:k,pane:S}}i(s,"locateTracked");async function o(a,u,d){let h=await r(a,u);if(h.length===0)return{kind:"not-found",id:a};if(h.length>1)return{kind:"ambiguous",id:a,candidates:h.map(n)};let c=h[0],p=Gt(d,c.path,t.canonicalizePath)??Yn(d,c.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:c.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:c.path,workspaceId:c.workspaceId,repoCwd:await t.resolveRepoCwd(c.path)},pane:p}}i(o,"locateDiscovered");async function l(a,u){let d=await Bt(t.listWorktrees),h=await Bt(t.listPlacements),c=d.ok?d.entries:void 0,p=h.ok?h.entries:void 0;return u===void 0?o(a,c,p):s(a,u,c,p)}return i(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:i(a=>t.readPane(a.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}i(Xn,"createAgentAssets");function Qt(t,e,r){return Xn({multiplexer:r.multiplexer,canonicalizePath:i(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:i(n=>{let s=I(n);return{path:s,present:q.existsSync(s)}},"deliverable"),listWorktrees:i(()=>r.listWorktrees(),"listWorktrees"),listPlacements:i(()=>r.listPlacements(),"listPlacements"),readPane:i(n=>r.observePane(n),"readPane"),worktreeRoot:i(async()=>{let n=te().cwd;if(!n)return;let s=await K(t,n).catch(()=>{});return s===void 0?void 0:qe(b().agent.worktreeRoot,s)},"worktreeRoot"),listRootEntries:i(async n=>{try{return await q.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:i(async n=>{try{return await K(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:i(n=>mt(t,n),"isWorktreeDirty"),worktreeExists:i(async n=>q.existsSync(n),"worktreeExists"),removeWorktree:i(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(n,s)=>(await ht(t,s,n),!q.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>ft(t,n,s=>e.isAttached(s,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:i(async n=>{await e.release(n,"placement")},"closePane"),teardownEnvironment:i(async({subagentId:n,runs:s})=>{let o=A();for(let l of s)try{await o.get(l.harness)?.teardown({pi:t,paneId:l.paneId,cwd:l.cwd,subagentId:n})}catch(a){zn.warn("harness teardown failed during environment teardown",{subagentId:n,harness:l.harness,error:y(a)})}},"teardownEnvironment")})}i(Qt,"createMultiplexerAgentAssets");var C=T("supervisor"),Jn=2e3;function Zn(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}i(Zn,"deferred");var le=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??Jn,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp,this.stopProcess=n.stopProcess??((s,o)=>e.waitUntilGone(s,{timeoutMs:o}))}host;deliverable;static{i(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=Zn();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,r){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:r};try{await this.host.start(r,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(n){throw this.isWatching()&&(this.phase={kind:"idle"}),n}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},C.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),C.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{C.error("poll loop failed",{errorMessage:y(r)})}),this.settlement.promise}async stop(e){let r=this.phase;if(r.kind!=="watching"||this.outcome!==null)return!1;let{ref:n}=r,s=await this.stopProcess(n,e).catch(o=>(C.debug("stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:s,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),s}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let r=this.phase;r.kind==="watching"&&(C.debug(e,{paneId:r.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,C.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let r=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);r.unref(),this.wakeLoop=()=>{clearTimeout(r),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!er(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 er(t,e){return t.content===e.content&&t.mtime===e.mtime}i(er,"sameReport");function de(t){let e=t.transport.createDeliverable(t.resultFile);return new le(t.host,e,t.supervisorOptions)}i(de,"createPaneSupervisor");function zt(t,e){t.host=e}i(zt,"placeExecution");function Vt(t,e){t.harness=e}i(Vt,"engageExecution");function Yt(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}i(Yt,"endExecutionRun");import Re from"node:fs";import $ from"node:path";import{SettingsManager as kr}from"@earendil-works/pi-coding-agent";import cr from"node:fs";import{loadProjectContextFiles as pr}from"@earendil-works/pi-coding-agent";function Xt(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
2
+ `):""}i(Xt,"buildOrchestrationGuidance");import{formatSkillsForPrompt as tr}from"@earendil-works/pi-coding-agent";function nr(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(Qn,"stripScaffolding");async function Pe(t,e,r,n,i="replace"){let o=["# Environment",`Working directory: ${e}`,r.isGitRepo?"Git repository: yes":"Not a git repository"];r.isGitRepo&&r.branch&&o.push(`Branch: ${r.branch}`),o.push(`Platform: ${r.platform}`);let l=o.join(`
9
- `),a=!!n?.skillMetas?.length||!!n?.inlinedSkills?.length,d="";if(a){let f=[];if(n?.skillMetas?.length){let k=n.skillMetas.map(x=>({name:x.name,description:x.description,filePath:x.location,baseDir:"",sourceInfo:{},disableModelInvocation:x.disableModelInvocation})),R=Gn(k).match(/<skill>[\s\S]*?<\/skill>/g);R&&f.push(...R)}for(let k of n?.inlinedSkills??[])f.push(`<skill><name>${M(k.name)}</name><description>${M(k.description)}</description><content>${M(k.content)}</content></skill>`);d=`
8
+ `),e.trim()}i(nr,"stripScaffolding");async function Ae(t,e,r,n,s="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,u="";if(a){let f=[];if(n?.skillMetas?.length){let P=n.skillMetas.map(x=>({name:x.name,description:x.description,filePath:x.location,baseDir:"",sourceInfo:{},disableModelInvocation:x.disableModelInvocation})),k=tr(P).match(/<skill>[\s\S]*?<\/skill>/g);k&&f.push(...k)}for(let P of n?.inlinedSkills??[])f.push(`<skill><name>${j(P.name)}</name><description>${j(P.description)}</description><content>${j(P.content)}</content></skill>`);u=`
10
10
 
11
11
  ${["The following skills provide specialized instructions for specific tasks.","Use the read tool to load a skill's file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>",...f,"</available_skills>"].join(`
12
- `)}`}let u=`
12
+ `)}`}let d=`
13
13
  <agent_instructions>
14
14
  ${t.systemPrompt}
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=`
15
+ </agent_instructions>`,h="";if(n?.contextFiles?.length){let f=["<project_context>","","Project-specific instructions and guidelines:",""];for(let w of n.contextFiles)f.push(`<project_instructions path="${j(w.path)}">`),f.push(w.content),f.push("</project_instructions>"),f.push("");f.push("</project_context>"),h=`
16
16
 
17
17
  ${f.join(`
18
- `)}`}let g=Kn(t),m=i==="inherit"?n?.parentSystemPrompt:i==="custom"?n?.customSystemPrompt:void 0,p=m&&Qn(m);return{prefix:`${p?`${p}
18
+ `)}`}let c=rr(t),p=s==="inherit"?n?.parentSystemPrompt:s==="custom"?n?.customSystemPrompt:void 0,g=p&&nr(p);return{prefix:`${g?`${g}
19
19
 
20
- ${l}`:l}${c}`,identity:`${g}
21
- ${u}`,skills:d}}s(Pe,"buildAgentPrompt");function Kn(t){let e=t.displayName?.trim(),r=e?` display_name="${M(e)}"`:"",n=`name="${M(t.name)}"${r}`,i=t.description.trim();return i?`<active_agent ${n}>
22
- ${M(i)}
23
- </active_agent>`:`<active_agent ${n}/>`}s(Kn,"buildActiveAgentTag");function M(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}s(M,"escapeXml");import{existsSync as zn,readFileSync as Yn,realpathSync as Vn}from"node:fs";import{homedir as be}from"node:os";import{join as G,resolve as W}from"node:path";import{loadSkills as Xn,loadSkillsFromDir as Bt}from"@earendil-works/pi-coding-agent";function Gt(t){let e=W(t),r=Jn(e,Bt),n=Bt({dir:G(be(),".agents","skills"),source:"agents"}),i=Qt(n.skills,G(be(),".agents","skills")),o=Xn({cwd:e,agentDir:G(be(),".pi","agent"),skillPaths:[],includeDefaults:!0}),l=new Set,a=new Set,d=[];for(let u of[...r,...i,...o.skills]){let c=er(u.filePath);a.has(c)||l.has(u.name)||(l.add(u.name),a.add(c),d.push(u))}return d}s(Gt,"loadAllSkills");function Jn(t,e){let r=Zn(t),n=[],i=t;for(;;){let o=G(i,".agents","skills"),l=e({dir:o,source:"agents"});if(n.push(...Qt(l.skills,o)),i===r)break;let a=W(i,"..");if(a===i)break;i=a}return n}s(Jn,"loadAncestorAgentsSkills");function Qt(t,e){let r=W(e);return t.filter(n=>W(n.filePath,"..")!==r)}s(Qt,"filterRootMdFiles");function Zn(t){let e=W(t);for(;;){if(zn(G(e,".git")))return e;let r=W(e,"..");if(r===e)return e;e=r}}s(Zn,"findGitRoot");function er(t){try{return Vn(t)}catch{return t}}s(er,"canonicalizePath");async function Kt(t,e){let r=Gt(e);return t.map(n=>{if(_e(n))return{name:n,description:"",content:`(Skill "${n}" skipped: name contains path traversal characters)`};let i=r.find(o=>o.name===n);if(!i)return{name:n,description:"",content:`(Skill "${n}" not found in .pi/skills/, .agents/skills/, or global skill locations)`};try{return{name:n,description:i.description,content:Yn(i.filePath,"utf-8").trim()}}catch{return{name:n,description:"",content:`(Skill "${n}" not found in .pi/skills/, .agents/skills/, or global skill locations)`}}})}s(Kt,"inlineSkills");async function zt(t,e){let r=Gt(e);return t.map(n=>{let i=r.find(o=>o.name===n);return i?{name:n,description:i.description,location:i.filePath,disableModelInvocation:i.disableModelInvocation}:{name:n,description:`(Skill "${n}" not found)`,location:"",disableModelInvocation:!1}})}s(zt,"loadSkillMeta");async function Yt(t,e,r){try{let n=await t.exec("git",e,{cwd:r,timeout:Ne});return n.code===0?n.stdout.trim():null}catch{return null}}s(Yt,"execGit");async function rr(t,e){let n=await Yt(t,["rev-parse","--is-inside-work-tree"],e)==="true",i=n?await Yt(t,["branch","--show-current"],e):null;return{isGitRepo:n,branch:i,platform:process.platform}}s(rr,"detectEnv");async function ir(t,e,r,n,i,o){let l=Je(),a=n?.includeContextFiles??o,d={};if(i==="inherit")try{d.parentSystemPrompt=t.getSystemPrompt()}catch(u){r(`Failed to get parent system prompt: ${y(u)}. Falling back to replace mode.`)}if(i==="custom")try{let u=tr.readFileSync(l,"utf-8").trim();u?d.customSystemPrompt=u:r(`Custom prompt file is empty: ${l}. Falling back to replace mode.`)}catch(u){u?.code==="ENOENT"?r(`Custom prompt file not found: ${l}. Falling back to replace mode.`):r(`Failed to read custom prompt file: ${y(u)}. Falling back to replace mode.`)}if(a)try{d.contextFiles=nr({cwd:e,agentDir:E()})}catch{}return d}s(ir,"resolveSystemPromptSources");async function sr(t,e,r,n,i,o,l){let a={...l},d=e?.inlinedSkills??[];if(d.length>0&&(a.inlinedSkills=await Kt(d,n)),Array.isArray(r.skills)&&(a.skillMetas=await zt(r.skills,n)),e)return await Pe(e,n,i,a,o);let u=mt.get("general-purpose");if(!u)throw new Error(`No fallback config available for unknown type "${t}"`);return await Pe({...u,name:t},n,i,a,o)}s(sr,"buildPrompt");function or(t){return t.filter(e=>!!e?.trim()).join(`
20
+ ${l}`:l}${h}`,identity:`${c}
21
+ ${d}`,skills:u}}i(Ae,"buildAgentPrompt");function rr(t){let e=t.displayName?.trim(),r=e?` display_name="${j(e)}"`:"",n=`name="${j(t.name)}"${r}`,s=t.description.trim();return s?`<active_agent ${n}>
22
+ ${j(s)}
23
+ </active_agent>`:`<active_agent ${n}/>`}i(rr,"buildActiveAgentTag");function j(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}i(j,"escapeXml");import{existsSync as sr,readFileSync as ir,realpathSync as or}from"node:fs";import{homedir as xe}from"node:os";import{join as z,resolve as N}from"node:path";import{loadSkills as ar,loadSkillsFromDir as Jt}from"@earendil-works/pi-coding-agent";function Zt(t){let e=N(t),r=lr(e,Jt),n=Jt({dir:z(xe(),".agents","skills"),source:"agents"}),s=en(n.skills,z(xe(),".agents","skills")),o=ar({cwd:e,agentDir:z(xe(),".pi","agent"),skillPaths:[],includeDefaults:!0}),l=new Set,a=new Set,u=[];for(let d of[...r,...s,...o.skills]){let h=ur(d.filePath);a.has(h)||l.has(d.name)||(l.add(d.name),a.add(h),u.push(d))}return u}i(Zt,"loadAllSkills");function lr(t,e){let r=dr(t),n=[],s=t;for(;;){let o=z(s,".agents","skills"),l=e({dir:o,source:"agents"});if(n.push(...en(l.skills,o)),s===r)break;let a=N(s,"..");if(a===s)break;s=a}return n}i(lr,"loadAncestorAgentsSkills");function en(t,e){let r=N(e);return t.filter(n=>N(n.filePath,"..")!==r)}i(en,"filterRootMdFiles");function dr(t){let e=N(t);for(;;){if(sr(z(e,".git")))return e;let r=N(e,"..");if(r===e)return e;e=r}}i(dr,"findGitRoot");function ur(t){try{return or(t)}catch{return t}}i(ur,"canonicalizePath");async function tn(t,e){let r=Zt(e);return t.map(n=>{if(_e(n))return{name:n,description:"",content:`(Skill "${n}" skipped: name contains path traversal characters)`};let s=r.find(o=>o.name===n);if(!s)return{name:n,description:"",content:`(Skill "${n}" not found in .pi/skills/, .agents/skills/, or global skill locations)`};try{return{name:n,description:s.description,content:ir(s.filePath,"utf-8").trim()}}catch{return{name:n,description:"",content:`(Skill "${n}" not found in .pi/skills/, .agents/skills/, or global skill locations)`}}})}i(tn,"inlineSkills");async function nn(t,e){let r=Zt(e);return t.map(n=>{let s=r.find(o=>o.name===n);return s?{name:n,description:s.description,location:s.filePath,disableModelInvocation:s.disableModelInvocation}:{name:n,description:`(Skill "${n}" not found)`,location:"",disableModelInvocation:!1}})}i(nn,"loadSkillMeta");async function rn(t,e,r){try{let n=await t.exec("git",e,{cwd:r,timeout:Ue});return n.code===0?n.stdout.trim():null}catch{return null}}i(rn,"execGit");async function gr(t,e){let n=await rn(t,["rev-parse","--is-inside-work-tree"],e)==="true",s=n?await rn(t,["branch","--show-current"],e):null;return{isGitRepo:n,branch:s,platform:process.platform}}i(gr,"detectEnv");async function hr(t,e,r,n,s,o){let l=nt(),a=n?.includeContextFiles??o,u={};if(s==="inherit")try{u.parentSystemPrompt=t.getSystemPrompt()}catch(d){r(`Failed to get parent system prompt: ${y(d)}. Falling back to replace mode.`)}if(s==="custom")try{let d=cr.readFileSync(l,"utf-8").trim();d?u.customSystemPrompt=d:r(`Custom prompt file is empty: ${l}. Falling back to replace mode.`)}catch(d){d?.code==="ENOENT"?r(`Custom prompt file not found: ${l}. Falling back to replace mode.`):r(`Failed to read custom prompt file: ${y(d)}. Falling back to replace mode.`)}if(a)try{u.contextFiles=pr({cwd:e,agentDir:E()})}catch{}return u}i(hr,"resolveSystemPromptSources");async function fr(t,e,r,n,s,o,l){let a={...l},u=e?.inlinedSkills??[];if(u.length>0&&(a.inlinedSkills=await tn(u,n)),Array.isArray(r.skills)&&(a.skillMetas=await nn(r.skills,n)),e)return await Ae(e,n,s,a,o);let d=vt.get("general-purpose");if(!d)throw new Error(`No fallback config available for unknown type "${t}"`);return await Ae({...d,name:t},n,s,a,o)}i(fr,"buildPrompt");function mr(t){return t.filter(e=>!!e?.trim()).join(`
24
24
 
25
- `)}s(or,"joinPromptSections");function ar(t,e){return t!==null&&t!==""?t:e}s(ar,"branchName");function Vt(t,e,r,n){let i=t&&e?ar(r,n):void 0;return i?["","## Worktree branch","",`You are working in a git worktree on branch \`${i}\`.`,"Every commit you make and every merge you run lands on THIS branch \u2014 never on `main` or any other branch.","Do NOT switch branches and do NOT merge into `main` yourself. Report the branch name in your final response so the orchestrator can merge it with the merge_cowboy_branch tool."].join(`
26
- `):""}s(Vt,"buildWorktreeBranchSection");function lr(){return["## Steering & Mid-Run Instructions","- You may receive additional instructions or steering messages while working (from the user or the orchestrator).","- Always treat mid-run steering and follow-up instructions as having higher priority than your original initial prompt.","- In your final report (written to the result file), you MUST explicitly disclose any steering or direction changes you received during implementation.","- If steering or code review comments caused you to diverge from, modify, or abandon parts of the original goal, clearly explain what changed and why, so the orchestrator understands that the divergence was intentional and requested."].join(`
27
- `)}s(lr,"buildSteeringInstructions");function dr(t){return["","## Your report","","When the task is done \u2014 every change committed, every check run \u2014 write your complete final answer, once, to the file:",t,"","That write is your last action. The parent session reads the file as your deliverable as soon as it stops changing, so an edit or a rewrite after it is announced to the parent as a separate report. Verify before you write, not after; then reply with a one-line confirmation."].join(`
28
- `)}s(dr,"buildResultInstruction");async function Xt(t){let{pi:e,ctx:r,cwd:n,notify:i}=t,o=await rr(e,n),l=await ir(r,n,i,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),a=await sr(t.type,t.agentConfig,t.config,n,o,t.globalSystemPromptMode,l);return or([a.prefix,a.identity,a.skills,Vt(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),lr(),dr(t.resultFile),Ut(t.agentGuidance)])}s(Xt,"buildSubagentSystemPrompt");function Jt(t,e){let r=Object.entries(e??{});return r.length===0?null:(N(t,`${r.map(([n,i])=>`export ${n}=${Be(i)}`).join(`
25
+ `)}i(mr,"joinPromptSections");function yr(t,e){return t!==null&&t!==""?t:e}i(yr,"branchName");function sn(t,e,r,n){let s=t&&e?yr(r,n):void 0;return s?["","## Worktree branch","",`You are working in a git worktree on branch \`${s}\`.`,"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
+ `):""}i(sn,"buildWorktreeBranchSection");function vr(){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
+ `)}i(vr,"buildSteeringInstructions");function wr(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
+ `)}i(wr,"buildResultInstruction");async function on(t){let{pi:e,ctx:r,cwd:n,notify:s}=t,o=await gr(e,n),l=await hr(r,n,s,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),a=await fr(t.type,t.agentConfig,t.config,n,o,t.globalSystemPromptMode,l);return mr([a.prefix,a.identity,a.skills,sn(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),vr(),wr(t.resultFile),Xt(t.agentGuidance)])}i(on,"buildSubagentSystemPrompt");function an(t,e){let r=Object.entries(e??{});return r.length===0?null:(U(t,`${r.map(([n,s])=>`export ${n}=${Ke(s)}`).join(`
29
29
  `)}
30
- `),t)}s(Jt,"stageLaunchEnv");function cr(t,e){let r=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||r.length>0?{kind:"none"}:{kind:"default"}}s(cr,"resolveSkillMode");function pr(t,e,r){let n=new Map,i=s((o,l)=>{let a=o.toLowerCase(),d=n.get(a);d===void 0?n.set(a,l):d!==l&&n.set(a,null)},"addSource");for(let o of e.packages){let l=typeof o=="string"?o:o.source,a=Zt(l);a&&i(a,l)}for(let o of e.extensionPaths){let l=Zt(o);l&&i(l,o)}return t.map(o=>{if(gr(o)||mr(o,r))return o;let l=fr(o),a=n.get(l.toLowerCase());if(a===null)throw new Error(`Extension entry "${o}" is ambiguous in pi settings; more than one source matches its name. The agent did not start.`);if(a===void 0)throw new Error(`Extension entry "${o}" is not in the pi settings and is not an npm:, git:, or path source. The agent did not start.`);return a})}s(pr,"resolveExtensionSources");function gr(t){return t.startsWith("npm:")||t.startsWith("git:")}s(gr,"isPiExtensionSource");function mr(t,e){return D.isAbsolute(t)?Ae.existsSync(t):Ae.existsSync(D.resolve(e,t))}s(mr,"isExistingPath");function fr(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}s(fr,"extensionEntryName");function Zt(t){let e=t.split("#",1)[0].replace(/[\\/]$/,"");if(!e)return;if(e.startsWith("npm:")){let o=e.slice(4);return(o.startsWith("@")?o.split("/",2).at(1)?.split("@",1)[0]:o.split("@",1)[0])?.toLowerCase()}let r=e.startsWith("git:")?e.slice(4):e,n=D.basename(r),i=D.basename(n,D.extname(n));return i==="index"?D.basename(D.dirname(r))||void 0:i||void 0}s(Zt,"extensionSourceName");function en(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}s(en,"notifyLaunchConfigurationError");function hr(t){let e=t,r=e.sessionFile??e.sessionManager?.getSessionFile?.();if(r)return r}s(hr,"resolveParentSessionFile");function tn(t,e){let r=new Set;for(let n of t){if(!n)throw new Error(`Empty entry in ${e} is not supported`);r.add(n)}return[...r]}s(tn,"resolveToolCliEntries");function yr(t,e,r,n){switch(t){case"pi":case"pig":case"pi-bolt":return{...e,family:"pi",...r};case"opencode":return{...e,family:"opencode"};case"codex":return{...e,family:"codex",...n};case"claude":return{...e,family:"claude"};default:{if(A().get(t)===void 0)throw new Error(`no harness registered for "${t}"`);return{...e,family:"plugin"}}}}s(yr,"buildLaunchRequest");function wr(t,e){return A().require(t).buildArgs(e)}s(wr,"buildHarnessArgs");function vr(t,e,r,n,i){let o=Ve(t,e);if(o===void 0)return;let l={};for(let[a,d]of Object.entries(o)){if(!r.includes(a)){l[a]=d;continue}n(`Ignoring environment variable ${a} for ${i}: it is reserved by the ${i} harness and cannot be overridden`)}return Xe(l)}s(vr,"resolveLaunchEnv");function Sr(t,e){return[...t===void 0?[]:Ue[t],...e===void 0?[]:qe(e)]}s(Sr,"familyReservations");async function nn(t,e,r,n,i){let o=P(),l=i.cwd??e.cwd,a=vt(r,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),d=wt(r),u=i.harness,c=cr(a.skills,d),g=[],m=s(w=>{g.push(w)},"bufferNotify"),p={kind:"default"};if(a.extensions===!1)p={kind:"none"};else if(Array.isArray(a.extensions))if(a.extensions.length===0)p={kind:"none"};else try{let w=ur.create(l,E(),{projectTrusted:i.projectTrusted!==!1});p={kind:"paths",paths:pr(a.extensions,{packages:w.getPackages(),extensionPaths:w.getExtensionPaths()},l)}}catch(w){let ge=w instanceof Error?w.message:String(w);en(e,ge)}let h=Ge(u),f={kind:"default"};try{let w=h===void 0?void 0:d?.toolsByFamily?.[h];w?.tools===!1?f={kind:"none"}:Array.isArray(w?.tools)?f={kind:"include",names:tn(w.tools,"tools")}:w?.excludeTools?.length&&(f={kind:"exclude",names:tn(w.excludeTools,"excludeTools")})}catch(w){let ge=w instanceof Error?w.message:String(w);en(e,ge)}let S=A().get(u),k=vr(o.harnessEnv(u),h===void 0?void 0:d?.envByFamily?.[h],Sr(h,S),m,u),v=i.agentId??"unknown",R=Me(v);Y(R);let x=I(v),_=De(v),Ce=je(v),Mn=Jt(Oe(v),k),Te=await Xt({pi:t,ctx:e,type:r,agentConfig:d,config:a,cwd:l,globalSystemPromptMode:o.agent.systemPromptMode,globalIncludeContextFiles:o.agent.includeContextFiles,worktreePath:i.worktree?.path,expectedBranch:i.worktree?.branch,agentGuidance:i.agentGuidance,resultFile:x,notify:m});try{N(_,Te)}catch(w){throw new Error(`cannot write the system prompt file ${_}: ${y(w)}. The agent did not start.`,{cause:w})}if(!Ae.existsSync(_))throw new Error(`the system prompt file is missing after the write: ${_}. The agent did not start.`);N(Ce,n);let Le=i.fork?hr(e):void 0;i.fork&&Le===void 0&&m("Fork session is enabled, but no parent session file is available; launching without --fork");let Dn={subagentId:v,systemPromptFile:_,taskFile:Ce,resultFile:x,modelKey:O(i.modelChoice)??null,thinking:i.modelChoice?.thinking??null,toolSelection:f,envFile:Mn},On={forkSessionFile:Le??null,skills:c,extensions:p,projectTrusted:i.projectTrusted!==!1},jn={projectTrusted:i.projectTrusted!==!1},Fe=yr(u,Dn,On,jn),Hn=wr(u,Fe);for(let w of g)e.ui.notify(`[cowboy] ${w}`,"warning");return{name:v,cwd:l,systemPrompt:Te,piArgs:Hn,launch:Fe,harness:u}}s(nn,"buildLaunchPlan");var xe="Agent manager disposed before the queued agent could start.";function sn(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}s(sn,"createRun");function on(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(on,"startRun");function an(t){return t.shell==="dropped"||t.process.kind!=="launching"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt},shell:t.shell}}s(an,"activateRun");function ln(t,e,r){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"stopped",initiator:e},completedAt:r},shell:t.shell}}s(ln,"abortQueuedRun");function dn(t,e,r){return t.shell!=="held"?t:t.process.kind==="queued"?{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:e},completedAt:r},shell:t.shell}:t.process.kind==="launching"?{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:{kind:"failed",error:e},completedAt:r},shell:t.shell}:t}s(dn,"failStart");function ae(t,e,r){return t.shell==="dropped"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:{kind:"settling",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,terminal:e,completedAt:r},shell:"held"}}s(ae,"enterSettling");function un(t){return t.shell!=="held"||t.process.kind!=="settling"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:t.process.terminal,completedAt:t.process.completedAt},shell:t.shell}}s(un,"finishSettling");function cn(t,e){return t.shell!=="held"||t.process.kind!=="settling"&&t.process.kind!=="settled"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(cn,"reviveRun");function pn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:xe},completedAt:e},shell:t.shell}}s(pn,"disposeQueuedRun");function gn(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}s(gn,"disposeLiveRun");function Re(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:Ie(t,e)}}s(Re,"dropRun");function rn(t,e,r,{launch:n,retention:i}){let o={phase:"settled",startedAt:t,...n===void 0?{}:{launch:n},...i===void 0?{}:{worktreeRetentionReason:i}};switch(e.kind){case"completed":return{...o,status:"completed",result:e.result,completedAt:r};case"failed":return{...o,status:"error",error:e.error,completedAt:r};case"stopped":return{...o,status:"stopped",completedAt:r,stop:{initiator:e.initiator}}}}s(rn,"settledStartedOutcome");function kr(t,e,r,{retention:n}){let i={phase:"never-started",queuedAt:t,...n===void 0?{}:{worktreeRetentionReason:n}};switch(e.kind){case"failed":return{...i,status:"error",error:e.error,completedAt:r};case"stopped":return{...i,status:"stopped",completedAt:r,stop:{initiator:e.initiator}}}}s(kr,"settledNeverStartedOutcome");function Pr(t,e){switch(t.kind){case"queued":return{phase:"queued",queuedAt:t.queuedAt};case"launching":case"active":return{phase:"spawned",startedAt:t.startedAt,...e.launch===void 0?{}:{launch:e.launch}};case"settling":return rn(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?rn(t.startedAt,t.terminal,t.completedAt,e):kr(t.queuedAt,t.terminal,t.completedAt,e)}}s(Pr,"projectProcess");function Ie(t,e){return t.shell==="dropped"?t.lifecycle:Pr(t.process,e)}s(Ie,"projectLifecycle");import*as mn from"node:fs";import*as fn from"node:path";function hn(t){let{spawn:e,hostRef:r,transport:n}=t,i=br(e),o=fn.dirname(i.resultFile);Y(o),mn.rmSync(i.resultFile,{force:!0});let l=oe({host:n.createHost(b()),resultFile:i.resultFile,supervisorOptions:t.supervisorOptions,transport:n});l.adopt(r),t.attachSupervisor(l,i),t.rebindParentSignal(),l.watch().then(a=>t.reportOutcome(l,a))}s(hn,"reviveSettledRun");function br(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??I(t.id)}}s(br,"resumeLaunch");var le=j("session");function Ar(t,e){let{type:r,options:n}=t;return{id:"",lifecycle:{phase:"queued",queuedAt:Date.now()},display:{type:r,description:n.description,taskSlug:n.taskSlug,invocation:n.invocation,orchestration:n.orchestration,worktree:n.worktree},execution:{promise:e,abortController:new AbortController,host:n.hostRef}}}s(Ar,"buildAgentSpawn");var Ee=class{static{s(this,"CompletionGate")}resolve;promise;constructor(){this.promise=new Promise(e=>{this.resolve=e})}open(e){let r=this.resolve;r&&(this.resolve=void 0,r(e))}},de=class{static{s(this,"SubagentSession")}id;args;deps;gate=new Ee;stableSpawn;run;launchState;retention;supervisor;parentBinding;constructor({id:e,args:r,deps:n}){this.id=e,this.args=r,this.deps=n,this.stableSpawn=Ar(r,this.gate.promise),this.stableSpawn.id=e;let i=this.stableSpawn.lifecycle;this.run=sn(i.phase==="queued"?i.queuedAt:Date.now()),T().add(this.stableSpawn),this.bindParentSignal()}get spawn(){return this.stableSpawn}get promise(){return this.gate.promise}isQueued(){return this.run.shell==="held"&&this.run.process.kind==="queued"}isLaunching(){return this.run.shell!=="dropped"&&this.run.process.kind==="launching"}isActive(){return this.run.shell!=="dropped"&&this.run.process.kind==="active"}isSettled(){return this.run.shell==="held"&&(this.run.process.kind==="settling"||this.run.process.kind==="settled")}commit(e){this.run=e,this.spawn.lifecycle=Ie(e,this.artifacts)}get artifacts(){return{launch:this.launchState,retention:this.retention}}start(e){this.isQueued()&&(e&&this.deps.pools.reserve(this.id,e),this.commit(on(this.run,Date.now())),this.launch())}rollbackStart(){this.commit(Re(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(dn(this.run,y(e),Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn)}async steer(e){if(this.isQueued())return{kind:"refused",reason:`agent ${this.id} is queued \u2014 it has no pane yet, so it cannot receive a message. Wait for a concurrency slot (or stop it).`};let r=this.spawn.execution.host;if(!r)return{kind:"refused",reason:this.isLaunching()?`agent ${this.id} is still starting up \u2014 its pane does not exist yet, so it cannot receive a message. Retry in a moment.`:this.spawn.lifecycle.phase==="never-started"?`agent ${this.id} never started, so it has no pane and there is nobody to receive the message.`:`agent ${this.id} has no pane (it was cleaned up), so there is nobody to receive the message.`};let n=this.isSettled(),i;try{i=await this.deps.transport.createHost(b()).deliver(r,e)}catch(o){i={kind:"not-submitted",detail:y(o)}}if(i.kind==="not-submitted")return{kind:"refused",reason:`the message could not be delivered to agent ${this.id} \u2014 ${i.detail}`};if(n)try{this.revive(r)}catch(o){return{kind:"delivered-not-revived",reason:`the message reached its pane, but the agent could not be revived: ${y(o)}. No completion message will arrive \u2014 read the pane for the result.`}}return{kind:"delivered"}}revive(e){let r=Date.now();hn({spawn:this.spawn,hostRef:e,transport:this.deps.transport,supervisorOptions:this.supervisorOptions(),attachSupervisor:s((n,i)=>{this.supervisor?.detach(),this.deps.pools.reacquire(this.id,{harness:this.args.options.harness,modelKey:O(this.args.options.modelChoice)}),this.supervisor=n,this.launchState=i,this.retention=void 0,this.commit(cn(this.run,r))},"attachSupervisor"),rebindParentSignal:s(()=>this.bindParentSignal(),"rebindParentSignal"),reportOutcome:s((n,i)=>{this.applySupervisorOutcome(n,i)},"reportOutcome")})}async abort(e){let r=this.isLaunching()||this.isActive(),n=this.run;return le.debug("abort requested",{initiator:e,process:n.shell==="dropped"?"dropped":n.process.kind,shell:n.shell,stopIssued:r}),this.isQueued()?(this.deps.pools.cancelQueued(this.id),this.commit(ln(this.run,e??"agent",Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn),!0):!this.isLaunching()&&!this.isActive()||(this.spawn.execution.abortController.abort(),await this.stopPaneProcess(),!this.isLaunching()&&!this.isActive())?!1:(this.commit(ae(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}drop(){this.commit(Re(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,B(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit(pn(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(gn(this.run)),this.gate.open("")),this.supervisor?.abandon(),this.supervisor=void 0,this.detachParentBinding()}async launch(){let e={kind:"none"},r={kind:"none"},n;try{let i=this.deps.transport.createHost(this.args.pi),o=this.deps.transport.createPane(this.args.pi),{pi:l,ctx:a,type:d,prompt:u,options:c}=this.args,g=c.hostRef;if(!g&&c.worktree?.kind==="owned"){let v;try{v=await Lt.allocate(l,{naming:{kind:"generated",taskSlug:c.taskSlug??d,id:this.spawn.id},parentCwd:a.cwd,worktreeRoot:P().agent.worktreeRoot,materialization:rt(),dirtyCheckout:bt(d),notify:s((R,x)=>a.ui.notify(R,x),"notify"),host:i})}catch(R){throw c.worktree=void 0,this.spawn.display.worktree=void 0,R}v.worktree?(c.worktree={kind:"owned",...v.worktree},this.spawn.display.worktree=c.worktree):(c.worktree=void 0,this.spawn.display.worktree=void 0),g=v.hostRef}let m=c.worktree?.branch??K(c.taskSlug??Q(d),this.id),p=await nn(l,a,d,u,{agentId:this.id,harness:c.harness,modelChoice:c.modelChoice,fork:c.fork,cwd:c.worktree?.path,projectTrusted:c.projectTrusted,description:c.description,worktree:c.worktree,agentGuidance:c.orchestration.guidance}),h={resultFile:p.launch.resultFile};this.launchState=h,n=p.cwd;let f=A(),S=f.require(p.harness);if(g=g??await i.hostAt({unit:"pane",cwd:p.cwd,label:c.taskSlug??d,name:m}),e={kind:"held",host:i,ref:g},!this.isLaunching())return;this.spawn.execution.host=g,this.spawn.execution.harness=p.harness,await S.prepare({pi:l,pane:o,paneId:g.paneId,cwd:p.cwd,launch:p.launch,config:f.config(p.harness)});let k=oe({host:i,resultFile:h.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=k,await k.start({name:m,cwd:p.cwd,piArgs:p.piArgs,agentMultiplexerKind:S.agentMultiplexerKind,taskSlug:c.taskSlug},g),e={kind:"committed"},!this.isLaunching())return;this.commit(an(this.run)),k.watch().then(v=>this.applySupervisorOutcome(k,v))}catch(i){r={kind:"failed",error:i}}finally{e.kind==="held"&&await e.host.release(e.ref,"placement").catch(()=>{})}if(r.kind==="failed"&&this.isLaunching()){let i=this.spawn.execution.harness;if(i!==void 0)try{await A().require(i).teardown({pi:this.args.pi,paneId:this.spawn.execution.host?.paneId??null,cwd:n??null,subagentId:this.spawn.id})}catch(o){le.warn("harness teardown failed after a failed launch",{spawnId:this.spawn.id,harness:i,error:y(o)})}this.commit(ae(this.run,{kind:"failed",error:y(r.error)},Date.now())),await this.settle()}}supervisorOptions(){return{stopInitiator:"agent",onFollowUp:s(e=>this.deps.onFollowUpResult(this.spawn,e),"onFollowUp")}}resultFilePath(){return this.launchState?.resultFile??I(this.id)}async applySupervisorOutcome(e,r){if(!(!this.isActive()||this.supervisor!==e))switch(le.debug("outcome mapped",{kind:r.kind}),r.kind){case"completed":{this.commit(ae(this.run,{kind:"completed",result:r.deliverable||""},Date.now())),await this.settle();return}case"stopped":await this.abort(r.initiator)}}async stopPaneProcess(){let e=this.supervisor;if(e){this.supervisor=void 0,await e.stop(2e3);return}let r=this.spawn.execution.host;r&&await this.deps.transport.createHost(b()).stop(r,{interruptGraceMs:2e3,confirmMs:1e4})}settleChain=Promise.resolve();async settle(){if(this.run.shell!=="held"||this.run.process.kind!=="settling")return;let e=this.settleChain,r,n=new Promise(i=>{r=i});this.settleChain=n,await e;try{await this.runSettlePass()}finally{r()}}async runSettlePass(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settling")return;let r=ze(this.spawn.lifecycle),n=await this.readWorktreeRetention();this.deps.pools.release(this.id),this.deps.onRunEnded(this.spawn),this.run===e&&this.detachParentBinding(),this.gate.open(r),this.run===e&&(this.retention=n??void 0,this.commit(un(this.run)))}async readWorktreeRetention(){let e=this.spawn.display.worktree;return e?.kind!=="owned"?null:gt(b(),e.path)}detachParentBinding(){let e=this.parentBinding;e&&(this.parentBinding=void 0,e.signal.removeEventListener("abort",e.handler))}bindParentSignal(){if(this.parentBinding)return;let e=this.args.options.signal;if(!e||e.aborted)return;let r=s(()=>{le.debug("parent signal fired",{initiator:"user"}),this.abort("user")},"handler");e.addEventListener("abort",r,{once:!0}),this.parentBinding={signal:e,handler:r}}};function wn(t){return{createHost:s(()=>t.host,"createHost"),createPane:s(()=>t.pane,"createPane"),createPlacements:s(()=>t.placements,"createPlacements"),createDeliverable:s(e=>new re(e),"createDeliverable")}}s(wn,"createAgentManagerTransport");var yn=j("manager");function xr(t){if(t.outcome.kind==="refused"){let e=t.outcome.reason;return e.kind==="dirty"||e.kind==="unverifiable"?e:void 0}if(t.worktree.kind==="removal-failed")return{kind:"unverifiable",detail:`the removal was not confirmed (${t.worktree.detail})`}}s(xr,"retentionForReport");var ue=class{constructor(e,r){this.transport=r;this.pools=e,this.registry=new te({listAgents:s(()=>this.listAgents(V),"listAgents"),spawn:s((n,i,o)=>this.spawn(b(),J(),n,i,o),"spawn"),getSpawn:s(n=>this.getSpawn(n),"getSpawn"),findTaskAttempts:s(n=>this.transport.createHost(b()).findAttempts(n),"findTaskAttempts"),queuePosition:s(n=>this.pools.queuePosition(n),"queuePosition")})}transport;static{s(this,"AgentManager")}sessions=new Map;onComplete;onFollowUp;teardowns=new Map;pools;registry;getRegistry(){return this.registry}setConcurrency(e){this.pools.setConcurrency(e)}setOnComplete(e){this.onComplete=e}setOnFollowUp(e){this.onFollowUp=e}mintSpawnId(){return T().mint()}spawn(e,r,n,i,o){let l=o.spawnId,{requestedHarness:a,...d}=o,u={...d,harness:At(n,a)},c={pi:e,ctx:r,type:n,prompt:i,options:u},g=this.pools.admitSpawn({harness:u.harness,modelKey:O(u.modelChoice)},{id:l,start:s(p=>this.startSession(l,c,p),"start")}),m;try{m=new de({id:l,args:c,deps:{transport:this.transport,pools:this.pools,onRunEnded:s(p=>this.notifyComplete(p),"onRunEnded"),onFollowUpResult:s((p,h)=>this.notifyFollowUp(p,h),"onFollowUpResult")}})}catch(p){throw this.pools.release(l),p}if(this.sessions.set(l,m),u.signal?.aborted)return m.abort("user"),l;if(g.kind==="queue")return l;try{m.start(g.reservation)}catch(p){throw m.rollbackStart(),this.pools.release(l),this.sessions.delete(l),T().drop(l),p}return l}startSession(e,r,n){let i=this.sessions.get(e);if(!i||!i.isQueued())return!1;try{i.start(n)}catch(o){i.settleStartFailure(o)}return!0}async steer(e,r){if(this.teardowns.has(e))return{kind:"refused",reason:`agent ${e} is being cleaned up, so its worktree is on its way out \u2014 wait for the report before steering it.`};let n=this.sessions.get(e);return n?n.steer(r):{kind:"refused",reason:`no live session tracks agent ${e} \u2014 check the id from its spawn or completion result (a cleaned-up agent is gone for good).`}}getSpawn(e){return T().get(e)}assets(){let e=b();return qt(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=Qe){return T().list(e).sort((r,n)=>fe(n.lifecycle)-fe(r.lifecycle))}async abort(e,r){return await this.sessions.get(e)?.abort(r)??!1}notifyComplete(e){try{this.onComplete?.(e)}catch(r){yn.warn("completion notification failed",{spawnId:e.id,detail:y(r)})}}notifyFollowUp(e,r){try{this.onFollowUp?.(e,r)}catch(n){yn.warn("follow-up notification failed",{spawnId:e.id,detail:y(n)})}}recordRetention(e,r){let n=e.lifecycle;q(n)&&(n.worktreeRetentionReason=r)}dropSpawn(e){this.sessions.get(e.id)?.drop(),this.sessions.delete(e.id),B(I(e.id)),T().drop(e.id)}async cleanup(e,r){let n=this.runCleanup(e,this.teardowns.get(e),r);this.teardowns.set(e,n);try{return await n}finally{this.teardowns.get(e)===n&&this.teardowns.delete(e)}}async runCleanup(e,r,n){await r?.catch(()=>{}),Z()?.dropNudge(e);let i=this.getSpawn(e)!==void 0,o=await Tt(this.assets()).cleanupAgent(e,{getSpawn:s(a=>this.getSpawn(a),"getSpawn"),dropSpawn:s(a=>this.dropSpawn(a),"dropSpawn")},n),l=this.getSpawn(e);if(l!==void 0){let a=xr(o);a!==void 0&&this.recordRetention(l,a)}return i&&o.outcome.kind==="torn-down"&&B(I(e)),o}dispose(){this.pools.clearQueue();for(let e of this.sessions.values())e.settleForDispose();this.sessions.clear()}};var Rr=200,ce=class{static{s(this,"SpawnCoordinator")}manager;backgroundAgentIds=new Set;pendingNudges=new Set;pendingFollowUps=new Map;nudgeTimer=null;disposed=!1;registry;constructor(e){this.manager=e,this.registry=e.getRegistry()}async spawn(e,r){let n=await this.registry.admit(r);if(n.status==="rejected")throw await this.inFlightError(r.taskSlug,n);let i=n.agentId,o=this.manager.getSpawn(i);return o.execution.spawnCtx=e,this.announceSpawn(e,o),r.runInBackground?this.backgroundAgentIds.add(i):await o.execution.promise,{agentId:i,spawn:o}}announceSpawn(e,r){if(!e.hasUI)return;let n=r.lifecycle;if(q(n))return;let i=n.phase==="queued"?"Queued":"Spawned";Ct(e.ui).succeeded(`${i} agent ${r.id} (${r.display.type})`)}async inFlightError(e,r){let n=this.manager.getSpawn(r.conflictingId);if(n)return new F({kind:"spawn",spawn:n},e);let i=await U().host.findAttempts(e),o=ne([],i);if(o.kind!=="none")return new F(o,e);let l={name:r.conflictingId};return new F({kind:"multiplexer",attempt:l},e)}dropNudge(e){this.pendingNudges.delete(e),this.pendingFollowUps.delete(e)}scheduleNudge(e){this.pendingNudges.add(e),this.ensureNudgeTimer()}onAgentFollowUp(e,r){this.backgroundAgentIds.has(e.id)&&(this.pendingFollowUps.set(e.id,r),this.ensureNudgeTimer())}ensureNudgeTimer(){this.nudgeTimer||(this.nudgeTimer=setTimeout(()=>{this.nudgeTimer=null;let e=[...this.pendingNudges];this.pendingNudges.clear();let r=[...this.pendingFollowUps];this.pendingFollowUps.clear();for(let n of e)this.emitIndividualNudge(n);for(let[n,i]of r)this.emitFollowUp(n,i)},Rr))}onAgentComplete(e){this.backgroundAgentIds.has(e.id)&&(Ir(e)||this.scheduleNudge(e.id))}dispose(){this.nudgeTimer&&(clearTimeout(this.nudgeTimer),this.nudgeTimer=null),this.pendingNudges.clear(),this.pendingFollowUps.clear(),this.backgroundAgentIds.clear(),this.disposed=!0}emitFollowUp(e,r){if(this.disposed||!H())return;let n=b(),i=this.manager.getSpawn(e);if(!i)return;let o=Se(i,{includeRunInfo:!0,includeStatus:!0}),l=`[Cowboy agent "${i.display.type}" ${i.id} reported again after settling]`;try{n.sendMessage({customType:"subagent-result",content:`${l}
30
+ `),t)}i(an,"stageLaunchEnv");function Sr(t,e){let r=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||r.length>0?{kind:"none"}:{kind:"default"}}i(Sr,"resolveSkillMode");function Pr(t,e,r){let n=new Map,s=i((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=ln(l);a&&s(a,l)}for(let o of e.extensionPaths){let l=ln(o);l&&s(l,o)}return t.map(o=>{if(br(o)||Ar(o,r))return o;let l=xr(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})}i(Pr,"resolveExtensionSources");function br(t){return t.startsWith("npm:")||t.startsWith("git:")}i(br,"isPiExtensionSource");function Ar(t,e){return $.isAbsolute(t)?Re.existsSync(t):Re.existsSync($.resolve(e,t))}i(Ar,"isExistingPath");function xr(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}i(xr,"extensionEntryName");function ln(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=$.basename(r),s=$.basename(n,$.extname(n));return s==="index"?$.basename($.dirname(r))||void 0:s||void 0}i(ln,"extensionSourceName");function dn(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}i(dn,"notifyLaunchConfigurationError");function Rr(t){let e=t,r=e.sessionFile??e.sessionManager?.getSessionFile?.();if(r)return r}i(Rr,"resolveParentSessionFile");function un(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]}i(un,"resolveToolCliEntries");function Ir(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"}}}}i(Ir,"buildLaunchRequest");function Er(t,e){return A().require(t).buildArgs(e)}i(Er,"buildHarnessArgs");function Cr(t,e,r,n,s,o){let l=ve(t,e),a=Lr(r,s,o);if(l===void 0)return a;let u={};for(let[d,h]of Object.entries(l)){if(!n.includes(d)){u[d]=h;continue}s(`Ignoring environment variable ${d} for ${o}: it is reserved by the ${o} harness and cannot be overridden`)}return ve(tt(u),a)}i(Cr,"resolveLaunchEnv");var Tr={name:"not a valid environment variable name",reserved:"reserved","not-string":"not a string",control:"carrying a control character"};function Lr(t,e,r){if(t===void 0)return;let n=et(t,{reserved:[],report:i((s,o)=>e(`Ignoring inherited environment variable ${s} for ${r}: it is ${Tr[o]} and cannot be carried`),"report")});return Object.keys(n).length===0?void 0:n}i(Lr,"inheritedEnvOverrides");function Fr(t,e){return[...t===void 0?[]:Ge[t],...e===void 0?[]:Be(e)]}i(Fr,"familyReservations");async function cn(t,e,r,n,s){let o=b(),l=s.cwd??e.cwd,a=bt(r,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),u=Pt(r),d=s.harness,h=Sr(a.skills,u),c=[],p=i(v=>{c.push(v)},"bufferNotify"),g={kind:"default"};if(a.extensions===!1)g={kind:"none"};else if(Array.isArray(a.extensions))if(a.extensions.length===0)g={kind:"none"};else try{let v=kr.create(l,E(),{projectTrusted:s.projectTrusted!==!1});g={kind:"paths",paths:Pr(a.extensions,{packages:v.getPackages(),extensionPaths:v.getExtensionPaths()},l)}}catch(v){let fe=v instanceof Error?v.message:String(v);dn(e,fe)}let m=Qe(d),f={kind:"default"};try{let v=m===void 0?void 0:u?.toolsByFamily?.[m];v?.tools===!1?f={kind:"none"}:Array.isArray(v?.tools)?f={kind:"include",names:un(v.tools,"tools")}:v?.excludeTools?.length&&(f={kind:"exclude",names:un(v.excludeTools,"excludeTools")})}catch(v){let fe=v instanceof Error?v.message:String(v);dn(e,fe)}let w=A().get(d),P=Cr(o.harnessEnv(d),m===void 0?void 0:u?.envByFamily?.[m],w?.inheritedEnv?.(),Fr(m,w),p,d),S=s.agentId??"unknown",k=De(S);Z(k);let x=I(S),O=He(S),Le=$e(S),Un=an(je(S),P),Fe=await on({pi:t,ctx:e,type:r,agentConfig:u,config:a,cwd:l,globalSystemPromptMode:o.agent.systemPromptMode,globalIncludeContextFiles:o.agent.includeContextFiles,worktreePath:s.worktree?.path,expectedBranch:s.worktree?.branch,agentGuidance:s.agentGuidance,resultFile:x,notify:p});try{U(O,Fe)}catch(v){throw new Error(`cannot write the system prompt file ${O}: ${y(v)}. The agent did not start.`,{cause:v})}if(!Re.existsSync(O))throw new Error(`the system prompt file is missing after the write: ${O}. The agent did not start.`);U(Le,n);let Oe=s.fork?Rr(e):void 0;s.fork&&Oe===void 0&&p("Fork session is enabled, but no parent session file is available; launching without --fork");let Bn={subagentId:S,systemPromptFile:O,taskFile:Le,resultFile:x,modelKey:M(s.modelChoice)??null,thinking:s.modelChoice?.thinking??null,toolSelection:f,envFile:Un},Gn={forkSessionFile:Oe??null,skills:h,extensions:g,projectTrusted:s.projectTrusted!==!1},Kn={projectTrusted:s.projectTrusted!==!1},Me=Ir(d,Bn,Gn,Kn),Qn=Er(d,Me);for(let v of c)e.ui.notify(`[cowboy] ${v}`,"warning");return{name:S,cwd:l,systemPrompt:Fe,piArgs:Qn,launch:Me,harness:d}}i(cn,"buildLaunchPlan");var Ie="Agent manager disposed before the queued agent could start.";function gn(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}i(gn,"createRun");function hn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(hn,"startRun");function fn(t){return t.shell==="dropped"||t.process.kind!=="launching"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt},shell:t.shell}}i(fn,"activateRun");function mn(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}}i(mn,"abortQueuedRun");function yn(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}i(yn,"failStart");function ue(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"}}i(ue,"enterSettling");function vn(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}}i(vn,"finishSettling");function wn(t,e){return t.shell!=="held"||t.process.kind!=="settled"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(wn,"handoverRun");function kn(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}}i(kn,"reviveRun");function Sn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:Ie},completedAt:e},shell:t.shell}}i(Sn,"disposeQueuedRun");function Pn(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}i(Pn,"disposeLiveRun");function Ee(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:Ce(t,e)}}i(Ee,"dropRun");function pn(t,e,r,{launch:n,retention:s}){let o={phase:"settled",startedAt:t,...n===void 0?{}:{launch:n},...s===void 0?{}:{worktreeRetentionReason:s}};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}}}}i(pn,"settledStartedOutcome");function Or(t,e,r,{retention:n}){let s={phase:"never-started",queuedAt:t,...n===void 0?{}:{worktreeRetentionReason:n}};switch(e.kind){case"failed":return{...s,status:"error",error:e.error,completedAt:r};case"stopped":return{...s,status:"stopped",completedAt:r,stop:{initiator:e.initiator}}}}i(Or,"settledNeverStartedOutcome");function Mr(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 pn(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?pn(t.startedAt,t.terminal,t.completedAt,e):Or(t.queuedAt,t.terminal,t.completedAt,e)}}i(Mr,"projectProcess");function Ce(t,e){return t.shell==="dropped"?t.lifecycle:Mr(t.process,e)}i(Ce,"projectLifecycle");import*as bn from"node:fs";import*as An from"node:path";function xn(t){let{spawn:e,hostRef:r,transport:n}=t,s=Dr(e),o=An.dirname(s.resultFile);Z(o),bn.rmSync(s.resultFile,{force:!0});let l=de({host:n.createHost(R()),resultFile:s.resultFile,supervisorOptions:t.supervisorOptions,transport:n});l.adopt(r),t.attachSupervisor(l,s),t.rebindParentSignal(),l.watch().then(a=>t.reportOutcome(l,a))}i(xn,"reviveSettledRun");function Dr(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??I(t.id)}}i(Dr,"resumeLaunch");var V=T("session");function Hr(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,history:[]}}}i(Hr,"buildAgentSpawn");var Te=class{static{i(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))}};function _(t){return{kind:"faulted",fault:t}}i(_,"faulted");var ce=class{static{i(this,"SubagentSession")}id;args;deps;gate=new Te;stableSpawn;run;launchState;retention;supervisor;parentBinding;constructor({id:e,args:r,deps:n}){this.id=e,this.args=r,this.deps=n,this.stableSpawn=Hr(r,this.gate.promise),this.stableSpawn.id=e;let s=this.stableSpawn.lifecycle;this.run=gn(s.phase==="queued"?s.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=Ce(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(hn(this.run,Date.now())),this.launch())}rollbackStart(){this.commit(Ee(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(yn(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(),s;try{s=await this.deps.transport.createHost(R()).deliver(r,e)}catch(o){s={kind:"not-submitted",detail:y(o)}}if(s.kind==="not-submitted")return{kind:"refused",reason:`the message could not be delivered to agent ${this.id} \u2014 ${s.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();xn({spawn:this.spawn,hostRef:e,transport:this.deps.transport,supervisorOptions:this.supervisorOptions(),attachSupervisor:i((n,s)=>{this.supervisor?.detach(),this.deps.pools.reacquire(this.id,{harness:this.args.options.harness,modelKey:M(this.args.options.modelChoice)}),this.supervisor=n,this.launchState=s,this.retention=void 0,this.commit(kn(this.run,r))},"attachSupervisor"),rebindParentSignal:i(()=>this.bindParentSignal(),"rebindParentSignal"),reportOutcome:i((n,s)=>{this.applySupervisorOutcome(n,s)},"reportOutcome")})}async abort(e){let r=this.isLaunching()||this.isActive(),n=this.run;return V.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(mn(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(ue(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}async handover(e){let r=this.run;if(r.shell!=="held"||r.process.kind!=="settled")return _({kind:"agent-not-settled",status:D(this.spawn.lifecycle)});let n=this.spawn.execution.harness,s=this.spawn.execution.host;if(n===void 0||s===void 0||!r.process.started)return _({kind:"never-started"});let o=this.args.options.worktree?.path??this.args.ctx.cwd,l=await Xe(A(),n,{pi:this.args.pi,subagentId:this.id,paneId:s.paneId,cwd:o},{maxExcludedRatio:b().agent.handoverMaxExcludedRatio});if(l.kind==="faulted")return l;if(this.run!==r)return _({kind:"agent-not-settled",status:D(this.spawn.lifecycle)});let a;try{a=await this.stopHarnessProcess(s,12e3)}catch(d){return _({kind:"stop-failed",detail:y(d)})}if(!a)return _({kind:"stop-failed",detail:"the source process did not confirm it was gone"});this.supervisor?.detach(),this.supervisor=void 0,Ut(this.resultFilePath());let u=Je({taskSlug:this.spawn.display.taskSlug,sourceName:A().displayName(n),previous:this.spawn.execution.history.map(({harness:d,sessionId:h})=>({harness:d,sessionId:h})),current:{harness:n,sessionId:l.sessionId},session:l.session});if(Yt(this.spawn.execution,{harness:n,host:s,cwd:o,sessionId:l.sessionId,startedAt:r.process.startedAt,endedAt:Date.now()}),this.args.prompt=u,this.args.options.harness=e.harness,this.args.options.modelChoice=e.modelChoice,this.launchState=void 0,this.retention=void 0,this.deps.pools.reacquire(this.id,{harness:e.harness,modelKey:M(e.modelChoice)}),this.commit(wn(this.run,Date.now())),this.bindParentSignal(),await this.launch({kind:"handover"}),!this.isActive()){let d=this.spawn.lifecycle;return _({kind:"launch-failed",detail:d.phase==="settled"&&d.status==="error"?d.error:"the next run did not start"})}return{kind:"handed-over",from:n,to:e.harness,...l.loss===void 0?{}:{loss:l.loss}}}drop(){this.commit(Ee(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,Q(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit(Sn(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(Pn(this.run)),this.gate.open("")),this.supervisor?.abandon(),this.supervisor=void 0,this.detachParentBinding()}async launch(e={kind:"spawn"}){let r={kind:"none"},n={kind:"none"},s;try{let o=this.deps.transport.createHost(this.args.pi),l=this.deps.transport.createPane(this.args.pi),{pi:a,ctx:u,type:d,prompt:h,options:c}=this.args,p=e.kind==="spawn"?c.hostRef:void 0;if(e.kind==="spawn"&&!p&&c.worktree?.kind==="owned"){let k;try{k=await Mt({pi:a,host:o,parentCwd:u.cwd,spawnId:this.spawn.id,agentType:d,taskSlug:c.taskSlug,worktreeRoot:b().agent.worktreeRoot,materialization:at(),notify:i((x,O)=>u.ui.notify(x,O),"notify")})}catch(x){throw c.worktree=void 0,this.spawn.display.worktree=void 0,x}c.worktree=k.kind==="owned"?{kind:"owned",...k.worktree}:void 0,this.spawn.display.worktree=c.worktree,p=k.kind==="owned"?k.hostRef:void 0}let g=c.worktree?.branch??X(c.taskSlug??Y(d),this.id),m=await cn(a,u,d,h,{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}),f={resultFile:m.launch.resultFile};this.launchState=f,s=m.cwd;let w=A(),P=w.require(m.harness);if(!p){let k=c.worktree;p=await o.hostAt({unit:"pane",cwd:m.cwd,label:c.taskSlug??d,name:g,...k===void 0?{}:{checkout:{path:k.path,repoCwd:await K(a,k.path),branch:k.branch}}})}if(r={kind:"held",host:o,ref:p},!this.isLaunching())return;zt(this.spawn.execution,p),Vt(this.spawn.execution,m.harness),await P.prepare({pi:a,pane:l,paneId:p.paneId,cwd:m.cwd,launch:m.launch,config:w.config(m.harness)});let S=de({host:o,resultFile:f.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=S,await S.start({name:g,cwd:m.cwd,piArgs:m.piArgs,agentMultiplexerKind:P.agentMultiplexerKind,taskSlug:c.taskSlug},p),r={kind:"committed"},!this.isLaunching())return;this.commit(fn(this.run)),S.watch().then(k=>this.applySupervisorOutcome(S,k))}catch(o){n={kind:"failed",error:o}}finally{r.kind==="held"&&await r.host.release(r.ref,"placement").catch(()=>{})}if(n.kind==="failed"&&this.isLaunching()){let o=this.spawn.execution.harness;if(o!==void 0)try{await A().require(o).teardown({pi:this.args.pi,paneId:this.spawn.execution.host?.paneId??null,cwd:s??null,subagentId:this.spawn.id})}catch(l){V.warn("harness teardown failed after a failed launch",{spawnId:this.spawn.id,harness:o,error:y(l)})}this.commit(ue(this.run,{kind:"failed",error:y(n.error)},Date.now())),await this.settle()}}supervisorOptions(){return{stopInitiator:"agent",stopProcess:i((e,r)=>this.stopHarnessProcess(e,r),"stopProcess"),onFollowUp:i(e=>this.deps.onFollowUpResult(this.spawn,e),"onFollowUp")}}async stopHarnessProcess(e,r){let n=this.spawn.execution.harness??this.args.options.harness;try{await A().require(n).stop({pi:this.args.pi,pane:this.deps.transport.createPane(this.args.pi),paneId:e.paneId})}catch(s){V.debug("harness stop failed",{harness:n,paneId:e.paneId,detail:y(s)})}return this.deps.transport.createHost(this.args.pi).waitUntilGone(e,{timeoutMs:r})}resultFilePath(){return this.launchState?.resultFile??I(this.id)}async applySupervisorOutcome(e,r){if(!(!this.isActive()||this.supervisor!==e))switch(V.debug("outcome mapped",{kind:r.kind}),r.kind){case"completed":{this.commit(ue(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.stopHarnessProcess(r,12e3)}settleChain=Promise.resolve();async settle(){if(this.run.shell!=="held"||this.run.process.kind!=="settling")return;let e=this.settleChain,r,n=new Promise(s=>{r=s});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=Ye(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(vn(this.run)))}async readWorktreeRetention(){let e=this.spawn.display.worktree;return e?.kind!=="owned"?null:yt(R(),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=i(()=>{V.debug("parent signal fired",{initiator:"user"}),this.abort("user")},"handler");e.addEventListener("abort",r,{once:!0}),this.parentBinding={signal:e,handler:r}}};function En(t){return{createHost:i(()=>t.host,"createHost"),createPane:i(()=>t.pane,"createPane"),createPlacements:i(()=>t.placements,"createPlacements"),createDeliverable:i(e=>new oe(e),"createDeliverable")}}i(En,"createAgentManagerTransport");var Rn=T("manager");function In(t){return{kind:"faulted",fault:{kind:"request-refused",detail:t}}}i(In,"handoverRefused");function jr(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})`}}i(jr,"retentionForReport");var pe=class{constructor(e,r){this.transport=r;this.pools=e,this.registry=new se({listAgents:i(()=>this.listAgents(ee),"listAgents"),spawn:i((n,s,o)=>this.spawn(R(),te(),n,s,o),"spawn"),getSpawn:i(n=>this.getSpawn(n),"getSpawn"),findTaskAttempts:i(n=>this.transport.createHost(R()).findAttempts(n),"findTaskAttempts"),queuePosition:i(n=>this.pools.queuePosition(n),"queuePosition")})}transport;static{i(this,"AgentManager")}sessions=new Map;onComplete;onFollowUp;teardowns=new Map;handovers=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,s,o){let l=o.spawnId,{requestedHarness:a,...u}=o,d={...u,harness:It(n,a)},h={pi:e,ctx:r,type:n,prompt:s,options:d},c=this.pools.admitSpawn({harness:d.harness,modelKey:M(d.modelChoice)},{id:l,start:i(g=>this.startSession(l,h,g),"start")}),p;try{p=new ce({id:l,args:h,deps:{transport:this.transport,pools:this.pools,onRunEnded:i(g=>this.notifyComplete(g),"onRunEnded"),onFollowUpResult:i((g,m)=>this.notifyFollowUp(g,m),"onFollowUpResult")}})}catch(g){throw this.pools.release(l),g}if(this.sessions.set(l,p),d.signal?.aborted)return p.abort("user"),l;if(c.kind==="queue")return l;try{p.start(c.reservation)}catch(g){throw p.rollbackStart(),this.pools.release(l),this.sessions.delete(l),L().drop(l),g}return l}startSession(e,r,n){let s=this.sessions.get(e);if(!s||!s.isQueued())return!1;try{s.start(n)}catch(o){s.settleStartFailure(o)}return!0}async steer(e,r){if(this.handovers.has(e))return{kind:"refused",reason:"it is being handed over to another harness \u2014 wait for the handover to finish before steering it."};if(this.teardowns.has(e))return{kind:"refused",reason:"it 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 it \u2014 check the id from its spawn or completion result (a cleaned-up agent is gone for good)."}}isHandingOver(e){return this.handovers.has(e)}async handover(e,r){if(this.teardowns.has(e))return In("it is being cleaned up \u2014 wait for the cleanup report before handing it over.");if(this.handovers.has(e))return In("a handover is already in progress \u2014 wait for it to finish.");let n=this.sessions.get(e);if(!n)return{kind:"faulted",fault:{kind:"agent-unknown"}};let s=n.handover(r);this.handovers.set(e,s);try{return await s}finally{this.handovers.get(e)===s&&this.handovers.delete(e)}}getSpawn(e){return L().get(e)}assets(){let e=R();return Qt(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=ze){return L().list(e).sort((r,n)=>ye(n.lifecycle)-ye(r.lifecycle))}async abort(e,r){return await this.sessions.get(e)?.abort(r)??!1}notifyComplete(e){try{this.onComplete?.(e)}catch(r){Rn.warn("completion notification failed",{spawnId:e.id,detail:y(r)})}}notifyFollowUp(e,r){try{this.onFollowUp?.(e,r)}catch(n){Rn.warn("follow-up notification failed",{spawnId:e.id,detail:y(n)})}}recordRetention(e,r){let n=e.lifecycle;B(n)&&(n.worktreeRetentionReason=r)}dropSpawn(e){this.sessions.get(e.id)?.drop(),this.sessions.delete(e.id),Q(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(()=>{}),await this.handovers.get(e)?.catch(()=>{}),ne()?.dropNudge(e);let s=this.getSpawn(e)!==void 0,o=await Ot(this.assets()).cleanupAgent(e,{getSpawn:i(a=>this.getSpawn(a),"getSpawn"),dropSpawn:i(a=>this.dropSpawn(a),"dropSpawn")},n),l=this.getSpawn(e);if(l!==void 0){let a=jr(o);a!==void 0&&this.recordRetention(l,a)}return s&&o.outcome.kind==="torn-down"&&Q(I(e)),o}dispose(){this.pools.clearQueue();for(let e of this.sessions.values())e.settleForDispose();this.sessions.clear()}};var $r=200,ge=class{static{i(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 s=n.agentId,o=this.manager.getSpawn(s);return o.execution.spawnCtx=e,this.announceSpawn(e,o),r.runInBackground?this.backgroundAgentIds.add(s):await o.execution.promise,{agentId:s,spawn:o}}announceSpawn(e,r){if(!e.hasUI)return;let n=r.lifecycle;if(B(n))return;let s=n.phase==="queued"?"Queued":"Spawned";Ft(e.ui).succeeded(`${s} agent ${r.id} (${r.display.type})`)}async inFlightError(e,r){let n=this.manager.getSpawn(r.conflictingId);if(n)return new H({kind:"spawn",spawn:n},e);let s=await G().host.findAttempts(e),o=ie([],s);if(o.kind!=="none")return new H(o,e);let l={name:r.conflictingId};return new H({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,s]of r)this.emitFollowUp(n,s)},$r))}onAgentComplete(e){this.backgroundAgentIds.has(e.id)&&(Wr(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||!W())return;let n=R(),s=this.manager.getSpawn(e);if(!s)return;let o=Pe(s,{includeRunInfo:!0,includeStatus:!0}),l=`[Cowboy agent "${s.display.type}" ${s.id} reported again after settling]`;try{n.sendMessage({customType:"subagent-result",content:`${l}
31
31
 
32
- ${r}`,details:o,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let a=i.execution.spawnCtx;if(a)try{a.ui.notify(`${l} New report available`,"info")}catch{}}}emitIndividualNudge(e){if(this.disposed||!H())return;let r=b(),n=this.manager.getSpawn(e);if(!n)return;let i=Se(n,{includeRunInfo:!0,includeStatus:!0});try{r.sendMessage({customType:"subagent-result",content:`${xt(n)}
32
+ ${r}`,details:o,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let a=s.execution.spawnCtx;if(a)try{a.ui.notify(`${l} New report available`,"info")}catch{}}}emitIndividualNudge(e){if(this.disposed||!W())return;let r=R(),n=this.manager.getSpawn(e);if(!n)return;let s=Pe(n,{includeRunInfo:!0,includeStatus:!0});try{r.sendMessage({customType:"subagent-result",content:`${Et(n)}
33
33
 
34
- ${Rt(n)}`,details:i,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let o=n.execution.spawnCtx;if(o)try{o.ui.notify(`[Cowboy agent "${n.display.type}" ${X(n.lifecycle)}] Result available`,"info")}catch{}}}};function Ir(t){let e=t.lifecycle;return q(e)&&e.status==="stopped"&&e.stop.initiator==="user"}s(Ir,"stoppedByUser");import*as xn from"node:fs";import{pathToFileURL as Mr}from"node:url";import*as bn from"node:path";import{DefaultPackageManager as Tr,SettingsManager as Lr}from"@earendil-works/pi-coding-agent";import*as vn from"node:fs";import*as Sn from"node:path";import{z as pe}from"zod";var kn="pi-cowboy",Er="pi-cowboy-",Cr=pe.object({name:pe.string().startsWith(Er),[kn]:pe.object({plugin:pe.string().min(1)})});function Pn(t){let e;try{e=vn.readFileSync(Sn.join(t,"package.json"),"utf-8")}catch{return}let r;try{r=JSON.parse(e)}catch{return}let n=Cr.safeParse(r);if(n.success)return{name:n.data.name,entry:n.data[kn].plugin}}s(Pn,"readPluginManifest");function Fr(t){let e=new Map;for(let r of t){if(r.installedPath===void 0)continue;let n=Pn(r.installedPath);n!==void 0&&(e.has(n.name)||e.set(n.name,{name:n.name,source:r.source,root:r.installedPath,entry:bn.resolve(r.installedPath,n.entry)}))}return[...e.values()].sort((r,n)=>r.name.localeCompare(n.name))}s(Fr,"pluginsAmong");async function An(t){let e=new Tr({cwd:t,agentDir:E(),settingsManager:Lr.create(t,E())});return Fr(e.listConfiguredPackages())}s(An,"discoverPluginPackages");function Rn(t){let e=null,r=null,n=null;async function i(o,l,a){let d=n;d!==null&&(await d,n===d&&(n=null));let u=[],c=[],g=[],m;try{m=await An(l)}catch(f){a(`[cowboy] installed plugins could not be discovered and were skipped: ${y(f)}`,"warning"),m=[]}for(let f of m){let S=c.length;try{let k=await jr(f,o,l,t,v=>c.push(v));k!==void 0&&u.push(k),g.push(f.name)}catch(k){for(let v of c.splice(S).reverse())v();a(`[cowboy] plugin "${f.name}" (${f.source}) could not load and was skipped: ${y(k)}`,"warning")}}let p,h={loaded:g,dispose:s(()=>(p??=(async()=>{e===h&&(e=null);for(let f=u.pop();f!==void 0;f=u.pop())try{await f()}catch(S){a(`[cowboy] a plugin disposer failed: ${y(S)}`,"warning")}for(let f=c.pop();f!==void 0;f=c.pop())f()})(),n=p,p),"dispose")};return e=h,r=null,h}return s(i,"startLoad"),{load(o,l,a){return e!==null?Promise.resolve(e):(r??=i(o,l,a),r)}}}s(Rn,"createPluginLoader");function Dr(t){try{return`?v=${xn.statSync(t).mtimeMs}`}catch{return""}}s(Dr,"cacheBust");function Or(t,e,r,n){return{pi:t,cwd:e,registerHarness:s(i=>{let o=r.harnesses.register(i);return o&&n(()=>r.harnesses.unregister(i.id)),o},"registerHarness"),registerMultiplexer:s(i=>{let o=r.multiplexers.register(i);return o&&n(()=>r.multiplexers.unregister(i.id)),o},"registerMultiplexer")}}s(Or,"pluginApi");async function jr(t,e,r,n,i){let o=Or(e,r,n,i),a=(await import(`${Mr(t.entry).href}${Dr(t.entry)}`)).default;if(typeof a!="function")throw new Error(`entry module ${t.entry} has no default-export factory`);let d=await a(o);return typeof d=="function"?d:void 0}s(jr,"loadOne");function Hr(){let t=[],e=[];for(let r of A().ids()){let n=$r(r);n.status==="available"?t.push(r):n.notice!==void 0&&e.push(n.notice)}return{availability:He(t),notices:e}}s(Hr,"probeHarnessAvailability");function $r(t){try{return A().require(t).availability()}catch(e){return{status:"unavailable",notice:`[cowboy] the "${t}" harness could not answer for itself and is not offered: ${y(e)}`}}}s($r,"askAvailability");function In(){let t=Hr();return nt(t.availability),t}s(In,"startHarnessAvailabilityProbe");function En(t){let e=tt(),r=A();for(let n of r.runnable(e))try{r.require(n).prefetchModels(t)}catch{}}s(En,"prefetchHarnessModels");async function Cn(t,e){let r=et(),n=await Rn(r).load(t,e.cwd,(d,u)=>{e.hasUI&&e.ui.notify(d,u)}),i=P();r.harnesses.validateConfigs(i.harnessConfigLayers(),(d,u)=>i.reportHarnessConfigIssue(d,u)),Wr(e,r);let o=r.multiplexers.hosting();if(o.length===0)return{kind:"unhosted",plugins:n,reason:me};let l=r.multiplexers.runtime(t,P().multiplexer);if(!o.includes(l.multiplexer))return{kind:"unhosted",plugins:n,reason:me};ee(l);let a=In();if(e.hasUI)for(let d of a.notices)e.ui.notify(d,"warning");return En(t),{kind:"hosted",plugins:n,runtime:l}}s(Cn,"startSessionRuntime");function Wr(t,e){if(!t.hasUI)return;let r=P(),n=new Set(e.harnesses.ids()),i=r.configuredHarnessIds().filter(o=>!n.has(o)).map(o=>`harness "${o}"`);e.multiplexers.has(r.multiplexer)||i.push(`multiplexer "${r.multiplexer}"`),i.length!==0&&t.ui.notify(`[cowboy] nothing registered for ${i.join(", ")}; those settings are ignored and the launch falls back to the default.`,"warning")}s(Wr,"reportUnregisteredConfig");function _r(t){if(!he()){let e=new ue(new Ye(P().concurrency),wn(t));ye(e),P().setDeps({manager:e});let r=new ce(e);we(r),e.setOnComplete(n=>{r.onAgentComplete(n)}),e.setOnFollowUp((n,i)=>{r.onAgentFollowUp(n,i)})}}s(_r,"wireManagerAndCoordinator");async function Nr(t){let e=E(),r=L.join(e,"agents"),n=t.isProjectTrusted(),i=n?L.join(t.cwd,".agents","agents"):"",o=n?L.join(t.cwd,".pi","agents"):"";ht(r,o,i);let l=P().agent.disableDefaultAgents,a=await yt({disableDefaultAgents:l,notify:s((d,u)=>{t.ui.notify(d,u)},"notify")});ft(a,{disableDefaultAgents:l})}s(Nr,"scanAndRegisterAgents");async function qr(t){let e=E(),r=L.join(e,"orchestrators"),n=t.isProjectTrusted(),i=n?L.join(t.cwd,".agents","orchestrators"):"",o=n?L.join(t.cwd,".pi","orchestrators"):"";kt(r,o,i);let l=await Pt({notify:s((a,d)=>{t.ui.notify(a,d)},"notify")});St(l)}s(qr,"scanAndRegisterOrchestrators");async function Ur(t){ot(Ze());let e=t.isProjectTrusted()?L.join(t.cwd,".pi"):void 0;P().setProjectDir(e),P().reload()}s(Ur,"loadSessionConfig");async function Br(t){await Nr(t),await qr(t)}s(Br,"scanSessionTemplates");function Tn(t){t.on("tool_call",It);let e=null;t.on("session_start",async(r,n)=>{st(n),await Ur(n);let i=await Cn(t,n);if(e=i.plugins,i.kind==="unhosted"){ke(n.ui),n.hasUI&&H()&&n.ui.notify(i.reason,"warning");return}await Br(n),_r(i.runtime),await Ft(t),H()?Mt(n.ui):(ke(n.ui),n.hasUI&&n.ui.notify("Cowboy extension is disabled \u2014 its tools are not loaded. Run /cowboy enable to turn it back on.","info"))}),t.on("session_shutdown",async(r,n)=>{let i=he();if(i){let a=i.listAgents(V);a.length>0&&n.hasUI&&n.ui.notify(`${a.length} subagent pane(s) left running in their panes (tracking stopped for the previous session)`,"warning")}Z()?.dispose(),we(null),P().dispose(),i?.dispose(),ye(null),Et();let o=e;e=null;let l=U();await o?.dispose(),U()===l&&ee(null)}),process.on("exit",()=>{try{process.stderr.write("\x1B[?2026l\x1B[?25h\x1B[0m")}catch{}})}s(Tn,"setupEventListeners");var Ln="pi-cowboy needs a git repository: this directory is not inside one, so pi-cowboy stays inactive";function Fn(t,e){t.on("session_start",async(r,n)=>{n.hasUI&&n.ui.notify(e,"warning")})}s(Fn,"reportInactive");function Gr(t){if(at()!==void 0)return;let e=lt();if(e!==void 0){Fn(t,e);return}if(!dt(process.cwd())){Fn(t,Ln),Ot(t,Ln);return}it(t),Dt(t),jt(t),Tn(t)}s(Gr,"default");export{Gr as default};
34
+ ${Ct(n)}`,details:s,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let o=n.execution.spawnCtx;if(o)try{o.ui.notify(`[Cowboy agent "${n.display.type}" ${D(n.lifecycle)}] Result available`,"info")}catch{}}}};function Wr(t){let e=t.lifecycle;return B(e)&&e.status==="stopped"&&e.stop.initiator==="user"}i(Wr,"stoppedByUser");import*as Dn from"node:fs";import{pathToFileURL as Gr}from"node:url";import*as On from"node:path";import{DefaultPackageManager as _r,SettingsManager as Ur}from"@earendil-works/pi-coding-agent";import*as Cn from"node:fs";import*as Tn from"node:path";import{z as he}from"zod";var Ln="pi-cowboy",qr="pi-cowboy-",Nr=he.object({name:he.string().startsWith(qr),[Ln]:he.object({plugin:he.string().min(1)})});function Fn(t){let e;try{e=Cn.readFileSync(Tn.join(t,"package.json"),"utf-8")}catch{return}let r;try{r=JSON.parse(e)}catch{return}let n=Nr.safeParse(r);if(n.success)return{name:n.data.name,entry:n.data[Ln].plugin}}i(Fn,"readPluginManifest");function Br(t){let e=new Map;for(let r of t){if(r.installedPath===void 0)continue;let n=Fn(r.installedPath);n!==void 0&&(e.has(n.name)||e.set(n.name,{name:n.name,source:r.source,root:r.installedPath,entry:On.resolve(r.installedPath,n.entry)}))}return[...e.values()].sort((r,n)=>r.name.localeCompare(n.name))}i(Br,"pluginsAmong");async function Mn(t){let e=new _r({cwd:t,agentDir:E(),settingsManager:Ur.create(t,E())});return Br(e.listConfiguredPackages())}i(Mn,"discoverPluginPackages");function Hn(t){let e=null,r=null,n=null;async function s(o,l,a){let u=n;u!==null&&(await u,n===u&&(n=null));let d=[],h=[],c=[],p;try{p=await Mn(l)}catch(f){a(`[cowboy] installed plugins could not be discovered and were skipped: ${y(f)}`,"warning"),p=[]}for(let f of p){let w=h.length;try{let P=await zr(f,o,l,t,S=>h.push(S));P!==void 0&&d.push(P),c.push(f.name)}catch(P){for(let S of h.splice(w).reverse())S();a(`[cowboy] plugin "${f.name}" (${f.source}) could not load and was skipped: ${y(P)}`,"warning")}}let g,m={loaded:c,dispose:i(()=>(g??=(async()=>{e===m&&(e=null);for(let f=d.pop();f!==void 0;f=d.pop())try{await f()}catch(w){a(`[cowboy] a plugin disposer failed: ${y(w)}`,"warning")}for(let f=h.pop();f!==void 0;f=h.pop())f()})(),n=g,g),"dispose")};return e=m,r=null,m}return i(s,"startLoad"),{load(o,l,a){return e!==null?Promise.resolve(e):(r??=s(o,l,a),r)}}}i(Hn,"createPluginLoader");function Kr(t){try{return`?v=${Dn.statSync(t).mtimeMs}`}catch{return""}}i(Kr,"cacheBust");function Qr(t,e,r,n){return{pi:t,cwd:e,registerHarness:i(s=>{let o=r.harnesses.register(s);return o&&n(()=>r.harnesses.unregister(s.id)),o},"registerHarness"),registerMultiplexer:i(s=>{let o=r.multiplexers.register(s);return o&&n(()=>r.multiplexers.unregister(s.id)),o},"registerMultiplexer")}}i(Qr,"pluginApi");async function zr(t,e,r,n,s){let o=Qr(e,r,n,s),a=(await import(`${Gr(t.entry).href}${Kr(t.entry)}`)).default;if(typeof a!="function")throw new Error(`entry module ${t.entry} has no default-export factory`);let u=await a(o);return typeof u=="function"?u:void 0}i(zr,"loadOne");function Vr(){let t=[],e=[];for(let r of A().ids()){let n=Yr(r);n.status==="available"?t.push(r):n.notice!==void 0&&e.push(n.notice)}return{availability:We(t),notices:e}}i(Vr,"probeHarnessAvailability");function Yr(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)}`}}}i(Yr,"askAvailability");function jn(){let t=Vr();return ot(t.availability),t}i(jn,"startHarnessAvailabilityProbe");function $n(t){let e=it(),r=A();for(let n of r.runnable(e))try{r.require(n).prefetchModels(t)}catch{}}i($n,"prefetchHarnessModels");async function Wn(t,e){let r=st(),n=await Hn(r).load(t,e.cwd,(u,d)=>{e.hasUI&&e.ui.notify(u,d)}),s=b();r.harnesses.validateConfigs(s.harnessConfigLayers(),(u,d)=>s.reportHarnessConfigIssue(u,d)),Xr(e,r);let o=r.multiplexers.hosting();if(o.length===0)return{kind:"unhosted",plugins:n,reason:me};let l=r.multiplexers.runtime(t,b().multiplexer);if(!o.includes(l.multiplexer))return{kind:"unhosted",plugins:n,reason:me};re(l);let a=jn();if(e.hasUI)for(let u of a.notices)e.ui.notify(u,"warning");return $n(t),{kind:"hosted",plugins:n,runtime:l}}i(Wn,"startSessionRuntime");function Xr(t,e){if(!t.hasUI)return;let r=b(),n=new Set(e.harnesses.ids()),s=r.configuredHarnessIds().filter(o=>!n.has(o)).map(o=>`harness "${o}"`);e.multiplexers.has(r.multiplexer)||s.push(`multiplexer "${r.multiplexer}"`),s.length!==0&&t.ui.notify(`[cowboy] nothing registered for ${s.join(", ")}; those settings are ignored and the launch falls back to the default.`,"warning")}i(Xr,"reportUnregisteredConfig");function Jr(t){if(!we()){let e=new pe(new Ze(b().concurrency),En(t));ke(e),b().setDeps({manager:e});let r=new ge(e);Se(r),e.setOnComplete(n=>{r.onAgentComplete(n)}),e.setOnFollowUp((n,s)=>{r.onAgentFollowUp(n,s)})}}i(Jr,"wireManagerAndCoordinator");async function Zr(t){let e=E(),r=F.join(e,"agents"),n=t.isProjectTrusted(),s=n?F.join(t.cwd,".agents","agents"):"",o=n?F.join(t.cwd,".pi","agents"):"";kt(r,o,s);let l=b().agent.disableDefaultAgents,a=await St({disableDefaultAgents:l,notify:i((u,d)=>{t.ui.notify(u,d)},"notify")});wt(a,{disableDefaultAgents:l})}i(Zr,"scanAndRegisterAgents");async function es(t){let e=E(),r=F.join(e,"orchestrators"),n=t.isProjectTrusted(),s=n?F.join(t.cwd,".agents","orchestrators"):"",o=n?F.join(t.cwd,".pi","orchestrators"):"";xt(r,o,s);let l=await Rt({notify:i((a,u)=>{t.ui.notify(a,u)},"notify")});At(l)}i(es,"scanAndRegisterOrchestrators");async function ts(t){ut(rt());let e=t.isProjectTrusted()?F.join(t.cwd,".pi"):void 0;b().setProjectDir(e),b().reload()}i(ts,"loadSessionConfig");async function ns(t){await Zr(t),await es(t)}i(ns,"scanSessionTemplates");function qn(t){t.on("tool_call",Tt);let e=null;t.on("session_start",async(r,n)=>{dt(n),await ts(n);let s=await Wn(t,n);if(e=s.plugins,s.kind==="unhosted"){be(n.ui),n.hasUI&&W()&&n.ui.notify(s.reason,"warning");return}await ns(n),Jr(s.runtime),await Dt(t),W()?Ht(n.ui):(be(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 s=we();if(s){let a=s.listAgents(ee);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")}ne()?.dispose(),Se(null),b().dispose(),s?.dispose(),ke(null),Lt();let o=e;e=null;let l=G();await o?.dispose(),G()===l&&re(null)}),process.on("exit",()=>{try{process.stderr.write("\x1B[?2026l\x1B[?25h\x1B[0m")}catch{}})}i(qn,"setupEventListeners");var Nn="pi-cowboy needs a git repository: this directory is not inside one, so pi-cowboy stays inactive";function _n(t,e){t.on("session_start",async(r,n)=>{n.hasUI&&n.ui.notify(e,"warning")})}i(_n,"reportInactive");function rs(t){if(ct()!==void 0)return;let e=pt();if(e!==void 0){_n(t,e);return}if(!gt(process.cwd())){_n(t,Nn),$t(t,Nn);return}lt(t),jt(t),Wt(t),qn(t)}i(rs,"default");export{rs as default};
35
35
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { HerdrAgents } from "./agents.js";
3
+ export interface WaitForAgentGoneOptions {
4
+ timeoutMs?: number;
5
+ }
6
+ export declare class HerdrAgentExit {
7
+ private readonly agents;
8
+ constructor(agents: HerdrAgents);
9
+ waitForAgentGone(paneId: string, opts?: WaitForAgentGoneOptions): Promise<boolean>;
10
+ }
11
+ export declare function createHerdrAgentExit(pi: ExtensionAPI): HerdrAgentExit;
12
+ export declare function waitForAgentGone(pi: ExtensionAPI, paneId: string, opts?: WaitForAgentGoneOptions): Promise<boolean>;
@@ -32,7 +32,6 @@ export declare class HerdrAgents {
32
32
  findTaskAttempts(taskSlug: string): Promise<LiveAttempt[]>;
33
33
  sendKeys(target: string, keys: readonly string[]): Promise<void>;
34
34
  submitPrompt(target: string, text: string): Promise<void>;
35
- interruptAgent(name: string): Promise<void>;
36
35
  }
37
36
  export declare function startAgent(pi: ExtensionAPI, options: {
38
37
  name: string;
@@ -4,4 +4,4 @@ export * from "./panes.js";
4
4
  export * from "./agents.js";
5
5
  export * from "./worktrees.js";
6
6
  export * from "./herdr-client.js";
7
- export * from "./agent-stopper.js";
7
+ export * from "./agent-exit.js";
@@ -1,3 +1,3 @@
1
- import{a as M,b as y}from"./chunk-F526OOT6.js";import{d as g,g as R,j as P,t as H}from"./chunk-KMXT7XW7.js";import{b as S,o as D}from"./chunk-WL3QYM2F.js";import{Ba as x,Ka as _,ea as I,ia as T,r as p,s as b,t as E,xa as v,y as A}from"./chunk-CTBFJWEE.js";import{a as t,d as N}from"./chunk-254PTGN5.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=E,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
1
+ import{a as M,b as y}from"./chunk-277WT5MT.js";import{T as H,d as g,g as R,j as P}from"./chunk-S4BS2R6G.js";import{b as S,o as D}from"./chunk-MZROKRT4.js";import{Aa as v,Ea as x,Na as _,ha as I,la as T,r as p,s as b,t as E,y as A}from"./chunk-M42XWVYW.js";import{a as t,d as N}from"./chunk-J5TU3AFX.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=E,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
2
2
  `)}t(Y,"describeCreatedWorktree");async function J(e,r,o,a){if($.existsSync(a))return`Cannot create the worktree: ${a} already exists. Pick another name.`;if(await g(e,["rev-parse","--verify","--quiet",`refs/heads/${o}`],r)!==void 0)return`Cannot create the worktree: the branch "${o}" already exists. Pick another name.`}t(J,"describeCollision");async function pe(e,r){let o=new S(e),a=t((n,i)=>e.ui.notify(n,i),"notify"),s=await o.open(({theme:n,close:i})=>new y(L({prefill:r,notify:a,onDone:t(m=>i(m),"onDone"),onCancel:t(()=>i(),"onCancel")}),{title:"Worktree Name",theme:n,passthroughKeys:!0}));if(s===void 0)return;let k=T(),c=I();if(!await P(c,e.cwd)){a("Cannot create a worktree: this session is not inside a git repository.","error");return}let d;try{d=await R(c,e.cwd)}catch(n){a(`Cannot create a worktree: ${N(n)}`,"error");return}let G=await g(c,["status","--porcelain"],d)==="",u=k.agent.worktreeCheckoutType;if(!G){let n=await o.open(({theme:i,close:m})=>{let h=new X(p.map(l=>({value:l,label:l,description:q[l]})),p.length,D(i));return h.setSelectedIndex(p.indexOf(k.agent.worktreeCheckoutType)),h.onSelect=l=>m(b(l.value)),h.onCancel=()=>m(),new y(h,{title:"Worktree Checkout",theme:i,onCancel:t(()=>m(),"onCancel")})});if(n===void 0)return;u=n}let C=z.join(A(k.agent.worktreeRoot,d),s),w=await J(c,d,s,C);if(w!==void 0){a(w,"error");return}let f=_(e.ui);f.pending(`Creating worktree ${s}`);let W;try{W=await H(c,{repoCwd:d,path:C,branch:s,materialization:v(),dirtyCheckout:u,notify:a,host:x().host})}catch(n){f.failed("Worktree creation failed",n);return}f.succeeded(Y(W,u))}t(pe,"showWorktreeCommandMenu");export{pe as showWorktreeCommandMenu};
3
- //# sourceMappingURL=menu-worktree-command-SXLBWK4D.js.map
3
+ //# sourceMappingURL=menu-worktree-command-THJ3VSWU.js.map