pi-cowboy 0.22.2 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +19 -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 +7 -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-export.d.ts +32 -0
  10. package/dist/agents/handover-file.d.ts +14 -0
  11. package/dist/agents/handover-target.d.ts +16 -0
  12. package/dist/agents/handover.d.ts +73 -0
  13. package/dist/agents/harness/claude/session-export.d.ts +7 -0
  14. package/dist/agents/harness/claude/staging.d.ts +9 -1
  15. package/dist/agents/harness/codex-session-schema.d.ts +103 -0
  16. package/dist/agents/harness/codex-session.d.ts +17 -0
  17. package/dist/agents/harness/opencode/session-export.d.ts +39 -0
  18. package/dist/agents/harness/pi-compatible.d.ts +3 -1
  19. package/dist/agents/harness/pi-session.d.ts +12 -0
  20. package/dist/agents/harness/pi-store.d.ts +8 -0
  21. package/dist/agents/harness/pi.d.ts +2 -0
  22. package/dist/agents/harness/pig-store.d.ts +7 -0
  23. package/dist/agents/harness/stop-keys.d.ts +2 -0
  24. package/dist/agents/harness.d.ts +56 -0
  25. package/dist/agents/run-state.d.ts +1 -0
  26. package/dist/agents/schemas/handover.schema.d.ts +8 -0
  27. package/dist/agents/subagent-session.d.ts +13 -1
  28. package/dist/agents/tool-cleanup.d.ts +16 -2
  29. package/dist/agents/tool-execution.d.ts +21 -2
  30. package/dist/agents/tool-handover.d.ts +28 -0
  31. package/dist/agents/tool-merge.d.ts +18 -2
  32. package/dist/agents/tool-renderer.d.ts +21 -0
  33. package/dist/agents/tool-result.d.ts +9 -2
  34. package/dist/agents/tool-steer.d.ts +17 -2
  35. package/dist/{chunk-F526OOT6.js → chunk-67VN34QV.js} +2 -2
  36. package/dist/chunk-CAWIXE4E.js +14 -0
  37. package/dist/chunk-GYO352IF.js +47 -0
  38. package/dist/chunk-NF2BSEPU.js +26 -0
  39. package/dist/{chunk-WL3QYM2F.js → chunk-ROCBRG4A.js} +2 -2
  40. package/dist/chunk-XXNZAWMK.js +2 -0
  41. package/dist/config/config-store.d.ts +1 -0
  42. package/dist/config/layered-config.d.ts +2 -3
  43. package/dist/cowboy-tools.d.ts +13 -0
  44. package/dist/dev-mode.d.ts +1 -0
  45. package/dist/host-multiplexer.d.ts +1 -1
  46. package/dist/index.js +17 -17
  47. package/dist/infrastructure/herdr/agent-exit.d.ts +12 -0
  48. package/dist/infrastructure/herdr/agents.d.ts +0 -1
  49. package/dist/infrastructure/herdr/index.d.ts +1 -1
  50. package/dist/{menu-worktree-command-SXLBWK4D.js → menu-worktree-command-FGIFMYRD.js} +2 -2
  51. package/dist/menus-QMEWZXAL.js +9 -0
  52. package/dist/{model-picker-IIXU4GJP.js → model-picker-I2L5LYS7.js} +2 -2
  53. package/dist/models/model-precedence.d.ts +1 -0
  54. package/dist/models/model-request-types.d.ts +8 -2
  55. package/dist/plugin/index.d.ts +1 -1
  56. package/dist/plugin/index.js +1 -1
  57. package/dist/predicates.d.ts +1 -0
  58. package/dist/registration.d.ts +3 -8
  59. package/dist/spawn/sandbox.d.ts +32 -0
  60. package/dist/subagent/result-artifacts.d.ts +1 -0
  61. package/dist/subagent/supervisor.d.ts +2 -0
  62. package/dist/types.d.ts +11 -0
  63. package/dist/ui/action-report.d.ts +1 -0
  64. package/dist/ui/menu/menu-agent-handover.d.ts +12 -0
  65. package/dist/ui/menu/menu-agent-status.d.ts +1 -1
  66. package/package.json +3 -3
  67. package/dist/chunk-254PTGN5.js +0 -2
  68. package/dist/chunk-CTBFJWEE.js +0 -10
  69. package/dist/chunk-KMXT7XW7.js +0 -15
  70. package/dist/chunk-PDV4AFO7.js +0 -24
  71. package/dist/infrastructure/herdr/agent-stopper.d.ts +0 -14
  72. package/dist/menus-Q3TEDIPV.js +0 -9
@@ -0,0 +1 @@
1
+ export declare const DEV_MODE: boolean;
@@ -3,4 +3,4 @@ export declare const HOST_MULTIPLEXERS: readonly ["herdr"];
3
3
  export type HostMultiplexer = (typeof HOST_MULTIPLEXERS)[number];
4
4
  export declare function multiplexerHosts(multiplexer: HostMultiplexer): boolean;
5
5
  export declare function getHostMultiplexer(): HostMultiplexer | undefined;
