pi-cowboy 0.23.2 → 0.27.1
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-6DIKQSF3.js} +2 -2
- package/dist/chunk-JISXMHPN.js +26 -0
- package/dist/{chunk-MZROKRT4.js → chunk-TRRZFG6L.js} +2 -2
- package/dist/chunk-UUTVNESQ.js +47 -0
- package/dist/chunk-XCX4DQTF.js +14 -0
- 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-C6GWZ4AZ.js} +2 -2
- package/dist/menus-NSSWTKGU.js +9 -0
- package/dist/{model-picker-FMMQY4KI.js → model-picker-TVBUIXMK.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](https://github.com/electric-dragon-80000v/pi-cowboy/blob/main/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-TRRZFG6L.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-6DIKQSF3.js.map
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{B as Ze,C as K,Ga as X,J as Je,L as et,M as me,N as W,S as tt,da as nt,ea as Q,h as Ge,i as Ue,l as le,m as Ve,ma as B,n as qe,q,qa as rt,r as Ke,u as Qe,w as ue,wa as D,y as Ye,za as Y}from"./chunk-UUTVNESQ.js";import{a as i,d as I,i as pe,j as fe,s as Xe}from"./chunk-XXNZAWMK.js";import*as v from"node:fs";import*as k from"node:path";var fn=`import ctypes, sys
|
|
2
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
3
|
+
# CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
|
|
4
|
+
if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
|
|
5
|
+
sys.exit(1)
|
|
6
|
+
`,mn=10*6e4,gn=1024,hn={darwin:["python3"],linux:[]},kn={darwin:{python3:"install the Xcode Command Line Tools: xcode-select --install"}},yn={darwin:"macOS",linux:"Linux"};function wn(e=process.platform){return(hn[e]??[]).filter(n=>Ze(n)===void 0)}i(wn,"missingClonePrograms");function qr(e=process.platform){let t=wn(e);if(t.length===0)return;let n=yn[e]??e;return`Copy-on-write worktrees need ${t.map(o=>{let a=kn[e]?.[o];return a===void 0?o:`${o}: ${a}`}).join(", ")}, which ${t.length===1?"is":"are"} not on PATH on ${n}. pi-cowboy stays inactive in this session. Install ${t.length===1?"it":"them"} and start a new session.`}i(qr,"missingCloneProgramReport");var y=class extends Error{constructor(n,r,o=[]){super(r);this.reason=n;this.failures=o;this.name="CowCloneError"}reason;failures;static{i(this,"CowCloneError")}};async function dt(e,t,n){let r=k.resolve(e.wtPath),o=k.resolve(e.mainRoot),a=await ot(r),s=await ot(o);if(a===s)throw new y("setup","the worktree is the main checkout; refusing to materialize");if(ke(a,s))throw new y("setup","the worktree contains the main checkout; refusing to materialize");await n.probe(r);let c=t.kind==="all"?await he(`cannot read ${o}`,()=>Cn(o,r,n)):await he(`cannot prepare the ignored paths in ${r}`,()=>vn(o,r,t.rels));t.kind==="all"&&await he(`cannot wipe ${r}`,()=>bn(r,n));let l=[];for(let d of c)try{await n.cloneEntry(d.src,d.dst)}catch(f){if(f instanceof y&&f.reason!=="entry-failed")throw f;l.push({path:d.src,message:f instanceof Error?f.message:String(f)})}if(l.length>0)throw new y("entry-failed",`${l.length} ${l.length===1?"entry":"entries"} could not be cloned`,l);return{mechanism:c.length===0?"empty":n.mechanism}}i(dt,"materializeCowClone");async function ot(e){try{return await v.promises.realpath(e)}catch{return e}}i(ot,"resolvedRoot");function lt(e,t){return ke(e,t)||ke(t,e)}i(lt,"overlapsPath");function ke(e,t){let n=k.resolve(e),r=k.resolve(t);return r===n||r.startsWith(n+k.sep)}i(ke,"containsPath");async function bn(e,t){for(let n of await t.list(e))n.name!==".git"&&await ut(k.join(e,n.name),n)}i(bn,"wipeWorktree");async function ut(e,t){if(!t.isDirectory()){await ge(()=>v.promises.unlink(e));return}let n=await ge(()=>v.promises.readdir(e,{withFileTypes:!0}));for(let r of n??[])await ut(k.join(e,r.name),r);await ge(()=>v.promises.rmdir(e))}i(ut,"removeEntry");async function ge(e){try{return await e()}catch(t){if(t?.code!=="ENOENT")throw t;return}}i(ge,"ignoreMissing");async function Cn(e,t,n){let r=[];for(let{name:o}of await n.list(e)){if(o===".git")continue;let a=k.join(e,o);lt(a,t)||r.push({src:a,dst:k.join(t,o)})}return r}i(Cn,"mainEntries");async function vn(e,t,n){let r=[];for(let o of n){let a=o.replace(/[/\\]+$/,"");if(a===""||a===".git"||a.startsWith(".git/")||a.startsWith(".git\\"))continue;let s=k.join(e,a);if(lt(s,t)||!await xn(s))continue;let c=k.join(t,a);await v.promises.mkdir(k.dirname(c),{recursive:!0}),r.push({src:s,dst:c})}return r}i(vn,"seedEntries");async function xn(e){try{return await v.promises.lstat(e),!0}catch{return!1}}i(xn,"exists");async function he(e,t){try{return await t()}catch(n){throw n instanceof y?n:new y("setup",`${e}: ${n instanceof Error?n.message:String(n)}`)}}i(he,"withSetupContext");function pt(e,t=mn){let n=i(o=>v.promises.readdir(o,{withFileTypes:!0}),"list"),r={cp:K("cp"),du:K("du"),python:K("python3")};switch(process.platform){case"darwin":return{mechanism:"clonefile",list:n,probe:i(o=>at(e,o,r,t,ft),"probe"),cloneEntry:i((o,a)=>Tn(e,r,o,a,t),"cloneEntry")};case"linux":return{mechanism:"reflink",list:n,probe:i(o=>at(e,o,r,t,ct),"probe"),cloneEntry:i((o,a)=>ct(e,r,o,a,t),"cloneEntry")};default:return{mechanism:"empty",list:n,probe:i(()=>Promise.reject(it()),"probe"),cloneEntry:i(()=>Promise.reject(it()),"cloneEntry")}}}i(pt,"defaultCowCloneDeps");function it(){return new y("unsupported",`copy-on-write worktree materialization is not implemented on ${process.platform}`)}i(it,"unsupportedPlatform");function Rn(){return new Date().toISOString().replace(/:/g,"-")}i(Rn,"utcTimestamp");async function at(e,t,n,r,o){let a=k.join(t,`.cow-probe-${process.pid}-${Rn()}`),s=k.join(a,"p");try{if(await v.promises.mkdir(a,{recursive:!0}),!(await v.promises.lstat(a)).isDirectory())throw new y("setup",`${a} is not a directory; refusing to probe the volume through it`);await v.promises.mkdir(s,{recursive:!0}),await v.promises.writeFile(k.join(s,"f"),"x"),await o(e,n,s,k.join(a,"p-clone"),r)}catch(c){throw c instanceof y&&c.reason==="entry-failed"?new y("unsupported",`copy-on-write is not supported on the worktree volume: ${c.message}`):c}finally{await v.promises.rm(a,{recursive:!0,force:!0}).catch(()=>{})}}i(at,"probe");async function Tn(e,t,n,r,o){return(await v.promises.lstat(n)).isDirectory()?await En(e,t,n,o)>=gn?ft(e,t,n,r,o):st(e,t,n,r,o,["-R"]):st(e,t,n,r,o,[])}i(Tn,"darwinEntry");async function En(e,t,n,r){try{let o=await Z(e,t.du,["-sk",n],r,`du -sk ${n}`);return Number.parseInt(o.trim().split(/\s+/)[0]??"",10)||0}catch{return 0}}i(En,"directoryKb");function ft(e,t,n,r,o){return Z(e,t.python,["-c",fn,n,r],o,`clonefile ${n}`,"could not start python3 (needed to clone a worktree on macOS)").then(()=>{})}i(ft,"clonefileChild");function st(e,t,n,r,o,a){return Z(e,t.cp,["-P","-c",...a,n,r],o,`cp -c ${n}`).then(()=>{})}i(st,"copyChild");function ct(e,t,n,r,o){return Z(e,t.cp,["-P","--reflink=always","-R",n,r],o,`cp --reflink ${n}`).then(()=>{})}i(ct,"reflinkChild");async function Z(e,t,n,r,o,a){let s=await e(t,[...n],{timeout:r}).catch(c=>{throw new y("launch",`${a??`could not start ${t}`}: ${c instanceof Error?c.message:String(c)}`)});if(s.killed)throw new y("timeout",`${o} exceeded ${Math.round(r/1e3)}s`);if(s.code!==0){let c=s.stderr.trim().split(`
|
|
7
|
+
`).at(-1)??"";throw new y("entry-failed",`${o} exited ${String(s.code)}${c===""?"":`: ${c}`}`)}return s.stdout}i(Z,"run");import*as ye from"node:fs";import*as T from"node:path";var An=3e4,E=6e4,h=class extends Error{static{i(this,"GitError")}constructor(t){super(t),this.name="GitError"}},b=class{constructor(t){this.pi=t}pi;static{i(this,"GitCommandRunner")}async run(t,n,r=pe){try{let o=await this.pi.exec("git",[...t],{cwd:n,timeout:r});return o.killed?void 0:{code:o.code,stdout:o.stdout.trim(),stderr:o.stderr.trim()}}catch{return}}async probe(t,n,r={}){let o=await this.run(t,n,r.timeoutMs??An);if(!(o===void 0||o.code!==0))return o.stdout}async exec(t,n,r){let o=await this.run(t,n,r);if(o===void 0)throw new h(`git ${t.join(" ")} failed in ${n}: the command could not be run`);if(o.code!==0)throw new h(`git ${t.join(" ")} failed in ${n} (exit ${o.code}): ${(o.stderr||o.stdout||`exit code ${o.code}`).trim().slice(0,500)}`);return o.stdout}async test(t,n,r){let o=await this.run(t,n,r);return o!==void 0&&o.code===0}async lines(t,n,r=`
|
|
8
|
+
`){let o=await this.probe(t,n);if(o!==void 0)return o.split(r).filter(a=>a!=="")}async helper(t,n,r){try{let o=await this.pi.exec(t,[...n],{...r.cwd===void 0?{}:{cwd:r.cwd},timeout:r.timeoutMs});return{code:o.code,stdout:o.stdout,stderr:o.stderr}}catch(o){return{code:1,stdout:"",stderr:o instanceof Error?o.message:String(o)}}}};async function we(e,t,n,r=pe){return new b(e).run(t,n,r)}i(we,"gitRun");async function mt(e,t,n){return new b(e).probe(t,n)}i(mt,"gitProbe");function j(e,t){let n=T.isAbsolute(e)?e:T.resolve(t,e);return{commonDir:n,mainRoot:T.dirname(n)}}i(j,"locateMainCheckout");function Xr(e){let t=T.resolve(e);for(;;){if(ye.existsSync(T.join(t,".git")))return!0;let n=T.dirname(t);if(n===t)return!1;t=n}}i(Xr,"isInsideGitRepository");async function J(e,t){let r=await new b(e).probe(["rev-parse","--git-common-dir"],t);if(r===void 0)throw new h(`cannot create worktree: ${t} is not inside a git repository`);let{mainRoot:o}=j(r,t);if(!ye.existsSync(T.join(o,".git")))throw new h(`cannot create worktree: main checkout not found for ${t}`);return o}i(J,"resolveMainCheckout");var gt=5e3,L=class{constructor(t,n,r){this.runner=t;this.path=n;this.branch=r}runner;path;branch;static{i(this,"GitWorktree")}async status(t){return this.runner.probe(["status","--porcelain"],this.path,t)}async isDirty(){let t=await this.status();if(t!==void 0)return t!==""}async remove(t=!0,n=this.path){await this.runner.run(t?["worktree","remove","--force",this.path]:["worktree","remove",this.path],n,E)}};async function F(e,t,n){await new L(new b(e),n).remove(!0,t)}i(F,"removeGitWorktree");async function be(e,t,n){let r=await e.run(["rev-parse","--verify","--quiet",`refs/heads/${t}`],n);if(r===void 0)throw new h(`git rev-parse --verify refs/heads/${t} could not run in ${n}`);return r.code===0}i(be,"refExists");async function Ce(e,t,n){let r=await e.run(["branch","-D","--",t],n);if(r===void 0)throw new h(`git branch -D ${t} could not run in ${n}`);return r.code!==0?{kind:"delete-failed",detail:(r.stderr||r.stdout||`git branch -D exited ${r.code}`).trim().slice(0,200)}:{kind:"deleted"}}i(Ce,"deleteBranchRef");async function M(e,t,n){let r=new b(e);try{return await be(r,t,n)?await Ce(r,t,n):{kind:"not-applicable"}}catch(o){return{kind:"delete-failed",detail:o instanceof Error?o.message:String(o)}}}i(M,"deleteCreatedBranch");function On(e){let t=[];for(let n of e.split(/\n\n+/)){if(!n.trim())continue;let r="",o=null,a=!1;for(let s of n.split(`
|
|
9
|
+
`))s.startsWith("worktree ")?r=s.slice(9):s.startsWith("branch refs/heads/")?o=s.slice(18):s==="detached"&&(a=!0);r&&t.push({path:r,branch:o,isDetached:a})}return t}i(On,"parseWorktreeList");async function to(e,t){let n=await new b(e).probe(["worktree","list","--porcelain"],t,{timeoutMs:gt});return n===void 0?null:On(n)}i(to,"listGitWorktrees");async function no(e,t){let n=await new b(e).probe(["rev-parse","--git-common-dir"],t,{timeoutMs:gt});return n!==void 0&&n!==""}i(no,"isGitRepo");import*as C from"node:fs";import{tmpdir as Pn}from"node:os";import*as g from"node:path";var Sn=`main checkout has uncommitted changes and the dirty-checkout policy is "clean"; tracked files stay as git's checkout, ignored state CoW-seeded`,_n="main checkout has uncommitted changes; its tracked edits and untracked files were cloned into the worktree",Wn="the worktree volume cannot clone; the checkout was completed by git instead";function ht(e){return e==="copy-on-write"?["--no-checkout"]:[]}i(ht,"worktreeAddArgs");function Fn(e){let t=[];for(let n of e){if(!n.startsWith("!! "))continue;let r=n.slice(3);r===""||r.includes(`
|
|
10
|
+
`)||t.push(r)}return t}i(Fn,"ignoredSeedPaths");var ve=class{constructor(t,n){this.runner=t;this.exec=n}runner;exec;static{i(this,"CowCloneMaterializer")}async materialize(t,n,r){return n==="checkout"?this.checkout(t,r):this.clone(t,r)}async clone(t,n){let r=g.resolve(t),o=await this.mainCheckoutOf(r),s=await this.mainStatus(o)===""?{kind:"clean-parent"}:{kind:"dirty-parent",policy:n},c=s.kind==="clean-parent"||s.policy==="dirty";try{await this.cloneWorkingTree(r,o,c?{kind:"all"}:{kind:"seed",rels:await this.ignoredRels(o)})}catch(l){if(!(l instanceof y)||l.reason!=="unsupported")throw l;return await this.fallbackToCheckout(r),{kind:"cow-fallback",reason:Wn}}return await this.completeCheckout(r,c),await this.verifyMaterialization(r,o,s),s.kind==="clean-parent"?{kind:"cow",clone:{mode:"cow"}}:{kind:"cow",clone:c?{mode:"cow",reason:_n}:{mode:"seeded",reason:Sn}}}async checkout(t,n){if(n==="dirty"){let r=g.resolve(t);await this.applyUncommitted(await this.mainCheckoutOf(r),r)}return{kind:"checkout"}}async applyUncommitted(t,n){let r=C.mkdtempSync(g.join(Pn(),"pi-cowboy-wip-")),o=g.join(r,"wip.patch");try{if(!await this.runner.test(["diff","HEAD","--binary","--no-renames",`--output=${o}`],t,E))throw new h("checkout worktree materialization failed: could not read the main checkout's tracked changes");if(!C.existsSync(o)||C.statSync(o).size===0)return;if(!await this.runner.test(["apply","--whitespace=nowarn",o],n,E))throw new h("checkout worktree materialization failed: could not apply the main checkout's tracked changes to the worktree")}finally{C.rmSync(r,{recursive:!0,force:!0})}}async mainCheckoutOf(t){let n;try{C.statSync(t).isDirectory()||w("target is not a directory"),C.lstatSync(g.join(t,".git")).isFile()||w("target is not a linked worktree (.git is not a file)"),n=C.readFileSync(g.join(t,".git"),"utf8")}catch(d){if(d instanceof h)throw d;w("target is not a git worktree")}let r=await this.runner.probe(["rev-parse","--git-common-dir"],t);r===void 0&&w("git rev-parse --git-common-dir failed");let{commonDir:o,mainRoot:a}=j(r,t);C.existsSync(g.join(a,".git"))||w("main checkout not found"),g.resolve(a)===g.resolve(t)&&w("target is the main checkout"),xe(t,a)&&w("main checkout lives inside the worktree");let s=n.trim(),c=s.startsWith("gitdir:")?s.slice(7).trim():"";c===""&&w("malformed .git worktree marker");let l=g.isAbsolute(c)?c:g.resolve(t,c);return l.startsWith(o+g.sep)||w("worktree gitdir is outside this repo"),C.existsSync(l)||w("worktree gitdir missing"),a}async mainStatus(t){let n=await this.runner.probe(["status","--porcelain"],t);return n===void 0&&w("could not read main checkout status"),n}async cloneWorkingTree(t,n,r){try{await dt({wtPath:t,mainRoot:n},r,pt(this.exec))}catch(o){if(o instanceof y&&o.reason==="unsupported")throw o;w(o instanceof y?o.message:String(o))}}async fallbackToCheckout(t){await this.runner.test(["reset","--hard","HEAD"],t,E)||w("the worktree volume cannot clone and its checkout could not be completed")}async ignoredRels(t){let n=await this.runner.lines(["status","--ignored","--porcelain","-z"],t,"\0");return n===void 0&&w("could not read main checkout ignored files"),Fn(n)}async completeCheckout(t,n){(n?await this.runner.test(["reset","-q"],t,E):await this.runner.test(["checkout","-q","HEAD","--","."],t,E))||w(n?"could not refresh the worktree index after materialization":"could not materialize tracked files in the worktree")}async verifyMaterialization(t,n,r){function o(l,d){let f=[...l].sort(),u=[...d].sort();return f.length===u.length&&f.every((m,x)=>m===u[x])}i(o,"samePaths");let a=i(l=>l.filter(d=>!In(n,d,t)),"carried");if(r.kind==="clean-parent")return this.assertClean(t,"a clean parent");if(r.policy==="clean")return this.assertClean(t,'the "clean" dirty-checkout policy');let s=await this.changeLists(n),c=await this.changeLists(t);(!o(a(s.tracked),c.tracked)||!o(a(s.untracked),c.untracked))&&w("worktree does not mirror the main checkout's uncommitted changes")}async changeLists(t){let n=await this.runner.lines(["diff","HEAD","--name-only","-z"],t,"\0");n===void 0&&w("could not read tracked changes");let r=await this.runner.lines(["ls-files","--others","--exclude-standard","-z"],t,"\0");return r===void 0&&w("could not read untracked files"),{tracked:n,untracked:r}}async assertClean(t,n){await this.runner.probe(["status","--porcelain"],t)!==""&&w(`${n} should leave the worktree clean, but it is not`)}};async function kt(e,t,n,r=q){return new ve(new b(e),$n(e)).materialize(t,n,r)}i(kt,"materializeWorktree");function $n(e){return(t,n,r)=>e.exec(t,n,r)}i($n,"execOf");function w(e){throw new h(`copy-on-write worktree materialization failed: ${e}`)}i(w,"cowFail");function xe(e,t){let n=g.relative(g.resolve(e),g.resolve(t));return n===""||!n.startsWith("..")&&!g.isAbsolute(n)}i(xe,"isWithin");function In(e,t,n){let r=g.resolve(e,t),o=g.resolve(n);return xe(r,o)||xe(o,r)}i(In,"overlapsWorktree");import*as bt from"node:fs";import*as Ct from"node:path";import{z as Dn}from"zod";var Mn=12e4,Nn=/^-|\.\.|@\{|[^A-Za-z0-9._/-]/,Bn=Dn.string().check(e=>{let t=e.value===""?"is empty":jn(e.value);t!==void 0&&e.issues.push({code:"custom",input:e.value,message:t})});function jn(e){let t=Nn.exec(e)?.[0];if(t!==void 0)return t==="-"?'starts with "-": git would parse that as a command-line flag, not a branch name':t===".."?'contains "..": revision ranges are not branch names':t==="@{"?'contains "@{": reflog/date syntax is not a branch name':`contains invalid character ${Ln(t)}: branch names may only use letters, digits, ".", "_", "/", and "-"`}i(jn,"refusalClauseFor");function Ln(e){let t=e.charCodeAt(0);return t<=32||t===127?`U+${t.toString(16).toUpperCase().padStart(4,"0")}`:JSON.stringify(e)}i(Ln,"describeRefChar");function yt(e,t){let n=Bn.safeParse(e);if(n.success)return;let r=n.error.issues.map(o=>o.message).join("; ");throw new Error(`refusing to merge: the ${t} ref ${JSON.stringify(e)} ${r}.`)}i(yt,"assertValidBranchRef");var Re=class{constructor(t){this.runner=t}runner;static{i(this,"BranchMerger")}async merge(t){let n=t.branch.trim();yt(n,"branch");let r=(t.target??"main").trim();yt(r,"target");let o=await this.runner.probe(["rev-parse","--show-toplevel"],t.cwd);if(o===void 0)throw new Error(`cannot merge "${n}": ${t.cwd} is not inside a git repository`);let a=await this.runner.probe(["rev-parse","--git-common-dir"],o);if(a===void 0)throw new Error(`cannot merge "${n}": could not resolve the repo's git directory`);let{mainRoot:s}=j(a,o);if(!bt.existsSync(Ct.join(s,".git")))throw new Error(`cannot merge "${n}": no main checkout found (unsupported repo layout)`);let c=await this.runner.probe(["branch","--show-current"],s);if(c!==r)throw new Error(c===void 0?`refusing to merge "${n}": could not read the current branch of the main checkout (${s})`:`refusing to merge "${n}": the main checkout (${s}) is on branch "${c||"(detached)"}", not the merge target "${r}". A merge would land on "${c||"(detached)"}" instead of "${r}".`);if(n===r)throw new Error(`refusing to merge "${n}" into itself (already on "${r}")`);if(!await this.runner.test(["rev-parse","--verify","--quiet",`refs/heads/${n}`],s))throw new Error(`refusing to merge: branch "${n}" does not exist in ${s}.`);let d=await this.runner.probe(["status","--porcelain"],s);if(d===void 0)throw new Error(`refusing to merge "${n}": could not read the status of the main checkout (${s})`);if(d!=="")throw new Error(`refusing to merge "${n}": the main checkout (${s}) has uncommitted changes. Nothing was merged.`);let f=await this.runner.run(["merge-base","--is-ancestor","--",n,"HEAD"],s);if(!f)throw new Error(`refusing to merge "${n}": could not read its merge ancestry`);if(f.code===0)return{merged:!1,alreadyMerged:!0,target:r,mainRoot:s};let u=await this.runner.run(["merge","--no-edit","--",n],s,Mn);if(!u)throw new Error(`merge of "${n}" into "${r}" failed to run (transport error); the checkout was not modified`);if(u.code===0)return{merged:!0,target:r,mainRoot:s,output:u.stdout||u.stderr||void 0};let m=await this.runner.probe(["diff","--name-only","--diff-filter=U"],s);throw m!==void 0&&m!==""?new Error(wt(n,r,s,m)):await this.runner.test(["rev-parse","--verify","--quiet","MERGE_HEAD"],s)?new Error(wt(n,r,s,void 0)):new Error(`merge of "${n}" into "${r}" failed: ${u.stderr||u.stdout||`exit code ${u.code}`}`)}};function wt(e,t,n,r){let o=r===void 0?`has conflicts in: (the conflicting files could not be listed \u2014 \`git diff --name-only --diff-filter=U\` did not run in ${n})`:`has conflicts in:
|
|
11
|
+
${r}`;return`merge of "${e}" into "${t}" ${o}
|
|
12
|
+
The merge is still in progress in ${n}. No conflict was resolved automatically.`}i(wt,"conflictMessage");var Te=class{constructor(t){this.runner=t}runner;static{i(this,"BranchCleaner")}async delete(t,n){let{branch:r,worktreePath:o,repoCwd:a}=t;if(!r.startsWith("cow-"))return{kind:"not-applicable"};try{if(!await be(this.runner,r,a))return{kind:"not-applicable"};let s=await this.runner.run(["merge-base","--is-ancestor","--",r,"HEAD"],a);if(s===void 0)throw new h(`git merge-base --is-ancestor -- ${r} HEAD could not run in ${a}`);return s.code!==0?{kind:"kept",reason:"unmerged"}:n&&await n(o)?{kind:"kept",reason:"checked-out"}:await Ce(this.runner,r,a)}catch(s){return{kind:"delete-failed",detail:s instanceof Error?s.message:String(s)}}}};async function go(e,t){return new Re(new b(e)).merge(t)}i(go,"mergeBranchIntoTarget");async function vt(e,t,n){return new Te(new b(e)).delete(t,n)}i(vt,"deleteWorktreeBranch");function xt(e,t){return new L(new b(e),t)}i(xt,"worktree");async function Rt(e,t){return xt(e,t).isDirty()}i(Rt,"isWorktreeDirty");async function bo(e,t){let n=await xt(e,t).isDirty();return n===void 0?{kind:"unverifiable",detail:"git status probe failed"}:n?{kind:"dirty"}:null}i(bo,"worktreeRetentionReason");function Tt(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`}}i(Tt,"formatRetentionClause");import*as _ from"node:fs";import*as $ from"node:path";var Hn=`Success! You delegated to an agent. A notification will arrive when done - USER: do not poll, don't check status and don't duplicate the delegated work!{{#has_worktree}}
|
|
13
|
+
(Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
|
|
14
|
+
|
|
15
|
+
Agent ID: {{agent_id}}`,zn=`Agent QUEUED \u2014 the concurrency limit is reached ({{queue_running}} {{queue_running_label}} already spawned), so this task is waiting for a slot. It is NOT spawned yet: the process has not started. It will start automatically when another agent settles; you'll get a message when it starts and when it settles. Do NOT re-delegate \u2014 this task IS in flight.{{#has_worktree}}
|
|
16
|
+
(Worktree: {{worktree_path}} (branch {{worktree_branch}}) \u2014 the agent's commits land on that branch, never on main. Merge it with the merge_cowboy_branch tool when done, then remove the worktree with cleanup_cowboy_agent.){{/has_worktree}}
|
|
17
|
+
|
|
18
|
+
Agent ID: {{agent_id}}`,Gn=`{{result}}{{#error}}
|
|
19
|
+
|
|
20
|
+
Error: {{error}}{{/error}}{{#has_worktree}}
|
|
21
|
+
(Worktree: {{worktree_path}} (branch {{worktree_branch}}){{#retention}} \u2014 KEPT: {{retention}}{{/retention}}.{{#process_alive}} The agent process and its {{multiplexer_id}} pane stay until you call cleanup_cowboy_agent \u2014 its pane is closed, which ends that process.{{/process_alive}} {{#retention}}Clean the worktree up, then call cleanup_cowboy_agent to remove it.{{/retention}}{{^retention}}The worktree stays until you call cleanup_cowboy_agent to remove it \u2014 call it once the branch is merged or rejected.{{/retention}}){{/has_worktree}}{{status_note}}`,O={default:{name:"default",displayName:"Default",guidance:"Update your report file each time you make a commit",cues:{spawned:Hn,queued:zn,settled:Gn}}};import*as ee from"node:fs";import*as Et from"node:path";import{parse as Un,TomlError as Vn}from"smol-toml";import{z as qn}from"zod";var Kn=".toml";function te(e){return Un(e.replace(/^\uFEFF/,""))}i(te,"parseTemplateToml");function A(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0))}i(A,"compactDefined");function Qn(e){let t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}i(Qn,"describeZodIssue");function Yn(e){if(e instanceof qn.ZodError)return e.issues.map(Qn).join("; ").replace(/\s+/g," ").trim();if(e instanceof Vn){let[n]=e.message.split(`
|
|
22
|
+
|
|
23
|
+
`);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}i(Yn,"describeParseError");var Xn={label:"File",problem:"was skipped"};async function ne(e,t,n,r,o=Xn,a){try{await ee.promises.access(e)}catch{return[]}let c=(await ee.promises.readdir(e,{withFileTypes:!0})).filter(d=>d.isFile()&&d.name.endsWith(Kn)),l=[];for(let d of c){let f=Et.join(e,d.name),u;try{u=await ee.promises.readFile(f,"utf-8")}catch{continue}try{let m=t(u),x=a?.(m);if(x!==void 0)throw new Error(x);n(m)&&l.push(m)}catch(m){r?.(`[cowboy] ${o.label} file ${f} ${o.problem}: ${Yn(m)}`,"warning")}}return l}i(ne,"scanTemplateFilesInDir");import{z as P}from"zod";import Pt from"mustache";function At(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}i(At,"worktreeVariables");function Zn(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}i(Zn,"outcomeVariables");function Jn(e){return e?{...At(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}i(Jn,"settledWorktreeVariables");function er(e){return e.worktree?{agent_id:e.agentId,...At(e.worktree)}:{agent_id:e.agentId}}i(er,"spawnCueContext");function Do(e){return{...er(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}i(Do,"queuedCueContext");function Mo(e){let{outcome:t,statusNote:n,worktree:r,multiplexerId:o}=e;return{...Zn(t),...n?{status_note:n}:{},...Jn(r),...o!=null?{multiplexer_id:o}:{}}}i(Mo,"settledCueContext");var tr={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},nr={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},rr={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},or=Object.keys(tr),ir=Object.keys(nr),ar=Object.keys(rr);function Ot(e){switch(e){case"spawned":return or;case"queued":return ir;case"settled":return ar;default:return}}i(Ot,"cueVariables");var sr={ok:!0},cr="&",dr=new Set(["name",cr,"#","^"]);function Ho(e,t,n){return Pt.render(e[t],n,void 0,{escape:i(r=>r==null?"":String(r),"escape")})}i(Ho,"renderCue");function lr(e){let t=e[4];return Array.isArray(t)?t:void 0}i(lr,"spanChildren");function St(e,t,n){for(let r of e){let[o,a]=r;if(o===">")return`partials are not supported: "{{>${a}}}"`;if(o==="=")return`delimiter changes are not supported: "{{=${a}=}}"`;if(dr.has(o)&&!t.includes(a))return`unknown variable "{{${a}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let s=lr(r);if(s){let c=St(s,t,n);if(c)return c}}}i(St,"findTemplateProblem");function _t(e,t){let n=Ot(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let r;try{r=Pt.parse(t)}catch(a){return{ok:!1,reason:`unparsable template: ${(a instanceof Error?a.message:String(a)).replace(/\s+/g," ").trim()}`}}let o=St(r,n,e);return o?{ok:!1,reason:o}:sr}i(_t,"validateCueTemplate");var ur=["spawned","queued","settled"],pr=P.strictObject({spawned:P.string().optional(),queued:P.string().optional(),settled:P.string().optional()}).superRefine((e,t)=>{for(let n of ur){let r=e[n];if(r===void 0)continue;let o=_t(n,r);o.ok||t.addIssue({code:"custom",message:o.reason,path:[n]})}}),Wt=P.strictObject({name:P.string().optional(),display_name:P.string().optional(),guidance:P.string().optional(),cues:pr.optional()});var fr={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function mr(e){return Wt.parse(te(e))}i(mr,"parseOrchestratorFile");async function H(e,t){return ne(e,mr,n=>n.name,t,fr)}i(H,"scanOrchestratorFilesInDir");function Ee(e,t,n,r){let o=new Map(e instanceof Map?e:Object.entries(e)),a=o.get("default")??O.default;for(let s of[t,n,r])for(let c of s)c.name&&o.set(c.name,hr(o.get(c.name)??gr(c.name,a),c));return o}i(Ee,"mergeOrchestrators");function gr(e,t){return{...t,name:e,displayName:e}}i(gr,"namedBase");function hr(e,t){return{...e,name:t.name??e.name,displayName:t.display_name??e.displayName,cues:{...e.cues,...t.cues},guidance:t.guidance??e.guidance}}i(hr,"applyOverride");function z(){return X().orchestrators}i(z,"registry");function ri(e,t){let n=new Map;if(!t?.disableDefaultOrchestrators)for(let[r,o]of Object.entries(O))n.set(r,o);for(let[r,o]of e)n.set(r,o);z().orchestrators=n}i(ri,"registerOrchestrators");function oi(e,t,n){z().scanDirs={user:e,project:t,shared:n??""}}i(oi,"setOrchestratorScanDirs");async function ii(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,r=z().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):H(Ue,n),H(r.user,n),H(r.shared,n),H(r.project,n)]),d=Ee(t?new Map:O,o,[],[]);return Ee(d,a,s,c)}i(ii,"scanAndMergeOrchestrators");function Ae(e){let{orchestrators:t}=z();if(!e)return;let n=t.get(e);if(n)return n;let r=e.toLowerCase(),o=[];for(let[a,s]of t)a.toLowerCase()===r&&o.push(s);return o.length===1?o[0]:void 0}i(Ae,"resolveOrchestrator");function ai(){return[...z().orchestrators.values()].map(e=>e.name)}i(ai,"getAvailableOrchestrators");import{z as p}from"zod";var Ft=p.union([p.boolean(),p.array(p.string())]),kr={name:"is not a valid environment variable name",reserved:"is a reserved environment variable and cannot be overridden","not-string":"must be a string",control:"contains a control character"};function oe(e){return p.record(p.string(),p.unknown()).transform((t,n)=>nt(t,{reserved:Xe[e],report:i((r,o)=>n.addIssue({code:"custom",path:[r],message:kr[o]}),"report")}))}i(oe,"envTable");var $t={model:p.string().optional(),thinking:et.optional(),extensions:Ft.optional(),skills:Ft.optional(),inlined_skills:p.array(p.string()).optional(),fork:p.boolean().optional(),tools:p.array(p.string()).optional(),exclude_tools:p.array(p.string()).optional(),env:oe("pi").optional()},yr=p.strictObject($t),wr=p.strictObject({model:p.string().optional(),variant:p.string().optional(),tools:p.array(p.string()).optional(),exclude_tools:p.array(p.string()).optional(),env:oe("opencode").optional()}),br=p.strictObject({model:p.string().optional(),thinking:p.string().optional(),env:oe("codex").optional()}),Cr=p.strictObject({model:p.string().optional(),thinking:p.string().optional(),tools:p.array(p.string()).optional(),exclude_tools:p.array(p.string()).optional(),env:oe("claude").optional()});function Oe(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}i(Oe,"toToolFilter");function re(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}i(re,"nonEmptyEnv");var vr=p.strictObject({include_context_files:p.boolean().optional(),pi:yr.optional(),opencode:wr.optional(),codex:br.optional(),claude:Cr.optional(),...$t}).transform(({pi:e,opencode:t,codex:n,claude:r,...o})=>{let{model:a,thinking:s,tools:c,exclude_tools:l,env:d,...f}=o,{model:u,thinking:m,tools:x,exclude_tools:de,env:V,...R}=A(e??{}),{model:Xt,variant:Zt,tools:Jt,exclude_tools:en,env:tn,...nn}=A(t??{}),{model:rn,thinking:on,env:an,...sn}=A(n??{}),{model:cn,thinking:dn,tools:ln,exclude_tools:un,env:pn}=A(r??{}),je=A({pi:u??a,opencode:Xt,codex:rn,claude:cn}),Le=A({pi:Oe(x??c,de??l),opencode:Oe(Jt,en),claude:Oe(ln,un)}),He=A({pi:m??s,opencode:Zt,codex:on,claude:dn}),ze=A({pi:re(Q(d,V)),opencode:re(tn),codex:re(an),claude:re(pn)});return{...f,...R,...nn,...sn,...Object.keys(je).length>0?{modelsByFamily:je}:{},...Object.keys(Le).length>0?{toolsByFamily:Le}:{},...Object.keys(He).length>0?{thinkingByFamily:He}:{},...Object.keys(ze).length>0?{envByFamily:ze}:{}}}),It=p.strictObject({name:p.string().optional(),display_name:p.string().optional(),description:p.string().optional(),hidden:p.boolean().optional(),worktree_checkout_type:p.enum(Ke).optional(),system_prompt:p.string().optional(),harness_type:p.string().min(1).optional(),harness:vr.optional()});function xr(e){return It.parse(te(e))}i(xr,"parseAgentFile");var Rr={label:"Agent",problem:"is not a valid agent template and was skipped"};async function N(e,t,n){return ne(e,xr,r=>r.name,t,Rr,n)}i(N,"scanAgentFilesInDir");function ie(e,t,n,r){let o=new Map;for(let[a,s]of e)o.set(a,{...s});return Pe(o,t),Pe(o,n),Pe(o,r),o}i(ie,"mergeAgents");function Pe(e,t){for(let n of t){if(!n.name)continue;let r=e.get(n.name);if(r){let o={displayName:n.display_name,description:n.description??""},a=Dt(n),s=Tr(r.modelsByFamily,a.modelsByFamily),c=Er(r.toolsByFamily,a.toolsByFamily),l=Ar(r.thinkingByFamily,a.thinkingByFamily),d=Or(r.envByFamily,a.envByFamily);e.set(n.name,{...r,...a,...s?{modelsByFamily:s}:{},...c?{toolsByFamily:c}:{},...l?{thinkingByFamily:l}:{},...d?{envByFamily:d}:{},...o})}else e.set(n.name,{...Pr,...Dt(n)})}}i(Pe,"mergeAgentOverrides");function Tr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Tr,"mergeModelsByFamily");function Er(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Er,"mergeToolsByFamily");function Ar(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Ar,"mergeThinkingByFamily");function Or(e,t){let n={...e};for(let[r,o]of Object.entries(t??{})){let a=r;n[a]=Q(n[a],o)}return Object.keys(n).length>0?n:void 0}i(Or,"mergeEnvByFamily");function Dt(e){let{harness:t}=e,n={name:e.name,displayName:e.display_name,description:e.description,harnessType:e.harness_type,toolsByFamily:t?.toolsByFamily,extensions:t?.extensions,skills:t?.skills,inlinedSkills:t?.inlined_skills,modelsByFamily:t?.modelsByFamily,thinkingByFamily:t?.thinkingByFamily,envByFamily:t?.envByFamily,hidden:e.hidden,fork:t?.fork,includeContextFiles:t?.include_context_files,worktreeCheckoutType:e.worktree_checkout_type,systemPrompt:e.system_prompt};return A(n)}i(Dt,"fromTemplate");var Pr={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Se=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return X().agents}i(S,"registry");function G(e){let t=e.harness_type;if(t===void 0)return;let n=D();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}i(G,"unregisteredHarness");function Ai(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[r,o]of Se)n.set(r,o);for(let[r,o]of e)n.set(r,o);S().agents=n}i(Ai,"registerAgents");function Oi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}i(Oi,"setAgentScanDirs");async function Sr(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,r=S().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):N(Ge,n,G),N(r.user,n,G),N(r.shared,n,G),N(r.project,n,G)]),d=ie(t?new Map:Se,o,[],[]);return ie(d,a,s,c)}i(Sr,"scanAndMerge");async function _r(e,t){let n=await Sr(t),{agents:r}=S(),o=0;for(let[a,s]of n)r.has(a)||(r.set(a,s),o++);if(e){let a=await N(e,t?.notify,G),s=ie(new Map,[],[],a);for(let[c,l]of s)r.has(c)||(r.set(c,l),o++)}return o}i(_r,"discoverNewAgents");function U(e){let{agents:t}=S();if(!e)return{kind:"not-found"};if(t.has(e))return{kind:"resolved",key:e};let n=e.toLowerCase(),r=[];for(let o of t.keys())o.toLowerCase()===n&&r.push(o);return r.length===1?{kind:"resolved",key:r[0]}:r.length>1?{kind:"ambiguous",candidates:r}:{kind:"not-found"}}i(U,"resolveType");async function Pi(e,t,n){let r=U(e);return r.kind==="not-found"&&(await _r(t,{notify:n}),r=U(e)),r}i(Pi,"resolveTypeOrDiscover");function ae(e){let t=U(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}i(ae,"getAgentConfig");function Si(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}i(Si,"getAvailableTypes");function _i(){return[...S().agents.keys()]}i(_i,"getAllTypes");function Mt(e,t,n,r){return{skills:e??n,extensions:t??r}}i(Mt,"applyGlobalDefaults");function Wi(e,t=!0,n=!0){let r=ae(e);if(r){let{skills:a,extensions:s,...c}=r,l=Mt(a,s,t,n);return{displayName:c.displayName??c.name,description:c.description,...l}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Mt(void 0,void 0,t,n)}}i(Wi,"getConfig");function Nt(e){return typeof e=="string"&&e!==""?e:void 0}i(Nt,"configuredString");function Wr(){let e=Nt(B().agent.defaultAgentType);if(e===void 0)return me;let t=U(e);return t.kind==="resolved"?t.key:me}i(Wr,"resolveDefaultAgentType");function Fr(){let e=Nt(B().agent.defaultOrchestrator);return e===void 0?W:e===W||Ae(e)?e:W}i(Fr,"resolveDefaultOrchestratorName");function Li(e){return typeof e=="string"&&e!==""?e:Wr()}i(Li,"resolveAgentTypeParam");function Hi(){let e=Fr();return Ae(e)??(e===W?O[W]:void 0)??O[W]}i(Hi,"resolveDefaultOrchestrator");function Bt(e){return ae(e)?.worktreeCheckoutType??B().agent.worktreeCheckoutType}i(Bt,"resolveWorktreeCheckoutType");function jt(e){return typeof e=="string"&&e.trim()!==""?e:void 0}i(jt,"harnessParam");function zi(e){let t=jt(e);if(t!==void 0&&D().get(t)!==void 0)return le(t,Y())?t:void 0}i(zi,"requestedHarnessId");function Gi(e){let t=jt(e);if(t===void 0)return;let n=D();if(n.get(t)===void 0)throw new Error(`Unknown harness_type "${t}": valid harnesses are ${n.ids().join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);let r=Y();if(!le(t,r))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${Ve(n.ids(),r).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}i(Gi,"resolveRequestedHarness");function Ui(e,t){if(t!==void 0)return t;let n=ae(e)?.harnessType??B().agent.harnessType;return D().resolve(n,Y())}i(Ui,"resolveHarnessType");function _e(e){return{kind:"recorded",phase:e.lifecycle.phase}}i(_e,"recordedSettlement");function Lt(e,t){let n=e.worktree;return n!==null&&n.repoCwd!==void 0?{kind:"worktree",worktree:{workspaceId:n.workspaceId,worktreePath:n.path,repoCwd:n.repoCwd,branchName:e.branch},panes:t}:e.worktreeManaged?{kind:"worktree-unlocatable",branchName:e.branch,worktreePath:n?.path??null,panes:t}:{kind:"no-worktree",panes:t}}i(Lt,"planRecovered");async function We(e,t,n){if(t?.force!==void 0)return{kind:"removable"};let r=await e(n.worktreePath);return r===void 0?{kind:"kept",reason:{kind:"unverifiable",detail:"git status probe failed"}}:r?{kind:"kept",reason:{kind:"dirty"}}:{kind:"removable"}}i(We,"assessRemovability");function Ht(e){if(e===void 0)return{kind:"allow",basis:{kind:"pane-absent"}};switch(e.state){case"working":return{kind:"refuse",basis:{kind:"pane-working"}};case"idle":case"blocked":case"done":case"unknown":return{kind:"allow",basis:{kind:"pane-not-working",state:e.state}};default:return fe(e.state)}}i(Ht,"recoveryGate");function Fe(e){switch(e.kind){case"pane-working":return{kind:"recovered-refusal",basis:e};case"pane-unreadable":return{kind:"unverifiable",detail:`the pane state could not be read (${e.detail})`};case"pane-absent":case"pane-not-working":case"forced":case"artifacts-ambiguous":return{kind:"unverifiable",detail:"the run's end could not be established"}}}i(Fe,"recoveryRefusalReason");function se(e,t,n,r,o){let a=n.kind==="worktree"?{kind:"kept",path:n.worktree.worktreePath}:n.kind==="worktree-unlocatable"?{kind:"kept",path:n.worktreePath}:{kind:"none"};return{agentId:e,source:t,outcome:{kind:"refused",reason:o.reason,forceable:o.forceable},branchName:n.kind==="worktree"?n.worktree.branchName:n.kind==="worktree-unlocatable"?n.branchName:void 0,settlement:r,panes:n.panes.map(s=>({kind:"open",paneId:s.paneId})),worktree:a,branch:{kind:"not-applicable"}}}i(se,"keptReport");function zt(e,t,n,r){return{agentId:e,source:t,outcome:{kind:"refused",reason:{kind:"ambiguous-artifacts",candidates:r},forceable:!1},settlement:n,panes:[],worktree:{kind:"kept",path:null},branch:{kind:"not-applicable"}}}i(zt,"ambiguousReport");function $e(e){return e?.force!==void 0?{forced:e.force}:{}}i($e,"forcedFields");function Gt(e,t,n,r,o,a){return{agentId:e,source:t,outcome:{kind:"torn-down",...$e(a)},branchName:n.kind==="worktree"?n.worktree.branchName:void 0,settlement:r,panes:o.panes,worktree:o.worktree,branch:o.branch}}i(Gt,"assembleReport");function Qi(e){return e.outcome.kind==="refused"&&e.outcome.forceable}i(Qi,"isForceableRefusal");function Ie(e){return e.worktree.kind==="removed"||e.worktree.kind==="absent"?!0:e.worktree.kind==="none"?e.panes.every(t=>t.kind==="closed"):!1}i(Ie,"shouldDropSpawn");function De(e){return e.workspaceId!==void 0?"multiplexer":"git"}i(De,"removalMechanismOf");function Ut(e,t){if(t.kind==="retained")return{kind:"leave-open"};let n=t.workspaceId===void 0||e.workspaceId===t.workspaceId;if(t.mechanism==="multiplexer"&&n)return{kind:"closed-with-workspace"};switch(t.mechanism){case"multiplexer":case"git":case null:return e.paneCreated?{kind:"close"}:{kind:"leave-open"};default:return fe(t.mechanism)}}i(Ut,"paneDispositionFor");var $r=Je("cleanup");function Ir(e,t){let n=e.pane,r=n?.workspaceId??e.worktree?.workspaceId;if(!(n===null||r===void 0))return{multiplexer:t,name:e.branch,paneId:n.paneId,tabId:n.tabId,workspaceId:r,paneCreated:e.paneCreated}}i(Ir,"hostRefFor");async function Vt(e,t,n){let r=n!==void 0&&t.workspaceId!==void 0;return(r?await e.removeWorktree(n):await e.removeGitWorktree(t.worktreePath,t.repoCwd))?{kind:"removed",path:t.worktreePath}:{kind:"removal-failed",path:t.worktreePath,detail:r?"herdr did not confirm the worktree removal":"git did not confirm the worktree removal"}}i(Vt,"removeOwnedTree");async function ce(e,t,n){let r=[];for(let o of t)switch(Ut(o,n).kind){case"closed-with-workspace":r.push({kind:"closed",paneId:o.paneId});break;case"close":await e.closePane(o),r.push({kind:"closed",paneId:o.paneId});break;case"leave-open":r.push({kind:"open",paneId:o.paneId});break}return r}i(ce,"paneOutcomes");async function Dr(e,t){let n=[];for(let r of t){let o;try{o=await e.observe(r)}catch{n.push({kind:"unknown",paneId:r.paneId});continue}n.push(o===void 0?{kind:"gone",paneId:r.paneId}:{kind:"open",paneId:r.paneId})}return n}i(Dr,"paneOutcomesForAbsentTree");async function Mr(e,t,n){if(t.kind==="no-worktree")return{panes:await ce(e,t.panes,{kind:"removed",mechanism:null,workspaceId:void 0}),worktree:{kind:"none"},branch:{kind:"not-applicable"}};let{worktree:r,panes:o}=t,a=await Vt(e,r,n);return a.kind==="removed"?{panes:await ce(e,o,{kind:"removed",mechanism:De(r),workspaceId:r.workspaceId}),worktree:a,branch:await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd})}:{panes:await ce(e,o,{kind:"retained"}),worktree:a,branch:{kind:"not-applicable"}}}i(Mr,"removeResources");function Me(e){return{async removeWorktree(t,n){let{worktree:r,panes:o,address:a}=t;try{if(!await e.worktreeExists(r.worktreePath))return{kind:"absent",path:r.worktreePath};let s=await We(e.isWorktreeDirty,n,r);if(s.kind==="kept")return{kind:"kept",path:r.worktreePath,reason:s.reason};let c=await Vt(e,r,a);if(c.kind==="removal-failed")return c;let l=De(r);await ce(e,o,{kind:"removed",mechanism:l,workspaceId:r.workspaceId});let d=await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd});return{kind:"removed",path:r.worktreePath,branchName:r.branchName,via:l,branch:d}}catch(s){return{kind:"removal-failed",path:r.worktreePath,detail:I(s)}}}}}i(Me,"createWorktreeTeardown");function Nr(e,t){let n=e===void 0?[]:[e];for(let r of t===void 0?[]:t.execution.history)n.some(o=>o.paneId===r.host.paneId)||n.push(r.host);return n}i(Nr,"environmentPanes");function Br(e,t){if(e===void 0)return[];let n=e.execution.history.map(o=>({harness:o.harness,paneId:o.host.paneId,cwd:o.cwd})),r=e.execution.harness===void 0?[]:[{harness:e.execution.harness,paneId:t.pane?.paneId??null,cwd:t.worktree?.path??null}];return[...n,...r]}i(Br,"teardownRuns");function na(e){let t=Me(e);function n(a,s){return{kind:"discovered",basis:s,deliverable:e.deliverable(a)}}i(n,"recovered");async function r(a,s,c,l){if(c!==void 0){let u=_e(c);return tt(c.lifecycle)?{kind:"torn-down",settlement:u}:{kind:"refused",settlement:u,reason:{kind:"agent-active",phase:c.lifecycle.phase},forceable:!1}}if(l?.force!==void 0)return{kind:"torn-down",settlement:n(a,{kind:"forced"})};let d;if(s.pane!==null)try{d=await e.observe(s.pane)}catch(u){let m={kind:"pane-unreadable",detail:I(u)};return{kind:"refused",settlement:n(a,m),reason:Fe(m),forceable:!0}}let f=Ht(d);return f.kind==="allow"?{kind:"torn-down",settlement:n(a,f.basis)}:{kind:"refused",settlement:n(a,f.basis),reason:Fe(f.basis),forceable:!0}}i(r,"verdictFor");async function o(a,s,c){let l=s.getSpawn(a),d=await e.locate(a,l);if(d.kind==="not-found")throw new Error(`Agent ${a} not found.`);if(d.kind==="ambiguous")return zt(a,l===void 0?"recovered":"tracked",l===void 0?n(a,{kind:"artifacts-ambiguous"}):_e(l),d.candidates.map(R=>R.worktreePath));let f=Ir(d,e.multiplexer),u=Lt(d,Nr(f,l)),m=await r(a,d,l,c);if(m.kind==="refused")return se(a,d.source,u,m.settlement,{reason:m.reason,forceable:m.forceable});let x=Br(l,d);if(x.length>0)try{await e.teardownEnvironment({subagentId:a,runs:x})}catch(R){$r.warn("environment teardown failed during cleanup",{spawnId:a,error:I(R)})}if(u.kind==="worktree-unlocatable"){if(u.worktreePath!==null&&!await e.worktreeExists(u.worktreePath)){let R={agentId:a,source:d.source,outcome:{kind:"torn-down",...$e(c)},branchName:u.branchName,settlement:m.settlement,panes:await Dr(e,u.panes),worktree:{kind:"absent",path:u.worktreePath},branch:{kind:"not-applicable"}};return Ie(R)&&l!==void 0&&s.dropSpawn(l),R}return se(a,d.source,u,m.settlement,{reason:{kind:"unverifiable",detail:"missing worktree path or repo cwd"},forceable:!1})}if(u.kind==="worktree"){let R=await We(e.isWorktreeDirty,c,u.worktree);if(R.kind==="kept")return se(a,d.source,u,m.settlement,{reason:R.reason,forceable:!0})}let de=await Mr(e,u,f),V=Gt(a,d.source,u,m.settlement,de,c);return Ie(V)&&l!==void 0&&s.dropSpawn(l),V}return i(o,"cleanupAgent"),{...t,cleanupAgent:o}}i(na,"createCleanup");import*as qt from"node:path";async function jr(e,t,n){let r=await we(e,["rev-parse","--verify","--quiet",`refs/heads/${n}`],t,E);return r===void 0?!0:r.code===0}i(jr,"branchExisted");async function Kt(e,t){let n=t.branch.trim();if(n==="")throw new h("worktree checkout requires a branch name");let r=await J(e,t.repoCwd),o=qt.resolve(t.path),a=t.materialization??qe,s=t.dirtyCheckout??q,c=await jr(e,r,n),l=await we(e,["worktree","add",...ht(a),"-b",n,o,t.base??"HEAD"],r,E);if(l===void 0||l.code!==0)throw await F(e,r,o),c||await M(e,n,r),new h(l===void 0?`git worktree add for "${n}" could not run (worktree removed)`:`git worktree add for "${n}" failed (worktree removed): ${(l.stderr||l.stdout||`exit ${l.code}`).slice(0,300)}`);let d=await mt(e,["branch","--show-current"],o);if(d!==n)throw await F(e,r,o),await M(e,n,r),new h(d===void 0?`worktree created at ${o} but its branch could not be verified (worktree removed)`:`worktree created at ${o} is on branch "${d||"(detached)"}", not the requested "${n}" (worktree removed). The branch "${d}" still exists.`);let f;try{f=await kt(e,o,a,s)}catch(u){await F(e,r,o),await M(e,n,r);let m=u instanceof Error?u.message:String(u);throw new h(`worktree created but ${a} materialization failed (worktree removed): ${m}`)}if(f.kind==="cow-fallback"){let u=s==="dirty"?" The parent's uncommitted work was not carried over.":"";t.notify?.(`[cowboy] ${f.reason}${u} Nothing is shared with the parent checkout.`,"warning")}return{path:o,branch:n,repoCwd:r,materialization:f}}i(Kt,"createWorktreeCheckout");function ha(e){return e.kind==="checkout"?e.branch:ue(e.taskSlug??Qe(e.type),e.id)}i(ha,"spawnAgentName");function Lr(e){try{let t=_.statSync(e,{bigint:!0});return`${t.dev}:${t.ino}`}catch{return $.resolve(e)}}i(Lr,"canonicalRepoKey");async function ka(e){let t=await Ne.allocate(e.pi,{naming:{kind:"generated",taskSlug:e.taskSlug??e.agentType,id:e.spawnId},parentCwd:e.parentCwd,worktreeRoot:e.worktreeRoot,materialization:e.materialization,dirtyCheckout:Bt(e.agentType),notify:e.notify,host:e.host}),n=t.worktree,r=t.hostRef;return n===void 0||r===void 0?{kind:"parent-cwd"}:{kind:"owned",hostRef:r,worktree:n}}i(ka,"provisionOwnedCheckout");var Ne=class e{static{i(this,"AgentSandbox")}branch;projectTrusted;host;placement;current={kind:"bound"};constructor(t,n,r,o){this.host=t,this.placement=n,this.branch=r,this.projectTrusted=o}static async allocate(t,n){let{naming:r,parentCwd:o,worktreeRoot:a,materialization:s,dirtyCheckout:c,notify:l,host:d}=n,f=r.kind==="generated"?ue(r.taskSlug,r.id):r.branch.trim();if(r.kind==="explicit"&&f==="")throw new Error("explicit worktree naming requires a branch name");let u;try{u=await J(t,o)}catch{return l?.("[cowboy] Parent is not inside a git repository \u2014 spawning in the parent cwd without a worktree","warning"),new e(d,{kind:"parent-cwd"},f,!0)}let m=await zr(t,{repoCwd:u,path:$.join(Ye(a,u),f),branch:f,materialization:s,dirtyCheckout:c,notify:l,host:d});return new e(d,{kind:"worktree",checkout:{path:m.path,branch:m.branch,repoCwd:m.repoCwd},ref:m.ref},f,!0)}get state(){return this.current}get worktree(){return this.placement.kind==="worktree"?{path:this.placement.checkout.path,branch:this.placement.checkout.branch}:void 0}get hostRef(){return this.placement.kind==="worktree"?this.placement.ref:void 0}async teardown(t,n){let r=this.placement;if(r.kind==="parent-cwd")return this.current={kind:"destroyed"},{kind:"absent"};if(this.current.kind==="destroyed")return{kind:"absent",path:r.checkout.path};let o=await Me(Ur(t,this.host)).removeWorktree({worktree:{workspaceId:r.ref.workspaceId,worktreePath:r.checkout.path,repoCwd:r.checkout.repoCwd,branchName:r.checkout.branch},address:r.ref,panes:[r.ref]},n);return this.current=Hr(o),o}};function Hr(e){switch(e.kind){case"kept":return{kind:"preserved",reason:e.reason};case"removed":case"absent":return{kind:"destroyed"};case"removal-failed":return{kind:"teardown-failed",detail:e.detail}}}i(Hr,"stateAfterTeardown");async function zr(e,t){let n=$.resolve(t.path);return _.mkdirSync($.dirname(n),{recursive:!0}),rt().run(Lr(t.repoCwd),()=>Gr(e,t.host,{...t,path:n}))}i(zr,"createAdoptedWorktree");async function Gr(e,t,n){let{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:l}=n,d;try{d=await Kt(e,{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:l})}catch(u){throw Yt(u,await Qt(e,r,o))}let f;try{f=await t.hostAt({unit:"pane",cwd:d.path,label:a,name:a,checkout:{path:d.path,repoCwd:r,branch:d.branch}})}catch(u){let m=await Qt(e,r,d.path),x=await M(e,d.branch,r);throw Yt(u,`${m}. ${Be(d.branch,x)}`)}return{path:d.path,branch:d.branch,repoCwd:r,materialization:d.materialization,ref:f}}i(Gr,"adoptWorktree");function Ur(e,t){return{isWorktreeDirty:i(n=>Rt(e,n),"isWorktreeDirty"),worktreeExists:i(async n=>_.existsSync(n),"worktreeExists"),removeWorktree:i(n=>t.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(n,r)=>(await F(e,r,n),!_.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>vt(e,n,r=>t.isAttached(r,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:i(async n=>{await t.release(n,"placement")},"closePane"),teardownEnvironment:i(async()=>{},"teardownEnvironment")}}i(Ur,"cleanupDeps");async function Qt(e,t,n){return await F(e,t,n),_.existsSync(n)?`worktree ${n} NOT removed \u2014 inspect it manually`:`worktree ${n} removed`}i(Qt,"removeFailedCheckout");function Yt(e,t){return new Error(`could not create the herdr worktree: ${I(e)}
|
|
24
|
+
|
|
25
|
+
Launch-failure cleanup: ${t}.`)}i(Yt,"createFailureMessage");function Be(e,t){switch(t.kind){case"deleted":return`branch ${e} deleted`;case"kept":return`branch ${e} kept (${t.reason})`;case"delete-failed":return`branch ${e} NOT deleted \u2014 ${t.detail}`;case"not-applicable":return`branch ${e} already gone`}}i(Be,"formatLaunchedBranchOutcome");function ya(e){switch(e.kind){case"removed":return e.via==="multiplexer"?`Launch-failure cleanup: worktree ${e.path} removed \u2014 its workspace, tab, and pane were closed with it. ${Be(e.branchName,e.branch)}.`:`Launch-failure cleanup: worktree ${e.path} removed. ${Be(e.branchName,e.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${e.path} KEPT \u2014 ${Tt(e.reason)}. No agent spawn exists for it, so extension cleanup cannot see it \u2014 inspect and remove it manually.`;case"removal-failed":return`Launch-failure cleanup FAILED for worktree ${e.path}: ${e.detail} \u2014 it may still exist, and no agent spawn exists for it, so inspect it manually.`;case"absent":return"Launch-failure cleanup: no worktree residue was left behind."}}i(ya,"formatLaunchCleanupNote");export{qr as a,pt as b,b as c,mt as d,j as e,Xr as f,J as g,F as h,to as i,no as j,yt as k,go as l,vt as m,Rt as n,bo as o,Tt as p,Se as q,Ai as r,Oi as s,Sr as t,Pi as u,ae as v,Si as w,_i as x,Wi as y,O as z,er as A,Do as B,Mo as C,Ho as D,ri as E,oi as F,ii as G,ai as H,Wr as I,Li as J,Hi as K,Bt as L,zi as M,Gi as N,Ui as O,Qi as P,na as Q,ha as R,ka as S,Ne as T,zr as U,ya as V};
|
|
26
|
+
//# sourceMappingURL=chunk-JISXMHPN.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{Da as x}from"./chunk-UUTVNESQ.js";import{a as s,e as f,l as C}from"./chunk-XXNZAWMK.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-TRRZFG6L.js.map
|