pi-cowboy 0.33.0 → 0.35.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.
@@ -44,10 +44,15 @@ interface NotFound {
44
44
  id: string;
45
45
  }
46
46
  export type LocateResult = Located | Ambiguous | NotFound;
47
+ export interface SpaceKey {
48
+ readonly workspaceId: string;
49
+ readonly checkoutPath?: string;
50
+ }
47
51
  export interface AgentAssets extends CleanupDeps {
48
52
  multiplexer: AgentMultiplexer;
49
53
  deliverable: (id: string) => RecoveredDeliverable;
50
54
  locate(id: string, hint?: AgentSpawn): Promise<LocateResult>;
55
+ otherTenants(space: SpaceKey, self: string): Promise<readonly string[]>;
51
56
  observe(pane: PaneRef): Promise<HostObservation | undefined>;
52
57
  }
53
58
  export interface AgentAssetsDeps extends CleanupDeps {
@@ -13,7 +13,11 @@ type AmbiguousArtifactsReason = {
13
13
  kind: "ambiguous-artifacts";
14
14
  candidates: readonly string[];
15
15
  };
16
- export type WorktreeKeptReason = WorktreeRetentionReason | AgentActiveReason | RecoveredRefusalReason | AmbiguousArtifactsReason;
16
+ export type WorktreeKeptReason = WorktreeRetentionReason | AgentActiveReason | RecoveredRefusalReason | AmbiguousArtifactsReason | SpaceInUseReason;
17
+ type SpaceInUseReason = {
18
+ kind: "space-in-use";
19
+ tenants: readonly string[];
20
+ };
17
21
  export type CleanupSource = "tracked" | "recovered";
18
22
  export type DiscoveryBasis = {
19
23
  kind: "pane-absent";
@@ -2,7 +2,7 @@ import type { AnyHarnessId, HarnessExportLoss } from "./harness.js";
2
2
  import type { HandoverSourceFault } from "./handover.js";
3
3
  import type { ToolSeverity } from "./tool-result.js";
4
4
  export interface HandoverExportArtifact {
5
- readonly path: string;
5
+ readonly defaultPath: string;
6
6
  readonly text: string;
7
7
  readonly sessionId: string;
8
8
  readonly loss?: HarnessExportLoss;
@@ -20,6 +20,9 @@ export type HandoverExportOutcome = ({
20
20
  export type PreparedHandoverExport = Extract<HandoverExportOutcome, {
21
21
  kind: "prepared";
22
22
  }>;
23
+ export declare function exportWorktreeName(worktree: {
24
+ readonly path: string;
25
+ } | undefined, agentId: string): string;
23
26
  export interface HandoverExportRequest {
24
27
  readonly worktree: string;
25
28
  readonly harness: AnyHarnessId;
@@ -125,11 +125,18 @@ export interface HarnessTeardownContext {
125
125
  export interface HarnessTeardownRequest extends HarnessTeardownContext {
126
126
  readonly pi: ExtensionAPI;
127
127
  }
128
+ export interface HarnessRunStaging {
129
+ readonly systemPromptFile: string;
130
+ readonly taskFile: string;
131
+ readonly resultFile: string;
132
+ }
128
133
  export interface HarnessExportRequest {
129
134
  readonly pi: ExtensionAPI;
130
135
  readonly subagentId: string;
131
136
  readonly paneId: string;
132
137
  readonly cwd: string;
138
+ readonly startedAt: number;
139
+ readonly staged: HarnessRunStaging;
133
140
  }
134
141
  export type HandoverRecord = {
135
142
  readonly kind: "user";
@@ -80,8 +80,10 @@ export declare class SubagentSession {
80
80
  private revive;
81
81
  private beginWatch;
82
82
  abort(initiator?: StopInitiator): Promise<boolean>;
83
+ private readTarget;
83
84
  private handoverSource;
84
- private exportSettledSession;
85
+ private exportSource;
86
+ private readRunSession;
85
87
  private handoverTask;
86
88
  handover(request: SessionHandoverRequest): Promise<HandoverOutcome>;
87
89
  exportHandover(): Promise<HandoverExportOutcome>;
@@ -1,14 +1,14 @@
1
- import{A as wt,B as vt,C as kt,D as z,J as V,K as bt,M as xt,N as At,O as Q,b as lt,c as ct,e as ut,g as pt,i as ht,k as be,l as gt,p as mt,u as ft,v as Y,w as yt}from"./chunk-UY5D2K62.js";import{A as Ge,Aa as it,B as Ye,Ca as at,Ea as L,Ia as dt,L as ge,La as ke,N as et,O as me,R as fe,S as tt,U as q,V as T,W as I,Y as nt,aa as rt,b as ue,ba as ot,c as Be,k as B,l as Le,la as b,m as je,ma as F,n as pe,na as w,p as Ue,pa as y,qa as E,ra as ye,sa as we,u as We,ua as st,v as qe,xa as ve,y as Fe,ya as K,z as Ke,za as G}from"./chunk-IIQ52KJZ.js";import{E as Ze,F as Je,a as r,h as $,j as he,k as ze,n as Ve,p as Qe,r as W,t as Xe}from"./chunk-3TPZINCV.js";import{visibleWidth as Te}from"@earendil-works/pi-tui";var xe="\u{1F920}",Rt="\u{1F404}",pn="\u{1F4A9}",hn=2,gn=1e3,X=Te(Rt),mn="76;175;80";function fn(e){return`\x1B[48;2;${mn}m${e}\x1B[49m`}r(fn,"greenBackground");function It(e){return e===0?0:Math.max(hn,Math.ceil(Math.sqrt(2*e)))}r(It,"pastureEdge");function Et(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Et,"emptyPasture");function yn(e,t){let n=It(e.cows+e.droppings),o=Et(n),i=Array.from({length:n*n},(s,d)=>d),a=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let s=0;s<a.length;s+=1){let d=s+Math.floor(t()*(i.length-s)),c=i[d];i[d]=i[s],i[s]=c,o[Math.floor(c/n)][c%n]=a[s]}return o}r(yn,"grazedPasture");function Z(e,t){let n=[];for(let o=0;o<e.length;o+=1)for(let i=0;i<e[o].length;i+=1)e[o][i]===t&&n.push({row:o,col:i});return n}r(Z,"cellsOf");function wn(e,t){return[{row:e.row-1,col:e.col},{row:e.row,col:e.col+1},{row:e.row+1,col:e.col},{row:e.row,col:e.col-1}].filter(({row:o,col:i})=>o>=0&&o<t&&i>=0&&i<t)}r(wn,"neighboursOf");function St(e,t){return wn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(St,"openNeighboursOf");function vn(e,t){let n=Z(e,"cow").filter(d=>St(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=St(o,e),a=i[Math.floor(t()*i.length)],s=e.map(d=>d.slice());return s[o.row][o.col]="empty",s[a.row][a.col]="cow",s}r(vn,"moveHerd");function Tt(e,t,n,o){for(let i=0;i<n;i+=1){let a=Z(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(Tt,"placeAtRandom");function kn(e,t,n,o){let i=Z(e,"cow"),a=Z(e,"dropping"),s=i.length-t,d=a.length-n;for(;s>0&&d<0;){let c=i.pop();e[c.row][c.col]="dropping",s-=1,d+=1}for(;s>0;){let c=i.pop();e[c.row][c.col]="empty",s-=1}for(;d>0;){let c=a.pop();e[c.row][c.col]="empty",d-=1}Tt(e,"cow",-s,o),Tt(e,"dropping",-d,o)}r(kn,"reconcileCounts");function bn(e,t,n){if(e===null)return yn(t,n);let o=It(t.cows+t.droppings),i=Et(o);for(let a=0;a<e.length&&a<o;a+=1)for(let s=0;s<e[a].length&&s<o;s+=1)i[a][s]=e[a][s];return kn(i,t.cows,t.droppings,n),i}r(bn,"reconcilePasture");var xn={anchor:"top-right",width:Te(xe),get offsetX(){return E()?.cowboyOffsetX??0},nonCapturing:!0},An={anchor:"top-right",offsetY:1,get width(){return E()?.pastureWidth??0},nonCapturing:!0};function Sn(e){return e==="cow"?Rt:e==="dropping"?pn:" ".repeat(X)}r(Sn,"cellText");function Tn(e,t){return e.map(n=>t(n.map(Sn).join("")))}r(Tn,"drawnRows");function Rn(){return we().list(["spawned"]).length}r(Rn,"liveAgentCount");function In(){return we().list(tt).length}r(In,"endedAgentCount");function En(){return{live:Rn(),ended:In()}}r(En,"agentCounts");function On(){return y().agent.grazingEnabled}r(On,"grazingEnabled");var Ae=class{constructor(t,n,o,i,a){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=a}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return Te(xe)}get pastureWidth(){return this.drawnPasture().length*X}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*X-(t*X-this.cowboyWidth)}render(){return this.frame(),[xe]}pastureRows(){return this.frame(),Tn(this.drawnPasture(),this.grass)}invalidate(){}attachCowboy(t){this.cowboyHandle=t}attachPasture(t){this.pastureHandle=t}dispose(){let t=this.drawnPasture().length>0&&(this.cowboyHandle!==null||this.pastureHandle!==null);this.disposed=!0,this.poll!==null&&(clearInterval(this.poll),this.poll=null),this.cowboyHandle?.hide(),this.cowboyHandle=null,this.pastureHandle?.hide(),this.pastureHandle=null,t&&this.tui.requestRender(!0)}drawnPasture(){return this.herd===null||!this.isGrazing()?[]:this.herd.pasture}frame(){if(this.disposed)return;let t=this.isGrazing();this.herd===null?(this.herd=this.place(this.countAgents()),this.grazing=t):t!==this.grazing&&this.recount(),this.pollWhile(t)}pollWhile(t){!t&&this.poll!==null?(clearInterval(this.poll),this.poll=null):t&&this.poll===null&&(this.poll=setInterval(()=>this.recount(),gn))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,a=(this.grazing??o)&&(this.herd?.pasture.length??0)>0;if(this.herd===null||t!==this.herd.liveAgents||n!==this.herd.endedAgents)this.herd=this.place({live:t,ended:n});else if(o&&!i)this.herd={...this.herd,pasture:vn(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let s=a&&this.drawnPasture().length===0;this.tui.requestRender(s)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:bn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Se=class{static{r(this,"PastureView")}render(){return E()?.pastureRows()??[]}invalidate(){}};function Ot(e){Re(),e.custom(t=>{let n=new Ae(t,En,On,fn,Math.random);return ye(n),n},{overlay:!0,overlayOptions:xn,onHandle:r(t=>E()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Se,{overlay:!0,overlayOptions:An,onHandle:r(t=>E()?.attachPasture(t),"onHandle")})}r(Ot,"showExtensionIndicator");function Re(){let e=E();ye(null),e?.dispose()}r(Re,"hideExtensionIndicator");function J(){return y().agent.extensionEnabled}r(J,"isExtensionEnabled");function Cn(){return J()&&y().agent.showActiveIndicator}r(Cn,"isActiveIndicatorShown");function ee(e){Cn()?Ot(e):Re()}r(ee,"syncExtensionIndicator");function so(e,t){y().mutate.agent.setShowActiveIndicator(t),ee(e)}r(so,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as jr}from"@earendil-works/pi-tui";import{Type as p}from"typebox";var _n="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",Pn=`REQUIRED. Short 2-3 word task name (e.g. "fix login flow"). This single value names the agent's branch/tab/worktree/agent so you can recognize it at a glance, and the extension appends a unique spawn id so parallel spawns \u2014 and every entry in a batch \u2014 are always distinct. Limits: 3 words, 19 characters when slugged (lowercase, dashes). A longer name throws with the exact overshoot \u2014 retry with a shorter name. Missing name throws too. The same name twice in one call is rejected before anything spawns.`,Mn=`Optional model for THIS agent as "provider/model-id". Omit it, or pass null, to leave it unset and use the configured default for this session and agent type \u2014 the usual case, and never a value to guess at. Pass it when the user asked for a specific model for this task. When a previous attempt failed with a provider/model error, pass a different model here and instruct the agent in plain text to continue where the failed attempt left off. A model that is not in this session's registry fails the call before anything is spawned.`,$n=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${W.join(", ")}) and any harness a plugin registered in this session. Omit it, or pass null, to leave it unset and use the agent template's harness_type, then the configured default \u2014 never pass a harness the user did not ask for. A harness this session did not register, or this machine cannot launch, fails the call before anything is spawned \u2014 unlike the configured default, an explicit request never falls back to pi.`,Nn='Optional worktree for THIS agent. Omit it, or pass null, for "new": an isolated cow-<task>-<id> worktree, the default. Pass "inherit" to run in the parent session cwd with no worktree of its own, or {"path":"/absolute/checkout"} to run inside an existing worktree of this repository; that checkout is never removed by cleanup. Never pick a target the user did not ask for \u2014 omit the parameter to keep the default.',Hn=p.Object({prompt:p.String({description:_n}),task_name:p.String({description:Pn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:Mn})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:$n})),worktree:p.Optional(p.Union([p.Literal("new"),p.Literal("inherit"),p.Object({path:p.String({description:"Absolute path of an existing git worktree of this repository."})},{additionalProperties:!1}),p.Null()],{description:Nn}))},{additionalProperties:!1,required:["prompt","task_name"]}),O=p.Object({agents:p.Array(Hn,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Ie=Object.values(m),k={type:"json_schema",strict:"prefer"};var Ee="_configuredModel",Oe="_configuredThinking";function N(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(N,"readModelKey");function te(e){return N(e.thinking)??N(e[Oe])}r(te,"readThinkingRequest");function ne(e){let t=N(e.model);if(t)return{source:"call",key:t};let n=N(e[Ee]);if(n)return{source:"configured",key:n}}r(ne,"readModelRequest");function j(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(j,"withoutModel");function re(e){switch(e.kind){case"resolved":return{model:e.model,key:e.modelKey,thinking:e.thinking};case"foreign":return{harness:e.harness,key:e.modelKey,name:e.modelName,thinking:e.thinking};case"level":return{levelOnly:!0,thinking:e.thinking};case"none":return}}r(re,"modelChoiceFor");function U(e){return`${e.provider}/${e.id}`}r(U,"modelKey");function Dn(e,t){if(t!==void 0&&!me.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${me.options.join(", ")}); launching "${U(e)}" with "${t}".`}r(Dn,"undeclaredLevelWarning");function Ct(e,t){let n=Dn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Ct,"resolvedModel");function Bn(e){return`No API key found for "${e}"`}r(Bn,"missingCredential");function _t(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:$(o)}}return!Qe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Bn(t.provider)}}r(_t,"probeCredentials");function Ce(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ce,"refusal");function _e(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return j(i);let d=_t(n,o);if(d.verdict!=="unusable")return Ct(o,i);throw new Error(Ce(`The parent session's model "${U(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?he(e.key,n,void 0):he(e.key,n,o);if(!a){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return j(i)}let s=_t(n,a);if(s.verdict!=="unusable")return Ct(a,i);throw e.source==="call"?new Error(Ce(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Ce(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(_e,"resolvePiModel");async function Ln(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Ln,"harnessModels");function jn(e,t,n){if(t===void 0||t.thinkingLevels.kind!=="closed")return;let{levels:o}=t.thinkingLevels;if(!o.includes(n))return o.length===0?`Model "${t.key}" (${e}) does not support thinking levels; launching with "${n}".`:`Thinking level "${n}" is not declared by ${e} model "${t.key}" (supported: ${o.join(", ")}); proceeding with "${n}".`}r(jn,"undeclaredLevelWarning");async function Pt(e,t){if(!e)return j(t.thinking);let n=await Ln(t),o=n.find(a=>a.key===e.key),i=[];if(n.length>0&&!o&&i.push(`The ${t.harness} model list does not include "${e.key}"; launching with that key anyway.`),t.thinking!==void 0){let a=jn(t.harness,o,t.thinking);a!==void 0&&i.push(a)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(Pt,"resolveForeignModel");async function oe(e,t){let{harness:n}=t;if(Xe(n))return _e(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Pt(e,o)}r(oe,"resolveSpawnModel");function H(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(H,"resultWithSeverity");function se(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(se,"foldSeverity");var Pe=`
1
+ import{A as wt,B as vt,C as kt,D as z,J as V,K as bt,M as xt,N as At,O as Q,b as lt,c as ct,e as ut,g as pt,i as ht,k as be,l as gt,p as mt,u as ft,v as Y,w as yt}from"./chunk-PGSPPQKP.js";import{$ as rt,A as ze,Ba as at,Da as L,Ha as dt,K as ge,Ka as ke,M as et,N as me,Q as fe,R as tt,T as q,U as T,V as I,X as nt,aa as ot,b as ue,c as Be,k as B,ka as b,l as Le,la as F,m as je,ma as w,n as pe,oa as y,p as We,pa as E,qa as ye,ra as we,ta as st,u as qe,v as Fe,wa as ve,x as Ke,xa as K,y as Ge,ya as G,z as Ye,za as it}from"./chunk-F25VVC3O.js";import{J as Ze,K as Je,a as r,l as Ue,p as $,r as he,s as Ve,v as Qe,w as W,y as Xe}from"./chunk-CTAS2E47.js";import{visibleWidth as Te}from"@earendil-works/pi-tui";var xe="\u{1F920}",Rt="\u{1F404}",hn="\u{1F4A9}",gn=2,mn=1e3,X=Te(Rt),fn="76;175;80";function yn(e){return`\x1B[48;2;${fn}m${e}\x1B[49m`}r(yn,"greenBackground");function It(e){return e===0?0:Math.max(gn,Math.ceil(Math.sqrt(2*e)))}r(It,"pastureEdge");function Et(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Et,"emptyPasture");function wn(e,t){let n=It(e.cows+e.droppings),o=Et(n),i=Array.from({length:n*n},(s,d)=>d),a=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let s=0;s<a.length;s+=1){let d=s+Math.floor(t()*(i.length-s)),c=i[d];i[d]=i[s],i[s]=c,o[Math.floor(c/n)][c%n]=a[s]}return o}r(wn,"grazedPasture");function Z(e,t){let n=[];for(let o=0;o<e.length;o+=1)for(let i=0;i<e[o].length;i+=1)e[o][i]===t&&n.push({row:o,col:i});return n}r(Z,"cellsOf");function vn(e,t){return[{row:e.row-1,col:e.col},{row:e.row,col:e.col+1},{row:e.row+1,col:e.col},{row:e.row,col:e.col-1}].filter(({row:o,col:i})=>o>=0&&o<t&&i>=0&&i<t)}r(vn,"neighboursOf");function St(e,t){return vn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(St,"openNeighboursOf");function kn(e,t){let n=Z(e,"cow").filter(d=>St(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=St(o,e),a=i[Math.floor(t()*i.length)],s=e.map(d=>d.slice());return s[o.row][o.col]="empty",s[a.row][a.col]="cow",s}r(kn,"moveHerd");function Tt(e,t,n,o){for(let i=0;i<n;i+=1){let a=Z(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(Tt,"placeAtRandom");function bn(e,t,n,o){let i=Z(e,"cow"),a=Z(e,"dropping"),s=i.length-t,d=a.length-n;for(;s>0&&d<0;){let c=i.pop();e[c.row][c.col]="dropping",s-=1,d+=1}for(;s>0;){let c=i.pop();e[c.row][c.col]="empty",s-=1}for(;d>0;){let c=a.pop();e[c.row][c.col]="empty",d-=1}Tt(e,"cow",-s,o),Tt(e,"dropping",-d,o)}r(bn,"reconcileCounts");function xn(e,t,n){if(e===null)return wn(t,n);let o=It(t.cows+t.droppings),i=Et(o);for(let a=0;a<e.length&&a<o;a+=1)for(let s=0;s<e[a].length&&s<o;s+=1)i[a][s]=e[a][s];return bn(i,t.cows,t.droppings,n),i}r(xn,"reconcilePasture");var An={anchor:"top-right",width:Te(xe),get offsetX(){return E()?.cowboyOffsetX??0},nonCapturing:!0},Sn={anchor:"top-right",offsetY:1,get width(){return E()?.pastureWidth??0},nonCapturing:!0};function Tn(e){return e==="cow"?Rt:e==="dropping"?hn:" ".repeat(X)}r(Tn,"cellText");function Rn(e,t){return e.map(n=>t(n.map(Tn).join("")))}r(Rn,"drawnRows");function In(){return we().list(["spawned"]).length}r(In,"liveAgentCount");function En(){return we().list(tt).length}r(En,"endedAgentCount");function On(){return{live:In(),ended:En()}}r(On,"agentCounts");function Cn(){return y().agent.grazingEnabled}r(Cn,"grazingEnabled");var Ae=class{constructor(t,n,o,i,a){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=a}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return Te(xe)}get pastureWidth(){return this.drawnPasture().length*X}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*X-(t*X-this.cowboyWidth)}render(){return this.frame(),[xe]}pastureRows(){return this.frame(),Rn(this.drawnPasture(),this.grass)}invalidate(){}attachCowboy(t){this.cowboyHandle=t}attachPasture(t){this.pastureHandle=t}dispose(){let t=this.drawnPasture().length>0&&(this.cowboyHandle!==null||this.pastureHandle!==null);this.disposed=!0,this.poll!==null&&(clearInterval(this.poll),this.poll=null),this.cowboyHandle?.hide(),this.cowboyHandle=null,this.pastureHandle?.hide(),this.pastureHandle=null,t&&this.tui.requestRender(!0)}drawnPasture(){return this.herd===null||!this.isGrazing()?[]:this.herd.pasture}frame(){if(this.disposed)return;let t=this.isGrazing();this.herd===null?(this.herd=this.place(this.countAgents()),this.grazing=t):t!==this.grazing&&this.recount(),this.pollWhile(t)}pollWhile(t){!t&&this.poll!==null?(clearInterval(this.poll),this.poll=null):t&&this.poll===null&&(this.poll=setInterval(()=>this.recount(),mn))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,a=(this.grazing??o)&&(this.herd?.pasture.length??0)>0;if(this.herd===null||t!==this.herd.liveAgents||n!==this.herd.endedAgents)this.herd=this.place({live:t,ended:n});else if(o&&!i)this.herd={...this.herd,pasture:kn(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let s=a&&this.drawnPasture().length===0;this.tui.requestRender(s)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:xn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Se=class{static{r(this,"PastureView")}render(){return E()?.pastureRows()??[]}invalidate(){}};function Ot(e){Re(),e.custom(t=>{let n=new Ae(t,On,Cn,yn,Math.random);return ye(n),n},{overlay:!0,overlayOptions:An,onHandle:r(t=>E()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Se,{overlay:!0,overlayOptions:Sn,onHandle:r(t=>E()?.attachPasture(t),"onHandle")})}r(Ot,"showExtensionIndicator");function Re(){let e=E();ye(null),e?.dispose()}r(Re,"hideExtensionIndicator");function J(){return y().agent.extensionEnabled}r(J,"isExtensionEnabled");function _n(){return J()&&y().agent.showActiveIndicator}r(_n,"isActiveIndicatorShown");function ee(e){_n()?Ot(e):Re()}r(ee,"syncExtensionIndicator");function io(e,t){y().mutate.agent.setShowActiveIndicator(t),ee(e)}r(io,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as Ur}from"@earendil-works/pi-tui";import{Type as p}from"typebox";var Pn="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",Mn=`REQUIRED. Short 2-3 word task name (e.g. "fix login flow"). This single value names the agent's branch/tab/worktree/agent so you can recognize it at a glance, and the extension appends a unique spawn id so parallel spawns \u2014 and every entry in a batch \u2014 are always distinct. Limits: 3 words, 19 characters when slugged (lowercase, dashes). A longer name throws with the exact overshoot \u2014 retry with a shorter name. Missing name throws too. The same name twice in one call is rejected before anything spawns.`,$n=`Optional model for THIS agent as "provider/model-id". Omit it, or pass null, to leave it unset and use the configured default for this session and agent type \u2014 the usual case, and never a value to guess at. Pass it when the user asked for a specific model for this task. When a previous attempt failed with a provider/model error, pass a different model here and instruct the agent in plain text to continue where the failed attempt left off. A model that is not in this session's registry fails the call before anything is spawned.`,Nn=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${W.join(", ")}) and any harness a plugin registered in this session. Omit it, or pass null, to leave it unset and use the agent template's harness_type, then the configured default \u2014 never pass a harness the user did not ask for. A harness this session did not register, or this machine cannot launch, fails the call before anything is spawned \u2014 unlike the configured default, an explicit request never falls back to pi.`,Hn='Optional worktree for THIS agent. Omit it, or pass null, for "new": an isolated cow-<task>-<id> worktree, the default. Pass "inherit" to run in the parent session cwd with no worktree of its own, or {"path":"/absolute/checkout"} to run inside an existing worktree of this repository; that checkout is never removed by cleanup. Never pick a target the user did not ask for \u2014 omit the parameter to keep the default.',Dn=p.Object({prompt:p.String({description:Pn}),task_name:p.String({description:Mn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:$n})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:Nn})),worktree:p.Optional(p.Union([p.Literal("new"),p.Literal("inherit"),p.Object({path:p.String({description:"Absolute path of an existing git worktree of this repository."})},{additionalProperties:!1}),p.Null()],{description:Hn}))},{additionalProperties:!1,required:["prompt","task_name"]}),O=p.Object({agents:p.Array(Dn,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Ie=Object.values(m),k={type:"json_schema",strict:"prefer"};var Ee="_configuredModel",Oe="_configuredThinking";function N(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(N,"readModelKey");function te(e){return N(e.thinking)??N(e[Oe])}r(te,"readThinkingRequest");function ne(e){let t=N(e.model);if(t)return{source:"call",key:t};let n=N(e[Ee]);if(n)return{source:"configured",key:n}}r(ne,"readModelRequest");function j(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(j,"withoutModel");function re(e){switch(e.kind){case"resolved":return{model:e.model,key:e.modelKey,thinking:e.thinking};case"foreign":return{harness:e.harness,key:e.modelKey,name:e.modelName,thinking:e.thinking};case"level":return{levelOnly:!0,thinking:e.thinking};case"none":return}}r(re,"modelChoiceFor");function U(e){return`${e.provider}/${e.id}`}r(U,"modelKey");function Bn(e,t){if(t!==void 0&&!me.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${me.options.join(", ")}); launching "${U(e)}" with "${t}".`}r(Bn,"undeclaredLevelWarning");function Ct(e,t){let n=Bn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Ct,"resolvedModel");function Ln(e){return`No API key found for "${e}"`}r(Ln,"missingCredential");function _t(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:$(o)}}return!Ue(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Ln(t.provider)}}r(_t,"probeCredentials");function Ce(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ce,"refusal");function _e(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return j(i);let d=_t(n,o);if(d.verdict!=="unusable")return Ct(o,i);throw new Error(Ce(`The parent session's model "${U(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?he(e.key,n,void 0):he(e.key,n,o);if(!a){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return j(i)}let s=_t(n,a);if(s.verdict!=="unusable")return Ct(a,i);throw e.source==="call"?new Error(Ce(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Ce(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(_e,"resolvePiModel");async function jn(e){try{return await e.listModels(e.harness)}catch{return[]}}r(jn,"harnessModels");function Un(e,t,n){if(t===void 0||t.thinkingLevels.kind!=="closed")return;let{levels:o}=t.thinkingLevels;if(!o.includes(n))return o.length===0?`Model "${t.key}" (${e}) does not support thinking levels; launching with "${n}".`:`Thinking level "${n}" is not declared by ${e} model "${t.key}" (supported: ${o.join(", ")}); proceeding with "${n}".`}r(Un,"undeclaredLevelWarning");async function Pt(e,t){if(!e)return j(t.thinking);let n=await jn(t),o=n.find(a=>a.key===e.key),i=[];if(n.length>0&&!o&&i.push(`The ${t.harness} model list does not include "${e.key}"; launching with that key anyway.`),t.thinking!==void 0){let a=Un(t.harness,o,t.thinking);a!==void 0&&i.push(a)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(Pt,"resolveForeignModel");async function oe(e,t){let{harness:n}=t;if(Xe(n))return _e(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Pt(e,o)}r(oe,"resolveSpawnModel");function H(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(H,"resultWithSeverity");function se(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(se,"foldSeverity");var Pe=`
2
2
 
3
3
  ---
4
4
 
5
- `,Un={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function R(e){let{items:t}=e;qn(t,e),await e.prepare?.();let n=Wn(e),o=[],i=[],a=r(({outcome:d,text:c})=>{o.push(d),i.push(c)},"record"),s;for(let d of t){let c=n.halt;if(c!==void 0&&s!==void 0){a(c.skip(d,s));continue}let l=await n.handle(d);a(l),c!==void 0&&c.halts(l.outcome)&&(s=d)}return H(se(o.map(e.severity)),i.join(Pe),{[e.detailsKey]:o})}r(R,"runBatch");function Wn(e){if("render"in e){let n=e.render,o=e.halt;return{handle:r(async i=>{let a=await e.handleItem(i);return{outcome:a,text:n(a)}},"handle"),halt:o===void 0?void 0:{halts:r(i=>o.on(i),"halts"),skip:r((i,a)=>{let s=o.skip(i,a);return{outcome:s,text:n(s)}},"skip")}}}let t=e.halt;return{handle:e.handleItem,halt:t===void 0?void 0:{halts:r(n=>t.on(n),"halts"),skip:t.skip}}}r(Wn,"batchSteps");function qn(e,{toolName:t,param:n}){let o=e.map(s=>s.trim()),i=o.filter((s,d)=>o.indexOf(s)!==d);if(i.length===0)return;let a=Un[n];throw new Error(`${t} received duplicate ${a.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(qn,"rejectRepeatedKeys");var Mt={user:"STOPPED BY THE USER before completion \u2014 output is partial; the task was NOT finished",agent:"STOPPED BY YOU before completion \u2014 output is partial; the task was NOT finished"},Fn={user:"STOPPED BY THE USER before the agent started \u2014 the task was NOT attempted",agent:"STOPPED BY YOU before the agent started \u2014 the task was NOT attempted"};function Kn(e){if(!T(e)||e.status!=="stopped")return Mt.agent;let{stop:t}=e;return e.phase==="never-started"?Fn[t.initiator]:Mt[t.initiator]}r(Kn,"stopNote");function $t(e){return!T(e)||e.status!=="stopped"?"":` (${Kn(e)})`}r($t,"getStatusNote");async function Gn(e,t){let n=L();return n!==null?await n.list(e):await G().require(e).listModels({pi:b(),modelCatalog:it(t.modelRegistry)})}r(Gn,"readHarnessModelList");function ie(e){return async t=>{let n=await Gn(t,e),o=Je(n);return o!==void 0&&e.hasUI&&e.ui.notify(o,"warning"),Ze(n)}}r(ie,"harnessModelReader");function C(e=w()){let t=e.listAgents(fe).filter(n=>q(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(C,"formatActiveAgents");function Me(e,t){let n={type:e.display.type,description:e.display.description};e.display.taskSlug&&(n.taskSlug=e.display.taskSlug),e.display.worktree&&(n.worktreePath=e.display.worktree.path,n.worktreeBranch=e.display.worktree.branch),e.display.worktree?.kind==="owned"&&(n.worktreeManaged=!0);let o=e.execution.host;if(o&&(n.herdrAgent=o.name,n.herdrPane=o.paneId,n.herdrTab=o.tabId),t?.includeStatus&&(n.status=I(e.lifecycle)),t?.includeRunInfo){let i=T(e.lifecycle)?e.lifecycle.completedAt-nt(e.lifecycle):0;n.durationMs=i,n.modelName=e.display.invocation?.modelName,n.modelId=e.display.invocation?.modelName,n.thinkingLevel=e.display.invocation?.thinkingLevel}return n}r(Me,"buildAgentDetails");function Yn(e){if(!T(e))return{kind:"stopped"};switch(e.status){case"completed":return{kind:"completed",result:e.result};case"error":return{kind:"failed",error:e.error};case"stopped":return{kind:"stopped"};default:return Ve(e)}}r(Yn,"settledOutcome");function zn(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${I(e.lifecycle)}]`}r(zn,"settledHeadline");function Vn(e){let t=e.lifecycle,n=T(t)?t.worktreeRetentionReason:void 0,o=e.display.orchestration,i=e.display.worktree?.kind==="owned"?e.display.worktree:void 0;return z(o.cues,"settled",kt({outcome:Yn(t),statusNote:$t(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?mt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:y().multiplexer||et}))}r(Vn,"formatResultContent");async function Qn(e,t){let n=qe(e);if(n.kind!=="picked")return n;let o=ue(n.path),a=(o===void 0?null:await ht(b(),t.cwd))?.find(s=>ue(s.path)===o);if(a===void 0)throw new Error(`Worktree "${n.path}" is not an existing checkout of this repository \u2014 nothing was spawned. Pass an absolute path from \`git worktree list\`, or "new"/"inherit".`);return{kind:"picked",path:a.path,branch:We(a)}}r(Qn,"resolveWorktreeRequest");var $e=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=V(t.agent_type),a=t.prompt,s=typeof t.task_name=="string"?t.task_name.trim():"";if(!s)throw new Error('cowboy_agent requires a short 2-3 word task name (e.g. "fix login flow") via the `task_name` parameter \u2014 it names the agent\'s branch/tab/worktree/agent so you can recognize it at a glance.');let d=Fe(s),c=bt(),l=await ft(i,void 0,(S,le)=>{n.ui.notify(S,le)});if(l.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${i}. Candidates: ${l.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(l.kind==="not-found")throw new Error(`Unknown agent type: ${i} \u2014 nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);let v=At(t.harness_type),g=Q(l.key,v),u=te(t),h=await oe(ne(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:u,listModels:ie(n)});for(let S of h.notices)n.ui.notify(S,"warning");let f=await Qn(t.worktree,n),A=t.run_in_background!==!1;return new e({ctx:n,toolCallId:o,taskSlug:d,prompt:a,description:a.split(`
6
- `)[0].slice(0,80)||a.slice(0,80),agentType:i,resolvedType:l.key,orchestrator:c,fork:Y(i)?.fork??!1,modelChoice:re(h.resolved),requestedHarness:v,worktree:f,isBackground:A})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:a}=this.intent,s=b(),d=w().mintSpawnId(),c=await this.resolveWorktree(s,d),l=this.intent.modelChoice?.thinking??void 0,v=ze(this.intent.modelChoice),{agentId:g,spawn:u}=await st().spawn(n,{spawnId:d,type:a,prompt:this.intent.prompt,description:this.intent.description,taskSlug:i,orchestration:this.intent.orchestrator,modelChoice:this.intent.modelChoice,requestedHarness:this.intent.requestedHarness,fork:this.intent.fork,worktree:c,invocation:{modelName:v,thinkingLevel:l,fork:this.intent.fork},runInBackground:o,signal:o?void 0:t});if(this.intent.toolCallId&&(u.display.toolCallId=this.intent.toolCallId),!o){let S=Me(u,{includeRunInfo:!0,includeStatus:!0});if(S.agentId=g,T(u.lifecycle)&&u.lifecycle.status==="error")throw new Error(`agent ${g} stopped with an error: ${u.lifecycle.error||"no error message was recorded"}`);return{message:`${zn(u)}
5
+ `,Wn={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function R(e){let{items:t}=e;Fn(t,e),await e.prepare?.();let n=qn(e),o=[],i=[],a=r(({outcome:d,text:c})=>{o.push(d),i.push(c)},"record"),s;for(let d of t){let c=n.halt;if(c!==void 0&&s!==void 0){a(c.skip(d,s));continue}let l=await n.handle(d);a(l),c!==void 0&&c.halts(l.outcome)&&(s=d)}return H(se(o.map(e.severity)),i.join(Pe),{[e.detailsKey]:o})}r(R,"runBatch");function qn(e){if("render"in e){let n=e.render,o=e.halt;return{handle:r(async i=>{let a=await e.handleItem(i);return{outcome:a,text:n(a)}},"handle"),halt:o===void 0?void 0:{halts:r(i=>o.on(i),"halts"),skip:r((i,a)=>{let s=o.skip(i,a);return{outcome:s,text:n(s)}},"skip")}}}let t=e.halt;return{handle:e.handleItem,halt:t===void 0?void 0:{halts:r(n=>t.on(n),"halts"),skip:t.skip}}}r(qn,"batchSteps");function Fn(e,{toolName:t,param:n}){let o=e.map(s=>s.trim()),i=o.filter((s,d)=>o.indexOf(s)!==d);if(i.length===0)return;let a=Wn[n];throw new Error(`${t} received duplicate ${a.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(Fn,"rejectRepeatedKeys");var Mt={user:"STOPPED BY THE USER before completion \u2014 output is partial; the task was NOT finished",agent:"STOPPED BY YOU before completion \u2014 output is partial; the task was NOT finished"},Kn={user:"STOPPED BY THE USER before the agent started \u2014 the task was NOT attempted",agent:"STOPPED BY YOU before the agent started \u2014 the task was NOT attempted"};function Gn(e){if(!T(e)||e.status!=="stopped")return Mt.agent;let{stop:t}=e;return e.phase==="never-started"?Kn[t.initiator]:Mt[t.initiator]}r(Gn,"stopNote");function $t(e){return!T(e)||e.status!=="stopped"?"":` (${Gn(e)})`}r($t,"getStatusNote");async function Yn(e,t){let n=L();return n!==null?await n.list(e):await G().require(e).listModels({pi:b(),modelCatalog:it(t.modelRegistry)})}r(Yn,"readHarnessModelList");function ie(e){return async t=>{let n=await Yn(t,e),o=Je(n);return o!==void 0&&e.hasUI&&e.ui.notify(o,"warning"),Ze(n)}}r(ie,"harnessModelReader");function C(e=w()){let t=e.listAgents(fe).filter(n=>q(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(C,"formatActiveAgents");function Me(e,t){let n={type:e.display.type,description:e.display.description};e.display.taskSlug&&(n.taskSlug=e.display.taskSlug),e.display.worktree&&(n.worktreePath=e.display.worktree.path,n.worktreeBranch=e.display.worktree.branch),e.display.worktree?.kind==="owned"&&(n.worktreeManaged=!0);let o=e.execution.host;if(o&&(n.herdrAgent=o.name,n.herdrPane=o.paneId,n.herdrTab=o.tabId),t?.includeStatus&&(n.status=I(e.lifecycle)),t?.includeRunInfo){let i=T(e.lifecycle)?e.lifecycle.completedAt-nt(e.lifecycle):0;n.durationMs=i,n.modelName=e.display.invocation?.modelName,n.modelId=e.display.invocation?.modelName,n.thinkingLevel=e.display.invocation?.thinkingLevel}return n}r(Me,"buildAgentDetails");function zn(e){if(!T(e))return{kind:"stopped"};switch(e.status){case"completed":return{kind:"completed",result:e.result};case"error":return{kind:"failed",error:e.error};case"stopped":return{kind:"stopped"};default:return Qe(e)}}r(zn,"settledOutcome");function Vn(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${I(e.lifecycle)}]`}r(Vn,"settledHeadline");function Qn(e){let t=e.lifecycle,n=T(t)?t.worktreeRetentionReason:void 0,o=e.display.orchestration,i=e.display.worktree?.kind==="owned"?e.display.worktree:void 0;return z(o.cues,"settled",kt({outcome:zn(t),statusNote:$t(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?mt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:y().multiplexer||et}))}r(Qn,"formatResultContent");async function Xn(e,t){let n=Fe(e);if(n.kind!=="picked")return n;let o=ue(n.path),a=(o===void 0?null:await ht(b(),t.cwd))?.find(s=>ue(s.path)===o);if(a===void 0)throw new Error(`Worktree "${n.path}" is not an existing checkout of this repository \u2014 nothing was spawned. Pass an absolute path from \`git worktree list\`, or "new"/"inherit".`);return{kind:"picked",path:a.path,branch:qe(a)}}r(Xn,"resolveWorktreeRequest");var $e=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=V(t.agent_type),a=t.prompt,s=typeof t.task_name=="string"?t.task_name.trim():"";if(!s)throw new Error('cowboy_agent requires a short 2-3 word task name (e.g. "fix login flow") via the `task_name` parameter \u2014 it names the agent\'s branch/tab/worktree/agent so you can recognize it at a glance.');let d=Ke(s),c=bt(),l=await ft(i,void 0,(S,le)=>{n.ui.notify(S,le)});if(l.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${i}. Candidates: ${l.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(l.kind==="not-found")throw new Error(`Unknown agent type: ${i} \u2014 nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);let v=At(t.harness_type),g=Q(l.key,v),u=te(t),h=await oe(ne(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:u,listModels:ie(n)});for(let S of h.notices)n.ui.notify(S,"warning");let f=await Xn(t.worktree,n),A=t.run_in_background!==!1;return new e({ctx:n,toolCallId:o,taskSlug:d,prompt:a,description:a.split(`
6
+ `)[0].slice(0,80)||a.slice(0,80),agentType:i,resolvedType:l.key,orchestrator:c,fork:Y(i)?.fork??!1,modelChoice:re(h.resolved),requestedHarness:v,worktree:f,isBackground:A})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:a}=this.intent,s=b(),d=w().mintSpawnId(),c=await this.resolveWorktree(s,d),l=this.intent.modelChoice?.thinking??void 0,v=Ve(this.intent.modelChoice),{agentId:g,spawn:u}=await st().spawn(n,{spawnId:d,type:a,prompt:this.intent.prompt,description:this.intent.description,taskSlug:i,orchestration:this.intent.orchestrator,modelChoice:this.intent.modelChoice,requestedHarness:this.intent.requestedHarness,fork:this.intent.fork,worktree:c,invocation:{modelName:v,thinkingLevel:l,fork:this.intent.fork},runInBackground:o,signal:o?void 0:t});if(this.intent.toolCallId&&(u.display.toolCallId=this.intent.toolCallId),!o){let S=Me(u,{includeRunInfo:!0,includeStatus:!0});if(S.agentId=g,T(u.lifecycle)&&u.lifecycle.status==="error")throw new Error(`agent ${g} stopped with an error: ${u.lifecycle.error||"no error message was recorded"}`);return{message:`${Vn(u)}
7
7
 
8
- ${Vn(u)}`,details:S}}let h=c;if(u.lifecycle.phase==="queued"){let S=w().listAgents(fe).filter(un=>un.lifecycle.phase==="spawned").length,le=z(this.intent.orchestrator.cues,"queued",vt({agentId:g,worktree:h,queueRunning:S})),ce=Me(u);return ce.agentId=g,ce.status="queued",{message:`[Agent queued] ${le}`,details:ce}}let f=z(this.intent.orchestrator.cues,"spawned",wt({agentId:g,worktree:h})),A=Me(u);return A.agentId=g,A.status="spawned",{message:`[Agent spawned] ${f}`,details:A}}async resolveWorktree(t,n){let o=this.intent.worktree;switch(o.kind){case"inherit":return;case"picked":return o;case"new":return this.expectedWorktree(t,n)}}async expectedWorktree(t,n){let o=await pt(t,F().cwd).catch(()=>{});if(o===void 0)return;let i=Ye(y().agent.worktreeRoot,o);return{kind:"owned",path:Ge(i,this.intent.taskSlug,n),branch:Ke(this.intent.taskSlug,n)}}};async function Nt(e,t,n,o){if(e.agents.length>1&&e.run_in_background===!1)throw new Error("run_in_background: false requires exactly one agent");let i=e.agents.map(l=>({...l,run_in_background:e.run_in_background})),a=await Promise.all(i.map(l=>$e.parse(l,t,n)));Xn(a);let s=await Promise.all(a.map(l=>l.run(o))),d=s.map(l=>l.message).join(Pe),c={agents:s.map(l=>l.details)};return{message:d,details:c}}r(Nt,"runDelegationBatch");function Xn(e){let t=e.map(o=>o.intent.taskSlug),n=t.filter((o,i)=>t.indexOf(o)!==i);if(n.length!==0)throw new Error(`cowboy_agent received the same task_name more than once: ${[...new Set(n)].join(", ")} \u2014 nothing was spawned. Give every item in \`agents\` its own task_name.`)}r(Xn,"rejectRepeatedTaskSlugs");import{Type as Ne}from"typebox";var Zn="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Ht=Ne.Object({agent_ids:Ne.Array(Ne.String({minLength:1}),{minItems:1,description:Zn})},{additionalProperties:!1,required:["agent_ids"]});function Jn(e){let t=Array.isArray(e.agents)?e.agents:[];return se(t.map(n=>typeof n=="object"&&n!==null&&n.status==="stopped"?"warning":"success"))}r(Jn,"delegationSeverity");async function Dt(e,t,n,o,i){let{message:a,details:s}=await Nt(t,i,e,n);return H(Jn(s),a,s)}r(Dt,"executeAgentTool");var Bt={name:m.stopAgent,label:m.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping sends the agent's harness its own exit keys (its pane is left in place) and settles the agent as stopped once the process is confirmed gone. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Ht,execute:nr,constrainedSampling:k};function er(e){switch(e.kind){case"stopped":return"success";case"failed":return"error";case"already-settled":case"unknown":case"refused":return"warning"}}r(er,"stopSeverity");function tr(e){switch(e.kind){case"stopped":return`Stopped agent ${e.agentId}`;case"already-settled":return`Agent ${e.agentId} is already ${e.status}. Active agents: ${e.activeAgents}`;case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`;case"refused":return`Agent ${e.agentId} was not stopped: ${e.reason}`;case"failed":return`Failed to stop agent ${e.agentId}: ${e.error}`}}r(tr,"renderStopOutcome");async function nr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:tr,severity:er,handleItem:r(async s=>{let d=w().getSpawn(s);if(!d)return{kind:"unknown",agentId:s,activeAgents:C()};if(w().isHandingOver(s))return{kind:"refused",agentId:s,reason:"it is being handed over to another harness \u2014 wait for the handover to finish, then stop the new run if you still want it stopped."};if(!q(d.lifecycle.phase))return{kind:"already-settled",agentId:s,status:I(d.lifecycle),activeAgents:C()};try{return await w().abort(s,"agent")?{kind:"stopped",agentId:s}:{kind:"failed",agentId:s,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:s,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}r(nr,"executeStopAgentTool");async function ws(e,t){if(e.toolName!=="cowboy_agent")return;let o=e.input.agents??[],i=t.model?`${t.model.provider}/${t.model.id}`:null;for(let a of o){let s=a.agent_type,d=V(s),c=Y(d),l=xt(a.harness_type),v=Q(d,l),g=N(a.model),u=g??y().modelFor(d,i,c,v);if(u&&!g&&(a[Ee]=u),a.thinking===void 0){let h=y().thinkingFor(d,c,v,t.thinkingLevel);h!==void 0&&(a[Oe]=h)}}}r(ws,"toolCallListener");import{Type as He}from"typebox";var rr="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",Lt=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:rr})},{additionalProperties:!1,required:["agent_ids"]});function jt(e){switch(e.kind){case"pane-absent":return"pane-absent";case"pane-not-working":return`pane-not-working: ${e.state}`;case"forced":return"forced";case"pane-working":return"pane-working";case"pane-unreadable":return`pane-unreadable: ${e.detail}`;case"artifacts-ambiguous":return"artifacts-ambiguous"}}r(jt,"formatBasis");function or(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${jt(e.basis)})`}r(or,"formatSettlement");function Ut(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`;case"agent-active":return`the agent is still ${e.phase} and has not reported a result \u2014 stop it with stop_cowboy_agent, then clean up`;case"recovered-refusal":return`no settlement was recorded and herdr still reports the agent at work (${jt(e.basis)}) \u2014 stop it before retrying`;case"ambiguous-artifacts":return`two artifacts answer to this id (${e.candidates.join(", ")}) \u2014 nothing was removed; work out which run owns the id before removing either by hand`}}r(Ut,"formatKeptReason");function sr(e){switch(e.kind){case"closed":return"closed";case"open":return"open";case"gone":return"gone (herdr has no such pane)";case"unknown":return"unknown (the pane was not read)"}}r(sr,"paneText");function ir(e){return e.length===0?"none (the agent never had a pane)":e.map(t=>`${t.paneId} ${sr(t)}`).join(", ")}r(ir,"panesText");function ar(e){switch(e.kind){case"closed":return"pane closed";case"open":return"pane left open";case"gone":return"pane already gone";case"unknown":return"pane state unknown"}}r(ar,"paneSummary");function dr(e){if(e.length===0)return"no pane";if(e.length===1)return ar(e[0]);let t=new Map;for(let o of e)t.set(o.kind,(t.get(o.kind)??0)+1);let n=[...t].map(([o,i])=>`${i} ${o}`).join(", ");return`${e.length} panes (${n})`}r(dr,"panesSummary");function Wt(e){switch(e.kind){case"removed":return`removed (${e.path})`;case"removal-failed":return`NOT removed \u2014 ${e.detail} (${e.path})`;case"kept":return`kept${e.path?` (${e.path})`:" (worktree path not recorded)"}`;case"absent":return`already gone (${e.path})`;case"none":return"none (agent ran without a worktree)"}}r(Wt,"worktreeText");function qt(e){let t=e.branch;return`${t.kind==="deleted"?"deleted":t.kind==="kept"?`kept (${t.reason})`:t.kind==="delete-failed"?`NOT deleted \u2014 ${t.detail}`:"not applicable"}${e.branchName?` (${e.branchName})`:""}`}r(qt,"branchText");function lr(e){return e?` forced${e.reason?` \u2014 ${Ut(e.reason)}`:""}`:""}r(lr,"forcedClause");function De(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Ut(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${lr(e.outcome.forced)}:`}r(De,"headline");function Ft(e){let t=[De(e),` agent status: ${or(e.settlement)}`,` panes: ${ir(e.panes)}`,` worktree: ${Wt(e.worktree)}`,` branch: ${qt(e)}`];if(e.source==="recovered"&&t.push(" recovered: no spawn record survived \u2014 this verdict rests on discovery (herdr's live read plus the worktree on disk)"),e.settlement.kind==="discovered"){let{path:n,present:o}=e.settlement.deliverable;t.push(o?` deliverable: UNREAD at ${n} \u2014 read it before deleting the directory`:` deliverable: none written (${n} does not exist)`)}return t.join(`
9
- `)}r(Ft,"renderCleanupReport");function As(e){let t=dr(e.panes);return e.outcome.kind==="refused"?`${De(e)} ${t}`:`${De(e)} ${t}, worktree ${Wt(e.worktree)}, branch ${qt(e)}`}r(As,"summarizeCleanupReport");function Ss(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Ss,"cleanupNeedsAttention");var Kt={name:m.cleanupAgent,label:m.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:Lt,execute:pr,constrainedSampling:k};function cr(e){return e.kind==="unknown"?"warning":e.report.outcome.kind==="torn-down"?"success":"warning"}r(cr,"cleanupSeverity");function ur(e){switch(e.kind){case"cleaned":return Ft(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(ur,"renderCleanupOutcome");async function pr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:ur,severity:cr,handleItem:r(async s=>{let d=w();if(!d.getSpawn(s)&&(await d.locate(s)).kind==="not-found")return{kind:"unknown",agentId:s,activeAgents:C(d)};let c=await d.cleanup(s);return{kind:"cleaned",agentId:s,report:c}},"handleItem")})}r(pr,"executeCleanupAgentTool");import*as zt from"node:fs";import*as D from"node:path";import{Type as _}from"typebox";var hr="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",gr="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",mr="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",Gt=_.Object({branches:_.Array(_.String({minLength:1}),{minItems:1,description:hr}),target:_.Optional(_.String({description:gr})),repo:_.Optional(_.String({description:mr}))},{additionalProperties:!1,required:["branches"]});function Yt(e){let t=D.normalize(e),{root:n}=D.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Yt,"normalizeRepoRoot");function fr(e,t){return Yt(e)===Yt(t)}r(fr,"isSameRepoRoot");function yr(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(yr,"formatOutsideRepoWarning");async function wr(e,t){let n=new ct(e),o=await n.probe(["rev-parse","--show-toplevel"],t);if(o===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: ${t} is not inside a git repository (git rev-parse --show-toplevel failed). Refusing to merge without a repo-scope check \u2014 run the session from inside a git checkout or pass an explicit \`repo\` inside one.`);let i=await n.probe(["rev-parse","--git-common-dir"],o);if(i===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: could not resolve the git directory for ${t}. Refusing to merge without a repo-scope check.`);let{mainRoot:a}=ut(i,o);if(!zt.existsSync(D.join(a,".git")))throw new Error(`merge_cowboy_branch cannot verify the session repo: no main checkout found for ${t} (unsupported repo layout). Refusing to merge without a repo-scope check.`);return a}r(wr,"resolveSessionMainRoot");var Vt={name:m.mergeBranch,label:m.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:Gt,execute:Sr,constrainedSampling:k};function vr(e){switch(e.kind){case"merged":return"success";case"already-merged":case"unknown":case"not-attempted":return"warning";case"conflict":case"failed":return"error"}}r(vr,"mergeSeverity");var kr="has conflicts in:";function br(e){return e.includes(kr)}r(br,"isConflictError");function xr(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
10
- `).map(n=>n.trim()).filter(n=>n!==""):[]}r(xr,"parseConflictFiles");function Ar(e,t){return e.includes(`branch "${t}" does not exist`)}r(Ar,"isUnknownBranchError");async function Sr(e,t,n,o,i){let a=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",s=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,d,c=r(()=>(d??=(async()=>{let l=F().cwd;if(typeof l!="string"||l.trim()==="")throw new Error("merge_cowboy_branch cannot verify the session repo: the session working directory is unavailable, so the repo-scope check is impossible. Refusing to merge without a repo-scope check.");return{sessionRoot:await wr(b(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:vr,prepare:r(async()=>{be(a,"target");for(let l of t.branches)be(l.trim(),"branch");await c()},"prepare"),halt:{on:r(l=>l.kind==="conflict","on"),skip:r((l,v)=>{let g=l.trim(),u=`not attempted \u2014 the merge of "${v.trim()}" conflicted and is still in progress`;return{outcome:{kind:"not-attempted",branch:g,reason:u},text:`"${g}" ${u}.`}},"skip")},handleItem:r(async l=>{let{sessionRoot:v,cwd:g}=await c(),u=l.trim();try{let h=await gt(b(),{cwd:g,branch:u,target:a}),f=fr(h.mainRoot,v)?void 0:yr(h.mainRoot,v);if(f!==void 0)try{i.ui.notify(f,"warning")}catch{}let A=f!==void 0?`${f}
8
+ ${Qn(u)}`,details:S}}let h=c;if(u.lifecycle.phase==="queued"){let S=w().listAgents(fe).filter(pn=>pn.lifecycle.phase==="spawned").length,le=z(this.intent.orchestrator.cues,"queued",vt({agentId:g,worktree:h,queueRunning:S})),ce=Me(u);return ce.agentId=g,ce.status="queued",{message:`[Agent queued] ${le}`,details:ce}}let f=z(this.intent.orchestrator.cues,"spawned",wt({agentId:g,worktree:h})),A=Me(u);return A.agentId=g,A.status="spawned",{message:`[Agent spawned] ${f}`,details:A}}async resolveWorktree(t,n){let o=this.intent.worktree;switch(o.kind){case"inherit":return;case"picked":return o;case"new":return this.expectedWorktree(t,n)}}async expectedWorktree(t,n){let o=await pt(t,F().cwd).catch(()=>{});if(o===void 0)return;let i=ze(y().agent.worktreeRoot,o);return{kind:"owned",path:Ye(i,this.intent.taskSlug,n),branch:Ge(this.intent.taskSlug,n)}}};async function Nt(e,t,n,o){if(e.agents.length>1&&e.run_in_background===!1)throw new Error("run_in_background: false requires exactly one agent");let i=e.agents.map(l=>({...l,run_in_background:e.run_in_background})),a=await Promise.all(i.map(l=>$e.parse(l,t,n)));Zn(a);let s=await Promise.all(a.map(l=>l.run(o))),d=s.map(l=>l.message).join(Pe),c={agents:s.map(l=>l.details)};return{message:d,details:c}}r(Nt,"runDelegationBatch");function Zn(e){let t=e.map(o=>o.intent.taskSlug),n=t.filter((o,i)=>t.indexOf(o)!==i);if(n.length!==0)throw new Error(`cowboy_agent received the same task_name more than once: ${[...new Set(n)].join(", ")} \u2014 nothing was spawned. Give every item in \`agents\` its own task_name.`)}r(Zn,"rejectRepeatedTaskSlugs");import{Type as Ne}from"typebox";var Jn="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Ht=Ne.Object({agent_ids:Ne.Array(Ne.String({minLength:1}),{minItems:1,description:Jn})},{additionalProperties:!1,required:["agent_ids"]});function er(e){let t=Array.isArray(e.agents)?e.agents:[];return se(t.map(n=>typeof n=="object"&&n!==null&&n.status==="stopped"?"warning":"success"))}r(er,"delegationSeverity");async function Dt(e,t,n,o,i){let{message:a,details:s}=await Nt(t,i,e,n);return H(er(s),a,s)}r(Dt,"executeAgentTool");var Bt={name:m.stopAgent,label:m.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping sends the agent's harness its own exit keys (its pane is left in place) and settles the agent as stopped once the process is confirmed gone. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Ht,execute:rr,constrainedSampling:k};function tr(e){switch(e.kind){case"stopped":return"success";case"failed":return"error";case"already-settled":case"unknown":case"refused":return"warning"}}r(tr,"stopSeverity");function nr(e){switch(e.kind){case"stopped":return`Stopped agent ${e.agentId}`;case"already-settled":return`Agent ${e.agentId} is already ${e.status}. Active agents: ${e.activeAgents}`;case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`;case"refused":return`Agent ${e.agentId} was not stopped: ${e.reason}`;case"failed":return`Failed to stop agent ${e.agentId}: ${e.error}`}}r(nr,"renderStopOutcome");async function rr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:nr,severity:tr,handleItem:r(async s=>{let d=w().getSpawn(s);if(!d)return{kind:"unknown",agentId:s,activeAgents:C()};if(w().isHandingOver(s))return{kind:"refused",agentId:s,reason:"it is being handed over to another harness \u2014 wait for the handover to finish, then stop the new run if you still want it stopped."};if(!q(d.lifecycle.phase))return{kind:"already-settled",agentId:s,status:I(d.lifecycle),activeAgents:C()};try{return await w().abort(s,"agent")?{kind:"stopped",agentId:s}:{kind:"failed",agentId:s,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:s,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}r(rr,"executeStopAgentTool");async function vs(e,t){if(e.toolName!=="cowboy_agent")return;let o=e.input.agents??[],i=t.model?`${t.model.provider}/${t.model.id}`:null;for(let a of o){let s=a.agent_type,d=V(s),c=Y(d),l=xt(a.harness_type),v=Q(d,l),g=N(a.model),u=g??y().modelFor(d,i,c,v);if(u&&!g&&(a[Ee]=u),a.thinking===void 0){let h=y().thinkingFor(d,c,v,t.thinkingLevel);h!==void 0&&(a[Oe]=h)}}}r(vs,"toolCallListener");import{Type as He}from"typebox";var or="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",Lt=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:or})},{additionalProperties:!1,required:["agent_ids"]});function jt(e){switch(e.kind){case"pane-absent":return"pane-absent";case"pane-not-working":return`pane-not-working: ${e.state}`;case"forced":return"forced";case"pane-working":return"pane-working";case"pane-unreadable":return`pane-unreadable: ${e.detail}`;case"artifacts-ambiguous":return"artifacts-ambiguous"}}r(jt,"formatBasis");function sr(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${jt(e.basis)})`}r(sr,"formatSettlement");function Ut(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`;case"agent-active":return`the agent is still ${e.phase} and has not reported a result \u2014 stop it with stop_cowboy_agent, then clean up`;case"recovered-refusal":return`no settlement was recorded and herdr still reports the agent at work (${jt(e.basis)}) \u2014 stop it before retrying`;case"ambiguous-artifacts":return`two artifacts answer to this id (${e.candidates.join(", ")}) \u2014 nothing was removed; work out which run owns the id before removing either by hand`;case"space-in-use":return`its workspace is still in use by ${e.tenants.join(", ")} \u2014 the checkout is removed when the last agent there has been cleaned up`}}r(Ut,"formatKeptReason");function ir(e){switch(e.kind){case"closed":return"closed";case"open":return"open";case"gone":return"gone (herdr has no such pane)";case"unknown":return"unknown (the pane was not read)"}}r(ir,"paneText");function ar(e){return e.length===0?"none (the agent never had a pane)":e.map(t=>`${t.paneId} ${ir(t)}`).join(", ")}r(ar,"panesText");function dr(e){switch(e.kind){case"closed":return"pane closed";case"open":return"pane left open";case"gone":return"pane already gone";case"unknown":return"pane state unknown"}}r(dr,"paneSummary");function lr(e){if(e.length===0)return"no pane";if(e.length===1)return dr(e[0]);let t=new Map;for(let o of e)t.set(o.kind,(t.get(o.kind)??0)+1);let n=[...t].map(([o,i])=>`${i} ${o}`).join(", ");return`${e.length} panes (${n})`}r(lr,"panesSummary");function Wt(e){switch(e.kind){case"removed":return`removed (${e.path})`;case"removal-failed":return`NOT removed \u2014 ${e.detail} (${e.path})`;case"kept":return`kept${e.path?` (${e.path})`:" (worktree path not recorded)"}`;case"absent":return`already gone (${e.path})`;case"none":return"none (agent ran without a worktree)"}}r(Wt,"worktreeText");function qt(e){let t=e.branch;return`${t.kind==="deleted"?"deleted":t.kind==="kept"?`kept (${t.reason})`:t.kind==="delete-failed"?`NOT deleted \u2014 ${t.detail}`:"not applicable"}${e.branchName?` (${e.branchName})`:""}`}r(qt,"branchText");function cr(e){return e?` forced${e.reason?` \u2014 ${Ut(e.reason)}`:""}`:""}r(cr,"forcedClause");function De(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Ut(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${cr(e.outcome.forced)}:`}r(De,"headline");function Ft(e){let t=[De(e),` agent status: ${sr(e.settlement)}`,` panes: ${ar(e.panes)}`,` worktree: ${Wt(e.worktree)}`,` branch: ${qt(e)}`];if(e.source==="recovered"&&t.push(" recovered: no spawn record survived \u2014 this verdict rests on discovery (herdr's live read plus the worktree on disk)"),e.settlement.kind==="discovered"){let{path:n,present:o}=e.settlement.deliverable;t.push(o?` deliverable: UNREAD at ${n} \u2014 read it before deleting the directory`:` deliverable: none written (${n} does not exist)`)}return t.join(`
9
+ `)}r(Ft,"renderCleanupReport");function Ss(e){let t=lr(e.panes);return e.outcome.kind==="refused"?`${De(e)} ${t}`:`${De(e)} ${t}, worktree ${Wt(e.worktree)}, branch ${qt(e)}`}r(Ss,"summarizeCleanupReport");function Ts(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Ts,"cleanupNeedsAttention");var Kt={name:m.cleanupAgent,label:m.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:Lt,execute:hr,constrainedSampling:k};function ur(e){return e.kind==="unknown"?"warning":e.report.outcome.kind==="torn-down"?"success":"warning"}r(ur,"cleanupSeverity");function pr(e){switch(e.kind){case"cleaned":return Ft(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(pr,"renderCleanupOutcome");async function hr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:pr,severity:ur,handleItem:r(async s=>{let d=w();if(!d.getSpawn(s)&&(await d.locate(s)).kind==="not-found")return{kind:"unknown",agentId:s,activeAgents:C(d)};let c=await d.cleanup(s);return{kind:"cleaned",agentId:s,report:c}},"handleItem")})}r(hr,"executeCleanupAgentTool");import*as zt from"node:fs";import*as D from"node:path";import{Type as _}from"typebox";var gr="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",mr="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",fr="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",Gt=_.Object({branches:_.Array(_.String({minLength:1}),{minItems:1,description:gr}),target:_.Optional(_.String({description:mr})),repo:_.Optional(_.String({description:fr}))},{additionalProperties:!1,required:["branches"]});function Yt(e){let t=D.normalize(e),{root:n}=D.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Yt,"normalizeRepoRoot");function yr(e,t){return Yt(e)===Yt(t)}r(yr,"isSameRepoRoot");function wr(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(wr,"formatOutsideRepoWarning");async function vr(e,t){let n=new ct(e),o=await n.probe(["rev-parse","--show-toplevel"],t);if(o===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: ${t} is not inside a git repository (git rev-parse --show-toplevel failed). Refusing to merge without a repo-scope check \u2014 run the session from inside a git checkout or pass an explicit \`repo\` inside one.`);let i=await n.probe(["rev-parse","--git-common-dir"],o);if(i===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: could not resolve the git directory for ${t}. Refusing to merge without a repo-scope check.`);let{mainRoot:a}=ut(i,o);if(!zt.existsSync(D.join(a,".git")))throw new Error(`merge_cowboy_branch cannot verify the session repo: no main checkout found for ${t} (unsupported repo layout). Refusing to merge without a repo-scope check.`);return a}r(vr,"resolveSessionMainRoot");var Vt={name:m.mergeBranch,label:m.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:Gt,execute:Tr,constrainedSampling:k};function kr(e){switch(e.kind){case"merged":return"success";case"already-merged":case"unknown":case"not-attempted":return"warning";case"conflict":case"failed":return"error"}}r(kr,"mergeSeverity");var br="has conflicts in:";function xr(e){return e.includes(br)}r(xr,"isConflictError");function Ar(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
10
+ `).map(n=>n.trim()).filter(n=>n!==""):[]}r(Ar,"parseConflictFiles");function Sr(e,t){return e.includes(`branch "${t}" does not exist`)}r(Sr,"isUnknownBranchError");async function Tr(e,t,n,o,i){let a=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",s=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,d,c=r(()=>(d??=(async()=>{let l=F().cwd;if(typeof l!="string"||l.trim()==="")throw new Error("merge_cowboy_branch cannot verify the session repo: the session working directory is unavailable, so the repo-scope check is impossible. Refusing to merge without a repo-scope check.");return{sessionRoot:await vr(b(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:kr,prepare:r(async()=>{be(a,"target");for(let l of t.branches)be(l.trim(),"branch");await c()},"prepare"),halt:{on:r(l=>l.kind==="conflict","on"),skip:r((l,v)=>{let g=l.trim(),u=`not attempted \u2014 the merge of "${v.trim()}" conflicted and is still in progress`;return{outcome:{kind:"not-attempted",branch:g,reason:u},text:`"${g}" ${u}.`}},"skip")},handleItem:r(async l=>{let{sessionRoot:v,cwd:g}=await c(),u=l.trim();try{let h=await gt(b(),{cwd:g,branch:u,target:a}),f=yr(h.mainRoot,v)?void 0:wr(h.mainRoot,v);if(f!==void 0)try{i.ui.notify(f,"warning")}catch{}let A=f!==void 0?`${f}
11
11
  `:"";return h.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${A}"${u}" is already merged into "${h.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:h.target,output:h.output},text:`${A}Merged "${u}" into "${h.target}" in ${h.mainRoot}.`+(h.output?`
12
- ${h.output}`:"")}}catch(h){let f=h instanceof Error?h.message:String(h);return br(f)?{outcome:{kind:"conflict",branch:u,target:a,files:xr(f)},text:`"${u}": ${f}`}:Ar(f,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${f}`}:{outcome:{kind:"failed",branch:u,error:f},text:`"${u}": ${f}`}}},"handleItem")})}r(Sr,"executeMergeBranchTool");import{Type as ae}from"typebox";var Tr="REQUIRED. One or more agent ids to steer (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A settled agent is revived by the delivery. A repeated id is rejected before anything is delivered \u2014 pass each id once.",Rr="REQUIRED. The single message delivered verbatim to every id in `agent_ids`. Plain instructions work best (e.g. \"stop refactoring; just fix the failing test and report\"). Delivery is fire-and-forget: nothing here waits for an agent to act on it. Because the text is entered into the agent's pi session, a command prefixed with `!` runs and adds its output to that agent's context, while `!!` runs it without adding the output to its context.",Qt=ae.Object({agent_ids:ae.Array(ae.String({minLength:1}),{minItems:1,description:Tr}),message:ae.String({description:Rr})},{additionalProperties:!1,required:["agent_ids","message"]});var Xt={name:m.steerAgent,label:m.steerAgent,description:"Send one message to one or more agents in one call: pass every id in `agent_ids` and the single `message` delivered to each. Each id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A repeated id in `agent_ids` is rejected before anything is delivered \u2014 pass each id once. A spawned agent receives the message before its next model call; a SETTLED one is REVIVED \u2014 spawned again, given the message, and it sends you another completion message when it settles again. That second result arrives only as that completion message: the spawn's result promise closed with the first turn and never opens again. Delivery is fire-and-forget: nothing here waits for an agent to act on it, so do not poll for a reply. The message is entered into the agent's pi session, so it can also be a bash command: `!command` runs the command and sends its output to the agent's context; `!!command` runs it without adding the output to the agent's context. A QUEUED agent cannot be steered \u2014 it has no pane yet; wait for a concurrency slot first. An agent whose pane is gone (cleaned up) cannot be steered either, and neither can an agent being TORN DOWN (wait for its report) or handed over (wait for the handover to finish). Every refusal states its reason and what to do about it.",parameters:Qt,execute:Er,constrainedSampling:k};function Ir(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(Ir,"steerSeverity");async function Er(e,t,n,o,i){let a=t.message.trim();return R({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,severity:Ir,prepare:r(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:r(async s=>{let d=w().getSpawn(s);if(!d){let g=`not found. Active agents: ${C()}`;return{outcome:{kind:"refused",agentId:s,reason:g},text:`Agent ${s} was not steered: ${g}`}}let c=I(d.lifecycle),l;try{l=await w().steer(s,a)}catch(g){l={kind:"refused",reason:`steering failed: ${$(g)}`}}if(l.kind==="refused")return{outcome:{kind:"refused",agentId:s,reason:l.reason},text:`Agent ${s} was not steered (${c}): ${l.reason}`};if(l.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:s,reason:l.reason},text:`Agent ${s} had settled (${c}) and the message reached its pane, but it was not revived: ${l.reason}`};let v=c!=="spawned"&&d.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:s},text:v?`Agent ${s} had settled (${c}) \u2014 revived: the message was delivered to its pane and the agent is spawned again. Merge nothing yet; a new completion message will arrive when it settles again.`:c==="spawned"?`Message delivered to spawned agent ${s}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${s} was delivered to (${c}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r(Er,"executeSteerAgentTool");function ri(e,t,n){return pe(e.ids(),t).filter(o=>o!==n)}r(ri,"handoverTargets");function Zt(e,t,n){let o=e.trim();return o===""?{kind:"faulted",fault:{kind:"request-refused",detail:"`harness_type` is required \u2014 name the harness that runs the next run. Nothing was changed."}}:t.get(o)===void 0?{kind:"faulted",fault:{kind:"request-refused",detail:`Unknown harness_type "${o}": this session registered ${t.ids().join(", ")}. Nothing was changed \u2014 name a registered harness that runs the next run.`}}:je(o,n)?{kind:"ready",harness:o}:{kind:"faulted",fault:{kind:"request-refused",detail:`Harness "${o}" cannot be launched on this machine \u2014 this machine can launch ${pe(t.ids(),n).join(", ")}. Nothing was changed.`}}}r(Zt,"resolveHandoverTarget");import{Type as x}from"typebox";var Or="REQUIRED. The id of the SETTLED agent to hand over, as printed by the cowboy_agent spawn result or a completion message. A live agent is refused, never stopped \u2014 stop it with stop_cowboy_agent and hand it over once it has settled.",Cr=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${W.join(", ")}) and any harness a plugin registered in this session. Unlike the configured default, an explicit harness never falls back: an ID this session did not register, or one this machine cannot launch, causes the call to be refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result and nothing changes.`,_r=`Optional model for the next run as "provider/model-id", in the target harness's own vocabulary. Omit it, or pass null, to leave it unset and let the harness choose its default. A model that is not in this session's registry (or in the target harness's list) refuses the call before anything is stopped.`,Pr="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",Jt=x.Object({agent_id:x.String({minLength:1,description:Or}),harness_type:x.String({description:Cr}),model:x.Optional(x.Union([x.String(),x.Null()],{description:_r})),thinking:x.Optional(x.Union([x.String(),x.Null()],{description:Pr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Mr(e,t){let n=Zt(e.harness_type,G(),at());if(n.kind==="faulted")return{kind:"faulted",fault:n.fault};let o=n.harness;try{let i=await oe(ne(e),{harness:o,registry:t.modelRegistry,parent:t.model,thinking:te(e),listModels:ie(t)});for(let a of i.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:o,modelChoice:re(i.resolved)}}catch(i){return{kind:"faulted",fault:{kind:"request-refused",detail:$(i)}}}}r(Mr,"resolveIntent");function $r(e,t){return`Agent ${e} ${Nr(t)}`}r($r,"renderHandoverOutcome");function Nr(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":rt(e.loss);return`handed over from "${e.from}" to "${e.to}".${t} The ended run is archived; the next one runs in the same checkout and reports when it settles.`}switch(e.fault.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return e.fault.status==="queued"?"is still queued \u2014 it has not started, so there is no session to hand over. Wait for a concurrency slot (or stop it). Nothing was changed.":`is still ${e.fault.status} \u2014 stop it with stop_cowboy_agent and hand it over once it has settled. Nothing was changed.`;case"harness-cannot-export-session":return`was not handed over: harness "${e.fault.harness}" cannot export its own session, so there is nothing to hand over. Nothing was stopped or changed.`;case"never-started":return"was not handed over: it never started, so there is no session to export.";case"stop-failed":return`was not handed over: its run could not be stopped (${e.fault.detail}). Nothing was changed.`;case"session-empty":return`was not handed over: harness "${e.fault.harness}" returned an empty session. Nothing was changed: the run was not stopped.`;case"session-export-failed":return`was not handed over: harness "${e.fault.harness}" could not export its session (${e.fault.detail}). Nothing was changed: the run was not stopped.`;case"request-refused":return`was not handed over: ${e.fault.detail}`;case"launch-failed":return`ended its previous run but its next one did not start (${e.fault.detail}). It stays tracked and can be cleaned up.`}}r(Nr,"handoverReport");async function Hr(e,t,n,o,i){let a=t.agent_id.trim(),s=await Mr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await w().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return H(ot(d),$r(a,d),{agentId:a,outcome:d})}r(Hr,"executeHandoverAgentTool");var en={name:m.handoverAgent,label:m.handoverAgent,description:"Hand over one SETTLED agent to another harness in one call: pass its `agent_id` and the `harness_type` that executes its next run. The ended run is stopped, its session exported by the source harness, the run archived, and the next one launched in the same checkout with that session and its ID quoted in its task \u2014 so the work continues under the new harness instead of starting over. Nothing is removed: the ended run's pane and harness state stay until cleanup_cowboy_agent, which tears every run down at its own address. A live agent is REFUSED, never stopped \u2014 stop it with stop_cowboy_agent first. `harness_type` is required and, unlike a configured default, never falls back: if an ID was not registered in this session or cannot be launched on this machine, the call is refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result, naming the harness, and nothing is stopped or changed. The next run reports through its own completion message; this call returns when that run has started, not when it finishes.",parameters:Jt,execute:Hr,constrainedSampling:k};import{Text as Dr}from"@earendil-works/pi-tui";var Br={success:"\u2713",warning:"!",error:"\u2717"};function Lr(e,t,n,o){let i=e.content.map(d=>d.text??"").join(`
13
- `),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Dr(`${n.fg(a,Br[a])} ${s}`,0,0)}r(Lr,"renderCowboyToolResult");function P(e){return{...e,renderResult:Lr}}r(P,"withCowboyRenderer");var Ur=Ie;function Wr(e){let t=M.Object({prompt:O.properties.agents.items.properties.prompt,task_name:O.properties.agents.items.properties.task_name,agent_type:M.Optional(M.Union([M.String(),M.Null()],{description:`Optional agent type. Omit it, or pass null, to use the configured default agent type \u2014 never pass a type the user did not ask for. An unknown or ambiguous name is rejected before any agent in the batch spawns.${e.length>0?` Available: ${e.join(",")}`:""}`})),model:O.properties.agents.items.properties.model,harness_type:O.properties.agents.items.properties.harness_type,worktree:O.properties.agents.items.properties.worktree},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:O.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Wr,"cowboyAgentsSchemaWithTypes");function tn(e){let t=Wr(yt()),n={name:m.agent,label:m.agent,description:"Delegate one or more tasks to agents. Each agent gets a fresh pi process and, by default, an isolated worktree \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. Always omit optional parameters the user did not explicitly ask for \u2014 `agent_type`, `model`, `harness_type`, and `worktree` each take this session's configured default when unset, so never guess or fill them in on the user's behalf. When an agent settles, the completion message names its branch when it has one and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.",parameters:t,execute:Dt,constrainedSampling:k};e.registerTool(P(n))}r(tn,"registerAgentTool");function qr(e,t){y().mutate.agent.setExtensionEnabled(t),t?Fr(e):Kr(e)}r(qr,"setExtensionEnabled");function Fr(e){let t=b();tn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Ur])]),ee(e)}r(Fr,"activateExtension");function Kr(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!Ie.includes(n))),ee(e)}r(Kr,"deactivateExtension");function Di(e){tn(e),e.registerTool(P(Bt)),e.registerTool(P(Vt)),e.registerTool(P(Xt)),e.registerTool(P(en)),e.registerTool(P(Kt)),e.registerMessageRenderer("subagent-result",(t,n,o)=>{let i=typeof t=="object"&&typeof t.content=="string"?t.content:"",a=/\b(error|stopped)\b/.test(i.slice(0,200)),s=o.fg(a?"error":"success",a?"\u2717":"\u2713");return new jr(`${s} ${i}`,0,0)})}r(Di,"registerTools");var nn="cowboy",Gr={wt:"worktree",sp:"spawn",st:"status"};function Bi(e,t){e.registerCommand(nn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Bi,"registerUnavailableCowboyCommand");function Li(e){e.registerCommand(nn,{description:"Manage agents: status, spawn, settings. `status` lists spawned, queued and settled agents; `spawn` opens the spawn wizard; `worktree` creates one git worktree with no agent attached to it. `status`, `spawn` and `worktree` also answer to `st`, `sp` and `wt`. `enable`/`disable` load or unload the cowboy tools. Pass `model` (optionally a provider/model-id) to set the model agents use for this session \u2014 opens pi's model picker.",getArgumentCompletions:r(async t=>(await import("./model-picker-VL4BU7LP.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{dt(n);let[o,...i]=t.trim().split(/\s+/),a=Gr[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&ke()===null){n.ui.notify(ge,"warning");return}if(J()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}qr(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(ke()===null){n.ui.notify(ge,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-OT7ANA4R.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!J()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-VL4BU7LP.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-OAVTJWLR.js");await l(n,s,L()?.options??new Map);return}if(s!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-OAVTJWLR.js");await c(n,L()?.options??new Map)},"handler")})}r(Li,"registerCowboyCommand");import*as rn from"node:fs";import{tmpdir as Yr}from"node:os";import*as de from"node:path";async function on(e,t){try{return await lt(e).probe(t),B(Ue)}catch{return B(["checkout"])}}r(on,"detectCowAvailability");function sn(e){let t=de.resolve(e??Be());for(;;){try{if(rn.statSync(t).isDirectory())return t}catch{}let n=de.dirname(t);if(n===t)return Yr();t=n}}r(sn,"probeTargetFor");function zr(e){return(t,n,o)=>e.exec(t,n,o)}r(zr,"execOf");function Zi(e){return an(e,ve())}r(Zi,"startCowSupportProbe");function Ji(e){let t=ve();return K(t,Le()),an(e,t)}r(Ji,"refreshCowSupportProbe");function an(e,t){let n=sn(y().agent.worktreeRoot);return on(zr(e),n).then(o=>{K(t,o)},()=>{K(t,B(["checkout"]))})}r(an,"probe");import dn from"node:fs";var Vr="/tmp";function Qr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(Qr,"handoverNameField");function ln(e){return`cowboy-handover_${[e.worktree,e.harness,e.sessionId].map(Qr).join("_")}.md`}r(ln,"handoverFileName");function cn(e){return`${Vr}/${e}`}r(cn,"handoverFilePath");function Xr(e){return dn.existsSync(e)}r(Xr,"handoverFileExists");function ra(e,t){let n=Xr(e);return dn.writeFileSync(e,t,"utf8"),{replaced:n}}r(ra,"writeHandoverFile");function aa(e){return{kind:"prepared",path:cn(ln({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(aa,"handoverExportArtifact");function da(e){switch(e.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return`is still ${e.status} \u2014 only a settled run has a session to export. Nothing was changed.`;case"harness-cannot-export-session":return`was not exported: harness "${e.harness}" cannot export its own session, so there is nothing to write.`;case"never-started":return"was not exported: it never started, so there is no session to export.";case"handover-in-progress":return`was not exported: ${e.detail}`;case"session-empty":return`was not exported: harness "${e.harness}" returned an empty session.`;case"session-export-failed":return`was not exported: harness "${e.harness}" could not export its session (${e.detail}).`}}r(da,"handoverExportFaultReason");function la(e){if(e.kind==="prepared")return e.loss===void 0?"success":"warning";switch(e.fault.kind){case"agent-unknown":case"agent-not-settled":case"harness-cannot-export-session":case"never-started":case"handover-in-progress":return"warning";case"session-empty":case"session-export-failed":return"error"}}r(la,"handoverExportSeverity");export{Me as a,zn as b,Vn as c,ws as d,Ut as e,As as f,Ss as g,ri as h,$r as i,Re as j,J as k,so as l,Xr as m,ra as n,aa as o,da as p,la as q,Zi as r,Ji as s,qr as t,Fr as u,Kr as v,Di as w,Bi as x,Li as y};
14
- //# sourceMappingURL=chunk-CRFTXDVY.js.map
12
+ ${h.output}`:"")}}catch(h){let f=h instanceof Error?h.message:String(h);return xr(f)?{outcome:{kind:"conflict",branch:u,target:a,files:Ar(f)},text:`"${u}": ${f}`}:Sr(f,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${f}`}:{outcome:{kind:"failed",branch:u,error:f},text:`"${u}": ${f}`}}},"handleItem")})}r(Tr,"executeMergeBranchTool");import{Type as ae}from"typebox";var Rr="REQUIRED. One or more agent ids to steer (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A settled agent is revived by the delivery. A repeated id is rejected before anything is delivered \u2014 pass each id once.",Ir="REQUIRED. The single message delivered verbatim to every id in `agent_ids`. Plain instructions work best (e.g. \"stop refactoring; just fix the failing test and report\"). Delivery is fire-and-forget: nothing here waits for an agent to act on it. Because the text is entered into the agent's pi session, a command prefixed with `!` runs and adds its output to that agent's context, while `!!` runs it without adding the output to its context.",Qt=ae.Object({agent_ids:ae.Array(ae.String({minLength:1}),{minItems:1,description:Rr}),message:ae.String({description:Ir})},{additionalProperties:!1,required:["agent_ids","message"]});var Xt={name:m.steerAgent,label:m.steerAgent,description:"Send one message to one or more agents in one call: pass every id in `agent_ids` and the single `message` delivered to each. Each id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A repeated id in `agent_ids` is rejected before anything is delivered \u2014 pass each id once. A spawned agent receives the message before its next model call; a SETTLED one is REVIVED \u2014 spawned again, given the message, and it sends you another completion message when it settles again. That second result arrives only as that completion message: the spawn's result promise closed with the first turn and never opens again. Delivery is fire-and-forget: nothing here waits for an agent to act on it, so do not poll for a reply. The message is entered into the agent's pi session, so it can also be a bash command: `!command` runs the command and sends its output to the agent's context; `!!command` runs it without adding the output to the agent's context. A QUEUED agent cannot be steered \u2014 it has no pane yet; wait for a concurrency slot first. An agent whose pane is gone (cleaned up) cannot be steered either, and neither can an agent being TORN DOWN (wait for its report) or handed over (wait for the handover to finish). Every refusal states its reason and what to do about it.",parameters:Qt,execute:Or,constrainedSampling:k};function Er(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(Er,"steerSeverity");async function Or(e,t,n,o,i){let a=t.message.trim();return R({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,severity:Er,prepare:r(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:r(async s=>{let d=w().getSpawn(s);if(!d){let g=`not found. Active agents: ${C()}`;return{outcome:{kind:"refused",agentId:s,reason:g},text:`Agent ${s} was not steered: ${g}`}}let c=I(d.lifecycle),l;try{l=await w().steer(s,a)}catch(g){l={kind:"refused",reason:`steering failed: ${$(g)}`}}if(l.kind==="refused")return{outcome:{kind:"refused",agentId:s,reason:l.reason},text:`Agent ${s} was not steered (${c}): ${l.reason}`};if(l.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:s,reason:l.reason},text:`Agent ${s} had settled (${c}) and the message reached its pane, but it was not revived: ${l.reason}`};let v=c!=="spawned"&&d.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:s},text:v?`Agent ${s} had settled (${c}) \u2014 revived: the message was delivered to its pane and the agent is spawned again. Merge nothing yet; a new completion message will arrive when it settles again.`:c==="spawned"?`Message delivered to spawned agent ${s}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${s} was delivered to (${c}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r(Or,"executeSteerAgentTool");function oi(e,t,n){return pe(e.ids(),t).filter(o=>o!==n)}r(oi,"handoverTargets");function Zt(e,t,n){let o=e.trim();return o===""?{kind:"faulted",fault:{kind:"request-refused",detail:"`harness_type` is required \u2014 name the harness that runs the next run. Nothing was changed."}}:t.get(o)===void 0?{kind:"faulted",fault:{kind:"request-refused",detail:`Unknown harness_type "${o}": this session registered ${t.ids().join(", ")}. Nothing was changed \u2014 name a registered harness that runs the next run.`}}:je(o,n)?{kind:"ready",harness:o}:{kind:"faulted",fault:{kind:"request-refused",detail:`Harness "${o}" cannot be launched on this machine \u2014 this machine can launch ${pe(t.ids(),n).join(", ")}. Nothing was changed.`}}}r(Zt,"resolveHandoverTarget");import{Type as x}from"typebox";var Cr="REQUIRED. The id of the SETTLED agent to hand over, as printed by the cowboy_agent spawn result or a completion message. A live agent is refused, never stopped \u2014 stop it with stop_cowboy_agent and hand it over once it has settled.",_r=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${W.join(", ")}) and any harness a plugin registered in this session. Unlike the configured default, an explicit harness never falls back: an ID this session did not register, or one this machine cannot launch, causes the call to be refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result and nothing changes.`,Pr=`Optional model for the next run as "provider/model-id", in the target harness's own vocabulary. Omit it, or pass null, to leave it unset and let the harness choose its default. A model that is not in this session's registry (or in the target harness's list) refuses the call before anything is stopped.`,Mr="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",Jt=x.Object({agent_id:x.String({minLength:1,description:Cr}),harness_type:x.String({description:_r}),model:x.Optional(x.Union([x.String(),x.Null()],{description:Pr})),thinking:x.Optional(x.Union([x.String(),x.Null()],{description:Mr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function $r(e,t){let n=Zt(e.harness_type,G(),at());if(n.kind==="faulted")return{kind:"faulted",fault:n.fault};let o=n.harness;try{let i=await oe(ne(e),{harness:o,registry:t.modelRegistry,parent:t.model,thinking:te(e),listModels:ie(t)});for(let a of i.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:o,modelChoice:re(i.resolved)}}catch(i){return{kind:"faulted",fault:{kind:"request-refused",detail:$(i)}}}}r($r,"resolveIntent");function Nr(e,t){return`Agent ${e} ${Hr(t)}`}r(Nr,"renderHandoverOutcome");function Hr(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":rt(e.loss);return`handed over from "${e.from}" to "${e.to}".${t} The ended run is archived; the next one runs in the same checkout and reports when it settles.`}switch(e.fault.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return e.fault.status==="queued"?"is still queued \u2014 it has not started, so there is no session to hand over. Wait for a concurrency slot (or stop it). Nothing was changed.":`is still ${e.fault.status} \u2014 stop it with stop_cowboy_agent and hand it over once it has settled. Nothing was changed.`;case"harness-cannot-export-session":return`was not handed over: harness "${e.fault.harness}" cannot export its own session, so there is nothing to hand over. Nothing was stopped or changed.`;case"never-started":return"was not handed over: it never started, so there is no session to export.";case"stop-failed":return`was not handed over: its run could not be stopped (${e.fault.detail}). Nothing was changed.`;case"session-empty":return`was not handed over: harness "${e.fault.harness}" returned an empty session. Nothing was changed: the run was not stopped.`;case"session-export-failed":return`was not handed over: harness "${e.fault.harness}" could not export its session (${e.fault.detail}). Nothing was changed: the run was not stopped.`;case"request-refused":return`was not handed over: ${e.fault.detail}`;case"launch-failed":return`ended its previous run but its next one did not start (${e.fault.detail}). It stays tracked and can be cleaned up.`}}r(Hr,"handoverReport");async function Dr(e,t,n,o,i){let a=t.agent_id.trim(),s=await $r(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await w().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return H(ot(d),Nr(a,d),{agentId:a,outcome:d})}r(Dr,"executeHandoverAgentTool");var en={name:m.handoverAgent,label:m.handoverAgent,description:"Hand over one SETTLED agent to another harness in one call: pass its `agent_id` and the `harness_type` that executes its next run. The ended run is stopped, its session exported by the source harness, the run archived, and the next one launched in the same checkout with that session and its ID quoted in its task \u2014 so the work continues under the new harness instead of starting over. Nothing is removed: the ended run's pane and harness state stay until cleanup_cowboy_agent, which tears every run down at its own address. A live agent is REFUSED, never stopped \u2014 stop it with stop_cowboy_agent first. `harness_type` is required and, unlike a configured default, never falls back: if an ID was not registered in this session or cannot be launched on this machine, the call is refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result, naming the harness, and nothing is stopped or changed. The next run reports through its own completion message; this call returns when that run has started, not when it finishes.",parameters:Jt,execute:Dr,constrainedSampling:k};import{Text as Br}from"@earendil-works/pi-tui";var Lr={success:"\u2713",warning:"!",error:"\u2717"};function jr(e,t,n,o){let i=e.content.map(d=>d.text??"").join(`
13
+ `),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Br(`${n.fg(a,Lr[a])} ${s}`,0,0)}r(jr,"renderCowboyToolResult");function P(e){return{...e,renderResult:jr}}r(P,"withCowboyRenderer");var Wr=Ie;function qr(e){let t=M.Object({prompt:O.properties.agents.items.properties.prompt,task_name:O.properties.agents.items.properties.task_name,agent_type:M.Optional(M.Union([M.String(),M.Null()],{description:`Optional agent type. Omit it, or pass null, to use the configured default agent type \u2014 never pass a type the user did not ask for. An unknown or ambiguous name is rejected before any agent in the batch spawns.${e.length>0?` Available: ${e.join(",")}`:""}`})),model:O.properties.agents.items.properties.model,harness_type:O.properties.agents.items.properties.harness_type,worktree:O.properties.agents.items.properties.worktree},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:O.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(qr,"cowboyAgentsSchemaWithTypes");function tn(e){let t=qr(yt()),n={name:m.agent,label:m.agent,description:"Delegate one or more tasks to agents. Each agent gets a fresh pi process and, by default, an isolated worktree \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. Always omit optional parameters the user did not explicitly ask for \u2014 `agent_type`, `model`, `harness_type`, and `worktree` each take this session's configured default when unset, so never guess or fill them in on the user's behalf. When an agent settles, the completion message names its branch when it has one and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.",parameters:t,execute:Dt,constrainedSampling:k};e.registerTool(P(n))}r(tn,"registerAgentTool");function Fr(e,t){y().mutate.agent.setExtensionEnabled(t),t?Kr(e):Gr(e)}r(Fr,"setExtensionEnabled");function Kr(e){let t=b();tn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Wr])]),ee(e)}r(Kr,"activateExtension");function Gr(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!Ie.includes(n))),ee(e)}r(Gr,"deactivateExtension");function Bi(e){tn(e),e.registerTool(P(Bt)),e.registerTool(P(Vt)),e.registerTool(P(Xt)),e.registerTool(P(en)),e.registerTool(P(Kt)),e.registerMessageRenderer("subagent-result",(t,n,o)=>{let i=typeof t=="object"&&typeof t.content=="string"?t.content:"",a=/\b(error|stopped)\b/.test(i.slice(0,200)),s=o.fg(a?"error":"success",a?"\u2717":"\u2713");return new Ur(`${s} ${i}`,0,0)})}r(Bi,"registerTools");var nn="cowboy",Yr={wt:"worktree",sp:"spawn",st:"status"};function Li(e,t){e.registerCommand(nn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Li,"registerUnavailableCowboyCommand");function ji(e){e.registerCommand(nn,{description:"Manage agents: status, spawn, settings. `status` lists spawned, queued and settled agents; `spawn` opens the spawn wizard; `worktree` creates one git worktree with no agent attached to it. `status`, `spawn` and `worktree` also answer to `st`, `sp` and `wt`. `enable`/`disable` load or unload the cowboy tools. Pass `model` (optionally a provider/model-id) to set the model agents use for this session \u2014 opens pi's model picker.",getArgumentCompletions:r(async t=>(await import("./model-picker-5L66JCRC.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{dt(n);let[o,...i]=t.trim().split(/\s+/),a=Yr[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&ke()===null){n.ui.notify(ge,"warning");return}if(J()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}Fr(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(ke()===null){n.ui.notify(ge,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-TE76CU24.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!J()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-5L66JCRC.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-FOXUBIBA.js");await l(n,s,L()?.options??new Map);return}if(s!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-FOXUBIBA.js");await c(n,L()?.options??new Map)},"handler")})}r(ji,"registerCowboyCommand");import*as rn from"node:fs";import{tmpdir as zr}from"node:os";import*as de from"node:path";async function on(e,t){try{return await lt(e).probe(t),B(We)}catch{return B(["checkout"])}}r(on,"detectCowAvailability");function sn(e){let t=de.resolve(e??Be());for(;;){try{if(rn.statSync(t).isDirectory())return t}catch{}let n=de.dirname(t);if(n===t)return zr();t=n}}r(sn,"probeTargetFor");function Vr(e){return(t,n,o)=>e.exec(t,n,o)}r(Vr,"execOf");function Ji(e){return an(e,ve())}r(Ji,"startCowSupportProbe");function ea(e){let t=ve();return K(t,Le()),an(e,t)}r(ea,"refreshCowSupportProbe");function an(e,t){let n=sn(y().agent.worktreeRoot);return on(Vr(e),n).then(o=>{K(t,o)},()=>{K(t,B(["checkout"]))})}r(an,"probe");import dn from"node:fs";var Qr="/tmp";function Xr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(Xr,"handoverNameField");function ln(e){return`${[e.worktree,e.harness,e.sessionId].map(Xr).join("-")}.md`}r(ln,"handoverFileName");function cn(e){return`${Qr}/${e}`}r(cn,"handoverFilePath");function Zr(e){return dn.existsSync(e)}r(Zr,"handoverFileExists");function oa(e,t){let n=Zr(e);return dn.writeFileSync(e,t,"utf8"),{replaced:n}}r(oa,"writeHandoverFile");import*as un from"node:path";function da(e,t){return e===void 0?`main-${t}`:un.basename(e.path)}r(da,"exportWorktreeName");function la(e){return{kind:"prepared",defaultPath:cn(ln({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(la,"handoverExportArtifact");function ca(e){switch(e.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return`is still ${e.status} \u2014 its session cannot be read while the run is in that state. Nothing was changed.`;case"harness-cannot-export-session":return`was not exported: harness "${e.harness}" cannot export its own session, so there is nothing to write.`;case"never-started":return"was not exported: it never started, so there is no session to export.";case"handover-in-progress":return`was not exported: ${e.detail}`;case"session-empty":return`was not exported: harness "${e.harness}" returned an empty session.`;case"session-export-failed":return`was not exported: harness "${e.harness}" could not export its session (${e.detail}).`}}r(ca,"handoverExportFaultReason");function ua(e){if(e.kind==="prepared")return e.loss===void 0?"success":"warning";switch(e.fault.kind){case"agent-unknown":case"agent-not-settled":case"harness-cannot-export-session":case"never-started":case"handover-in-progress":return"warning";case"session-empty":case"session-export-failed":return"error"}}r(ua,"handoverExportSeverity");export{Me as a,Vn as b,Qn as c,vs as d,Ut as e,Ss as f,Ts as g,oi as h,Nr as i,Re as j,J as k,io as l,Zr as m,oa as n,da as o,la as p,ca as q,ua as r,Ji as s,ea as t,Fr as u,Kr as v,Gr as w,Bi as x,Li as y,ji as z};
14
+ //# sourceMappingURL=chunk-7K5AIPXH.js.map
@@ -1,2 +1,2 @@
1
- import{Ja as x}from"./chunk-IIQ52KJZ.js";import{a as s,i as f,t as C}from"./chunk-3TPZINCV.js";import{Container as y,fuzzyFilter as M,getKeybindings as N,Input as k,Spacer as v,Text as b}from"@earendil-works/pi-tui";import{DynamicBorder as w}from"@earendil-works/pi-coding-agent";var h=10,g=class extends y{static{s(this,"SearchableSelectDialog")}searchInput;listContainer;items;filteredItems;selectedIndex;currentValue;callbacks;theme;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}constructor(e,n,r,l){super(),this.items=e,this.currentValue=n,this.callbacks=r,this.theme=l,this.filteredItems=[...e];let a=e.findIndex(o=>o.value===n);this.selectedIndex=a>=0?a:0,this.addChild(new w),this.addChild(new v(1)),this.searchInput=new k,this.searchInput.onSubmit=()=>{this.filteredItems[this.selectedIndex]&&this.callbacks.onSelect(this.filteredItems[this.selectedIndex].value)},this.addChild(this.searchInput),this.addChild(new v(1)),this.listContainer=new y,this.addChild(this.listContainer),this.addChild(new v(1)),this.addChild(new w),this.updateList()}handleInput(e){let n=N();if(!(this.filteredItems.length===0&&(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")||n.matches(e,"tui.select.pageUp")||n.matches(e,"tui.select.pageDown")))){if(n.matches(e,"tui.select.up")){this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(n.matches(e,"tui.select.down")){this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}if(n.matches(e,"tui.select.pageUp")){this.selectedIndex=Math.max(0,this.selectedIndex-h),this.updateList();return}if(n.matches(e,"tui.select.pageDown")){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+h),this.updateList();return}if(n.matches(e,"tui.select.confirm")){let r=this.filteredItems.at(this.selectedIndex);r&&this.callbacks.onSelect(r.value);return}if(n.matches(e,"tui.select.cancel")){this.callbacks.onCancel();return}this.searchInput.handleInput(e),this.filterItems()}}invalidate(){}filterItems(){let e=this.searchInput.getValue();e?this.filteredItems=M(this.items,e,n=>`${n.label} ${n.provider} ${n.value??""}`):this.filteredItems=[...this.items],this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList()}updateList(){this.listContainer.clear();let{filteredItems:e}=this;if(e.length===0){this.listContainer.addChild(new b(this.theme.fg("muted"," No matching items"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(h/2),e.length-h)),r=Math.min(n+h,e.length);for(let l=n;l<r;l++){let a=e.at(l);if(!a)continue;let o=l===this.selectedIndex,d=a.value===this.currentValue,c=o?this.theme.fg("accent","\u2192 ")+this.theme.fg("accent",a.label):` ${a.label}`,i=a.provider?this.theme.fg("muted",`[${a.provider}]`):"",u=d?this.theme.fg("success"," \u2713"):"",m=`${c} ${i}${u}`;this.listContainer.addChild(new b(m,0,0))}if(n>0||r<e.length){let l=this.theme.fg("muted",` (${this.selectedIndex+1}/${e.length})`);this.listContainer.addChild(new b(l,0,0))}}};import{isFocusable as L}from"@earendil-works/pi-tui";var O=class{constructor(e){this.ctx=e}ctx;static{s(this,"ScreenHost")}async open(e){return await this.show(e,!1)}async openOverlay(e){return await this.show(e,!0)}async show(e,n){if(x(this.ctx))return await new Promise(r=>{this.ctx.ui.custom((l,a,o,d)=>e({tui:l,theme:a,keybindings:o,close:s(c=>{x(this.ctx)&&d(c),r(c)},"close")}),n?{overlay:!0}:void 0).then(r)})}},j=void 0;function K(t){return Object.assign(t,{focused:!0})}s(K,"asSubmenuComponent");var I=class{static{s(this,"SwappableView")}active;constructor(e){this.active=e}activate(e){this.active=e}invalidate(){this.active.invalidate()}render(e){return this.active.render(e)}handleInput(e){this.active.handleInput?.(e)}get focused(){return L(this.active)?this.active.focused:!1}set focused(e){L(this.active)&&(this.active.focused=e)}};var F="group-header";function q(t,e){return{id:T,kind:F,label:t.bold(t.fg("accent",e)),currentValue:""}}s(q,"headerItem");var T="__sep__",p=new WeakMap;function X(t){if(!Array.isArray(t.items))return;let e=s(o=>o?.value===T||o?.id===T,"isSep"),n=s((o,d,c)=>{let i=d+c;for(;i>=0&&i<o.length&&e(o[i]);)i+=c;return i},"firstNonSepFrom"),r=s((o,d)=>d>=0&&d<o.length,"inBounds"),l=s((o,d)=>{let c=Math.max(0,Math.min(d,o.length-1));for(let i=c;i<o.length;i+=1)if(!e(o[i]))return i;for(let i=c-1;i>=0;i-=1)if(!e(o[i]))return i;return 0},"seedIndex"),a=t.selectedIndex??0;Object.defineProperty(t,"selectedIndex",{get(){return p.get(t)},set(o){let d=t.items,c=p.get(t)??0,i=Math.max(0,Math.min(o,d.length-1));if(!e(d[i])){p.set(t,i);return}let u=o>c?1:-1,m=n(d,i,u),S=n(d,i,-u);r(d,m)?p.set(t,m):r(d,S)?p.set(t,S):p.set(t,i)},configurable:!0}),p.set(t,l(t.items,a))}s(X,"installSeparatorSkip");function J(t,e,n){let r=[{value:null,label:"(none)",provider:""}],l=[];for(let i of t){let u=f(i);u&&l.push({value:i,label:u.modelId,provider:u.provider})}if(e===null&&n.length===0)return r.push(...l),r;let a=[],o=[],d=[],c=new Set;if(e){let i=f(e);i&&(a.push({value:e,label:i.modelId,provider:i.provider}),c.add(e))}for(let i of n){if(c.has(i))continue;let u=f(i);u&&(o.push({value:i,label:u.modelId,provider:u.provider}),c.add(i))}for(let i of l)i.value!=null&&!c.has(i.value)&&d.push(i);return r.push(...a,...o,...d),r}s(J,"buildModelOptions");function Q(t){let e=[];t.default&&typeof t.default=="string"&&e.push(t.default);for(let[n,r]of Object.entries(t))n!=="default"&&typeof r=="string"&&r.includes("/")&&e.push(r);return[...new Set(e)]}s(Q,"extractConfiguredModels");function Y(t,e){return C(t)?e:[]}s(Y,"mergedModelsForHarness");function Z(t){return{label:s((e,n)=>n?t.fg("accent",e):e,"label"),value:s((e,n)=>n?t.fg("accent",e):t.fg("muted",e),"value"),description:s(e=>t.fg("dim",e),"description"),cursor:t.fg("accent","\u2192 "),hint:s(e=>t.fg("dim",e),"hint")}}s(Z,"buildSettingsListTheme");function ee(t,e){let n=t.trim();if(!/^\d*\.?\d+$/.test(n))return;let r=parseFloat(n);if(!(r<e))return r}s(ee,"validateNumeric");var _=new Map([["k","\x1B[A"],["j","\x1B[B"]]);function te(t){let e=t,n=e.handleInput?.bind(e);return n&&(e.handleInput=r=>{let l=e.submenuComponent?void 0:_.get(r);n(l??r)}),t}s(te,"withVimKeys");function ne(t){return{selectedPrefix:s(()=>t.fg("accent","\u2192 "),"selectedPrefix"),selectedText:s(e=>t.fg("accent",e),"selectedText"),description:s(e=>t.fg("muted",e),"description"),scrollInfo:s(e=>t.fg("dim",e),"scrollInfo"),noMatch:s(e=>t.fg("dim",e),"noMatch")}}s(ne,"buildSelectListTheme");function ie(t,e,n){let r,l=new g(t,null,{onSelect:s(a=>{let o=e.onSelect(a);o&&r.activate(o)},"onSelect"),onCancel:e.onCancel},n);return r=new I(l),r}s(ie,"createSearchableSelect");function se(t){return t.length===1?`agent ${t[0]}`:`${t.length} agent(s)`}s(se,"agentSubject");export{g as a,O as b,j as c,K as d,I as e,q as f,T as g,X as h,J as i,Q as j,Y as k,Z as l,ee as m,te as n,ne as o,ie as p,se as q};
2
- //# sourceMappingURL=chunk-3P4DDY2M.js.map
1
+ import{Ia as x}from"./chunk-F25VVC3O.js";import{a as s,q as f,y as C}from"./chunk-CTAS2E47.js";import{Container as y,fuzzyFilter as M,getKeybindings as N,Input as k,Spacer as v,Text as b}from"@earendil-works/pi-tui";import{DynamicBorder as w}from"@earendil-works/pi-coding-agent";var h=10,g=class extends y{static{s(this,"SearchableSelectDialog")}searchInput;listContainer;items;filteredItems;selectedIndex;currentValue;callbacks;theme;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}constructor(e,n,r,l){super(),this.items=e,this.currentValue=n,this.callbacks=r,this.theme=l,this.filteredItems=[...e];let a=e.findIndex(o=>o.value===n);this.selectedIndex=a>=0?a:0,this.addChild(new w),this.addChild(new v(1)),this.searchInput=new k,this.searchInput.onSubmit=()=>{this.filteredItems[this.selectedIndex]&&this.callbacks.onSelect(this.filteredItems[this.selectedIndex].value)},this.addChild(this.searchInput),this.addChild(new v(1)),this.listContainer=new y,this.addChild(this.listContainer),this.addChild(new v(1)),this.addChild(new w),this.updateList()}handleInput(e){let n=N();if(!(this.filteredItems.length===0&&(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")||n.matches(e,"tui.select.pageUp")||n.matches(e,"tui.select.pageDown")))){if(n.matches(e,"tui.select.up")){this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(n.matches(e,"tui.select.down")){this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}if(n.matches(e,"tui.select.pageUp")){this.selectedIndex=Math.max(0,this.selectedIndex-h),this.updateList();return}if(n.matches(e,"tui.select.pageDown")){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+h),this.updateList();return}if(n.matches(e,"tui.select.confirm")){let r=this.filteredItems.at(this.selectedIndex);r&&this.callbacks.onSelect(r.value);return}if(n.matches(e,"tui.select.cancel")){this.callbacks.onCancel();return}this.searchInput.handleInput(e),this.filterItems()}}invalidate(){}filterItems(){let e=this.searchInput.getValue();e?this.filteredItems=M(this.items,e,n=>`${n.label} ${n.provider} ${n.value??""}`):this.filteredItems=[...this.items],this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList()}updateList(){this.listContainer.clear();let{filteredItems:e}=this;if(e.length===0){this.listContainer.addChild(new b(this.theme.fg("muted"," No matching items"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(h/2),e.length-h)),r=Math.min(n+h,e.length);for(let l=n;l<r;l++){let a=e.at(l);if(!a)continue;let o=l===this.selectedIndex,d=a.value===this.currentValue,c=o?this.theme.fg("accent","\u2192 ")+this.theme.fg("accent",a.label):` ${a.label}`,i=a.provider?this.theme.fg("muted",`[${a.provider}]`):"",u=d?this.theme.fg("success"," \u2713"):"",m=`${c} ${i}${u}`;this.listContainer.addChild(new b(m,0,0))}if(n>0||r<e.length){let l=this.theme.fg("muted",` (${this.selectedIndex+1}/${e.length})`);this.listContainer.addChild(new b(l,0,0))}}};import{isFocusable as L}from"@earendil-works/pi-tui";var O=class{constructor(e){this.ctx=e}ctx;static{s(this,"ScreenHost")}async open(e){return await this.show(e,!1)}async openOverlay(e){return await this.show(e,!0)}async show(e,n){if(x(this.ctx))return await new Promise(r=>{this.ctx.ui.custom((l,a,o,d)=>e({tui:l,theme:a,keybindings:o,close:s(c=>{x(this.ctx)&&d(c),r(c)},"close")}),n?{overlay:!0}:void 0).then(r)})}},j=void 0;function K(t){return Object.assign(t,{focused:!0})}s(K,"asSubmenuComponent");var I=class{static{s(this,"SwappableView")}active;constructor(e){this.active=e}activate(e){this.active=e}invalidate(){this.active.invalidate()}render(e){return this.active.render(e)}handleInput(e){this.active.handleInput?.(e)}get focused(){return L(this.active)?this.active.focused:!1}set focused(e){L(this.active)&&(this.active.focused=e)}};var F="group-header";function q(t,e){return{id:T,kind:F,label:t.bold(t.fg("accent",e)),currentValue:""}}s(q,"headerItem");var T="__sep__",p=new WeakMap;function X(t){if(!Array.isArray(t.items))return;let e=s(o=>o?.value===T||o?.id===T,"isSep"),n=s((o,d,c)=>{let i=d+c;for(;i>=0&&i<o.length&&e(o[i]);)i+=c;return i},"firstNonSepFrom"),r=s((o,d)=>d>=0&&d<o.length,"inBounds"),l=s((o,d)=>{let c=Math.max(0,Math.min(d,o.length-1));for(let i=c;i<o.length;i+=1)if(!e(o[i]))return i;for(let i=c-1;i>=0;i-=1)if(!e(o[i]))return i;return 0},"seedIndex"),a=t.selectedIndex??0;Object.defineProperty(t,"selectedIndex",{get(){return p.get(t)},set(o){let d=t.items,c=p.get(t)??0,i=Math.max(0,Math.min(o,d.length-1));if(!e(d[i])){p.set(t,i);return}let u=o>c?1:-1,m=n(d,i,u),S=n(d,i,-u);r(d,m)?p.set(t,m):r(d,S)?p.set(t,S):p.set(t,i)},configurable:!0}),p.set(t,l(t.items,a))}s(X,"installSeparatorSkip");function J(t,e,n){let r=[{value:null,label:"(none)",provider:""}],l=[];for(let i of t){let u=f(i);u&&l.push({value:i,label:u.modelId,provider:u.provider})}if(e===null&&n.length===0)return r.push(...l),r;let a=[],o=[],d=[],c=new Set;if(e){let i=f(e);i&&(a.push({value:e,label:i.modelId,provider:i.provider}),c.add(e))}for(let i of n){if(c.has(i))continue;let u=f(i);u&&(o.push({value:i,label:u.modelId,provider:u.provider}),c.add(i))}for(let i of l)i.value!=null&&!c.has(i.value)&&d.push(i);return r.push(...a,...o,...d),r}s(J,"buildModelOptions");function Q(t){let e=[];t.default&&typeof t.default=="string"&&e.push(t.default);for(let[n,r]of Object.entries(t))n!=="default"&&typeof r=="string"&&r.includes("/")&&e.push(r);return[...new Set(e)]}s(Q,"extractConfiguredModels");function Y(t,e){return C(t)?e:[]}s(Y,"mergedModelsForHarness");function Z(t){return{label:s((e,n)=>n?t.fg("accent",e):e,"label"),value:s((e,n)=>n?t.fg("accent",e):t.fg("muted",e),"value"),description:s(e=>t.fg("dim",e),"description"),cursor:t.fg("accent","\u2192 "),hint:s(e=>t.fg("dim",e),"hint")}}s(Z,"buildSettingsListTheme");function ee(t,e){let n=t.trim();if(!/^\d*\.?\d+$/.test(n))return;let r=parseFloat(n);if(!(r<e))return r}s(ee,"validateNumeric");var _=new Map([["k","\x1B[A"],["j","\x1B[B"]]);function te(t){let e=t,n=e.handleInput?.bind(e);return n&&(e.handleInput=r=>{let l=e.submenuComponent?void 0:_.get(r);n(l??r)}),t}s(te,"withVimKeys");function ne(t){return{selectedPrefix:s(()=>t.fg("accent","\u2192 "),"selectedPrefix"),selectedText:s(e=>t.fg("accent",e),"selectedText"),description:s(e=>t.fg("muted",e),"description"),scrollInfo:s(e=>t.fg("dim",e),"scrollInfo"),noMatch:s(e=>t.fg("dim",e),"noMatch")}}s(ne,"buildSelectListTheme");function ie(t,e,n){let r,l=new g(t,null,{onSelect:s(a=>{let o=e.onSelect(a);o&&r.activate(o)},"onSelect"),onCancel:e.onCancel},n);return r=new I(l),r}s(ie,"createSearchableSelect");function se(t){return t.length===1?`agent ${t[0]}`:`${t.length} agent(s)`}s(se,"agentSubject");export{g as a,O as b,j as c,K as d,I as e,q as f,T as g,X as h,J as i,Q as j,Y as k,Z as l,ee as m,te as n,ne as o,ie as p,se as q};
2
+ //# sourceMappingURL=chunk-BG5YDJXX.js.map
@@ -0,0 +1,2 @@
1
+ var k=Object.defineProperty;var t=(e,n)=>k(e,"name",{value:n,configurable:!0});function z(e){return!e||e.length>128||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)}t(z,"isUnsafeName");function C(e){return e.replace(/[\r\n]+/g," ").trim()}t(C,"toSingleLine");function b(e){return new Promise(n=>setTimeout(n,e))}t(b,"sleep");function Z(e){return C(e instanceof Error?e.message:String(e))}t(Z,"errorMessage");function w(e){if(typeof e!="string")return null;let n=e.indexOf("/");return n<=0?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}t(w,"parseModelKey");function J(e,n,r){if(!e)return r;let o=w(e);return o?n.find(o.provider,o.modelId)??r:r}t(J,"findModelInRegistry");function Q(e){if(e)return"model"in e?e.model.id:"harness"in e?e.name:void 0}t(Q,"modelChoiceName");function ee(e){return e!=null&&"key"in e?e.key:void 0}t(ee,"modelChoiceKey");var ne=5e3;function re(e){throw new Error(`Unhandled variant: ${JSON.stringify(e)}`)}t(re,"assertNever");import{randomBytes as v}from"node:crypto";import{Buffer as p}from"buffer";var c="0123456789ABCDEFGHJKMNPQRSTVWXYZ",R="*~$=U",g=class extends Error{static{t(this,"InvalidChecksumCharacterError")}constructor(n){super(n),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},x=class extends Error{static{t(this,"InvalidChecksumError")}constructor(n){super(n),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},y=class{static{t(this,"CrockfordBase32")}static encode(n,r){p.isBuffer(n)?n=p.from(n):n=this.createBuffer(n);let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(n)}let s=[],a=0,i=0;for(let d of n)for(i=i<<8|d,a+=8;a>=5;)s.push(i>>>a-5&31),a-=5;a>0&&s.push(i<<5-a&31);let l=s.map(d=>c.charAt(d)).join("");return u&&(l+=this.computeChecksum(n)),l}static computeChecksum(n){let r=0;for(let o of n)r=(r*256+o)%37;return(c+R).charAt(r)}static decode(n,r){n=n.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(n,r)}let s=null;if(u){if(n.length===0)throw new g("Cannot validate checksum: input is empty");let d=n.charAt(n.length-1);if((c+R).indexOf(d)===-1)throw new g(`Invalid checksum character: ${d}`);s=d,n=n.slice(0,-1)}let a=[],i=0,l=0;for(let d of n){let f=c.indexOf(d);if(f===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);i+=5,i>=8?(i-=8,a.push(l|f>>i),l=f<<8-i&255):l|=f<<8-i}if((l>0||i>=5)&&a.push(l),s!==null){let d=this.computeChecksum(a);if(s!==d)throw new x(`Checksum mismatch: expected '${d}' but found '${s}'`)}return r?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(n){try{return this.decode(n,{checksum:!0}),!0}catch{return!1}}static encodeUlid(n){if(n.length===0)return"";let r=0n;for(let s of n)r=r<<8n|BigInt(s);let o=[];for(;r>0n;){let s=Number(r%32n);o.unshift(c.charAt(s)),r/=32n}let u=Math.ceil(n.length*8/5);return o.join("").padStart(u,"0")}static decodeUlid(n,r){if(n.length===0)return r?.asNumber===!0?0n:p.from([]);let o=0n;for(let i of n){let l=c.indexOf(i);if(l===-1)throw new Error(`Invalid base 32 character found in string: ${i}`);o=o*32n+BigInt(l)}let u=Math.floor(n.length*5/8),s=[],a=o;for(;a>0n;)s.unshift(Number(a&0xffn)),a>>=8n;for(o===0n&&s.push(0);s.length<u;)s.unshift(0);return r?.asNumber===!0?this.asNumber(s):this.asBuffer(s)}static createBuffer(n){if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new Error("Input must be a safe integer");n=BigInt(n)}if(n<0n)throw new Error("Input cannot be a negative number");let r=[];for(;n>0n;)r.unshift(Number(n&0xffn)),n>>=8n;return p.from(r)}static asNumber(n){let r=0n;return n.forEach(o=>{r<<=8n,r|=BigInt(o)}),r}static asBuffer(n){return p.from(n.map(r=>r.toString(16).padStart(2,"0")).join(""),"hex")}};var S="0123456789abcdefghjkmnpqrstvwxyz",A=8,O=5,I=32,E=class extends Error{static{t(this,"SpawnIdExhaustedError")}constructor(n){super(`Could not mint a unique spawn id after ${n} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function T(){return y.encode(v(O)).toLowerCase()}t(T,"generateSpawnId");function le(e,n=T){for(let r=0;r<I;r++){let o=n();if(!e(o))return o}throw new E(I)}t(le,"generateUniqueSpawnId");var M=`[${S}]{${A}}`,L=32,m=9,ge=String(m).length+1;function ye(e,n){if(!Number.isInteger(n)||n<1||n>m)throw new Error(`agent index must be an integer in 1..${m}, got ${String(n)}`);let r=`${e}-${n}`;if(r.length>L)throw new Error(`agent name "${r}" is ${r.length} characters, over herdr's ${L}-character limit`);return r}t(ye,"agentNameWithIndex");function me(e){let n=/^(.*)-(\d+)$/.exec(e);if(n===null)return{base:e,index:1};let r=Number(n[2]);return!Number.isSafeInteger(r)||r<1||r>m?{base:e,index:1}:{base:n[1],index:r}}t(me,"parseAgentName");function he(e,n){return new RegExp(`^cow-${n}-${M}(-\\d+)?$`).test(e)}t(he,"isTaskAgentName");function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}t(_,"isRecord");function xe(e){if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}t(xe,"nonEmpty");var D=["pi","pig","pi-bolt","opencode","codex","claude"],Ie="pi",q=["pi","pig","pi-bolt"];function Se(e){return q.some(n=>n===e)}t(Se,"isPiFamilyHarness");function Ae(e){return D.find(n=>n===e)}t(Ae,"parseHarnessId");var F=["PATH","HOME","SHELL","PWD","OLDPWD","IFS","CDPATH","GLOBIGNORE","PS1","PS2","PS3","PS4","BASH_ENV","ENV","NODE_OPTIONS","LD_PRELOAD","LD_AUDIT"],B=["DYLD_","HERDR_","COWBOY_"],N=Object.freeze([]),$=/^[A-Za-z_][A-Za-z0-9_]*$/;function Le(e){return $.test(e)}t(Le,"isEnvVarName");function _e(e){return new RegExp("\\p{Cc}","u").test(e)}t(_e,"hasControlCharacter");function V(e){return F.includes(e)||B.some(n=>e.startsWith(n))}t(V,"isUniversalReservedEnvVar");function He(e,n=N){return V(e)||n.includes(e)}t(He,"isReservedEnvVar");function Ne(e){return e.reservedEnvVars?.()??N}t(Ne,"reservedEnvVarsOf");var Pe={pi:["PI_CODING_AGENT_DIR","PI_CODING_AGENT_SESSION_DIR","HERDR_AGENT"],opencode:["OPENCODE_CONFIG_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_CONTENT","OPENCODE_DISABLE_PROJECT_CONFIG","OPENCODE_DISABLE_AUTOUPDATE"],codex:["CODEX_HOME"],claude:["CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_DISABLE_CLAUDE_MDS","ANTHROPIC_API_KEY","COWBOY_API_KEY"]};function ke(e,n){return{kind:"other",unmappedKind:typeof e=="string"&&e!==""?e:"unknown",content:n}}t(ke,"otherRecord");function Ce(e){if(!_(e)||typeof e.content!="string")return h(e);let n=e.kind;if(typeof n!="string")return h(e);switch(n){case"user":case"assistant":case"thinking":case"tool-call":case"compaction":case"unparseable":return{kind:n,content:e.content};case"other":return typeof e.unmappedKind=="string"?{kind:n,unmappedKind:e.unmappedKind,content:e.content}:h(e);default:return h(e)}}t(Ce,"readHandoverRecord");function h(e){if(typeof e=="string")return{kind:"unparseable",content:e};try{return{kind:"unparseable",content:JSON.stringify(e)??String(e)}}catch{return{kind:"unparseable",content:String(e)}}}t(h,"unreadableRecord");var H=class extends Error{static{t(this,"SessionExportError")}fault;constructor(n,r){super(r),this.name="SessionExportError",this.fault=n}};function we(e){return e.kind==="unavailable"?[]:e.entries}t(we,"modelListEntries");function ve(e){return e.kind==="listed"?void 0:e.notice}t(ve,"modelListNotice");function Oe(e){return e.readHandoverRecords!==void 0}t(Oe,"canReadHandoverRecords");function U(e){return`'${e.replaceAll("'","'\\''")}'`}t(U,"singleQuoteShellWord");function qe(e,n){return e===null?n:`( . ${U(e)} && { ${n}; } )`}t(qe,"launchEnvBody");var P=5,G=2e3,W=250;function j(e){let n=e.indexOf("_");return n===-1?e:`${e.slice(0,n+1)}""${e.slice(n+1)}`}t(j,"splitMarker");async function Fe(e,n,r){let o=`${r.commandName}() { : "${r.signature}"; ${r.body}; }`,u=`typeset -f ${r.commandName} 2>/dev/null | grep -q "${r.signature}" && echo ${j(r.readyMarker)}`;for(let s=1;s<=P;s++){if(await e.run(n,o),await e.run(n,u),await K(e,n,r.readyMarker,G)){r.proof!==void 0&&await Y(e,n,r.proof);return}s<P&&await b(W)}throw new Error(`failed to prepare pane ${n}: the ${r.commandName} launcher never landed`)}t(Fe,"installPaneLauncher");async function K(e,n,r,o){try{return await e.waitForOutput(n,r,o),!0}catch{return!1}}t(K,"panePrinted");async function Y(e,n,r){await e.run(n,r.command);try{await e.waitForOutput(n,r.output,r.timeoutMs)}catch{throw new Error(r.failure)}}t(Y,"requirePaneProof");export{t as a,S as b,A as c,T as d,le as e,L as f,m as g,ge as h,ye as i,me as j,he as k,_ as l,xe as m,z as n,b as o,Z as p,w as q,J as r,Q as s,ee as t,ne as u,re as v,D as w,Ie as x,Se as y,Ae as z,Le as A,_e as B,V as C,He as D,Ne as E,Pe as F,ke as G,Ce as H,H as I,we as J,ve as K,Oe as L,U as M,qe as N,j as O,Fe as P};
2
+ //# sourceMappingURL=chunk-CTAS2E47.js.map
@@ -1,2 +1,2 @@
1
- import{h as l,n as h}from"./chunk-3P4DDY2M.js";import{a as r}from"./chunk-3TPZINCV.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
2
- //# sourceMappingURL=chunk-PBWQODAQ.js.map
1
+ import{h as l,n as h}from"./chunk-BG5YDJXX.js";import{a as r}from"./chunk-CTAS2E47.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
2
+ //# sourceMappingURL=chunk-DEDD7SGT.js.map