6
- export declare const NO_HOST_REASON = "pi-cowboy launches agents in panes, so it runs only inside a multiplexer it can detect. None hosting this process is registered \u2014 run pi inside herdr, or install a plugin multiplexer for the multiplexer you run pi inside.";
6
+ export declare const NO_HOST_REASON = "Warning: pi-cowboy is disabled. Run pi inside herdr (or a compatible multiplexer plugin you have installed)";
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 ke,b as Et,c as Ct,d as Tt,j as Lt,k as q,o as Dt,r as jt,u as $t,v as Se,w as Wt,x as qt,y as Nt}from"./chunk-CAWIXE4E.js";import{E as At,F as xt,G as Rt,O as It,Q as Ot,R as Ht,S as Mt,a as pt,f as gt,g as K,h as ht,m as ft,n as mt,o as yt,q as vt,r as wt,s as kt,t as St,v as Pt,y as bt}from"./chunk-NF2BSEPU.js";import{$ as Xe,A as Ne,Aa as ot,Ba as at,E as X,F as U,Fa as G,G as Qe,Ha as lt,I as he,Ia as dt,J as T,Ja as ve,Ka as we,La as te,Ma as ut,Na as ct,O as J,Oa as Ft,Q as ze,R as Ve,S as B,T as L,U as Ye,V as fe,a as E,aa as Je,c as Oe,ca as Ze,d as I,da as et,e as He,ea as me,f as Me,fa as tt,g as De,ga as nt,ha as rt,ia as R,j as je,ja as Z,la as ye,ma as b,pa as F,sa as ee,u as $e,w as We,wa as A,y as qe,ya as st,z as Y,za as it}from"./chunk-GYO352IF.js";import{a as i,b as _e,d as y,h as M,i as Ue,r as Be,s as Ge,x as Ke}from"./chunk-XXNZAWMK.js";import*as O from"node:path";function re(t,e){let r=t.at(0);if(r)return{kind:"spawn",spawn:r};let n=e.at(0);return n?{kind:"multiplexer",attempt:n}:{kind:"none"}}i(re,"findTaskDedup");var D=class extends Error{static{i(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",s=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?L(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${s} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},ne=class{constructor(e){this.deps=e}deps;static{i(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let s=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,s);try{return await s}finally{this.admissionBySlug.get(r)===s&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let p=this.deps.listAgents().filter(g=>g.display.taskSlug===e.taskSlug&&Ve(g.lifecycle.phase)),c=re(p,await this.deps.findTaskAttempts(e.taskSlug));if(c.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:c.kind==="spawn"?c.spawn.id:c.attempt.name}}let{type:r,prompt:n,runInBackground:s,signal:o,...l}=e,a={...l,isBackground:s,signal:o},d=this.deps.spawn(r,n,a);return this.deps.getSpawn(d)?.lifecycle.phase==="queued"?{status:"queued",agentId:d,queuePosition:this.deps.queuePosition(d)}:{status:"admitted",agentId:d}}};import _t from"node:fs";var se=class{constructor(e){this.resultFile=e}resultFile;static{i(this,"FileDeliverable")}async readDeliverable(){try{let e=_t.statSync(this.resultFile).mtimeMs,r=_t.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import Ut from"node:fs";import*as Bt from"node:path";function Q(t){try{Ut.rmSync(Bt.dirname(t),{recursive:!0,force:!0})}catch{}}i(Q,"removeResultArtifacts");function Gt(t){try{Ut.rmSync(t,{force:!0})}catch{}}i(Gt,"removeResultFile");import*as N from"node:fs";import*as ie from"node:path";var Yn=T("assets");async function Kt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}i(Kt,"probeList");function Xn(t,e,r){let n=r(e);return t?.find(s=>r(s.path)===n)}i(Xn,"matchWorktree");function zt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}i(zt,"paneOf");function Qt(t,e,r){let n=r(e),s=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return s===void 0?void 0:zt(s)}i(Qt,"paneInWorktree");function Jn(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:zt(r)}i(Jn,"paneInWorkspace");function Zn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}i(e,"root");async function r(a,d){let u=await e(),p=[],c=new Set,g=i(h=>{let m=t.canonicalizePath(h.path);c.has(m)||(c.add(m),p.push(h))},"push");for(let h of d??[]){let m=ie.basename(h.path);Y(m,a)&&(u!==void 0&&!Ne(h.path,u)||g({path:h.path,branch:h.branch!==void 0&&Y(h.branch,a)?h.branch:m,workspaceId:h.workspaceId}))}if(p.length>0||u===void 0)return p;for(let h of await t.listRootEntries(u))Y(h,a)&&g({path:ie.join(u,h),branch:h});return p}i(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}i(n,"candidateSummary");async function s(a,d,u,p){let c=d.execution.host,g=d.display.worktree,h=g?.kind==="owned",m=c?{paneId:c.paneId,tabId:c.tabId,workspaceId:c.workspaceId}:null,f="tracked",w=g?.kind==="owned"?g.path:void 0,P=c?.workspaceId;if(w!==void 0){let x=Xn(u,w,t.canonicalizePath);x!==void 0&&(P=x.workspaceId)}let S=w===void 0?m:Qt(p,w,t.canonicalizePath)??m,k=w===void 0?null:{path:w,workspaceId:P,repoCwd:await t.resolveRepoCwd(w)};return{kind:"located",source:f,id:a,branch:g?.branch??We(d.display.taskSlug??$e(d.display.type),d.id),worktreeManaged:h||k!==null,paneCreated:c?.paneCreated===!0,worktree:k,pane:S}}i(s,"locateTracked");async function o(a,d,u){let p=await r(a,d);if(p.length===0)return{kind:"not-found",id:a};if(p.length>1)return{kind:"ambiguous",id:a,candidates:p.map(n)};let c=p[0],g=Qt(u,c.path,t.canonicalizePath)??Jn(u,c.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:c.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:c.path,workspaceId:c.workspaceId,repoCwd:await t.resolveRepoCwd(c.path)},pane:g}}i(o,"locateDiscovered");async function l(a,d){let u=await Kt(t.listWorktrees),p=await Kt(t.listPlacements),c=u.ok?u.entries:void 0,g=p.ok?p.entries:void 0;return d===void 0?o(a,c,g):s(a,d,c,g)}return i(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:i(a=>t.readPane(a.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}i(Zn,"createAgentAssets");function Vt(t,e,r){return Zn({multiplexer:r.multiplexer,canonicalizePath:i(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:i(n=>{let s=I(n);return{path:s,present:N.existsSync(s)}},"deliverable"),listWorktrees:i(()=>r.listWorktrees(),"listWorktrees"),listPlacements:i(()=>r.listPlacements(),"listPlacements"),readPane:i(n=>r.observePane(n),"readPane"),worktreeRoot:i(async()=>{let n=Z().cwd;if(!n)return;let s=await K(t,n).catch(()=>{});return s===void 0?void 0:qe(b().agent.worktreeRoot,s)},"worktreeRoot"),listRootEntries:i(async n=>{try{return await N.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:i(async n=>{try{return await K(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:i(n=>mt(t,n),"isWorktreeDirty"),worktreeExists:i(async n=>N.existsSync(n),"worktreeExists"),removeWorktree:i(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(n,s)=>(await ht(t,s,n),!N.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>ft(t,n,s=>e.isAttached(s,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:i(async n=>{await e.release(n,"placement")},"closePane"),teardownEnvironment:i(async({subagentId:n,runs:s})=>{let o=A();for(let l of s)try{await o.get(l.harness)?.teardown({pi:t,paneId:l.paneId,cwd:l.cwd,subagentId:n})}catch(a){Yn.warn("harness teardown failed during environment teardown",{subagentId:n,harness:l.harness,error:y(a)})}},"teardownEnvironment")})}i(Vt,"createMultiplexerAgentAssets");var C=T("supervisor"),er=2e3;function tr(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}i(tr,"deferred");var oe=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??er,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp,this.stopProcess=n.stopProcess??((s,o)=>e.waitUntilGone(s,{timeoutMs:o}))}host;deliverable;static{i(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=tr();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,r){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:r};try{await this.host.start(r,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(n){throw this.isWatching()&&(this.phase={kind:"idle"}),n}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},C.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),C.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{C.error("poll loop failed",{errorMessage:y(r)})}),this.settlement.promise}async stop(e){let r=this.phase;if(r.kind!=="watching"||this.outcome!==null)return!1;let{ref:n}=r,s=await this.stopProcess(n,e).catch(o=>(C.debug("stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:s,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),s}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let r=this.phase;r.kind==="watching"&&(C.debug(e,{paneId:r.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,C.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let r=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);r.unref(),this.wakeLoop=()=>{clearTimeout(r),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!nr(this.held,e)){this.held=e,C.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return C.debug("readDeliverable failed",{errorMessage:y(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function nr(t,e){return t.content===e.content&&t.mtime===e.mtime}i(nr,"sameReport");function ae(t){let e=t.transport.createDeliverable(t.resultFile);return new oe(t.host,e,t.supervisorOptions)}i(ae,"createPaneSupervisor");function Yt(t,e){t.host=e}i(Yt,"placeExecution");function Xt(t,e){t.harness=e}i(Xt,"engageExecution");function Jt(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}i(Jt,"endExecutionRun");import Ae from"node:fs";import $ from"node:path";import{SettingsManager as Pr}from"@earendil-works/pi-coding-agent";import gr from"node:fs";import{loadProjectContextFiles as hr}from"@earendil-works/pi-coding-agent";function Zt(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
2
+ `):""}i(Zt,"buildOrchestrationGuidance");import{formatSkillsForPrompt as rr}from"@earendil-works/pi-coding-agent";function sr(t){let e=t;return e=e.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g,`
3
3
  `),e=e.replace(/\n?(?:The following skills provide[\s\S]*?)?<\s*available_skills\s*>[\s\S]*?<\/\s*available_skills\s*>\n?/g,`
4
4
  `),e=e.replace(/\n?Current date:.*\n?/g,`
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(sr,"stripScaffolding");async function Pe(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,d="";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=rr(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>`);d=`
10
10
 
11
11
  ${["The following skills provide specialized instructions for specific tasks.","Use the read tool to load a skill's file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>",...f,"</available_skills>"].join(`
12
12
  `)}`}let u=`
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>`,p="";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>"),p=`
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=ir(t),g=s==="inherit"?n?.parentSystemPrompt:s==="custom"?n?.customSystemPrompt:void 0,h=g&&sr(g);return{prefix:`${h?`${h}
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}${p}`,identity:`${c}
21
+ ${u}`,skills:d}}i(Pe,"buildAgentPrompt");function ir(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(ir,"buildActiveAgentTag");function j(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}i(j,"escapeXml");import{existsSync as or,readFileSync as ar,realpathSync as lr}from"node:fs";import{homedir as be}from"node:os";import{join as z,resolve as _}from"node:path";import{loadSkills as dr,loadSkillsFromDir as en}from"@earendil-works/pi-coding-agent";function tn(t){let e=_(t),r=ur(e,en),n=en({dir:z(be(),".agents","skills"),source:"agents"}),s=nn(n.skills,z(be(),".agents","skills")),o=dr({cwd:e,agentDir:z(be(),".pi","agent"),skillPaths:[],includeDefaults:!0}),l=new Set,a=new Set,d=[];for(let u of[...r,...s,...o.skills]){let p=pr(u.filePath);a.has(p)||l.has(u.name)||(l.add(u.name),a.add(p),d.push(u))}return d}i(tn,"loadAllSkills");function ur(t,e){let r=cr(t),n=[],s=t;for(;;){let o=z(s,".agents","skills"),l=e({dir:o,source:"agents"});if(n.push(...nn(l.skills,o)),s===r)break;let a=_(s,"..");if(a===s)break;s=a}return n}i(ur,"loadAncestorAgentsSkills");function nn(t,e){let r=_(e);return t.filter(n=>_(n.filePath,"..")!==r)}i(nn,"filterRootMdFiles");function cr(t){let e=_(t);for(;;){if(or(z(e,".git")))return e;let r=_(e,"..");if(r===e)return e;e=r}}i(cr,"findGitRoot");function pr(t){try{return lr(t)}catch{return t}}i(pr,"canonicalizePath");async function rn(t,e){let r=tn(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:ar(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(rn,"inlineSkills");async function sn(t,e){let r=tn(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(sn,"loadSkillMeta");async function on(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(on,"execGit");async function fr(t,e){let n=await on(t,["rev-parse","--is-inside-work-tree"],e)==="true",s=n?await on(t,["branch","--show-current"],e):null;return{isGitRepo:n,branch:s,platform:process.platform}}i(fr,"detectEnv");async function mr(t,e,r,n,s,o){let l=nt(),a=n?.includeContextFiles??o,d={};if(s==="inherit")try{d.parentSystemPrompt=t.getSystemPrompt()}catch(u){r(`Failed to get parent system prompt: ${y(u)}. Falling back to replace mode.`)}if(s==="custom")try{let u=gr.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=hr({cwd:e,agentDir:E()})}catch{}return d}i(mr,"resolveSystemPromptSources");async function yr(t,e,r,n,s,o,l){let a={...l},d=e?.inlinedSkills??[];if(d.length>0&&(a.inlinedSkills=await rn(d,n)),Array.isArray(r.skills)&&(a.skillMetas=await sn(r.skills,n)),e)return await Pe(e,n,s,a,o);let u=vt.get("general-purpose");if(!u)throw new Error(`No fallback config available for unknown type "${t}"`);return await Pe({...u,name:t},n,s,a,o)}i(yr,"buildPrompt");function vr(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(vr,"joinPromptSections");function wr(t,e){return t!==null&&t!==""?t:e}i(wr,"branchName");function an(t,e,r,n){let s=t&&e?wr(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(an,"buildWorktreeBranchSection");function kr(){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(kr,"buildSteeringInstructions");function Sr(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(Sr,"buildResultInstruction");async function ln(t){let{pi:e,ctx:r,cwd:n,notify:s}=t,o=await fr(e,n),l=await mr(r,n,s,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),a=await yr(t.type,t.agentConfig,t.config,n,o,t.globalSystemPromptMode,l);return vr([a.prefix,a.identity,a.skills,an(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),kr(),Sr(t.resultFile),Zt(t.agentGuidance)])}i(ln,"buildSubagentSystemPrompt");function dn(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(dn,"stageLaunchEnv");function br(t,e){let r=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||r.length>0?{kind:"none"}:{kind:"default"}}i(br,"resolveSkillMode");function Ar(t,e,r){let n=new Map,s=i((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=un(l);a&&s(a,l)}for(let o of e.extensionPaths){let l=un(o);l&&s(l,o)}return t.map(o=>{if(xr(o)||Rr(o,r))return o;let l=Ir(o),a=n.get(l.toLowerCase());if(a===null)throw new Error(`Extension entry "${o}" is ambiguous in pi settings; more than one source matches its name. The agent did not start.`);if(a===void 0)throw new Error(`Extension entry "${o}" is not in the pi settings and is not an npm:, git:, or path source. The agent did not start.`);return a})}i(Ar,"resolveExtensionSources");function xr(t){return t.startsWith("npm:")||t.startsWith("git:")}i(xr,"isPiExtensionSource");function Rr(t,e){return $.isAbsolute(t)?Ae.existsSync(t):Ae.existsSync($.resolve(e,t))}i(Rr,"isExistingPath");function Ir(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}i(Ir,"extensionEntryName");function un(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(un,"extensionSourceName");function cn(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}i(cn,"notifyLaunchConfigurationError");function Er(t){let e=t,r=e.sessionFile??e.sessionManager?.getSessionFile?.();if(r)return r}i(Er,"resolveParentSessionFile");function pn(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(pn,"resolveToolCliEntries");function Cr(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(Cr,"buildLaunchRequest");function Tr(t,e){return A().require(t).buildArgs(e)}i(Tr,"buildHarnessArgs");function Lr(t,e,r,n,s,o){let l=me(t,e),a=Or(r,s,o);if(l===void 0)return a;let d={};for(let[u,p]of Object.entries(l)){if(!n.includes(u)){d[u]=p;continue}s(`Ignoring environment variable ${u} for ${o}: it is reserved by the ${o} harness and cannot be overridden`)}return me(tt(d),a)}i(Lr,"resolveLaunchEnv");var Fr={name:"not a valid environment variable name",reserved:"reserved","not-string":"not a string",control:"carrying a control character"};function Or(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 ${Fr[o]} and cannot be carried`),"report")});return Object.keys(n).length===0?void 0:n}i(Or,"inheritedEnvOverrides");function Hr(t,e){return[...t===void 0?[]:Ge[t],...e===void 0?[]:Be(e)]}i(Hr,"familyReservations");async function gn(t,e,r,n,s){let o=b(),l=s.cwd??e.cwd,a=bt(r,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),d=Pt(r),u=s.harness,p=br(a.skills,d),c=[],g=i(v=>{c.push(v)},"bufferNotify"),h={kind:"default"};if(a.extensions===!1)h={kind:"none"};else if(Array.isArray(a.extensions))if(a.extensions.length===0)h={kind:"none"};else try{let v=Pr.create(l,E(),{projectTrusted:s.projectTrusted!==!1});h={kind:"paths",paths:Ar(a.extensions,{packages:v.getPackages(),extensionPaths:v.getExtensionPaths()},l)}}catch(v){let ge=v instanceof Error?v.message:String(v);cn(e,ge)}let m=Qe(u),f={kind:"default"};try{let v=m===void 0?void 0:d?.toolsByFamily?.[m];v?.tools===!1?f={kind:"none"}:Array.isArray(v?.tools)?f={kind:"include",names:pn(v.tools,"tools")}:v?.excludeTools?.length&&(f={kind:"exclude",names:pn(v.excludeTools,"excludeTools")})}catch(v){let ge=v instanceof Error?v.message:String(v);cn(e,ge)}let w=A().get(u),P=Lr(o.harnessEnv(u),m===void 0?void 0:d?.envByFamily?.[m],w?.inheritedEnv?.(),Hr(m,w),g,u),S=s.agentId??"unknown",k=Oe(S);X(k);let x=I(S),H=He(S),Ce=De(S),Gn=dn(Me(S),P),Te=await ln({pi:t,ctx:e,type:r,agentConfig:d,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:g});try{U(H,Te)}catch(v){throw new Error(`cannot write the system prompt file ${H}: ${y(v)}. The agent did not start.`,{cause:v})}if(!Ae.existsSync(H))throw new Error(`the system prompt file is missing after the write: ${H}. The agent did not start.`);U(Ce,n);let Le=s.fork?Er(e):void 0;s.fork&&Le===void 0&&g("Fork session is enabled, but no parent session file is available; launching without --fork");let Kn={subagentId:S,systemPromptFile:H,taskFile:Ce,resultFile:x,modelKey:M(s.modelChoice)??null,thinking:s.modelChoice?.thinking??null,toolSelection:f,envFile:Gn},Qn={forkSessionFile:Le??null,skills:p,extensions:h,projectTrusted:s.projectTrusted!==!1},zn={projectTrusted:s.projectTrusted!==!1},Fe=Cr(u,Kn,Qn,zn),Vn=Tr(u,Fe);for(let v of c)e.ui.notify(`[cowboy] ${v}`,"warning");return{name:S,cwd:l,systemPrompt:Te,piArgs:Vn,launch:Fe,harness:u}}i(gn,"buildLaunchPlan");var xe="Agent manager disposed before the queued agent could start.";function fn(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}i(fn,"createRun");function mn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(mn,"startRun");function yn(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(yn,"activateRun");function vn(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(vn,"abortQueuedRun");function wn(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(wn,"failStart");function le(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(le,"enterSettling");function kn(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(kn,"finishSettling");function Sn(t,e){return t.shell!=="held"||t.process.kind!=="settled"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(Sn,"handoverRun");function Pn(t,e){return t.shell!=="held"||t.process.kind!=="settling"&&t.process.kind!=="settled"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(Pn,"reviveRun");function bn(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}}i(bn,"disposeQueuedRun");function An(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}i(An,"disposeLiveRun");function Re(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:Ie(t,e)}}i(Re,"dropRun");function hn(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(hn,"settledStartedOutcome");function Mr(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(Mr,"settledNeverStartedOutcome");function Dr(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 hn(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?hn(t.startedAt,t.terminal,t.completedAt,e):Mr(t.queuedAt,t.terminal,t.completedAt,e)}}i(Dr,"projectProcess");function Ie(t,e){return t.shell==="dropped"?t.lifecycle:Dr(t.process,e)}i(Ie,"projectLifecycle");import*as xn from"node:fs";import*as Rn from"node:path";function In(t){let{spawn:e,hostRef:r,transport:n}=t,s=jr(e),o=Rn.dirname(s.resultFile);X(o),xn.rmSync(s.resultFile,{force:!0});let l=ae({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(In,"reviveSettledRun");function jr(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??I(t.id)}}i(jr,"resumeLaunch");var V=T("session");function $r(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($r,"buildAgentSpawn");var Ee=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 W(t){return{kind:"faulted",fault:t}}i(W,"faulted");var de=class{static{i(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=$r(r,this.gate.promise),this.stableSpawn.id=e;let s=this.stableSpawn.lifecycle;this.run=fn(s.phase==="queued"?s.queuedAt:Date.now()),F().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(mn(this.run,Date.now())),this.launch())}rollbackStart(){this.commit(Re(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(wn(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();In({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(Pn(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(vn(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(le(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}handoverSource(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settled")return W({kind:"agent-not-settled",status:L(this.spawn.lifecycle)});let r=this.spawn.execution.harness,n=this.spawn.execution.host;return r===void 0||n===void 0||!e.process.started?W({kind:"never-started"}):{kind:"ready",from:r,ref:n,cwd:this.args.options.worktree?.path??this.args.ctx.cwd,settled:e,startedAt:e.process.startedAt}}async exportSettledSession(e){return await Xe(A(),e.from,{pi:this.args.pi,subagentId:this.id,paneId:e.ref.paneId,cwd:e.cwd},{maxExcludedRatio:b().agent.handoverMaxExcludedRatio})}handoverTask(e,r,n){return Je({taskSlug:this.spawn.display.taskSlug,sourceName:A().displayName(e.from),previous:this.spawn.execution.history.map(({harness:s,sessionId:o})=>({harness:s,sessionId:o})),current:{harness:e.from,sessionId:r},session:n})}async handover(e){let r=this.handoverSource();if(r.kind==="faulted")return r;let{from:n,ref:s,cwd:o,settled:l}=r,a=await this.exportSettledSession(r);if(a.kind==="faulted")return a;if(this.run!==l)return W({kind:"agent-not-settled",status:L(this.spawn.lifecycle)});let d;try{d=await this.stopHarnessProcess(s,12e3)}catch(p){return W({kind:"stop-failed",detail:y(p)})}if(!d)return W({kind:"stop-failed",detail:"the source process did not confirm it was gone"});this.supervisor?.detach(),this.supervisor=void 0,Gt(this.resultFilePath());let u=this.handoverTask(r,a.sessionId,a.session);if(Jt(this.spawn.execution,{harness:n,host:s,cwd:o,sessionId:a.sessionId,startedAt:r.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(Sn(this.run,Date.now())),this.bindParentSignal(),await this.launch({kind:"handover"}),!this.isActive()){let p=this.spawn.lifecycle;return W({kind:"launch-failed",detail:p.phase==="settled"&&p.status==="error"?p.error:"the next run did not start"})}return{kind:"handed-over",from:n,to:e.harness,...a.loss===void 0?{}:{loss:a.loss}}}async exportHandover(){let e=this.handoverSource();if(e.kind==="faulted")return e;let r=await this.exportSettledSession(e);return r.kind==="faulted"?r:this.run!==e.settled?W({kind:"agent-not-settled",status:L(this.spawn.lifecycle)}):Dt({worktree:this.spawn.display.worktree?.branch??`main-${this.spawn.id}`,harness:e.from,sessionId:r.sessionId,text:this.handoverTask(e,r.sessionId,r.session),...r.loss===void 0?{}:{loss:r.loss}})}drop(){this.commit(Re(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,Q(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit(bn(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(An(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:d,type:u,prompt:p,options:c}=this.args,g=e.kind==="spawn"?c.hostRef:void 0;if(e.kind==="spawn"&&!g&&c.worktree?.kind==="owned"){let k;try{k=await Mt({pi:a,host:o,parentCwd:d.cwd,spawnId:this.spawn.id,agentType:u,taskSlug:c.taskSlug,worktreeRoot:b().agent.worktreeRoot,materialization:at(),notify:i((x,H)=>d.ui.notify(x,H),"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,g=k.kind==="owned"?k.hostRef:void 0}let h=Ht(c.worktree===void 0?{kind:"parent-cwd",type:u,taskSlug:c.taskSlug,id:this.id}:{kind:"checkout",branch:c.worktree.branch}),m=await gn(a,d,u,p,{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(!g){let k=c.worktree;g=await o.hostAt({unit:"pane",cwd:m.cwd,label:c.taskSlug??u,name:h,...k===void 0?{}:{checkout:{path:k.path,repoCwd:await K(a,k.path),branch:k.branch}}})}if(r={kind:"held",host:o,ref:g},!this.isLaunching())return;Yt(this.spawn.execution,g),Xt(this.spawn.execution,m.harness),await P.prepare({pi:a,pane:l,paneId:g.paneId,cwd:m.cwd,launch:m.launch,config:w.config(m.harness)});let S=ae({host:o,resultFile:f.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=S,await S.start({name:h,cwd:m.cwd,piArgs:m.piArgs,agentMultiplexerKind:P.agentMultiplexerKind,taskSlug:c.taskSlug},g),r={kind:"committed"},!this.isLaunching())return;this.commit(yn(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(le(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(le(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(kn(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 Tn(t){return{createHost:i(()=>t.host,"createHost"),createPane:i(()=>t.pane,"createPane"),createPlacements:i(()=>t.placements,"createPlacements"),createDeliverable:i(e=>new se(e),"createDeliverable")}}i(Tn,"createAgentManagerTransport");var En=T("manager");function Cn(t){return{kind:"faulted",fault:{kind:"request-refused",detail:t}}}i(Cn,"handoverRefused");function Wr(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(Wr,"retentionForReport");var ue=class{constructor(e,r){this.transport=r;this.pools=e,this.registry=new ne({listAgents:i(()=>this.listAgents(J),"listAgents"),spawn:i((n,s,o)=>this.spawn(R(),Z(),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 F().mint()}spawn(e,r,n,s,o){let l=o.spawnId,{requestedHarness:a,...d}=o,u={...d,harness:It(n,a)},p={pi:e,ctx:r,type:n,prompt:s,options:u},c=this.pools.admitSpawn({harness:u.harness,modelKey:M(u.modelChoice)},{id:l,start:i(h=>this.startSession(l,p,h),"start")}),g;try{g=new de({id:l,args:p,deps:{transport:this.transport,pools:this.pools,onRunEnded:i(h=>this.notifyComplete(h),"onRunEnded"),onFollowUpResult:i((h,m)=>this.notifyFollowUp(h,m),"onFollowUpResult")}})}catch(h){throw this.pools.release(l),h}if(this.sessions.set(l,g),u.signal?.aborted)return g.abort("user"),l;if(c.kind==="queue")return l;try{g.start(c.reservation)}catch(h){throw g.rollbackStart(),this.pools.release(l),this.sessions.delete(l),F().drop(l),h}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 Cn("it is being cleaned up \u2014 wait for the cleanup report before handing it over.");if(this.handovers.has(e))return Cn("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)}}async exportHandover(e){if(this.handovers.has(e))return{kind:"faulted",fault:{kind:"handover-in-progress",detail:"a handover is already in progress \u2014 wait for it to finish before exporting it."}};let r=this.sessions.get(e);return r?r.exportHandover():{kind:"faulted",fault:{kind:"agent-unknown"}}}getSpawn(e){return F().get(e)}assets(){let e=R();return Vt(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=ze){return F().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){En.warn("completion notification failed",{spawnId:e.id,detail:y(r)})}}notifyFollowUp(e,r){try{this.onFollowUp?.(e,r)}catch(n){En.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)),F().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(()=>{}),ee()?.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=Wr(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 qr=200,ce=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 D({kind:"spawn",spawn:n},e);let s=await G().host.findAttempts(e),o=re([],s);if(o.kind!=="none")return new D(o,e);let l={name:r.conflictingId};return new D({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)},qr))}onAgentComplete(e){this.backgroundAgentIds.has(e.id)&&(Nr(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||!q())return;let n=R(),s=this.manager.getSpawn(e);if(!s)return;let o=ke(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||!q())return;let r=R(),n=this.manager.getSpawn(e);if(!n)return;let s=ke(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}" ${L(n.lifecycle)}] Result available`,"info")}catch{}}}};function Nr(t){let e=t.lifecycle;return B(e)&&e.status==="stopped"&&e.stop.initiator==="user"}i(Nr,"stoppedByUser");import*as jn from"node:fs";import{pathToFileURL as Qr}from"node:url";import*as Mn from"node:path";import{DefaultPackageManager as Br,SettingsManager as Gr}from"@earendil-works/pi-coding-agent";import*as Ln from"node:fs";import*as Fn from"node:path";import{z as pe}from"zod";var On="pi-cowboy",_r="pi-cowboy-",Ur=pe.object({name:pe.string().startsWith(_r),[On]:pe.object({plugin:pe.string().min(1)})});function Hn(t){let e;try{e=Ln.readFileSync(Fn.join(t,"package.json"),"utf-8")}catch{return}let r;try{r=JSON.parse(e)}catch{return}let n=Ur.safeParse(r);if(n.success)return{name:n.data.name,entry:n.data[On].plugin}}i(Hn,"readPluginManifest");function Kr(t){let e=new Map;for(let r of t){if(r.installedPath===void 0)continue;let n=Hn(r.installedPath);n!==void 0&&(e.has(n.name)||e.set(n.name,{name:n.name,source:r.source,root:r.installedPath,entry:Mn.resolve(r.installedPath,n.entry)}))}return[...e.values()].sort((r,n)=>r.name.localeCompare(n.name))}i(Kr,"pluginsAmong");async function Dn(t){let e=new Br({cwd:t,agentDir:E(),settingsManager:Gr.create(t,E())});return Kr(e.listConfiguredPackages())}i(Dn,"discoverPluginPackages");function $n(t){let e=null,r=null,n=null;async function s(o,l,a){let d=n;d!==null&&(await d,n===d&&(n=null));let u=[],p=[],c=[],g;try{g=await Dn(l)}catch(f){a(`[cowboy] installed plugins could not be discovered and were skipped: ${y(f)}`,"warning"),g=[]}for(let f of g){let w=p.length;try{let P=await Yr(f,o,l,t,S=>p.push(S));P!==void 0&&u.push(P),c.push(f.name)}catch(P){for(let S of p.splice(w).reverse())S();a(`[cowboy] plugin "${f.name}" (${f.source}) could not load and was skipped: ${y(P)}`,"warning")}}let h,m={loaded:c,dispose:i(()=>(h??=(async()=>{e===m&&(e=null);for(let f=u.pop();f!==void 0;f=u.pop())try{await f()}catch(w){a(`[cowboy] a plugin disposer failed: ${y(w)}`,"warning")}for(let f=p.pop();f!==void 0;f=p.pop())f()})(),n=h,h),"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($n,"createPluginLoader");function zr(t){try{return`?v=${jn.statSync(t).mtimeMs}`}catch{return""}}i(zr,"cacheBust");function Vr(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(Vr,"pluginApi");async function Yr(t,e,r,n,s){let o=Vr(e,r,n,s),a=(await import(`${Qr(t.entry).href}${zr(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}i(Yr,"loadOne");function Xr(){let t=[],e=[];for(let r of A().ids()){let n=Jr(r);n.status==="available"?t.push(r):n.notice!==void 0&&e.push(n.notice)}return{availability:je(t),notices:e}}i(Xr,"probeHarnessAvailability");function Jr(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(Jr,"askAvailability");function Wn(){let t=Xr();return ot(t.availability),t}i(Wn,"startHarnessAvailabilityProbe");function qn(t){let e=it(),r=A();for(let n of r.runnable(e))try{r.require(n).prefetchModels(t)}catch{}}i(qn,"prefetchHarnessModels");async function Nn(t,e){let r=st(),n=await $n(r).load(t,e.cwd,(d,u)=>{e.hasUI&&e.ui.notify(d,u)}),s=b();r.harnesses.validateConfigs(s.harnessConfigLayers(),(d,u)=>s.reportHarnessConfigIssue(d,u)),Zr(e,r);let o=r.multiplexers.hosting();if(o.length===0)return{kind:"unhosted",plugins:n,reason:he};let l=r.multiplexers.runtime(t,b().multiplexer);if(!o.includes(l.multiplexer))return{kind:"unhosted",plugins:n,reason:he};te(l);let a=Wn();if(e.hasUI)for(let d of a.notices)e.ui.notify(d,"warning");return qn(t),{kind:"hosted",plugins:n,runtime:l}}i(Nn,"startSessionRuntime");function Zr(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(Zr,"reportUnregisteredConfig");function es(t){if(!ye()){let e=new ue(new Ze(b().concurrency),Tn(t));ve(e),b().setDeps({manager:e});let r=new ce(e);we(r),e.setOnComplete(n=>{r.onAgentComplete(n)}),e.setOnFollowUp((n,s)=>{r.onAgentFollowUp(n,s)})}}i(es,"wireManagerAndCoordinator");async function ts(t){let e=E(),r=O.join(e,"agents"),n=t.isProjectTrusted(),s=n?O.join(t.cwd,".agents","agents"):"",o=n?O.join(t.cwd,".pi","agents"):"";kt(r,o,s);let l=b().agent.disableDefaultAgents,a=await St({disableDefaultAgents:l,notify:i((d,u)=>{t.ui.notify(d,u)},"notify")});wt(a,{disableDefaultAgents:l})}i(ts,"scanAndRegisterAgents");async function ns(t){let e=E(),r=O.join(e,"orchestrators"),n=t.isProjectTrusted(),s=n?O.join(t.cwd,".agents","orchestrators"):"",o=n?O.join(t.cwd,".pi","orchestrators"):"";xt(r,o,s);let l=await Rt({notify:i((a,d)=>{t.ui.notify(a,d)},"notify")});At(l)}i(ns,"scanAndRegisterOrchestrators");async function rs(t){ut(rt());let e=t.isProjectTrusted()?O.join(t.cwd,".pi"):void 0;b().setProjectDir(e),b().reload()}i(rs,"loadSessionConfig");async function ss(t){await ts(t),await ns(t)}i(ss,"scanSessionTemplates");function _n(t){t.on("tool_call",Tt);let e=null;t.on("session_start",async(r,n)=>{dt(n),await rs(n);let s=await Nn(t,n);if(e=s.plugins,s.kind==="unhosted"){Se(n.ui),n.hasUI&&q()&&n.ui.notify(s.reason,"warning");return}await ss(n),es(s.runtime),await jt(t),q()?$t(n.ui):(Se(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=ye();if(s){let a=s.listAgents(J);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")}ee()?.dispose(),we(null),b().dispose(),s?.dispose(),ve(null),Lt();let o=e;e=null;let l=G();await o?.dispose(),G()===l&&te(null)}),process.on("exit",()=>{try{process.stderr.write("\x1B[?2026l\x1B[?25h\x1B[0m")}catch{}})}i(_n,"setupEventListeners");var Un="pi-cowboy needs a git repository: this directory is not inside one, so pi-cowboy stays inactive";function Bn(t,e){t.on("session_start",async(r,n)=>{n.hasUI&&n.ui.notify(e,"warning")})}i(Bn,"reportInactive");function is(t){if(ct()!==void 0)return;let e=pt();if(e!==void 0){Bn(t,e);return}if(!gt(process.cwd())){Bn(t,Un),qt(t,Un);return}lt(t),Wt(t),Nt(t),_n(t)}i(is,"default");export{is 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-67VN34QV.js";import{U as H,d as g,g as R,j as P}from"./chunk-NF2BSEPU.js";import{b as S,o as D}from"./chunk-ROCBRG4A.js";import{Ba as v,Fa as x,Oa as _,ia as I,ma as T,r as p,s as b,t as E,y as A}from"./chunk-GYO352IF.js";import{a as t,d as N}from"./chunk-XXNZAWMK.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=E,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
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-FGIFMYRD.js.map
@@ -0,0 +1,9 @@
1
+ import{e as Re,f as Xt,g as et,h as Zt,i as Jt,l as Qt,m as sn,n as an,p as De,q as nt,s as ln,t as cn}from"./chunk-CAWIXE4E.js";import{a as on,b as j}from"./chunk-67VN34QV.js";import{H as Ut,I as qt,K as zt,L as Yt,O as oe,P as tn,T as nn,V as rn,i as Wt,j as Kt,v as U,w as Pe,x as Gt,z as Bt}from"./chunk-NF2BSEPU.js";import{a as pe,b as W,c as ie,d as se,e as He,f as fe,g as q,h as je,i as tt,j as Fe,k as we,l as _,m as en,n as Y,o as Z,p as _e,q as Te}from"./chunk-ROCBRG4A.js";import{Ba as Le,Ea as Vt,Fa as Ee,G as Ze,H as Q,L as At,M as xt,N as $t,Oa as X,Q as Ae,R as Ce,S as xe,T as Lt,U as Et,V as Pt,W as Rt,X as Ht,Y as jt,Z as Ft,_ as _t,a as ht,b as yt,ba as $e,ga as Je,ia as le,ja as me,ka as Dt,l as Xe,la as ee,m as ke,ma as L,o as vt,p as bt,r as kt,ra as Nt,s as St,t as Ct,ta as Qe,wa as B,za as re}from"./chunk-GYO352IF.js";import{a as t,d as ue,e as wt,f as Se,g as Tt,k as Ot,l as ne,m as Mt,w as It}from"./chunk-XXNZAWMK.js";import{SettingsList as er}from"@earendil-works/pi-tui";import{SettingsManager as nr}from"@earendil-works/pi-coding-agent";async function dn(e,n){return nr.create(e,n??ht()).getDefaultThinkingLevel()}t(dn,"getPiDefaultThinkingLevel");import{SettingsList as ur}from"@earendil-works/pi-tui";var rr={queued:{icon:"\u25C6",color:"accent"},spawned:{icon:"\u25C8",color:"accent"},completed:{icon:"\u2713",color:"success"},error:{icon:"\u2717",color:"error"},stopped:{icon:"\u25A0",color:"dim"}};function un(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=rr[e];return n.fg(o.color,o.icon)}t(un,"statusIcon");function rt(e){if(!Number.isFinite(e)||e<1e3)return"<1s";let n=Math.floor(e/1e3),o=Math.floor(n/3600),r=Math.floor(n%3600/60),i=n%60,s=[];return o>0&&s.push(`${o}h`),r>0&&s.push(`${r}m`),(i>0||s.length===0)&&s.push(`${i}s`),s.join(" ")}t(rt,"formatMs");function mn(e){let n=U(e);return n?.displayName??n?.name??"Agent"}t(mn,"getDisplayName");function ae(e){return`${e.fg("accent","\u2022")} `}t(ae,"agentBulletPrefix");function pn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(pn,"truncatePath");function Ne(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(Ne,"formatSlotLimit");function fn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:i,harnessDefaultFor:s,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:c}=e,d=new Map;for(let u of n){let g=o[u],{model:k,source:y}=Rt({subagentType:u,harnessFamily:l(u),agentConfig:g,config:{agent:r},harnessDefault:s(u),parentModelId:c,sessionOverrides:i});if(!ot(i,r,u,e.sessionThinking))continue;let v=y==="session-per-type"||y==="session-default"?"[session]":a(u)?"[project]":"",{level:p,source:b}=it({type:u,agentConfig:g,harnessFamily:l(u),config:r,harnessDefault:e.harnessDefaultThinkingFor(u),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),C=b==="session-per-type"?" [session]":b==="parent"?" [parent]":b==="config-per-type"&&e.hasProjectThinkingKey(u)?" [project]":"",I=d.get(k)??[];I.push({type:u,thinking:p,thinkingTag:C,tag:v}),d.set(k,I)}return[...d.entries()].sort((u,g)=>u[0]===g[0]?0:u[0]===null?-1:g[0]===null?1:u[0]<g[0]?-1:1).map(([u,g])=>({modelId:u,rows:g}))}t(fn,"buildModelGroups");function ot(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(ot,"hasExplicitPerTypeOverride");function it(e){let n=jt({subagentType:e.type,harnessFamily:e.harnessFamily,agentConfig:e.agentConfig,config:{agent:e.config},harnessDefault:e.harnessDefault,parentThinking:e.parentThinking,sessionThinking:e.sessionThinking});return n!==void 0?{level:n.value,source:n.source}:{level:e.harnessFamily==="pi"?Ht:null,source:void 0}}t(it,"displayedThinking");import{SettingsList as sr}from"@earendil-works/pi-tui";import{matchesKey as Oe,SelectList as or,truncateToWidth as ir}from"@earendil-works/pi-tui";function gn(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],i=Y(new or(r,5,Z(e.theme)));return i.onSelect=s=>{s.value==="Yes"?(e.onConfirm(),o("Yes")):o()},i.onCancel=()=>o(),i}}t(gn,"createConfirmSubmenu");function Ve(e){return se({invalidate(){},render(o){let r=Math.max(0,o-4),i=t(l=>` ${ir(l,r,"...",!0)}`,"line"),s=[i(e.theme.bold(e.message))];if(e.detail)for(let l of e.detail.split(`
2
+ `))s.push(i(l));return s.push(i(e.theme.fg("dim","Y yes \xB7 N no"))),s},handleInput(o){if(Oe(o,"y")||Oe(o,"shift+y")){e.onYes();return}(Oe(o,"n")||Oe(o,"shift+n")||Oe(o,"escape"))&&e.onNo()}})}t(Ve,"createKeyConfirm");var ar={session:{label:"Session",setDescription:"Not saved",clearDescription:"Removes from the session"},global:{label:"Global",setDescription:"Saves to the global config file",clearDescription:"Removes from the global config file"},project:{label:"Project",setDescription:"Saves to the project config file",clearDescription:"Removes from the project config file"}};function st(e,n){let o=ar[e];return{id:e,label:o.label,currentValue:"",description:n?o.clearDescription:o.setDescription}}t(st,"levelItem");function ge(e){let n=[];return e.offered.session&&n.push(st("session",e.clearMode===!0)),e.offered.global&&n.push(st("global",e.clearMode===!0)),e.offered.project&&n.push(st("project",e.clearMode===!0)),e.includeClear&&n.push({id:"clear",label:"Clear...",currentValue:""}),e.includeAll&&n.push({id:"all",label:"All levels",currentValue:""}),n}t(ge,"buildLevelItems");function te(e){return(n,o)=>{let r=e.items.map(s=>({...s,submenu:t((l,a)=>{let c=e.onPick(s.id,a,()=>o());return c||(a(s.id),ie)},"submenu")})),i=Y(new sr(r,r.length,_(e.theme),(s,l)=>o(l),()=>o()));return se(i)}}t(te,"createLevelPickerSubmenu");function We(e){let n=e.availableLevels,o=e.includeAll===!0,r=(e.includeSession??!0)&&(!n||n.session),i=!n||n.global,s=e.projectOffered&&(!n||n.project),l=[r,i,s].filter(Boolean).length,a=e.showClear===!0?e.onClear:void 0,c=ge({offered:{session:r,global:i,project:s},clearMode:o,includeClear:a!==void 0,includeAll:n?l>=2:e.includeAll===!0});return te({theme:e.theme,items:c,onPick:t((d,u)=>d==="clear"?he({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,availableLevels:e.availableLevels,onClear:t(g=>a?.(g),"onClear")})("",u):e.onPick(d,u),"onPick")})}t(We,"createTargetSelectSubmenu");function he(e){return We({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,includeAll:!0,availableLevels:e.availableLevels,onPick:t(n=>e.onClear(n),"onPick")})}t(he,"createClearPickerSubmenu");function Ke(e){return(n,o)=>We({theme:e.theme,projectOffered:e.projectOffered,includeAll:!0,availableLevels:e.availableLevels,onPick:t((r,i)=>gn({message:e.message(r),theme:e.theme,onConfirm:t(()=>e.onConfirm(r),"onConfirm")})(n,i),"onPick")})(n,o)}t(Ke,"createClearAllSubmenu");import{Input as hn}from"@earendil-works/pi-tui";function at(e,n){let o=n.min??1,r=t(s=>s===0?"\u2265 0":`\u2265 ${s}`,"fmtLabel"),i=t(s=>e.ui.notify(s,"error"),"onError");return(s,l)=>{let a=new hn;return a.setValue(s),a.onSubmit=c=>{let d=c.trim();if(!d||/^unlimited$/i.test(d))switch(n.kind){case"required":i(`Invalid value \u2014 must be a number ${r(o)}`);return;case"defaulted":n.onValid?.(n.default),l(String(n.default));return;case"optional":n.onEmpty?.(),l("");return}let u=en(d,o);if(u===void 0){i(`Invalid value \u2014 must be a number ${r(o)}`);return}n.onValid?.(u),l(String(u))},a.onEscape=()=>l(),a}}t(at,"createNumericSubmenu");function ye(e,n){return(o,r)=>{let i=new hn;return i.setValue(o),i.onSubmit=s=>{let l=s.trim();if(!l){if(n?.required){e.ui.notify("Cannot be empty","error");return}r();return}r(l)},i.onEscape=()=>r(),i}}t(ye,"createInputSubmenu");var yn="__custom__",ve="__none__";function lr(e,n){let o=[];if(e.kind!=="none"){for(let r of e.levels)o.push({id:r,label:r==="off"?"Off":r.charAt(0).toUpperCase()+r.slice(1),currentValue:n===r?"(current)":""});e.kind==="advisory"&&o.push({id:yn,label:"Custom token...",currentValue:"",description:"A level or variant this harness advertises beyond its own list."})}return o.push({id:ve,label:"None",currentValue:n===null?"(current)":"",description:"Use the template, configured default, or parent session's level."}),o}t(lr,"valueItems");function vn(e){return te({theme:e.theme,items:lr(e.offering,e.current),onPick:t((n,o)=>{if(n===yn)return ye(e.ctx)(e.current??"",r=>{if(r===void 0){o();return}e.onPick(r),o(r)});e.onPick(n===ve?null:n)},"onPick")})}t(vn,"createThinkingValuePicker");function bn(e){let n=e.currentModel??null,o=e.showClear===!0?e.onClear:void 0;return te({theme:e.theme,items:ge({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:o!==void 0}),onPick:t((r,i,s)=>{if(r==="clear")return he({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(a=>o?.(a),"onClear")})("",i);let l=r;return new pe(tt(e.modelOptions,n,e.mergedModels),n,{onSelect:t(a=>{e.onSet(l,a),a==null?s():i(a)},"onSelect"),onCancel:t(()=>i(),"onCancel")},e.theme)},"onPick")})}t(bn,"createModelSelectSubmenu");function kn(e){let n=e.currentModel??null;return te({theme:e.theme,items:ge({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:e.showClear}),onPick:t((o,r,i)=>{if(o==="clear")return he({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(c=>e.onClear(c),"onClear")})("",r);let s=o,l,a=new pe(tt(e.modelOptions,n,e.mergedModels),n,{onSelect:t(c=>{if(c==null){e.onClear(s),i();return}let d=e.offeringFor(c);if(d.kind==="none"){e.onSet(s,c,null),r(c);return}l.activate(vn({theme:e.theme,ctx:e.ctx,offering:d,current:e.currentThinking,onPick:t(u=>e.onSet(s,c,u),"onPick")})("",r))},"onSelect"),onCancel:t(()=>r(),"onCancel")},e.theme);return l=new He(a),l},"onPick")})}t(kn,"createModelThinkingSubmenu");import{getSupportedThinkingLevels as cr}from"@earendil-works/pi-ai";function Ge(e){let{harnessId:n,modelKey:o,entries:r,piModel:i}=e;if(ne(n))return i===void 0?{kind:"advisory",levels:[]}:i.reasoning?{kind:"closed",levels:cr(i)}:{kind:"none"};if(o==="")return dr(r);let s=r.find(l=>l.key===o);return s===void 0?{kind:"advisory",levels:[]}:s.thinkingLevels.kind==="advisory"?{kind:"advisory",levels:s.thinkingLevels.levels}:s.thinkingLevels.levels.length===0?{kind:"none"}:{kind:"closed",levels:s.thinkingLevels.levels}}t(Ge,"thinkingOfferingFor");function dr(e){let n=[...new Set(e.flatMap(r=>r.thinkingLevels.levels))],o=e.length===0||e.some(r=>r.thinkingLevels.kind==="advisory");return n.length===0&&!o?{kind:"none"}:o?{kind:"advisory",levels:n}:{kind:"closed",levels:n}}t(dr,"unionThinkingOffering");function Sn(e){return Ge({harnessId:e.harnessId,modelKey:e.modelKey??"",entries:e.entries.get(e.harnessId)??[],piModel:Se(e.modelKey??"",e.registry,e.parentModel)})}t(Sn,"thinkingOfferingForModel");function Be(e){let n=e.model??"(none)",o=e.thinking??"(none)",r=e.model?e.modelTag:"",i=e.thinking?e.thinkingTag:"";return r!==""&&r===i?`${n} \xB7 ${o}${i}`:`${n}${r} \xB7 ${o}${i}`}t(Be,"pairedRow");function Ue(e,n){return e?" [session]":n?" [project]":""}t(Ue,"layerTag");function lt(e,n){return n===null?"":Ue(e.session,e.project)}t(lt,"thinkingTagOf");function Cn(e,n,o,r){if(o===null){e.mutate.agent.clearHarnessDefaultThinking(n,r);return}r!=="session"&&ne(n)&&!At.safeParse(o).success||e.mutate.agent.setHarnessDefaultThinking(n,o,r)}t(Cn,"writeHarnessDefaultThinking");function mr(e,n,o,r){o===null?e.mutate.agent.clearThinkingOverride(n,r):e.mutate.agent.setThinkingOverride(n,o,r)}t(mr,"writeTypeThinking");function pr(e){return B().runnable(e).filter(n=>!ne(n))}t(pr,"harnessDefaultRowIds");function fr(e){let n=pr(re());return se(gr(e,n))}t(fr,"buildModelSettingsScreen");function gr(e,n){let{ctx:o,store:r,theme:i,harnessModelOptions:s,piDefaultThinking:l,close:a}=e,c,d=t(k=>{let y=[],v=r.isProjectWritable,p=t((h,P)=>o.ui.notify(h,P),"notify"),b=me(),C=b.model??o.model,I=C?`${C.provider}/${C.id}`:null,O=b.thinkingLevel??null,$=r.agentConfigSnapshot(),V=Fe($),H=t(()=>{c?.(d(k))},"refresh"),R=t(h=>P=>Sn({harnessId:h,modelKey:P,entries:s,registry:b.modelRegistry,parentModel:C}),"offeringFor"),D=t(h=>{let P={session:h.modelLevels.session||h.thinkingLevels.session,global:h.modelLevels.global||h.thinkingLevels.global,project:h.modelLevels.project||h.thinkingLevels.project};return kn({modelOptions:h.modelOptions,mergedModels:h.mergedModels,projectOffered:v,theme:k,ctx:o,currentModel:h.model,currentThinking:h.thinking,showClear:P.session||P.global||P.project,availableLevels:P,offeringFor:R(h.harnessId),onSet:t((M,G,N)=>{h.write(M,G,N),p(`${h.label} set to ${G} \xB7 ${N??"(none)"} (${M})`,"info")},"onSet"),onClear:t(M=>{h.clear(M),p(`${h.label} cleared (${M})`,"info"),H()},"onClear")})},"pairSubmenu"),K=$.default,f=r.modelOverrideLevels("default"),m=r.harnessDefaultThinkingLevels("pi"),S=r.defaultThinkingForHarness("pi"),w=r.sessionDefaultModel??K;y.push({id:"defaultModel",label:"Pi Default Model",currentValue:Be({model:w,modelTag:Ue(f.session,r.hasProjectModelKey("default")),thinking:S,thinkingTag:lt(m,S)}),description:"Default model and thinking level applied when no session, per-type, or template override is set.",submenu:D({label:"Pi Default Model",harnessId:"pi",modelOptions:Q(s,"pi"),mergedModels:we("pi",V),model:w,thinking:S,modelLevels:f,thinkingLevels:m,write:t((h,P,M)=>{r.mutate.agent.setModelOverride("default",P,h),Cn(r,"pi",M,h)},"write"),clear:t(h=>{r.mutate.agent.clearModelOverride("default",h),r.mutate.agent.clearHarnessDefaultThinking("pi",h)},"clear")})});for(let h of n){let P=`${B().displayName(h)} Default Model`,M=r.harnessDefaultModelLevels(h),G=r.harnessDefaultThinkingLevels(h),N=r.defaultThinkingForHarness(h);y.push({id:`harness:${h}`,label:P,currentValue:Be({model:r.defaultModelForHarness(h),modelTag:Ue(M.session,M.project),thinking:N,thinkingTag:lt(G,N)}),description:`Default model and thinking level applied to agents launched under ${h} when no session, per-type, or template override is set.`,submenu:D({label:P,harnessId:h,modelOptions:Q(s,h),mergedModels:[],model:r.defaultModelForHarness(h),thinking:N,modelLevels:M,thinkingLevels:G,write:t((J,Ye,tr)=>{r.mutate.agent.setHarnessDefaultModel(h,Ye,J),Cn(r,h,tr,J)},"write"),clear:t(J=>{r.mutate.agent.clearHarnessDefaultModel(h,J),r.mutate.agent.clearHarnessDefaultThinking(h,J)},"clear")})})}let T=Gt(),A={default:r.sessionDefaultModel},x={};for(let h of T)A[h]=r.sessionModelOverride(h),x[h]=U(h);let E={};for(let h of T)E[h]=r.sessionThinkingOverride(h);let F=fn({types:T,agentConfigs:x,config:$,sessionOverrides:A,sessionThinking:E,harnessDefaultFor:t(h=>r.defaultModelForHarness(oe(h)),"harnessDefaultFor"),harnessDefaultThinkingFor:t(h=>{let P=oe(h),M=r.defaultThinkingForHarness(P);return M!==null?M:ne(P)&&O===null?l??null:null},"harnessDefaultThinkingFor"),harnessFamilyFor:t(h=>Ze(oe(h)),"harnessFamilyFor"),hasProjectModelKey:t(h=>r.hasProjectModelKey(h),"hasProjectModelKey"),hasProjectThinkingKey:t(h=>r.hasProjectThinkingKey(h),"hasProjectThinkingKey"),parentModelId:I,parentThinking:O}),z=t((h,P,M,G)=>D({label:h,harnessId:P,modelOptions:Q(s,P),mergedModels:we(P,V),model:M,thinking:G,modelLevels:r.modelOverrideLevels(h),thinkingLevels:r.thinkingOverrideLevels(h),write:t((N,J,Ye)=>{r.mutate.agent.setModelOverride(h,J,N),mr(r,h,Ye,N)},"write"),clear:t(N=>{r.mutate.agent.clearModelOverride(h,N),r.mutate.agent.clearThinkingOverride(h,N)},"clear")}),"typeSubmenu");for(let h of F){y.push({id:q,label:" ",currentValue:""}),y.push(fe(k,h.modelId??"(no model)"));let P=Math.max(...h.rows.map(M=>`${M.thinking??"(none)"}${M.thinkingTag}`.length));for(let M of h.rows){let G=oe(M.type),N=`${M.thinking??"(none)"}${M.thinkingTag}`,J=M.thinking!==null&&M.thinkingTag.trim()===M.tag.trim()?"":M.tag;y.push({id:`type:${M.type}`,label:`${ae(k)}${M.type}`,currentValue:`${N.padEnd(P)} ${J}`.trimEnd(),description:`Model and thinking level for the ${M.type} agent type.`,submenu:z(M.type,G,h.modelId,M.thinking)})}}y.push({id:q,label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",currentValue:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});let Me=T.filter(h=>!ot(A,$,h,E));Me.length>0&&y.push({id:"overrideType",label:"Override another type...",currentValue:"",description:"Configure model and thinking level overrides for an agent type currently using inherited defaults.",submenu:t((h,P)=>_e(Me.map(M=>({value:M,label:`${ae(k)}${M}`})),{onSelect:t(M=>{if(M==null)return P();let G=oe(M),N=U(M),J=r.modelFor(M,I,N,G);return z(M,G,J,it({type:M,agentConfig:N,harnessFamily:Ze(G),config:$,harnessDefault:r.defaultThinkingForHarness(G),parentThinking:O??void 0,sessionThinking:E}).level)("",P)},"onSelect"),onCancel:t(()=>P(),"onCancel")},k),"submenu")}),y.push({id:q,label:" ",currentValue:""});let gt=r.modelSettingsLevels(),Ie={...gt,project:gt.project&&v};return(Ie.session||Ie.global||Ie.project)&&y.push({id:"clearAll",label:"Clear all model and thinking overrides...",currentValue:"",description:"Remove model and thinking level overrides across a selected configuration layer (session, global, project, or all).",submenu:Ke({theme:k,projectOffered:v,availableLevels:Ie,message:t(h=>`Clear all model and thinking overrides at the ${h} level?`,"message"),onConfirm:t(h=>{r.mutate.agent.clearAllModelOverrides(h),p(`Model and thinking overrides cleared (${h})`,"info")},"onConfirm")})}),y},"buildItems"),u=new ur(d(i),15,_(i),(k,y)=>c?.(d(i)),a),g=new j(u,{title:"Model Settings",theme:i,onCancel:a,onRebuild:t(k=>{c=k},"onRebuild")});return se(g)}t(gr,"buildModelSettingsList");function wn(e){let{ctx:n,store:o,theme:r,harnessModelOptions:i,piDefaultThinking:s}=e,l=t(()=>{let a=o.modelOverrideLevels("default"),c=o.harnessDefaultThinkingLevels("pi"),d=o.defaultThinkingForHarness("pi");return Be({model:o.sessionDefaultModel??o.agentConfigSnapshot().default,modelTag:Ue(a.session,o.hasProjectModelKey("default")),thinking:d,thinkingTag:lt(c,d)})},"defaultDisplay");return{id:"modelOverrides",label:"Model overrides",currentValue:l(),description:"Pi's default model and thinking level, plus per-harness and per-type overrides; opens the model settings screen.",submenu:t((a,c)=>fr({ctx:n,store:o,theme:r,harnessModelOptions:i,piDefaultThinking:s,close:t(()=>c(l()),"close")}),"submenu")}}t(wn,"buildModelOverridesRow");import{SettingsList as Tn}from"@earendil-works/pi-tui";function On(e,n){return e==="pi"?n:`${e}:${n}`}t(On,"qualifiedKey");function qe(e){let n=new Map;for(let o of e){let r=$e(o)?.harness??"pi",i=n.get(r);i?i.push(o):n.set(r,[o])}return n}t(qe,"groupKeysByHarness");function yr(e,n){let o=[...e];for(let r of n.keys())o.includes(r)||o.push(r);return o}t(yr,"sectionHarnesses");async function Mn(e,n){let o=[...n.keys()],r=t((s,l)=>{let a=[],c=s.isProjectWritable,d=t((f,m,S)=>m==="default"?f.default!==void 0:S===void 0?!1:m==="harnesses"?f.harnesses?.[S]!==void 0:f[m]?.[S]!==void 0,"layerHas"),u=t((f,m)=>({session:d(s.sessionConcurrency,f,m),global:d(s.globalConcurrency,f,m),project:d(s.projectConcurrency,f,m)}),"entryLevels"),g=t((f,m)=>d(s.sessionConcurrency,f,m)?" [session]":d(s.projectConcurrency,f,m)?" [project]":"","limitTag"),k=t((f,m)=>(S,w)=>We({theme:l,projectOffered:c,onPick:t((T,A)=>at(e,{kind:"optional",min:1,onValid:t(x=>m(T,x),"onValid")})(f,A),"onPick")})(S,w),"targetThenValueSubmenu"),y=t((f,m,S,w)=>(T,A)=>{let x=ge({offered:{session:!0,global:!0,project:c},includeClear:w.session||w.global||w.project});return te({theme:l,items:x,onPick:t((E,F)=>{if(E==="clear")return he({theme:l,projectOffered:c,availableLevels:w,onClear:S})("",F);let z=E;return at(e,{kind:"optional",min:1,onValid:t(Me=>m(z,Me),"onValid")})(String(f),F)},"onPick")})(T,A)},"limitSubmenu"),v=t(f=>(m,S)=>{let w=t(()=>f(),"buildFresh"),T,A=Y(new Tn(w(),15,_(l),(x,E)=>{let F=T,z=w();F.items=z,F.filteredItems=z,F.submenuComponent=null,F.selectedIndex=0},()=>S("closed")));return T=A,je(T),se(A)},"nestedListSubmenu"),p=t(f=>{let m=L(),S=m.concurrency.harnesses[f],w=B().displayName(f),T=`Concurrent agents of every model launched under ${f}.`;if(S===void 0)return{id:`harness:${f}`,label:w,currentValue:"unset",description:T,submenu:k("",(x,E)=>{L().mutate.concurrency.setHarness(f,E,x),e.ui.notify(`${f} concurrency set to ${E} (${x})`,"info")})};let A=d(m.sessionConcurrency,"harnesses",f)?" [session]":d(m.projectConcurrency,"harnesses",f)?" [project]":"";return{id:`harness:${f}`,label:w,currentValue:Ne(S,A),description:T,submenu:y(S,(x,E)=>{L().mutate.concurrency.setHarness(f,E,x),e.ui.notify(`${w} concurrency set to ${E} (${x})`,"info")},x=>{L().mutate.concurrency.removeHarness(f,x),e.ui.notify(`Removed per-harness limit for ${f} (${x})`,"info")},{session:d(m.sessionConcurrency,"harnesses",f),global:d(m.globalConcurrency,"harnesses",f),project:d(m.projectConcurrency,"harnesses",f)})}},"harnessLimitRow"),b=t(()=>{let f=L(),m=[...o];for(let S of Object.keys(f.concurrency.harnesses))S.trim()!==""&&!m.includes(S)&&m.push(S);return m.map(S=>p(S))},"harnessListItems"),C=t(f=>{let m=Q(n,f);return[...new Set(m.map(S=>wt(S)?.provider).filter(S=>S!==void 0))].sort()},"providerOptionsFor"),I=t((f,m)=>{let S=L(),w=S.concurrency.providers[m],T=`Concurrent slots reserved for agents under ${f} using the ${$e(m)?.provider??m} provider.`;if(w===void 0)return{id:`provider:${m}`,label:m,currentValue:"unset",description:T,submenu:k("",(x,E)=>{L().mutate.concurrency.setProvider(m,E,x),e.ui.notify(`${m} concurrency set to ${E} (${x})`,"info")})};let A=d(S.sessionConcurrency,"providers",m)?" [session]":d(S.projectConcurrency,"providers",m)?" [project]":"";return{id:`provider:${m}`,label:m,currentValue:Ne(w,A),description:T,submenu:y(w,(x,E)=>{L().mutate.concurrency.setProvider(m,E,x),e.ui.notify(`${m} concurrency set to ${E} (${x})`,"info")},x=>{L().mutate.concurrency.removeProvider(m,x),e.ui.notify(`Removed per-provider limit for ${m} (${x})`,"info")},{session:d(S.sessionConcurrency,"providers",m),global:d(S.globalConcurrency,"providers",m),project:d(S.projectConcurrency,"providers",m)})}},"providerLimitRow"),O=t(f=>{let m=L(),S=qe(Object.keys(m.concurrency.providers)).get(f)??[],w=C(f).map(A=>On(f,A));return[...new Set([...w,...S])].sort().map(A=>I(f,A))},"providerListItems"),$=t((f,m)=>{let S=L(),w=S.concurrency.models[m],T=$e(m),A=T?.kind==="model"?T.model:m,x=`Concurrent slots reserved for agents under ${f} using the ${A} model.`;if(w===void 0)return{id:`model:${m}`,label:m,currentValue:"unset",description:x,submenu:k("",(F,z)=>{L().mutate.concurrency.setModel(m,z,F),e.ui.notify(`${m} concurrency set to ${z} (${F})`,"info")})};let E=d(S.sessionConcurrency,"models",m)?" [session]":d(S.projectConcurrency,"models",m)?" [project]":"";return{id:`model:${m}`,label:m,currentValue:Ne(w,E),description:x,submenu:y(w,(F,z)=>{L().mutate.concurrency.setModel(m,z,F),e.ui.notify(`${m} concurrency set to ${z} (${F})`,"info")},F=>{L().mutate.concurrency.removeModel(m,F),e.ui.notify(`Removed per-model limit for ${m} (${F})`,"info")},{session:d(S.sessionConcurrency,"models",m),global:d(S.globalConcurrency,"models",m),project:d(S.projectConcurrency,"models",m)})}},"modelLimitRow"),V=t(f=>{let m=L(),S=qe(Object.keys(m.concurrency.models)).get(f)??[],w=Q(n,f).map(A=>On(f,A));return[...new Set([...w,...S])].sort().map(A=>$(f,A))},"modelListItems"),H=t(f=>{let m=L(),S=qe(Object.keys(f==="providers"?m.concurrency.providers:m.concurrency.models));return yr(o,S).filter(w=>{let T=(S.get(w)??[]).length>0;return f==="providers"?T||C(w).length>0:T||Q(n,w).length>0}).map(w=>({id:`${f}-harness:${w}`,label:B().displayName(w),currentValue:"",description:f==="providers"?`Provider limits under ${w}.`:`Model limits under ${w}.`,submenu:v(()=>f==="providers"?O(w):V(w))}))},"harnessPickerItems"),R=s.concurrency.default;a.push({id:"defaultConcurrency",label:"Default concurrency limit",currentValue:`${R}${g("default")}`,description:"Concurrent agents, whatever harness, provider, or model they use.",submenu:y(R,(f,m)=>{s.mutate.concurrency.setDefault(m,f),e.ui.notify(`Default concurrency set to ${m} (${f})`,"info")},f=>{s.mutate.concurrency.removeDefault(f),e.ui.notify(`Removed default concurrency limit (${f})`,"info")},u("default"))}),a.push({id:"harnessLimits",label:"Per-harness limits",currentValue:"",description:"Cap how many agents run at once under a single harness.",submenu:v(b)}),a.push({id:"providerLimits",label:"Per-provider limits",currentValue:"",description:"Cap how many agents run at once for a single provider.",submenu:v(()=>H("providers"))}),a.push({id:"modelLimits",label:"Per-model limits",currentValue:"",description:"Cap how many agents run at once for a single model.",submenu:v(()=>H("models"))});let D=s.concurrencySettingsLevels(),K={...D,project:D.project&&c};return(K.session||K.global||K.project)&&a.push({id:"resetAll",label:"Clear all concurrency limits...",currentValue:"",description:"Remove concurrency overrides at the chosen level (session, global, project, or all).",submenu:Ke({theme:l,projectOffered:c,availableLevels:K,message:t(f=>`Clear all concurrency limits at the ${f} level?`,"message"),onConfirm:t(f=>{s.mutate.concurrency.clearAll(f),e.ui.notify(`Concurrency limits cleared (${f})`,"info")},"onConfirm")})}),a},"buildItems"),i;await new W(e).open(({theme:s,close:l})=>{let a=t(()=>i?.(r(L(),s)),"triggerRebuild"),c=L(),d=r(c,s),u=new Tn(d,15,_(s),(g,k)=>a(),l);return new j(u,{title:"Concurrency Settings",theme:s,onCancel:l,onRebuild:t(g=>{i=g},"onRebuild")})})}t(Mn,"showConcurrencySettingsMenu");import{matchesKey as ce,SelectList as dt,truncateToWidth as Ln,visibleWidth as ze}from"@earendil-works/pi-tui";import{SelectList as vr}from"@earendil-works/pi-tui";async function In(e,n){let o=ee();if(!o)return e.map(i=>({id:i,kind:"error",error:"manager unavailable"}));let r=[];for(let i of e)try{r.push({id:i,kind:"report",report:await o.cleanup(i,n(i))})}catch(s){r.push({id:i,kind:"error",error:ue(s)})}return r}t(In,"runCleanupPass");function ct(e,n){let o=X(e.ui);for(let r of n)r.kind==="report"?o.succeeded(Xt(r.report),et(r.report)?"warning":"info"):o.failed(`Failed to clean up agent ${r.id}`,r.error)}t(ct,"reportCleanupOutcomes");function An(e){return e.outcome.kind==="refused"?e.outcome.reason:void 0}t(An,"refusalReason");function br(e){return e.worktree.kind==="kept"?e.worktree.path??void 0:void 0}t(br,"refusalWorktreePath");function kr(e){switch(e.kind){case"dirty":return"It has uncommitted changes";case"unverifiable":return`Its state could not be verified (${e.detail})`;case"recovered-refusal":return"Herdr still reports it at work";default:return Re(e)}}t(kr,"offerReason");function Sr(e,n){return{invalidate(){},render:t(()=>[` ${e.fg("dim",n)}`],"render")}}t(Sr,"progressBody");function Cr(e,n,o,r){let i=[{value:"force",label:"Force",description:n},{value:"cancel",label:"Cancel",description:"Keep the worktree and its changes"}],s=Y(new vr(i,6,Z(e)));return s.onSelect=l=>l.value==="force"?o():r(),s.onCancel=r,s}t(Cr,"forceOfferList");function xn(e){let{ctx:n,theme:o,view:r,refresh:i,close:s,requestRender:l}=e,a=t(u=>{r.activate(u),l()},"show"),c=t((u,g,k,y)=>{let v=u.length===1;a(Ve({theme:o,message:v?`Force cleanup of agent ${u[0]}?`:`Force cleanup of ${u.length} agents?`,detail:[...k,"",v?"This DELETES its worktree and anything uncommitted in it.":"This DELETES their worktrees and anything uncommitted in them."].join(`
3
+ `),onNo:y,onYes:t(()=>{s(),X(n.ui).pending(`Forcing cleanup of ${Te(u)}`),(async()=>{let p=await In(u,b=>{let C=g.get(b);return{force:C?{reason:C}:{}}});ct(n,p)})()},"onYes")}))},"askForceConfirm"),d=t(u=>{let g=new Map;for(let{id:I,report:O}of u){let $=An(O);$&&g.set(I,$)}let k=[...g.keys()],y=k.length===1,v=u.map(({id:I,report:O})=>{let $=An(O),V=$?y?Re($):`${I}: ${Re($)}`:`${I}: kept`,H=br(O);return H?`${V} (${H})`:V}),p=g.get(k[0]??""),b=y?`Clean up agent ${k[0]} anyway? ${p?kr(p):"kept"}.`:`Clean up ${k.length} agents anyway?`,C=t(()=>{ct(n,u),i()},"backOut");a(Cr(o,b,()=>c(k,g,v,C),C))},"offerForce");return u=>{a(Sr(o,`Cleaning up ${Te(u)}\u2026`)),(async()=>{let g=await In(u,()=>{}),k=g.filter(p=>p.kind==="report"&&tn(p.report)),y=new Set(k.map(p=>p.id));if(ct(n,g.filter(p=>!y.has(p.id))),k.length>0){d(k);return}g.some(p=>p.kind==="error"||et(p.report))?i():s()})()}}t(xn,"createStatusCleanup");import{SelectList as wr}from"@earendil-works/pi-tui";function $n(e){let{ctx:n,theme:o,view:r,close:i,requestRender:s}=e,l=X(n.ui),a=t(v=>{r.activate(v),s()},"show"),c=t((v,p)=>{i(),l.outcome("warning",`Agent ${v.id} ${p}`)},"refuse"),d=t((v,p)=>{try{an(p.path,p.text)}catch(C){l.failed(`Failed to export agent ${v} to ${p.path}`,C);return}let b=p.loss===void 0?"":Ft(p.loss);l.outcome(nt(p),`Exported handover for agent ${v} to ${p.path}.${b}`)},"writeAndReport"),u=t((v,p)=>{a(Ve({theme:o,message:`Overwrite ${p.path}?`,detail:"An export of this run already exists there. Y replaces it with the current export; Esc keeps the existing file.",onYes:t(()=>{i(),d(v,p)},"onYes"),onNo:t(()=>{i(),l.outcome("warning",`Did not export agent ${v}: kept the existing file at ${p.path}`)},"onNo")}))},"askOverwrite"),g=t(v=>{let p=ee();if(!p){i(),l.failed(`Failed to export agent ${v.id}`,"manager unavailable");return}l.pending(`Exporting handover for agent ${v.id}`),(async()=>{let b=await p.exportHandover(v.id);if(b.kind==="faulted"){i(),l.outcome(nt(b),`Agent ${v.id} ${De(b.fault)}`);return}if(sn(b.path)){u(v.id,b);return}i(),d(v.id,b)})()},"runExport"),k=t((v,p)=>{let b=ee();if(i(),!b){l.failed(`Failed to hand agent ${v.id} over to ${p}`,"manager unavailable");return}l.pending(`Handing agent ${v.id} over to ${p}`),(async()=>{let C=await b.handover(v.id,{harness:p});l.outcome(_t(C),Jt(v.id,C))})()},"runHandover"),y=t((v,p)=>{let b=B(),C=Zt(b,re(),p).map(O=>({value:`harness:${O}`,label:`Hand over to ${b.displayName(O)}`,description:`Launch the next run of this agent under ${b.displayName(O)}`}));C.push({value:"export",label:"Export",description:"Write the handover file to /tmp (nothing is stopped or launched)"});let I=Y(new wr(C,10,Z(o)));I.onSelect=O=>{if(O.value==="export"){g(v);return}k(v,O.value.slice(8))},I.onCancel=()=>i(),a(I)},"openSubmenu");return v=>{let p=v.execution.harness;if(p===void 0){c(v,De({kind:"never-started"}));return}let b=B().get(p);if(b===void 0||!It(b)){c(v,De({kind:"harness-cannot-export-session",harness:p}));return}y(v,p)}}t($n,"createStatusHandover");async function Tr(e,n){let o=n.execution.host;if(!o){e.ui.notify("Agent has no herdr pane yet (still queued)","info");return}let r=Ee();if(!r){e.ui.notify("Agent runtime is not initialized","warning");return}let i=X(e.ui);i.pending(`Focusing agent ${n.id}'s herdr pane`);try{await r.view.focus(o),i.succeeded(`Focused agent ${n.id}'s herdr pane`)}catch(s){i.failed(`Failed to focus agent ${n.id}'s herdr pane`,s)}}t(Tr,"focusHerdrPane");async function En(e,n,o,r){let i=o==="result"?n.id:"Error",s=r.split(`
4
+ `),l=mn(n.display.type),a=5,c=3,d=70,u=0,g=!0;await new W(e).openOverlay(({tui:k,theme:y,close:v})=>{let p=y.fg("border","\u2502"),b=t(()=>{let C=Math.floor(k.terminal.rows*d/100);return Math.max(c,C-a)},"viewportHeight");return{invalidate(){},render(C){let I=C-4,O=[y.fg("border",`\u256D${"\u2500".repeat(C-2)}\u256E`)],$=y.bold(y.fg("accent",`${l} \xB7 ${i}`)),V=Math.max(0,I-ze($));O.push(`${p} ${Ln($+" ".repeat(V),I,"...",!0)} ${p}`),O.push(`${p} ${y.fg("dim","\u2500".repeat(I))} ${p}`);let H=b(),R=Math.max(0,s.length-H);g&&(u=R);let D=Math.min(u,R),K=s.slice(D,D+H);for(let T=0;T<H;T++){let A=K[T]??"",x=Ln(A,I,"...",!0),E=Math.max(0,I-ze(x));O.push(`${p} ${x}${" ".repeat(E)} ${p}`)}let f=s.length<=H?"100%":`${Math.round((D+H)/s.length*100)}%`,m=y.fg("dim",`${s.length} lines \xB7 ${f}`),S=y.fg("dim","q/Esc close"),w=Math.max(1,I-ze(m)-ze(S));return O.push(`${p} ${m}${" ".repeat(w)}${S} ${p}`),O.push(y.fg("border",`\u2570${"\u2500".repeat(C-2)}\u256F`)),O},handleInput(C){if(ce(C,"q")||ce(C,"escape")){v();return}let I=b(),O=Math.max(0,s.length-I);ce(C,"up")?(u=Math.max(0,u-1),g=u>=O):ce(C,"down")?(u=Math.min(O,u+1),g=u>=O):ce(C,"pageUp")?(u=Math.max(0,u-I),g=!1):ce(C,"pageDown")?(u=Math.min(O,u+I),g=u>=O):ce(C,"home")||C==="g"?(u=0,g=!1):C==="G"&&(u=O,g=!0)}}})}t(En,"showTextViewer");function Pn(e,n){let o=ee(),r=Te(n),i=X(e.ui);if(!o){i.failed(`Failed to stop ${r}`,"manager unavailable");return}(async()=>{let s=0,l=[];for(let c of n)try{await o.abort(c,"user")?s+=1:l.push({id:c,reason:"already settled"})}catch(d){l.push({id:c,reason:ue(d)})}if(l.length===0){i.succeeded(n.length===1?`Stopped ${n[0]}`:`Stopped ${n.length} agent(s)`);return}let a=l.map(({id:c,reason:d})=>n.length===1?d:`${c} (${d})`).join(", ");s>0?i.succeeded(`Stopped ${s} of ${n.length} agent(s); ${a}`,"warning"):i.failed(`Failed to stop ${r}`,a)})()}t(Pn,"stopAgentsOffMenu");function Or(e,n,o,r,i,s,l){let a=[],c=n.id,d=Ce(n.lifecycle.phase),u=n.execution.host!==void 0,g=Et(n.lifecycle),k=xe(n.lifecycle)&&n.lifecycle.status==="error"?n.lifecycle.error:"",y=g.length>0,v=k.length>0;if(u&&a.push({value:"focus-pane",label:"View shell",description:"Focus the subagent's herdr pane"}),y&&a.push({value:"view-result",label:"View result"}),v&&a.push({value:"view-error",label:"View error"}),d?a.push({value:"stop",label:"Stop"}):(n.lifecycle.phase==="settled"&&a.push({value:"handover",label:"Handover",description:"Hand this run's session to another harness, or export it to /tmp"}),a.push({value:"cleanup",label:"Clean up",description:"Close its pane and remove its worktree and merged branch"})),a.length===0)return e.ui.notify(`Agent ${c} \u2014 no actions available`,"info"),r(),new dt([],5,Z(o));let p=Y(new dt(a,10,Z(o)));return p.onSelect=async b=>{b.value==="focus-pane"?await Tr(e,n):b.value==="view-result"?await En(e,n,"result",g):b.value==="view-error"?await En(e,n,"error",k):b.value==="stop"?(X(e.ui).pending(`Stopping agent ${c}`),r(),Pn(e,[n.id])):b.value==="cleanup"?s([n.id]):b.value==="handover"&&l(n)},p.onCancel=()=>r(),p}t(Or,"buildAgentActionsList");async function Rn(e){if((ee()?.listAgents(Ae)??[]).length===0){e.ui.notify("No agents have been spawned this session","info");return}await new W(e).open(({tui:n,theme:o,close:r})=>{let i=ee()?.listAgents(Ae)??[],s=t(()=>i.filter(p=>Ce(p.lifecycle.phase)),"activeAgents"),l=t(()=>i.filter(p=>!Ce(p.lifecycle.phase)),"finishedAgents"),a=t(()=>i.filter(p=>xe(p.lifecycle)&&p.lifecycle.status==="completed"),"completedAgents"),c=t(()=>{let p=Date.now(),b=i.map($=>{let V=Lt($.lifecycle),H=Ce($.lifecycle.phase),R=xe($.lifecycle)?$.lifecycle.completedAt:p,D=rt(R-Pt($.lifecycle)),K=H?"":` ${rt(p-R)} ago`,f=un(V,o),m=$.display.description?$.display.description:"",S=m?` \u2014 ${m}`:"",w=ae(o),T=$.display.worktree?` wt:${$.display.worktree.branch}`:"";return{value:$.id,label:`${f} ${$.id} ${w}${$.display.type} ${V} ${D}${T}${S}${K}`}}),C=s(),I=l(),O=a();return C.length>0&&(b.push({value:q,label:" "}),b.push({value:"__stop-all",label:`Stop ${C.length} active agent(s)`})),I.length>0&&(b.push({value:q,label:" "}),b.push({value:"__cleanup-finished",label:`Clean up ${I.length} settled agent(s)`}),O.length>0&&b.push({value:"__cleanup-completed",label:`Clean up ${O.length} completed agent(s)`})),b},"buildAgentItems"),d=Y(new dt(c(),15,Z(o)));je(d);let u=new He(d),g=t(()=>n.requestRender(),"requestRender"),k=t(p=>{i=ee()?.listAgents(Ae)??[];let b=d,C=c();b.items=C,b.filteredItems=C;let I=p?C.findIndex(O=>O.value===p):-1;d.setSelectedIndex(I>=0?I:0),u.activate(d),g()},"refresh"),y=xn({ctx:e,theme:o,view:u,refresh:k,close:r,requestRender:g}),v=$n({ctx:e,theme:o,view:u,close:r,requestRender:g});return d.onSelect=async p=>{if(p.value==="__stop-all"){let C=s();X(e.ui).pending(`Stopping ${C.length} agent(s)`),r(),Pn(e,C.map(I=>I.id));return}if(p.value==="__cleanup-finished"){y(l().map(C=>C.id));return}if(p.value==="__cleanup-completed"){y(a().map(C=>C.id));return}let b=i.find(C=>C.id===p.value);b&&u.activate(Or(e,b,o,()=>k(b.id),()=>r(),y,v))},d.onCancel=()=>r(),new j(u,{title:"Status",theme:o,passthroughKeys:!0})})}t(Rn,"showAgentStatusMenu");import{SettingsList as Mr,Input as Ir}from"@earendil-works/pi-tui";function Ar(e){let n="Harness that launches agents whose template omits harness_type. pi = the real pi binary; pig and pi-bolt = pi-compatible binaries launched through a shell function in the agent's own pane; opencode and codex = binaries of their own launched as their interactive UIs in the agent's own pane.",o=Ot.filter(l=>l!=="pi"&&!Xe(l,e)),r=o.length===0?n:`${n} Not on PATH: ${o.join(", ")}.`,i=B(),s=Hn().filter(l=>Mt(l)===void 0);return s.length===0?r:`${r} Plugin harnesses: ${s.map(l=>i.displayName(l)).join(", ")}.`}t(Ar,"harnessDescription");function Hn(){return[...ke(B().ids(),re())]}t(Hn,"offerableHarnesses");async function jn(e){let n=L(),o=t(s=>[fe(s,"Spawn defaults"),{id:q,label:" ",currentValue:""},{id:"harnessType",label:"Default harness",currentValue:Vt(),values:Hn(),description:Ar(re())},{id:q,label:" ",currentValue:""},fe(s,"Worktrees"),{id:"worktreeRoot",label:"Worktree root",currentValue:n.agent.worktreeRoot??"(default)",submenu:t((l,a)=>{let c=new Ir;return c.setValue(l==="(default)"?"":l),c.onSubmit=d=>{let u=d.trim();n.mutate.agent.setWorktreeRoot(u||void 0),ln(le()),e.ui.notify(u?`Worktree root set to ${u}`:"Worktree root cleared (default)","info"),a(u||"(default)")},c.onEscape=()=>a(),c},"submenu"),description:`Where worktrees are created. Blank = ${yt()}.`},{id:"worktreeMaterialization",label:"Worktree materialization",currentValue:Le(),values:[...ke(vt,Qe())],description:Xe("copy-on-write",Qe())?"Copy-on-write = clone of the parent working tree (shares node_modules, .env). checkout = git's classic checkout, nothing shared.":"This volume cannot clone, so copy-on-write is unavailable and new worktrees use git's classic checkout."},{id:"worktreeCheckoutType",label:"Worktree checkout",currentValue:n.agent.worktreeCheckoutType,values:[...kt],description:"Where a new worktree's checkout starts when the parent has uncommitted work. clean = the worktree starts at HEAD: under copy-on-write, only ignored files like node_modules and .env are copied in; under checkout, it is git's plain checkout. dirty = the parent's work rides along: copy-on-write clones its edits and untracked files too, while checkout applies only its tracked changes, leaving untracked files behind. A clean parent starts at HEAD either way."},{id:q,label:" ",currentValue:""},fe(s,"Tools"),{id:"disableDefaultAgents",label:"Disable default agents",currentValue:n.agent.disableDefaultAgents?"ON":"OFF",values:["ON","OFF"],description:"Skip auto-loading built-in agent types next session; only .pi/agents types load."}],"buildItems"),r=t((s,l)=>{switch(s){case"worktreeRoot":break;case"worktreeMaterialization":{let a=bt(l);a!==void 0&&(n.mutate.agent.setWorktreeMaterialization(a),e.ui.notify(`Worktree materialization set to ${a}`,"info"));break}case"worktreeCheckoutType":{let a=St(l);a!==void 0&&(n.mutate.agent.setWorktreeCheckoutType(a),e.ui.notify(`Worktree checkout set to ${a}`,"info"));break}case"harnessType":{n.mutate.agent.setHarnessType(l),e.ui.notify(`Default harness set to ${l}`,"info");break}case"disableDefaultAgents":n.mutate.agent.setDisableDefaultAgents(l==="ON"),e.ui.notify(`Disable default agents ${l} (takes effect on next session)`,"info");break}},"onChange"),i;await new W(e).open(({theme:s,close:l})=>{let a=o(s),c=t(()=>i?.(o(s)),"triggerRebuild"),d=new Mr(a,10,_(s),(u,g)=>{r(u,g),a.some(k=>k.id===u&&k.submenu)&&c()},l);return new j(d,{title:"Agent settings",theme:s,onCancel:l,onRebuild:t(u=>{i=u},"onRebuild")})})}t(jn,"showSpawnOptionsMenu");function xr(e,n,o){return(r,i)=>{let s=Pe();s.length===0&&n("No agent types available","error");let l=s.map(a=>({value:a,label:a,provider:U(a)?.description??""}));return new pe(l,e.agent.defaultAgentType,{onSelect:t(a=>{a!=null&&(e.mutate.agent.setDefaultAgentType(a),n(`Agent set to ${a}`,"info")),i(a??void 0)},"onSelect"),onCancel:t(()=>i(),"onCancel")},o)}}t(xr,"createAgentTypeSubmenu");function $r(e,n,o){return(r,i)=>{let s=Ut(),a=(s.length>0?s:Object.keys(Bt)).map(c=>({value:c,label:c}));return new pe(a,e.agent.defaultOrchestrator,{onSelect:t(c=>{c!=null&&(e.mutate.agent.setDefaultOrchestrator(c),n(`Default orchestrator set to ${c}`,"info")),i(c??void 0)},"onSelect"),onCancel:t(()=>i(),"onCancel")},o)}}t($r,"createOrchestratorSubmenu");function Fn(e){return{id:"defaultAgentType",label:"Agent",currentValue:e.store.agent.defaultAgentType,submenu:xr(e.store,e.notify,e.theme),description:`Agent type used when cowboy_agent omits \`agent_type\`. Default: ${xt}.`}}t(Fn,"buildDefaultAgentTypeRow");function _n(e){return{id:"defaultOrchestrator",label:"Default orchestrator",currentValue:e.store.agent.defaultOrchestrator,submenu:$r(e.store,e.notify,e.theme),description:`Orchestration template used for every cowboy_agent spawn; the tool accepts no per-call orchestrator input. Default: ${$t}.`}}t(_n,"buildDefaultOrchestratorRow");import ut from"node:fs";import Lr from"node:path";import{SettingsList as Er}from"@earendil-works/pi-tui";async function Dn(e){let n=L(),o=t(()=>{let l=Je(),a=[{id:"systemPromptMode",label:"System prompt mode",currentValue:n.agent.systemPromptMode,values:["replace","inherit","custom"],description:"How the subagent system prompt is built: replace, inherit, or custom."}];return n.agent.systemPromptMode==="custom"&&!ut.existsSync(l)&&a.push({id:"createPromptFile",label:"Create prompt file",currentValue:l,values:["Create"],description:`Create ${l} with a starter template for custom mode.`}),a.push({id:"includeContextFiles",label:"Include context files",currentValue:n.agent.includeContextFiles?"ON":"OFF",values:["ON","OFF"],description:"Load project and ~/.pi/agent AGENTS.md as shared <project_context>."},{id:"loadSkillsImplicitly",label:"Load skills implicitly",currentValue:n.agent.loadSkillsImplicitly?"ON":"OFF",values:["ON","OFF"],description:"Give new agents all skills when an agent template omits the field."},{id:"loadExtensionsImplicitly",label:"Load extensions implicitly",currentValue:n.agent.loadExtensionsImplicitly?"ON":"OFF",values:["ON","OFF"],description:"Give new agents all extensions when an agent template omits the field."}),a},"buildItems"),r=o(),i=null,s=t((l,a)=>{switch(l){case"systemPromptMode":n.mutate.agent.setSystemPromptMode(a),e.ui.notify(`System prompt mode set to ${a}`,"info"),r=o(),i?.(r);break;case"createPromptFile":try{let c=Je();ut.mkdirSync(Lr.dirname(c),{recursive:!0}),ut.writeFileSync(c,`You are a Pi, an expert coding sub-agent.
5
+ You have been invoked to handle a specific task autonomously`,"utf-8"),e.ui.notify(`Created prompt file: ${c}`,"info")}catch(c){e.ui.notify(`Failed to create prompt file: ${ue(c)}`,"error")}return;case"includeContextFiles":n.mutate.agent.setIncludeContextFiles(a==="ON"),e.ui.notify(`Include context files set to ${a}`,"info");break;case"loadSkillsImplicitly":n.mutate.agent.setLoadSkillsImplicitly(a==="ON"),e.ui.notify(`Load skills implicitly set to ${a}`,"info");break;case"loadExtensionsImplicitly":n.mutate.agent.setLoadExtensionsImplicitly(a==="ON"),e.ui.notify(`Load extensions implicitly set to ${a}`,"info");break}},"onChange");await new W(e).open(({theme:l,close:a})=>{let c=new Er(r,10,_(l),s,a);return new j(c,{title:"System Prompt",theme:l,onCancel:a,onRebuild:t(d=>{i=d},"onRebuild")})})}t(Dn,"showSystemPromptMenu");var mt="thinkingLevel",Nn="__custom__";function Vn(e){return{modelName:Tt(e),thinkingLevel:e?.thinking??void 0}}t(Vn,"choiceInvocation");function Wn(e){let{entries:n,registry:o,parentModel:r}=e,i=t((l,a)=>Ge({harnessId:l,modelKey:a,entries:n.get(l)??[],piModel:Se(a,o,r)}),"offeringOf"),s=t((l,a,c)=>{if(l.kind==="none")return;let d=l.levels.map(u=>({id:u,label:u==="off"?"Off":u.charAt(0).toUpperCase()+u.slice(1),currentValue:a===u?"(current)":""}));return l.kind==="advisory"&&d.push({id:Nn,label:"Custom token...",currentValue:"",description:"A level or variant this model advertises beyond its own list."}),d.push({id:ve,label:"None",currentValue:a===void 0?"(current)":"",description:"Use the template, configured default, or parent session's level."}),te({theme:c.theme,items:d,onPick:t((u,g)=>{if(u===Nn)return ye(c.ctx)(a??"",g)},"onPick")})},"levelRow");return{clamp(l,a,c){if(c===void 0)return;let d=i(l,a);if(d.kind!=="none")return d.kind==="advisory"||d.levels.includes(c)?c:void 0},row(l,a,c,d){let u=i(l,a);return{id:mt,label:"Thinking level",currentValue:c??"(none)",description:u.kind==="none"?"The selected model does not support thinking levels.":"Reasoning effort for this spawn, supported by the selected harness",submenu:s(u,c,d)}},choice(l,a,c){if(a==="")return c===void 0?{kind:"none"}:{kind:"chosen",modelChoice:ne(l)?{inherit:!0,thinking:c}:{levelOnly:!0,thinking:c}};let d=ne(l)?Pr(a,c,o):Rr(l,a,c,n);return d===void 0?{kind:"missing",modelKey:a}:{kind:"chosen",modelChoice:d}}}}t(Wn,"spawnChoices");function Pr(e,n,o){let r=Se(e,o,void 0);if(r!==void 0)return{model:r,key:`${r.provider}/${r.id}`,thinking:n??null}}t(Pr,"piChoice");function Rr(e,n,o,r){let i=(r.get(e)??[]).find(s=>s.key===n);return{harness:e,key:n,name:i?.label??n,thinking:o??null}}t(Rr,"foreignChoice");import*as Bn from"node:path";var de="cow-",pt=Ct;function Hr(e){if(!e.startsWith(de))return{kind:"missing-prefix"};let n=e.slice(de.length);return n===""?{kind:"empty-name"}:/^[a-z0-9_-]+$/.test(n)?e.length>pt?{kind:"too-long"}:null:{kind:"invalid-characters"}}t(Hr,"validateWorktreeBranchName");function jr(e){switch(e.kind){case"missing-prefix":return`Worktree name must start with "${de}" \u2014 it is prefilled; add your name after it.`;case"empty-name":return`Enter a name after "${de}" (for example cow-fix-login).`;case"invalid-characters":return"Invalid name: only lowercase letters, numbers, hyphens, and underscores allowed.";case"too-long":return`Worktree name is too long: herdr agent names cap at ${pt} characters, so the name after "${de}" can be at most ${pt-de.length} characters.`}}t(jr,"describeWorktreeNameProblem");function Kn(e){return on({prefill:de,notify:e.notify,validate:Hr,describeProblem:jr,onDone:e.onDone,onCancel:e.onCancel})}t(Kn,"createWorktreeNameInput");var Un="__inherit_worktree__",qn="__create_new_worktree__",Fr=60;function _r(e){return e.branch??Bn.basename(e.path)}t(_r,"worktreeBranch");function Gn(e){switch(e.kind){case"inherit":return"Inherits parent cwd";case"picked":return e.branch;case"new":return"New worktree"}}t(Gn,"pickLabel");function Dr(e){return[{value:qn,label:"New worktree"},{value:Un,label:"Inherits parent cwd"},...e.map(n=>({value:n.path,label:pn(n.path,Fr),provider:n.isDetached?"detached":n.branch??"detached"}))]}t(Dr,"pickerItems");async function zn(e,n){return n===null||!await Kt(e,n)?null:await Wt(e,n)??[]}t(zn,"loadWorktreeChoices");function Yn(e,n){return{id:"worktree",label:"Worktree",currentValue:Gn(n.current),description:"Run in a linked git worktree instead of parent cwd; a new one is named after Spawn",submenu:t((o,r)=>{let i=t(s=>{n.onPick(s),r(Gn(s))},"record");return _e(Dr(e),{onSelect:t(s=>{if(s===qn){i({kind:"new"});return}if(s===Un){i({kind:"inherit"});return}let l=e.find(a=>a.path===s);l&&i({kind:"picked",path:l.path,branch:_r(l)})},"onSelect"),onCancel:t(()=>r(),"onCancel")},n.theme)},"submenu")}}t(Yn,"buildWorktreeRow");async function Xn(e,n){return await e.open(({theme:o,close:r})=>new j(Kn({notify:n,onDone:t(i=>r(i),"onDone"),onCancel:t(()=>r(),"onCancel")}),{title:"Worktree Name",theme:o,passthroughKeys:!0}))}t(Xn,"showWorktreeNameStep");import{Editor as Nr}from"@earendil-works/pi-tui";function Zn(e){let{tui:n,theme:o,keybindings:r,prefill:i,onDone:s,onCancel:l}=e,a=new Nr(n,{borderColor:t(c=>o.fg("dim",c),"borderColor"),selectList:Z(o)},{paddingX:2});return a.focused=!0,i&&a.setText(i),a.onSubmit=c=>{let d=c.trim();if(!d&&e.required){e.notify("Cannot be empty","error");return}s(d)},{render:t(c=>a.render(c),"render"),invalidate:t(()=>a.invalidate(),"invalidate"),handleInput:t(c=>{if(r.matches(c,"tui.select.cancel")){l();return}a.handleInput(c)},"handleInput"),get focused(){return a.focused},set focused(c){a.focused=c}}}t(Zn,"createTextEditor");import{SettingsList as ft}from"@earendil-works/pi-tui";async function Jn(e,n){let o=Pe();if(o.length===0){e.ui.notify("No agent types available","error");return}let r=qt(),i=o.includes(r)?r:o[0],s=me(),l=await zn(le(),s.cwd),a=L(),c=s.model?`${s.model.provider}/${s.model.id}`:null,d=[...ke(B().ids(),re())],u=t((f,m)=>a.modelFor(f,c,U(f),m)??"","modelFor"),g=Wn({entries:n,registry:s.modelRegistry,parentModel:s.model}),k=t((f,m)=>a.thinkingFor(f,U(f),m,s.thinkingLevel),"seedThinking"),y=oe(i),v=u(i,y),p=k(i,y),b=!0,C=U(i)?.fork??!1,I=l?{kind:"new"}:{kind:"inherit"},O="",$=t(f=>{i=f,y=oe(f),v=u(f,y),p=k(f,y),C=U(f)?.fork??!1},"applyType"),V=t(f=>{y=f,v=u(i,f),p=k(i,f)},"applyHarness"),H=t(()=>{let f=v||"(no model)";return[{id:"spawn",label:"Spawn",currentValue:"",description:"Ask for the worktree name and prompt, then launch",submenu:t((m,S)=>{let w=g.choice(y,v,p);return w.kind==="missing"?(e.ui.notify(`Model not found: ${w.modelKey}`,"error"),S(),ie):(D({type:i,harness:y,modelChoice:w.kind==="chosen"?w.modelChoice:void 0,worktreeChoice:I,description:O,fork:C,runInBackground:b}),ie)},"submenu")},{id:q,label:" ",currentValue:""},{id:"type",label:"Type",currentValue:i,description:U(i)?.description??"Agent type",submenu:t((m,S)=>{let w=new ft(o.map(T=>({id:T,label:`${ae(R)}${T}`,currentValue:T,description:U(T)?.description??"Agent type",submenu:t((A,x)=>(S(T),ie),"submenu")})),10,_(R),()=>{},()=>S(),{enableSearch:!0});return w.selectItem(i),w},"submenu")},{id:"harness",label:"Harness",currentValue:y,description:"Harness that launches this agent. A change re-seeds the model and thinking level from that harness's own defaults: both belong to the harness that reads them.",submenu:t((m,S)=>{let w=new ft(d.map(T=>({id:T,label:`${ae(R)}${T}`,currentValue:T,submenu:t((A,x)=>(S(T),ie),"submenu")})),10,_(R),()=>{},()=>S(),{enableSearch:!0});return w.selectItem(y),w},"submenu")},{id:"model",label:"Model",currentValue:f,description:"Override the default model for this agent",submenu:bn({modelOptions:Q(n,y),mergedModels:we(y,Fe(a.agentConfigSnapshot())),showClear:!1,projectOffered:a.isProjectWritable,theme:R,onSet:t((m,S)=>{v=S??"",p=g.clamp(y,v,p),K?.(H())},"onSet")})},{id:"background",label:"Background",currentValue:b?"ON":"OFF",description:"Run the agent in the background",values:["ON","OFF"]},{id:"fork",label:"Fork session",currentValue:C?"Yes":"No",description:"Fork the parent session context into the subagent",values:["Yes","No"]},...l?[Yn(l,{current:I,theme:R,onPick:t(m=>{I=m},"onPick")})]:[],g.row(y,v,p,{ctx:e,theme:R}),{id:q,label:" ",currentValue:""},{id:"description",label:"Description",currentValue:O,description:"Short label shown in the agents list; derived from the prompt when left empty",submenu:ye(e)}]},"buildItems"),R,D,K;return await new W(e).open(({theme:f,close:m})=>{R=f,D=m;let S=t((T,A)=>{switch(T){case"type":$(A);break;case"harness":{let x=d.find(E=>E===A);x!==void 0&&V(x);break}case mt:p=A===ve?k(i,y):A;break;case"background":b=A==="ON";break;case"fork":C=A==="Yes";break;case"description":O=A;break}K?.(H())},"onChange"),w=new ft(H(),15,_(R),S,m);return new j(w,{title:"Spawn Options",theme:R,onCancel:m,onRebuild:t(T=>{K=T},"onRebuild")})})}t(Jn,"askSpawnConfiguration");var Vr=50;async function Qn(e,n){let o=me(),r=L(),i=o.cwd,s=t(async(g,k)=>{try{return await nn.allocate(le(),{naming:{kind:"explicit",branch:g},parentCwd:i,worktreeRoot:r.agent.worktreeRoot,materialization:Le(),dirtyCheckout:Yt(k),notify:t((y,v)=>e.ui.notify(y,v),"notify"),host:Ee().host})}catch(y){e.ui.notify(`Worktree creation failed: ${y instanceof Error?y.message:String(y)}`,"error");return}},"allocateWorktree"),l=t(async(g,k,y)=>{let v=le(),p=Dt().mintSpawnId();X(e.ui).pending(`Spawning agent ${p} (${g.type})`);let b;if(k.kind==="new"&&(b=await s(k.branch,g.type),!b))return;let C=b?.worktree,I=C!==void 0?{kind:"owned",path:C.path,branch:C.branch}:k.kind==="picked"?{kind:"picked",path:k.path,branch:k.branch}:void 0,O=g.description.trim()!==""?g.description:(y.split(`
6
+ `,1)[0]??"").slice(0,Vr),$=Nt(),V=zt();try{await $.spawn(o,{spawnId:p,type:g.type,requestedHarness:g.harness,prompt:y,description:O,orchestration:V,modelChoice:g.modelChoice,worktree:I,hostRef:b?.hostRef,projectTrusted:b?.projectTrusted,invocation:{...Vn(g.modelChoice),runInBackground:g.runInBackground,fork:g.fork},runInBackground:g.runInBackground,fork:g.fork})}catch(H){let R=`Spawn failed: ${H instanceof Error?H.message:String(H)}`;if(!b){e.ui.notify(R,"error");return}let D=await b.teardown(v);e.ui.notify(`${R}
7
+
8
+ ${rn(D)}`,"error")}},"launch"),a=await Jn(e,n);if(a===void 0)return;let c=new W(e),d;if(a.worktreeChoice.kind==="new"){let g=await Xn(c,(k,y)=>e.ui.notify(k,y));if(g===void 0)return;d={kind:"new",branch:g}}else d=a.worktreeChoice;let u=await c.open(({tui:g,theme:k,keybindings:y,close:v})=>new j(Zn({prefill:"",onDone:t(p=>v(p),"onDone"),onCancel:t(()=>v(),"onCancel"),tui:g,theme:k,keybindings:y}),{title:"Agent Prompt (optional)",theme:k,passthroughKeys:!0}));u!==void 0&&await l(a,d,u)}t(Qn,"showSpawnAgentMenu");async function Wr(e){return await new W(e).open(({theme:n,close:o})=>{let r=t(d=>o(d),"handOff"),i=L(),s=i.agent.showActiveIndicator,l=i.agent.grazingEnabled,a=[be("concurrency","Concurrency Settings","Set per-model slot limits",r),be("spawnoptions","Agent behavior","spawn defaults, results delivery, output, tools, worktrees",r),be("systemprompt","System prompt","Prompt mode, AGENTS.md, skills, extensions",r),{id:"showActiveIndicator",label:"Show cowboy \u{1F920}",currentValue:s?"ON":"OFF",values:["ON","OFF"]},{id:"grazingEnabled",label:"Grazing \u{1F404}",currentValue:l?"ON":"OFF",values:["ON","OFF"]}],c=new er(a,10,_(n),(d,u)=>{d==="showActiveIndicator"?Qt(e.ui,u==="ON"):d==="grazingEnabled"&&i.mutate.agent.setGrazingEnabled(u==="ON")},o);return new j(c,{title:"Settings",theme:n,onCancel:o})})}t(Wr,"showSettingsList");async function Kr(e,n){for(;;){let o=await Wr(e);if(o===void 0)return;switch(o){case"concurrency":await Mn(e,n);break;case"spawnoptions":await jn(e);break;case"systemprompt":await Dn(e);break}}}t(Kr,"showSettingsMenu");async function Gr(e,n,o){switch(n){case"status":await Rn(e);break;case"spawn":await Qn(e,o);break;case"settings":await Kr(e,o);break}}t(Gr,"showAgentsActionMenu");function be(e,n,o,r){return{id:e,label:n,description:o,currentValue:"",submenu:t(()=>(r(e),ie),"submenu")}}t(be,"handOffRow");async function Br(e,n){let o=await dn(e.cwd),r;return await new W(e).open(({theme:i,close:s})=>{let l=t(d=>s(d),"handOff"),a=t(()=>{let d=L(),u=t((y,v)=>e.ui.notify(y,v),"notify"),g=d.agent.extensionEnabled,k={id:"extensionEnabled",label:"Enabled",currentValue:g?"ON":"OFF",values:["ON","OFF"],description:g?"Unload the cowboy tools and stop subagent-result notifications. Persisted; active agents keep working.":"cowboy tools are unloaded and the rest of this menu is hidden. Active agents keep working."};return g?[wn({ctx:e,store:d,theme:i,harnessModelOptions:n,piDefaultThinking:o}),_n({store:d,theme:i,notify:u}),Fn({store:d,theme:i,notify:u}),be("status","Status","List spawned, queued and settled agents",l),be("spawn","Spawn agent","Manually spawn a new agent",l),be("settings","Settings","Concurrency, agent behavior, and system prompt settings",l),k]:[k]},"buildItems"),c=new er(a(),10,_(i),(d,u)=>{let g=d==="extensionEnabled";if(g){let k=u==="ON";cn(e.ui,k),e.ui.notify(k?"pi-cowboy enabled":"pi-cowboy disabled","info")}r?.(a(),g?"extensionEnabled":void 0)},s);return new j(c,{title:"Agents",theme:i,onCancel:s,onRebuild:t(d=>{r=d},"onRebuild")})})}t(Br,"showAgentsMainList");async function ja(e,n){for(;;){let o=await Br(e,n);if(o===void 0)return;await Gr(e,o,n)}}t(ja,"showAgentsMainMenu");export{Gr as showAgentsActionMenu,ja as showAgentsMainMenu,Kr as showSettingsMenu,Qn as showSpawnAgentMenu};
9
+ //# sourceMappingURL=menus-QMEWZXAL.js.map
@@ -1,2 +1,2 @@
1
- import{a as E,b as R,i as A}from"./chunk-WL3QYM2F.js";import{ea as v,fa as u,ia as c,sa as S,ta as k}from"./chunk-CTBFJWEE.js";import{a as s,e as w,f as m,t as h,u as C}from"./chunk-254PTGN5.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
- //# sourceMappingURL=model-picker-IIXU4GJP.js.map
1
+ import{a as E,b as R,i as A}from"./chunk-ROCBRG4A.js";import{ia as v,ja as u,ma as c,wa as S,xa as k}from"./chunk-GYO352IF.js";import{a as s,e as w,f as m,u as h,v as C}from"./chunk-XXNZAWMK.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
+ //# sourceMappingURL=model-picker-I2L5LYS7.js.map