pi-cowboy 0.23.2 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/agents/agent-manager.d.ts +2 -0
- package/dist/agents/handover-export.d.ts +32 -0
- package/dist/agents/handover-file.d.ts +14 -0
- package/dist/agents/handover-target.d.ts +16 -0
- package/dist/agents/handover.d.ts +7 -5
- package/dist/agents/harness/codex-session-schema.d.ts +13 -0
- package/dist/agents/harness/codex-session.d.ts +2 -2
- package/dist/agents/harness/opencode/session-export.d.ts +1 -1
- package/dist/agents/harness.d.ts +4 -1
- package/dist/agents/subagent-session.d.ts +5 -0
- package/dist/{chunk-277WT5MT.js → chunk-67VN34QV.js} +2 -2
- package/dist/chunk-CAWIXE4E.js +14 -0
- package/dist/chunk-GYO352IF.js +47 -0
- package/dist/chunk-NF2BSEPU.js +26 -0
- package/dist/{chunk-MZROKRT4.js → chunk-ROCBRG4A.js} +2 -2
- package/dist/{chunk-J5TU3AFX.js → chunk-XXNZAWMK.js} +1 -1
- package/dist/host-multiplexer.d.ts +1 -1
- package/dist/index.js +17 -17
- package/dist/{menu-worktree-command-THJ3VSWU.js → menu-worktree-command-FGIFMYRD.js} +2 -2
- package/dist/menus-QMEWZXAL.js +9 -0
- package/dist/{model-picker-FMMQY4KI.js → model-picker-I2L5LYS7.js} +2 -2
- package/dist/plugin/index.js +1 -1
- package/dist/spawn/sandbox.d.ts +10 -0
- package/dist/ui/action-report.d.ts +1 -0
- package/dist/ui/menu/menu-agent-handover.d.ts +12 -0
- package/dist/ui/menu/menu-agent-status.d.ts +1 -1
- package/package.json +2 -2
- package/dist/chunk-M42XWVYW.js +0 -45
- package/dist/chunk-S4BS2R6G.js +0 -26
- package/dist/chunk-TFQCH2TO.js +0 -14
- package/dist/menus-KXKDXZRN.js +0 -9
package/README.md
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
**✨ NEW FEATURE - Cross-harness handover: pi-cowboy can now handover sessions between harnesses automatically. Ask pi to hand over a cowboy agent from one harness to another, or [use the menu](docs/Menu.md#handing-over-and-exporting).**
|
|
1
2
|
<p align="center">
|
|
2
3
|
<img src="https://raw.githubusercontent.com/electric-dragon-80000v/pi-cowboy/main/docs/assets/logo-labeled-readme.png" alt="pi-cowboy">
|
|
3
4
|
</p>
|
|
@@ -8,6 +9,8 @@
|
|
|
8
9
|
|
|
9
10
|
**License:** MIT
|
|
10
11
|
|
|
12
|
+
|
|
13
|
+
`
|
|
11
14
|
`pi-cowboy` is a multi-agent orchestrator for [pi](https://pi.dev). Break a large job into focused subtasks, hand them off to background agents running in parallel, and consolidate them when they finish.
|
|
12
15
|
|
|
13
16
|
Each agent runs in its own terminal pane inside [Herdr](https://github.com/electric-dragon-80000v/herdr) and works in an isolated copy-on-write Git worktree. You can watch agents work in real time, jump into any pane to steer them, or mix and match harnesses like Pi, Claude Code, OpenCode, and Codex in the same session. When the work is finished, `pi-cowboy` cleans up the leftovers for you.
|
|
@@ -6,6 +6,7 @@ import type { SupervisorTransport } from "../subagent/pane-supervisor.js";
|
|
|
6
6
|
import type { ExecutionRuntime } from "./agent-host.js";
|
|
7
7
|
import { type LocateResult } from "./agent-assets.js";
|
|
8
8
|
import type { CleanupOptions, CleanupReport } from "./cleanup-policy.js";
|
|
9
|
+
import type { HandoverExportOutcome } from "./handover-export.js";
|
|
9
10
|
import type { HandoverOutcome } from "./handover.js";
|
|
10
11
|
import { DISPOSE_QUEUED_MESSAGE, type SessionHandoverRequest, type SpawnOptions, type SteerOutcome } from "./subagent-session.js";
|
|
11
12
|
import type { SubagentType } from "./types.js";
|
|
@@ -33,6 +34,7 @@ export declare class AgentManager {
|
|
|
33
34
|
steer(id: string, message: string): Promise<SteerOutcome>;
|
|
34
35
|
isHandingOver(id: string): boolean;
|
|
35
36
|
handover(id: string, request: SessionHandoverRequest): Promise<HandoverOutcome>;
|
|
37
|
+
exportHandover(id: string): Promise<HandoverExportOutcome>;
|
|
36
38
|
getSpawn(id: string): AgentSpawn | undefined;
|
|
37
39
|
private assets;
|
|
38
40
|
locate(id: string): Promise<LocateResult>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { AnyHarnessId, HarnessExportLoss } from "./harness.js";
|
|
2
|
+
import type { HandoverSourceFault } from "./handover.js";
|
|
3
|
+
import type { ToolSeverity } from "./tool-result.js";
|
|
4
|
+
export interface HandoverExportArtifact {
|
|
5
|
+
readonly path: string;
|
|
6
|
+
readonly text: string;
|
|
7
|
+
readonly sessionId: string;
|
|
8
|
+
readonly loss?: HarnessExportLoss;
|
|
9
|
+
}
|
|
10
|
+
export type HandoverExportFault = HandoverSourceFault | {
|
|
11
|
+
readonly kind: "handover-in-progress";
|
|
12
|
+
readonly detail: string;
|
|
13
|
+
};
|
|
14
|
+
export type HandoverExportOutcome = ({
|
|
15
|
+
readonly kind: "prepared";
|
|
16
|
+
} & HandoverExportArtifact) | {
|
|
17
|
+
readonly kind: "faulted";
|
|
18
|
+
readonly fault: HandoverExportFault;
|
|
19
|
+
};
|
|
20
|
+
export type PreparedHandoverExport = Extract<HandoverExportOutcome, {
|
|
21
|
+
kind: "prepared";
|
|
22
|
+
}>;
|
|
23
|
+
export interface HandoverExportRequest {
|
|
24
|
+
readonly worktree: string;
|
|
25
|
+
readonly harness: AnyHarnessId;
|
|
26
|
+
readonly sessionId: string;
|
|
27
|
+
readonly text: string;
|
|
28
|
+
readonly loss?: HarnessExportLoss;
|
|
29
|
+
}
|
|
30
|
+
export declare function handoverExportArtifact(request: HandoverExportRequest): PreparedHandoverExport;
|
|
31
|
+
export declare function handoverExportFaultReason(fault: HandoverExportFault): string;
|
|
32
|
+
export declare function handoverExportSeverity(outcome: HandoverExportOutcome): ToolSeverity;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AnyHarnessId } from "./harness.js";
|
|
2
|
+
export declare const HANDOVER_EXPORT_DIR = "/tmp";
|
|
3
|
+
export declare function handoverNameField(value: string): string;
|
|
4
|
+
export interface HandoverFileRequest {
|
|
5
|
+
readonly worktree: string;
|
|
6
|
+
readonly harness: AnyHarnessId;
|
|
7
|
+
readonly sessionId: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function handoverFileName(request: HandoverFileRequest): string;
|
|
10
|
+
export declare function handoverFilePath(name: string): string;
|
|
11
|
+
export declare function handoverFileExists(path: string): boolean;
|
|
12
|
+
export declare function writeHandoverFile(path: string, text: string): {
|
|
13
|
+
readonly replaced: boolean;
|
|
14
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type Availability } from "../availability.js";
|
|
2
|
+
import type { HarnessRegistry } from "./harness/harness-registry.js";
|
|
3
|
+
import type { AnyHarnessId } from "./harness.js";
|
|
4
|
+
export interface HandoverTargetFault {
|
|
5
|
+
readonly kind: "request-refused";
|
|
6
|
+
readonly detail: string;
|
|
7
|
+
}
|
|
8
|
+
export type TargetRegistry = Pick<HarnessRegistry, "ids" | "get">;
|
|
9
|
+
export declare function handoverTargets(registry: TargetRegistry, availability: Availability<AnyHarnessId>, source: AnyHarnessId): AnyHarnessId[];
|
|
10
|
+
export declare function resolveHandoverTarget(raw: string, registry: TargetRegistry, availability: Availability<AnyHarnessId>): {
|
|
11
|
+
readonly kind: "ready";
|
|
12
|
+
readonly harness: AnyHarnessId;
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: "faulted";
|
|
15
|
+
readonly fault: HandoverTargetFault;
|
|
16
|
+
};
|
|
@@ -6,7 +6,7 @@ export interface SessionExportPolicy {
|
|
|
6
6
|
readonly maxExcludedRatio: number;
|
|
7
7
|
}
|
|
8
8
|
export declare const DEFAULT_MAX_EXCLUDED_RATIO = 0.5;
|
|
9
|
-
export type
|
|
9
|
+
export type HandoverSourceFault = {
|
|
10
10
|
readonly kind: "agent-unknown";
|
|
11
11
|
} | {
|
|
12
12
|
readonly kind: "agent-not-settled";
|
|
@@ -16,9 +16,6 @@ export type HandoverFault = {
|
|
|
16
16
|
readonly harness: AnyHarnessId;
|
|
17
17
|
} | {
|
|
18
18
|
readonly kind: "never-started";
|
|
19
|
-
} | {
|
|
20
|
-
readonly kind: "stop-failed";
|
|
21
|
-
readonly detail: string;
|
|
22
19
|
} | {
|
|
23
20
|
readonly kind: "session-empty";
|
|
24
21
|
readonly harness: AnyHarnessId;
|
|
@@ -27,6 +24,10 @@ export type HandoverFault = {
|
|
|
27
24
|
readonly harness: AnyHarnessId;
|
|
28
25
|
readonly detail: string;
|
|
29
26
|
readonly exportFault?: SessionExportFault;
|
|
27
|
+
};
|
|
28
|
+
export type HandoverFault = HandoverSourceFault | {
|
|
29
|
+
readonly kind: "stop-failed";
|
|
30
|
+
readonly detail: string;
|
|
30
31
|
} | {
|
|
31
32
|
readonly kind: "request-refused";
|
|
32
33
|
readonly detail: string;
|
|
@@ -43,6 +44,7 @@ export type HandoverOutcome = {
|
|
|
43
44
|
readonly kind: "faulted";
|
|
44
45
|
readonly fault: HandoverFault;
|
|
45
46
|
};
|
|
47
|
+
export declare function handoverLossClause(loss: HarnessExportLoss): string;
|
|
46
48
|
export declare function handoverSeverity(outcome: HandoverOutcome): ToolSeverity;
|
|
47
49
|
export type RunSession = {
|
|
48
50
|
readonly kind: "exported";
|
|
@@ -51,7 +53,7 @@ export type RunSession = {
|
|
|
51
53
|
readonly loss?: HarnessExportLoss;
|
|
52
54
|
} | {
|
|
53
55
|
readonly kind: "faulted";
|
|
54
|
-
readonly fault:
|
|
56
|
+
readonly fault: HandoverSourceFault;
|
|
55
57
|
};
|
|
56
58
|
export declare function completeHandoverExport(source: HandoverRecordSource): HarnessExport;
|
|
57
59
|
export declare function exportRunSession(harnesses: HarnessRegistry, from: AnyHarnessId, request: HarnessExportRequest, policy: SessionExportPolicy): Promise<RunSession>;
|
|
@@ -77,6 +77,19 @@ export declare const RolloutLineSchema: z.ZodUnion<readonly [z.ZodPipe<z.ZodObje
|
|
|
77
77
|
} | {
|
|
78
78
|
type: string;
|
|
79
79
|
};
|
|
80
|
+
}>>, z.ZodPipe<z.ZodObject<{
|
|
81
|
+
type: z.ZodLiteral<"compacted">;
|
|
82
|
+
payload: z.ZodObject<{
|
|
83
|
+
message: z.ZodString;
|
|
84
|
+
}, z.core.$strip>;
|
|
85
|
+
}, z.core.$strip>, z.ZodTransform<{
|
|
86
|
+
kind: "compacted";
|
|
87
|
+
summary: string;
|
|
88
|
+
}, {
|
|
89
|
+
type: "compacted";
|
|
90
|
+
payload: {
|
|
91
|
+
message: string;
|
|
92
|
+
};
|
|
80
93
|
}>>, z.ZodPipe<z.ZodObject<{
|
|
81
94
|
type: z.ZodString;
|
|
82
95
|
}, z.core.$strip>, z.ZodTransform<{
|
|
@@ -8,10 +8,10 @@ export interface CodexSessionExportRequest {
|
|
|
8
8
|
readonly codexHome: string;
|
|
9
9
|
}
|
|
10
10
|
export interface CodexSessionExport extends CodexSessionRecord {
|
|
11
|
-
readonly records:
|
|
11
|
+
readonly records: Iterable<HandoverRecord>;
|
|
12
12
|
}
|
|
13
13
|
export declare const CODEX_HOME_ENV_VAR = "CODEX_HOME";
|
|
14
14
|
export declare function codexHomeDirectory(): string;
|
|
15
15
|
export declare function findCodexSession(request: CodexSessionExportRequest): CodexSessionRecord;
|
|
16
16
|
export declare function exportCodexSession(request: CodexSessionExportRequest): CodexSessionExport;
|
|
17
|
-
export declare function readCodexSession(file: string):
|
|
17
|
+
export declare function readCodexSession(file: string): Iterable<HandoverRecord>;
|
|
@@ -34,6 +34,6 @@ export declare function selectOpencodeRunSession(sessions: readonly OpencodeSess
|
|
|
34
34
|
readonly proofModel: string;
|
|
35
35
|
}): OpencodeSessionSummary | undefined;
|
|
36
36
|
export declare function parseOpencodeSessionExport(stdout: string): OpencodeSessionExport | undefined;
|
|
37
|
-
export declare function classifyOpencodeMessages(messages: readonly unknown[]):
|
|
37
|
+
export declare function classifyOpencodeMessages(messages: readonly unknown[]): Iterable<HandoverRecord>;
|
|
38
38
|
export declare function readOpencodeSessionRecords(request: OpencodeSessionExportRequest): Promise<HandoverRecordSource>;
|
|
39
39
|
export {};
|
package/dist/agents/harness.d.ts
CHANGED
|
@@ -129,10 +129,13 @@ export type HandoverRecord = {
|
|
|
129
129
|
} | {
|
|
130
130
|
readonly kind: "unparseable";
|
|
131
131
|
readonly content: string;
|
|
132
|
+
} | {
|
|
133
|
+
readonly kind: "compaction";
|
|
134
|
+
readonly summary: string;
|
|
132
135
|
};
|
|
133
136
|
export interface HandoverRecordSource {
|
|
134
137
|
readonly sessionId: string;
|
|
135
|
-
readonly records:
|
|
138
|
+
readonly records: Iterable<HandoverRecord>;
|
|
136
139
|
}
|
|
137
140
|
export interface HarnessExportLoss {
|
|
138
141
|
readonly excluded: number;
|
|
@@ -4,6 +4,7 @@ import type { ConcurrencyPools, PoolReservation } from "../concurrency-pools.js"
|
|
|
4
4
|
import type { AgentSpawn, ModelChoice, SpawnConfig, StopInitiator } from "../types.js";
|
|
5
5
|
import type { AnyHarnessId } from "./harness.js";
|
|
6
6
|
import { type HandoverOutcome } from "./handover.js";
|
|
7
|
+
import { type HandoverExportOutcome } from "./handover-export.js";
|
|
7
8
|
import type { SubagentType } from "./types.js";
|
|
8
9
|
export { DISPOSE_QUEUED_MESSAGE } from "./run-state.js";
|
|
9
10
|
export type SteerOutcome = {
|
|
@@ -71,7 +72,11 @@ export declare class SubagentSession {
|
|
|
71
72
|
steer(message: string): Promise<SteerOutcome>;
|
|
72
73
|
private revive;
|
|
73
74
|
abort(initiator?: StopInitiator): Promise<boolean>;
|
|
75
|
+
private handoverSource;
|
|
76
|
+
private exportSettledSession;
|
|
77
|
+
private handoverTask;
|
|
74
78
|
handover(request: SessionHandoverRequest): Promise<HandoverOutcome>;
|
|
79
|
+
exportHandover(): Promise<HandoverExportOutcome>;
|
|
75
80
|
drop(): void;
|
|
76
81
|
settleForDispose(): void;
|
|
77
82
|
private launch;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as l,n as h}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{h as l,n as h}from"./chunk-ROCBRG4A.js";import{a as r}from"./chunk-XXNZAWMK.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-67VN34QV.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import{A as pt,B as gt,C as ht,D as Z,J,K as mt,M as ft,N as yt,O as ee,b as ot,c as st,e as it,g as at,k as xe,l as dt,p as lt,u as ct,v as X,w as ut}from"./chunk-NF2BSEPU.js";import{Ca as rt,D as Qe,Fa as be,I as me,K as Xe,L as fe,O as ye,P as Ze,R as Y,S as T,T as I,V as Je,Z as et,_ as tt,b as Le,ia as x,j,ja as z,k as je,ka as w,l as Ue,m as ge,ma as y,na as E,o as qe,oa as we,pa as ve,ra as nt,ua as ke,v as We,va as V,w as Fe,wa as O,x as Ke,xa as N,y as Ge,za as Q}from"./chunk-GYO352IF.js";import{a as r,d as $,f as he,g as Ye,j as ze,k as F,l as Ve,u as K,v as G}from"./chunk-XXNZAWMK.js";import{visibleWidth as Re}from"@earendil-works/pi-tui";var Ae="\u{1F920}",kt="\u{1F404}",an="\u{1F4A9}",dn=2,ln=1e3,te=Re(kt),cn="76;175;80";function un(e){return`\x1B[48;2;${cn}m${e}\x1B[49m`}r(un,"greenBackground");function bt(e){return e===0?0:Math.max(dn,Math.ceil(Math.sqrt(2*e)))}r(bt,"pastureEdge");function xt(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(xt,"emptyPasture");function pn(e,t){let n=bt(e.cows+e.droppings),o=xt(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(pn,"grazedPasture");function ne(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(ne,"cellsOf");function gn(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(gn,"neighboursOf");function wt(e,t){return gn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(wt,"openNeighboursOf");function hn(e,t){let n=ne(e,"cow").filter(d=>wt(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=wt(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(hn,"moveHerd");function vt(e,t,n,o){for(let i=0;i<n;i+=1){let a=ne(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(vt,"placeAtRandom");function mn(e,t,n,o){let i=ne(e,"cow"),a=ne(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}vt(e,"cow",-s,o),vt(e,"dropping",-d,o)}r(mn,"reconcileCounts");function fn(e,t,n){if(e===null)return pn(t,n);let o=bt(t.cows+t.droppings),i=xt(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 mn(i,t.cows,t.droppings,n),i}r(fn,"reconcilePasture");var yn={anchor:"top-right",width:Re(Ae),get offsetX(){return E()?.cowboyOffsetX??0},nonCapturing:!0},wn={anchor:"top-right",offsetY:1,get width(){return E()?.pastureWidth??0},nonCapturing:!0};function vn(e){return e==="cow"?kt:e==="dropping"?an:" ".repeat(te)}r(vn,"cellText");function kn(e,t){return e.map(n=>t(n.map(vn).join("")))}r(kn,"drawnRows");function bn(){return ve().list(["spawned"]).length}r(bn,"liveAgentCount");function xn(){return ve().list(Ze).length}r(xn,"endedAgentCount");function An(){return{live:bn(),ended:xn()}}r(An,"agentCounts");function Sn(){return y().agent.grazingEnabled}r(Sn,"grazingEnabled");var Se=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 Re(Ae)}get pastureWidth(){return this.drawnPasture().length*te}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*te-(t*te-this.cowboyWidth)}render(){return this.frame(),[Ae]}pastureRows(){return this.frame(),kn(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(),ln))}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:hn(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:fn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Te=class{static{r(this,"PastureView")}render(){return E()?.pastureRows()??[]}invalidate(){}};function At(e){Ie(),e.custom(t=>{let n=new Se(t,An,Sn,un,Math.random);return we(n),n},{overlay:!0,overlayOptions:yn,onHandle:r(t=>E()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Te,{overlay:!0,overlayOptions:wn,onHandle:r(t=>E()?.attachPasture(t),"onHandle")})}r(At,"showExtensionIndicator");function Ie(){let e=E();we(null),e?.dispose()}r(Ie,"hideExtensionIndicator");function re(){return y().agent.extensionEnabled}r(re,"isExtensionEnabled");function Tn(){return re()&&y().agent.showActiveIndicator}r(Tn,"isActiveIndicatorShown");function oe(e){Tn()?At(e):Ie()}r(oe,"syncExtensionIndicator");function Xr(e,t){y().mutate.agent.setShowActiveIndicator(t),oe(e)}r(Xr,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as Pr}from"@earendil-works/pi-tui";import{Type as h}from"typebox";var Rn="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.",In=`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.`,En=`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.`,On=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${F.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.`,Cn=h.Object({prompt:h.String({description:Rn}),task_name:h.String({description:In}),agent_type:h.Optional(h.Union([h.String(),h.Null()])),model:h.Optional(h.Union([h.String(),h.Null()],{description:En})),harness_type:h.Optional(h.Union([h.String(),h.Null()],{description:On}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=h.Object({agents:h.Array(Cn,{minItems:1}),run_in_background:h.Optional(h.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"},Ee=Object.values(m),b={type:"json_schema",strict:"prefer"};var Oe="_configuredModel",Ce="_configuredThinking";function D(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(D,"readModelKey");function se(e){return D(e.thinking)??D(e[Ce])}r(se,"readThinkingRequest");function ie(e){let t=D(e.model);if(t)return{source:"call",key:t};let n=D(e[Oe]);if(n)return{source:"configured",key:n}}r(ie,"readModelRequest");function U(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(U,"withoutModel");function ae(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(ae,"modelChoiceFor");function q(e){return`${e.provider}/${e.id}`}r(q,"modelKey");function _n(e,t){if(t!==void 0&&!fe.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${fe.options.join(", ")}); launching "${q(e)}" with "${t}".`}r(_n,"undeclaredLevelWarning");function St(e,t){let n=_n(e,t);return{resolved:{kind:"resolved",model:e,modelKey:q(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(St,"resolvedModel");function Pn(e){return`No API key found for "${e}"`}r(Pn,"missingCredential");function Tt(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:Pn(t.provider)}}r(Tt,"probeCredentials");function _e(e,t){return`${e}: ${t}. Nothing was spawned.`}r(_e,"refusal");function Pe(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return U(i);let d=Tt(n,o);if(d.verdict!=="unusable")return St(o,i);throw new Error(_e(`The parent session's model "${q(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 U(i)}let s=Tt(n,a);if(s.verdict!=="unusable")return St(a,i);throw e.source==="call"?new Error(_e(`Model "${q(a)}" cannot authenticate in this session`,s.reason)):new Error(_e(`The subagent model "${q(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(Pe,"resolvePiModel");async function Mn(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Mn,"harnessModels");function $n(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($n,"undeclaredLevelWarning");async function Rt(e,t){if(!e)return U(t.thinking);let n=await Mn(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=$n(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(Rt,"resolveForeignModel");async function de(e,t){let{harness:n}=t;if(Ve(n))return Pe(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Rt(e,o)}r(de,"resolveSpawnModel");function B(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(B,"resultWithSeverity");function le(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(le,"foldSeverity");var Me=`
|
|
2
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
`,Nn={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function R(e){let{items:t}=e;Dn(t,e),await e.prepare?.();let n=Hn(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 B(le(o.map(e.severity)),i.join(Me),{[e.detailsKey]:o})}r(R,"runBatch");function Hn(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(Hn,"batchSteps");function Dn(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=Nn[n];throw new Error(`${t} received duplicate ${a.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(Dn,"rejectRepeatedKeys");var It={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"},Bn={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 Ln(e){if(!T(e)||e.status!=="stopped")return It.agent;let{stop:t}=e;return e.phase==="never-started"?Bn[t.initiator]:It[t.initiator]}r(Ln,"stopNote");function Et(e){return!T(e)||e.status!=="stopped"?"":` (${Ln(e)})`}r(Et,"getStatusNote");function C(e=w()){let t=e.listAgents(ye).filter(n=>Y(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(C,"formatActiveAgents");function $e(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-Je(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($e,"buildAgentDetails");function jn(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 ze(e)}}r(jn,"settledOutcome");function Un(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${I(e.lifecycle)}]`}r(Un,"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",ht({outcome:jn(t),statusNote:Et(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?lt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:y().multiplexer||Xe}))}r(qn,"formatResultContent");var Ne=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=J(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=We(s),c=mt(),l=await ct(i,void 0,(k,S)=>{n.ui.notify(k,S)});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=yt(t.harness_type),g=ee(l.key,v),u=se(t),p=await de(ie(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:u,listModels:r(async k=>{let S=await O().require(k).listModels({pi:x(),modelCatalog:N(n.modelRegistry)}),W=G(S);return W!==void 0&&n.hasUI&&n.ui.notify(W,"warning"),K(S)},"listModels")});for(let k of p.notices)n.ui.notify(k,"warning");let f=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:X(i)?.fork??!1,modelChoice:ae(p.resolved),requestedHarness:v,isBackground:f})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:a}=this.intent,s=x(),d=w().mintSpawnId(),c=await this.expectedWorktree(s,d),l=this.intent.modelChoice?.thinking??void 0,v=Ye(this.intent.modelChoice),{agentId:g,spawn:u}=await nt().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=$e(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:`${Un(u)}
|
|
7
|
+
|
|
8
|
+
${qn(u)}`,details:S}}let p=c;if(u.lifecycle.phase==="queued"){let S=w().listAgents(ye).filter(sn=>sn.lifecycle.phase==="spawned").length,W=Z(this.intent.orchestrator.cues,"queued",gt({agentId:g,worktree:p,queueRunning:S})),pe=$e(u);return pe.agentId=g,pe.status="queued",{message:`[Agent queued] ${W}`,details:pe}}let f=Z(this.intent.orchestrator.cues,"spawned",pt({agentId:g,worktree:p})),k=$e(u);return k.agentId=g,k.status="spawned",{message:`[Agent spawned] ${f}`,details:k}}async expectedWorktree(t,n){let o=await at(t,z().cwd).catch(()=>{});if(o===void 0)return;let i=Ge(y().agent.worktreeRoot,o);return{kind:"owned",path:Ke(i,this.intent.taskSlug,n),branch:Fe(this.intent.taskSlug,n)}}};async function Ot(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=>Ne.parse(l,t,n)));Wn(a);let s=await Promise.all(a.map(l=>l.run(o))),d=s.map(l=>l.message).join(Me),c={agents:s.map(l=>l.details)};return{message:d,details:c}}r(Ot,"runDelegationBatch");function Wn(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(Wn,"rejectRepeatedTaskSlugs");import{Type as He}from"typebox";var Fn="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).",Ct=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:Fn})},{additionalProperties:!1,required:["agent_ids"]});function Kn(e){let t=Array.isArray(e.agents)?e.agents:[];return le(t.map(n=>typeof n=="object"&&n!==null&&n.status==="stopped"?"warning":"success"))}r(Kn,"delegationSeverity");async function _t(e,t,n,o,i){let{message:a,details:s}=await Ot(t,i,e,n);return B(Kn(s),a,s)}r(_t,"executeAgentTool");var Pt={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:Ct,execute:zn,constrainedSampling:b};function Gn(e){switch(e.kind){case"stopped":return"success";case"failed":return"error";case"already-settled":case"unknown":case"refused":return"warning"}}r(Gn,"stopSeverity");function Yn(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(Yn,"renderStopOutcome");async function zn(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:Yn,severity:Gn,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(!Y(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(zn,"executeStopAgentTool");async function ss(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=J(s),c=X(d),l=ft(a.harness_type),v=ee(d,l),g=D(a.model),u=g??y().modelFor(d,i,c,v);if(u&&!g&&(a[Oe]=u),a.thinking===void 0){let p=y().thinkingFor(d,c,v,t.thinkingLevel);p!==void 0&&(a[Ce]=p)}}}r(ss,"toolCallListener");import{Type as De}from"typebox";var Vn="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).",Mt=De.Object({agent_ids:De.Array(De.String({minLength:1}),{minItems:1,description:Vn})},{additionalProperties:!1,required:["agent_ids"]});function $t(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($t,"formatBasis");function Qn(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${$t(e.basis)})`}r(Qn,"formatSettlement");function Nt(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 (${$t(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(Nt,"formatKeptReason");function Xn(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(Xn,"paneText");function Zn(e){return e.length===0?"none (the agent never had a pane)":e.map(t=>`${t.paneId} ${Xn(t)}`).join(", ")}r(Zn,"panesText");function Jn(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(Jn,"paneSummary");function er(e){if(e.length===0)return"no pane";if(e.length===1)return Jn(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(er,"panesSummary");function Ht(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(Ht,"worktreeText");function Dt(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(Dt,"branchText");function tr(e){return e?` forced${e.reason?` \u2014 ${Nt(e.reason)}`:""}`:""}r(tr,"forcedClause");function Be(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Nt(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${tr(e.outcome.forced)}:`}r(Be,"headline");function Bt(e){let t=[Be(e),` agent status: ${Qn(e.settlement)}`,` panes: ${Zn(e.panes)}`,` worktree: ${Ht(e.worktree)}`,` branch: ${Dt(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(Bt,"renderCleanupReport");function cs(e){let t=er(e.panes);return e.outcome.kind==="refused"?`${Be(e)} ${t}`:`${Be(e)} ${t}, worktree ${Ht(e.worktree)}, branch ${Dt(e)}`}r(cs,"summarizeCleanupReport");function us(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(us,"cleanupNeedsAttention");var Lt={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:Mt,execute:or,constrainedSampling:b};function nr(e){return e.kind==="unknown"?"warning":e.report.outcome.kind==="torn-down"?"success":"warning"}r(nr,"cleanupSeverity");function rr(e){switch(e.kind){case"cleaned":return Bt(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(rr,"renderCleanupOutcome");async function or(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:rr,severity:nr,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(or,"executeCleanupAgentTool");import*as qt from"node:fs";import*as L from"node:path";import{Type as _}from"typebox";var sr="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",ir="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",ar="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.",jt=_.Object({branches:_.Array(_.String({minLength:1}),{minItems:1,description:sr}),target:_.Optional(_.String({description:ir})),repo:_.Optional(_.String({description:ar}))},{additionalProperties:!1,required:["branches"]});function Ut(e){let t=L.normalize(e),{root:n}=L.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Ut,"normalizeRepoRoot");function dr(e,t){return Ut(e)===Ut(t)}r(dr,"isSameRepoRoot");function lr(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(lr,"formatOutsideRepoWarning");async function cr(e,t){let n=new st(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}=it(i,o);if(!qt.existsSync(L.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(cr,"resolveSessionMainRoot");var Wt={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:jt,execute:fr,constrainedSampling:b};function ur(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(ur,"mergeSeverity");var pr="has conflicts in:";function gr(e){return e.includes(pr)}r(gr,"isConflictError");function hr(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(hr,"parseConflictFiles");function mr(e,t){return e.includes(`branch "${t}" does not exist`)}r(mr,"isUnknownBranchError");async function fr(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=z().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 cr(x(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:ur,prepare:r(async()=>{xe(a,"target");for(let l of t.branches)xe(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 p=await dt(x(),{cwd:g,branch:u,target:a}),f=dr(p.mainRoot,v)?void 0:lr(p.mainRoot,v);if(f!==void 0)try{i.ui.notify(f,"warning")}catch{}let k=f!==void 0?`${f}
|
|
11
|
+
`:"";return p.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${k}"${u}" is already merged into "${p.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:p.target,output:p.output},text:`${k}Merged "${u}" into "${p.target}" in ${p.mainRoot}.`+(p.output?`
|
|
12
|
+
${p.output}`:"")}}catch(p){let f=p instanceof Error?p.message:String(p);return gr(f)?{outcome:{kind:"conflict",branch:u,target:a,files:hr(f)},text:`"${u}": ${f}`}:mr(f,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${f}`}:{outcome:{kind:"failed",branch:u,error:f},text:`"${u}": ${f}`}}},"handleItem")})}r(fr,"executeMergeBranchTool");import{Type as ce}from"typebox";var yr="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.",wr="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.",Ft=ce.Object({agent_ids:ce.Array(ce.String({minLength:1}),{minItems:1,description:yr}),message:ce.String({description:wr})},{additionalProperties:!1,required:["agent_ids","message"]});var Kt={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:Ft,execute:kr,constrainedSampling:b};function vr(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(vr,"steerSeverity");async function kr(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:vr,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(kr,"executeSteerAgentTool");function Fs(e,t,n){return ge(e.ids(),t).filter(o=>o!==n)}r(Fs,"handoverTargets");function Gt(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.`}}:Ue(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 ${ge(t.ids(),n).join(", ")}. Nothing was changed.`}}}r(Gt,"resolveHandoverTarget");import{Type as A}from"typebox";var br="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.",xr=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${F.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.`,Ar=`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.`,Sr="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",Yt=A.Object({agent_id:A.String({minLength:1,description:br}),harness_type:A.String({description:xr}),model:A.Optional(A.Union([A.String(),A.Null()],{description:Ar})),thinking:A.Optional(A.Union([A.String(),A.Null()],{description:Sr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Tr(e,t){let n=Gt(e.harness_type,O(),Q());if(n.kind==="faulted")return{kind:"faulted",fault:n.fault};let o=n.harness;try{let i=await de(ie(e),{harness:o,registry:t.modelRegistry,parent:t.model,thinking:se(e),listModels:r(async a=>{let s=await O().require(a).listModels({pi:x(),modelCatalog:N(t.modelRegistry)}),d=G(s);return d!==void 0&&t.hasUI&&t.ui.notify(d,"warning"),K(s)},"listModels")});for(let a of i.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:o,modelChoice:ae(i.resolved)}}catch(i){return{kind:"faulted",fault:{kind:"request-refused",detail:$(i)}}}}r(Tr,"resolveIntent");function Rr(e,t){return`Agent ${e} ${Ir(t)}`}r(Rr,"renderHandoverOutcome");function Ir(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":et(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(Ir,"handoverReport");async function Er(e,t,n,o,i){let a=t.agent_id.trim(),s=await Tr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await w().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return B(tt(d),Rr(a,d),{agentId:a,outcome:d})}r(Er,"executeHandoverAgentTool");var zt={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:Yt,execute:Er,constrainedSampling:b};import{Text as Or}from"@earendil-works/pi-tui";var Cr={success:"\u2713",warning:"!",error:"\u2717"};function _r(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 Or(`${n.fg(a,Cr[a])} ${s}`,0,0)}r(_r,"renderCowboyToolResult");function P(e){return{...e,renderResult:_r}}r(P,"withCowboyRenderer");var Mr=Ee;function $r(e){let t=M.Object({prompt:H.properties.agents.items.properties.prompt,task_name:H.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:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r($r,"cowboyAgentsSchemaWithTypes");function Qt(e){let t=$r(ut()),n={name:m.agent,label:m.agent,description:"Delegate one or more tasks to agents. Each agent gets an isolated worktree and a fresh pi process \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. When an agent settles, the completion message names its `cow-` branch and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.",parameters:t,execute:_t,constrainedSampling:b};e.registerTool(P(n))}r(Qt,"registerAgentTool");function Nr(e,t){y().mutate.agent.setExtensionEnabled(t),t?Hr(e):Dr(e)}r(Nr,"setExtensionEnabled");function Hr(e){let t=x();Qt(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Mr])]),oe(e)}r(Hr,"activateExtension");function Dr(e){let t=x();t.setActiveTools(t.getActiveTools().filter(n=>!Ee.includes(n))),oe(e)}r(Dr,"deactivateExtension");function Si(e){Qt(e),e.registerTool(P(Pt)),e.registerTool(P(Wt)),e.registerTool(P(Kt)),e.registerTool(P(zt)),e.registerTool(P(Lt)),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 Pr(`${s} ${i}`,0,0)})}r(Si,"registerTools");async function Vt(e,t){let n=await O().listModelOptions({pi:e,modelCatalog:N(t.modelRegistry)},Q());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Vt,"harnessModelOptions");var Xt="cowboy",Br={wt:"worktree",sp:"spawn",st:"status"};function Ti(e,t){e.registerCommand(Xt,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Ti,"registerUnavailableCowboyCommand");function Ri(e){e.registerCommand(Xt,{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-I2L5LYS7.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{rt(n);let[o,...i]=t.trim().split(/\s+/),a=Br[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&be()===null){n.ui.notify(me,"warning");return}if(re()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}Nr(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(be()===null){n.ui.notify(me,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-FGIFMYRD.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!re()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-I2L5LYS7.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-QMEWZXAL.js");await l(n,s,await Vt(e,n));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-QMEWZXAL.js");await c(n,await Vt(e,n))},"handler")})}r(Ri,"registerCowboyCommand");import*as Zt from"node:fs";import{tmpdir as Lr}from"node:os";import*as ue from"node:path";async function Jt(e,t){try{return await ot(e).probe(t),j(qe)}catch{return j(["checkout"])}}r(Jt,"detectCowAvailability");function en(e){let t=ue.resolve(e??Le());for(;;){try{if(Zt.statSync(t).isDirectory())return t}catch{}let n=ue.dirname(t);if(n===t)return Lr();t=n}}r(en,"probeTargetFor");function jr(e){return(t,n,o)=>e.exec(t,n,o)}r(jr,"execOf");function Li(e){return tn(e,ke())}r(Li,"startCowSupportProbe");function ji(e){let t=ke();return V(t,je()),tn(e,t)}r(ji,"refreshCowSupportProbe");function tn(e,t){let n=en(y().agent.worktreeRoot);return Jt(jr(e),n).then(o=>{V(t,o)},()=>{V(t,j(["checkout"]))})}r(tn,"probe");import nn from"node:fs";var Ur="/tmp";function qr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(qr,"handoverNameField");function rn(e){return`cowboy-handover_${[e.worktree,e.harness,e.sessionId].map(qr).join("_")}.md`}r(rn,"handoverFileName");function on(e){return`${Ur}/${e}`}r(on,"handoverFilePath");function Wr(e){return nn.existsSync(e)}r(Wr,"handoverFileExists");function Fi(e,t){let n=Wr(e);return nn.writeFileSync(e,t,"utf8"),{replaced:n}}r(Fi,"writeHandoverFile");function zi(e){return{kind:"prepared",path:on(rn({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(zi,"handoverExportArtifact");function Vi(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(Vi,"handoverExportFaultReason");function Qi(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(Qi,"handoverExportSeverity");export{$e as a,Un as b,qn as c,ss as d,Nt as e,cs as f,us as g,Fs as h,Rr as i,Ie as j,re as k,Xr as l,Wr as m,Fi as n,zi as o,Vi as p,Qi as q,Li as r,ji as s,Nr as t,Hr as u,Dr as v,Si as w,Ti as x,Ri as y};
|
|
14
|
+
//# sourceMappingURL=chunk-CAWIXE4E.js.map
|