pi-cowboy 0.36.0 → 0.36.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,8 +25,7 @@ export declare class AgentManager {
25
25
  private readonly registry;
26
26
  constructor(pools: ConcurrencyPools, transport: SupervisorTransport);
27
27
  getRegistry(): HerdrTaskRegistry;
28
- attachLiveSpawns(): void;
29
- private attachSpawn;
28
+ attachSpawns(): void;
30
29
  setConcurrency(config: ConcurrencyConfig): void;
31
30
  setOnComplete(cb: OnAgentComplete): void;
32
31
  setOnFollowUp(cb: OnAgentFollowUp): void;
@@ -107,6 +107,7 @@ export interface HarnessStopRequest {
107
107
  readonly pi: ExtensionAPI;
108
108
  readonly pane: PaneControl;
109
109
  readonly paneId: string;
110
+ readonly staged: HarnessRunStaging;
110
111
  }
111
112
  export type HarnessStop = (request: HarnessStopRequest) => Promise<void>;
112
113
  export interface HarnessSteerRequest {
@@ -115,6 +116,7 @@ export interface HarnessSteerRequest {
115
116
  readonly paneId: string;
116
117
  readonly message: string;
117
118
  readonly signal: AbortSignal;
119
+ readonly staged: HarnessRunStaging;
118
120
  }
119
121
  export type HarnessSteer = (request: HarnessSteerRequest) => Promise<DeliverOutcome>;
120
122
  export interface HarnessTeardownContext {
@@ -71,6 +71,7 @@ export declare function finishSettling(state: RunState): RunState;
71
71
  export declare function handoverRun(state: RunState, startedAt: number): RunState;
72
72
  export declare function reviveRun(state: RunState, startedAt: number): RunState;
73
73
  export declare function activeRun(queuedAt: number, startedAt: number): RunState;
74
+ export declare function restoreRun(lifecycle: AgentLifecycleState): RunState | undefined;
74
75
  export declare function disposeQueuedRun(state: RunState, completedAt: number): RunState;
75
76
  export declare function disposeLiveRun(state: RunState): RunState;
76
77
  export declare function dropRun(state: RunState, artifacts: RunArtifacts): RunState;
@@ -83,6 +83,7 @@ export declare class SubagentSession {
83
83
  private readTarget;
84
84
  private handoverSource;
85
85
  private exportSource;
86
+ private stagedPaths;
86
87
  private readRunSession;
87
88
  private handoverTask;
88
89
  handover(request: SessionHandoverRequest): Promise<HandoverOutcome>;
@@ -91,6 +92,7 @@ export declare class SubagentSession {
91
92
  settleForDispose(): void;
92
93
  private launch;
93
94
  private launchAborted;
95
+ private renewAbortController;
94
96
  private supervisorOptions;
95
97
  private stopHarnessProcess;
96
98
  private resultFilePath;
@@ -1,2 +1,2 @@
1
- import{h as l,n as h}from"./chunk-DD4TYA7R.js";import{a as r}from"./chunk-YEXMGUZI.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-F45A7CCD.js.map
1
+ import{h as l,n as h}from"./chunk-OR6LWM7F.js";import{a as r}from"./chunk-AOUEQXPY.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-2RG6EJRC.js.map
@@ -1,4 +1,4 @@
1
- import{A as Jt,B as Xt,D as qt,G as x,H as Qt,I as m,J as Oe,K as Zt,L as er,M as O,N as C,O as nr,P as F,a as r,c as Wt,d as Kt,e as Ut,f as Ce,g as Kn,h as Bt,i as Vt,j as zt,k as Un,l as y,m as A,o as Yt,p as h,v as Xe,w as qe,x as X,y as $,z as Bn}from"./chunk-YEXMGUZI.js";import*as Q from"node:path";import*as rr from"node:fs";import{homedir as Vn,tmpdir as ks}from"node:os";import*as P from"node:path";import{fileURLToPath as or}from"node:url";var tr={name:"pi-cowboy",version:"0.36.0",type:"module",packageManager:"pnpm@12.9.1",description:"\u{1F920} Agent orchestrator for pi. It can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents and handover sessions in between them. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",keywords:["pi-package","pi","pi-agent","pi-coding-agent","pi-extension","subagents","herdr","ai","agents"],license:"MIT",author:"electric-dragon-80000v",homepage:"https://github.com/electric-dragon-80000v/pi-cowboy#readme",repository:{type:"git",url:"git+https://github.com/electric-dragon-80000v/pi-cowboy.git"},bugs:{url:"https://github.com/electric-dragon-80000v/pi-cowboy/issues"},engines:{node:">=24.20.0",pnpm:">=12"},main:"./dist/index.js",types:"./dist/index.d.ts",files:["dist/","!dist/**/*.js.map","!dist/**/.*","agents/","orchestrators/","!orchestrators/with-code-review.toml","README.md","LICENSE"],exports:{".":"./dist/index.js","./plugin":"./dist/plugin/index.js","./package.json":"./package.json"},scripts:{format:"prettier --write src/ test/ scripts/ lint/ docs/","format:check":"prettier --check src/ test/ scripts/ lint/ docs/",typecheck:"tsc6 --noEmit","find-unused":"node --disable-warning=ExperimentalWarning scripts/find-unused.ts",build:"node scripts/build.ts && tsc6 -p tsconfig.build.json",prepack:"pnpm run build",test:"pnpm run build && vitest run","test:unit":"vitest run --project unit","test:integration":"pnpm run build && vitest run --project integration-no-cow --project integration-cow","test:integration-no-cow":"pnpm run build && vitest run --project integration-no-cow","test:integration-cow":"pnpm run build && vitest run --project integration-cow","dev:install":"pi remove . 2>/dev/null; pi install ./dev",lint:"oxlint","lint:fix":"oxlint --fix",commitlint:"commitlint",release:"semantic-release","release:stage":"npm stage publish","release:approve":"scripts/publish.sh",prepare:"husky"},pi:{image:"https://raw.githubusercontent.com/electric-dragon-80000v/pi-cowboy/main/docs/assets/logo-pi-package-landscape.png",video:"https://github.com/electric-dragon-80000v/pi-cowboy/raw/refs/heads/main/docs/assets/pi-cowboy.mp4",extensions:["./dist/index.js"]},peerDependencies:{"@earendil-works/pi-ai":"*","@earendil-works/pi-coding-agent":"*","@earendil-works/pi-tui":"*",typebox:"*"},devDependencies:{"@commitlint/cli":"^21.2.3","@commitlint/config-conventional":"^21.2.3","@commitlint/types":"^21.2.3","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/exec":"^7.1.0","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/estree":"^1.0.9","@types/mustache":"^4.2.6","@types/node":"^26.6.4","@vitest/coverage-v8":"5.0.3","@vitest/ui":"^5.0.3",esbuild:"^0.28.2",eslint:"^10.12.0","eslint-plugin-import-x":"^4.17.1",husky:"^9.1.7",oxlint:"1.93.0","oxlint-tsgolint":"7.0.2006",prettier:"^3.9.9","semantic-release":"^25.0.9",typescript:"npm:@typescript/typescript6@^6.0.2",vitest:"^5.0.3"},dependencies:{"jsonc-parser":"^3.3.1",mustache:"^4.2.0","smol-toml":"^1.9.0",yaml:"^2.9.1",zod:"^4.6.5"}};var zn=tr.name,As="PI_CODING_AGENT_DIR";function Ss(){let e=process.env[As];return e?v(e):P.join(Vn(),".pi","agent")}r(Ss,"agentDir");function v(e){return e==="~"?Vn():e.startsWith("~/")?P.join(Vn(),e.slice(2)):e}r(v,"expandTilde");function M(e){try{return rr.realpathSync.native(e)}catch{return}}r(M,"canonicalPath");function Qe(){return P.join(Ss(),zn)}r(Qe,"defaultExtensionDir");function sr(){return P.join(Qe(),"worktrees")}r(sr,"defaultWorktreeRoot");function Rs(){return P.join(ks(),"pi-cowboy")}r(Rs,"subagentResultDir");function q(e){return P.join(Rs(),e)}r(q,"subagentResultDirFor");function Qc(e){return P.join(q(e),"result.md")}r(Qc,"subagentResultFileFor");var Is="system.md",Ts="prompt.md";function Zc(e){return P.join(q(e),Is)}r(Zc,"subagentSystemFileFor");var _s="env.sh";function ir(e){return P.join(q(e),_s)}r(ir,"subagentEnvFileFor");function eu(e){return P.join(q(e),Ts)}r(eu,"subagentTaskFileFor");var Yn="cowboy-subagent-";function ye(e){return`${Yn}${e}`}r(ye,"subagentTokenFor");var nu=or(new URL("../agents/",import.meta.url)),tu=or(new URL("../orchestrators/",import.meta.url));function su(e){return{status:"known",available:new Set(e)}}r(su,"probed");function Jn(){return{status:"unknown"}}r(Jn,"unprobed");function Pe(e,n){return n.status==="unknown"||n.available.has(e)}r(Pe,"isAvailable");function iu(e,n){return e.filter(t=>Pe(t,n))}r(iu,"selectable");function ar(e,n){return n.status==="known"&&n.available.has(e)}r(ar,"isProven");var Ze="cow-",Me="copy-on-write",gu=["copy-on-write","checkout"];function fu(e){if(e==="copy-on-write"||e==="checkout")return e}r(fu,"parseWorktreeMaterialization");function ur(e,n){return Pe("copy-on-write",n)?e??Me:"checkout"}r(ur,"resolveWorktreeMaterialization");var en="clean",mu=["dirty","clean"];function yu(e){if(e==="dirty"||e==="clean")return e}r(yu,"parseWorktreeCheckoutType");function hu(e){return e.branch??Q.basename(e.path)}r(hu,"worktreeBranchOf");function Eu(e){if(e==null)return{kind:"new"};if(e==="new"||e==="inherit")return{kind:e};if(typeof e=="object"&&!Array.isArray(e)&&typeof e.path=="string"){let n=e.path.trim();if(n!=="")return{kind:"picked",path:n}}throw new Error('Invalid `worktree`: pass "new", "inherit", or { "path": "/absolute/checkout" }. Nothing was spawned.')}r(Eu,"parseWorktreeRequest");var dr=3,lr=Ce-Ze.length-1-Wt-Bt;function Cs(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}r(Cs,"slugifyWorktreeType");function Os(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(n=>n.length>0)}r(Os,"taskNameWords");function bu(e){let n=Os(e);if(n.length===0)throw new Error("Task name is empty \u2014 provide a short 2-3 word name.");if(n.length>dr)throw new Error(`Task name "${e}" gives the branch name "${n.join("-")}" with ${n.length} words. The limit is ${dr} words.`);let t=n.join("-");if(t.length>lr)throw new Error(`Task name "${e}" gives the branch name "${t}" with ${t.length} characters. The limit is ${lr} characters, because herdr limits agent names to 32 characters.`);return t}r(bu,"buildTaskSlug");function Ps(e,n){return`${Ze}${Cs(e)}-${n}`}r(Ps,"buildWorktreeBranch");function xu(e,n,t){return Q.join(e,Ps(n,t))}r(xu,"buildWorktreePath");function wu(e,n){return e&&e.trim()!==""?Q.isAbsolute(e)?e:Q.resolve(n,e):sr()}r(wu,"resolveWorktreeRoot");function cr(e){return(M(e)??e.replace(/\\/g,"/")).replace(/\/+$/,"")}r(cr,"normalizeRoot");function vu(e,n){return n!==""&&e.startsWith(Ze)&&e.length>n.length&&e.endsWith(`-${n}`)}r(vu,"isSpawnArtifactName");function ku(e,n){let t=cr(e),o=cr(n);return t!==o&&!t.startsWith(`${o}/`)?!1:(t.split("/").filter(Boolean).pop()??"").startsWith(Ze)}r(ku,"isExtensionWorktree");import{getSupportedThinkingLevels as Wc}from"@earendil-works/pi-ai";var nn=class{static{r(this,"RepoLock")}tails=new Map;async run(n,t){let o=(this.tails.get(n)??Promise.resolve()).then(t),s=o.then(()=>{},()=>{});this.tails.set(n,s);try{return await o}finally{this.tails.get(n)===s&&this.tails.delete(n)}}};import*as he from"node:fs";import*as tn from"node:path";function V(e){for(let n of(process.env.PATH??"").split(tn.delimiter)){if(n==="")continue;let t=tn.join(n,e);try{if(!he.statSync(t).isFile())continue;return he.accessSync(t,he.constants.X_OK),t}catch{}}}r(V,"commandPath");function Tu(e){return V(e)??e}r(Tu,"resolveCommand");import{readFile as Xn,readdir as Ms}from"node:fs/promises";import*as He from"node:path";import{z as Ee}from"zod";var pr=3,Hs="sessionDir",fr=Ee.object({type:Ee.string(),text:Ee.string().optional(),thinking:Ee.string().optional()}),Ls=Ee.array(Ee.unknown());function rn(e){return`--${(M(e)??He.resolve(e)).replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}r(rn,"sessionBucketName");async function be(e){let n;try{n=await Xn(He.join(e,"settings.json"),"utf8")}catch{return}let t;try{t=JSON.parse(n)}catch{return}if(y(t))return A(t[Hs])}r(be,"readSessionDirSetting");async function Ns(e,n,t){let o;try{o=await Ms(e,{withFileTypes:!0})}catch{throw new m("session-not-found",`no session record under ${e} for ${t} (subagent ${n})`)}let s=[];for(let i of o){if(!i.isFile()||!i.name.endsWith(".jsonl"))continue;let a=He.join(e,i.name);await Ds(a)===n&&s.push(a)}if(s.length===0)throw new m("session-not-found",`no session record under ${e} for ${t} (subagent ${n})`);if(s.length>1)throw new m("ambiguous-session",`more than one session record under ${e} names subagent ${n}: ${s.join(", ")}`);return s[0]}r(Ns,"findSessionFile");async function Ds(e){let n;try{n=await Xn(e,"utf8")}catch{return}let t;for(let o of n.split(`
1
+ import{A as Jt,B as Xt,D as qt,G as x,H as Qt,I as m,J as Oe,K as Zt,L as er,M as O,N as C,O as nr,P as F,a as r,c as Wt,d as Kt,e as Ut,f as Ce,g as Kn,h as Bt,i as Vt,j as zt,k as Un,l as y,m as A,o as Yt,p as h,v as Xe,w as qe,x as X,y as $,z as Bn}from"./chunk-AOUEQXPY.js";import*as Q from"node:path";import*as rr from"node:fs";import{homedir as Vn,tmpdir as ks}from"node:os";import*as P from"node:path";import{fileURLToPath as or}from"node:url";var tr={name:"pi-cowboy",version:"0.36.2",type:"module",packageManager:"pnpm@12.9.1",description:"\u{1F920} Agent orchestrator for pi. It can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents and handover sessions in between them. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",keywords:["pi-package","pi","pi-agent","pi-coding-agent","pi-extension","subagents","herdr","ai","agents"],license:"MIT",author:"electric-dragon-80000v",homepage:"https://github.com/electric-dragon-80000v/pi-cowboy#readme",repository:{type:"git",url:"git+https://github.com/electric-dragon-80000v/pi-cowboy.git"},bugs:{url:"https://github.com/electric-dragon-80000v/pi-cowboy/issues"},engines:{node:">=24.20.0",pnpm:">=12"},main:"./dist/index.js",types:"./dist/index.d.ts",files:["dist/","!dist/**/*.js.map","!dist/**/.*","agents/","orchestrators/","!orchestrators/with-code-review.toml","README.md","LICENSE"],exports:{".":"./dist/index.js","./plugin":"./dist/plugin/index.js","./package.json":"./package.json"},scripts:{format:"prettier --write src/ test/ scripts/ lint/ docs/","format:check":"prettier --check src/ test/ scripts/ lint/ docs/",typecheck:"tsc6 --noEmit","find-unused":"node --disable-warning=ExperimentalWarning scripts/find-unused.ts",build:"node scripts/build.ts && tsc6 -p tsconfig.build.json",prepack:"pnpm run build",test:"pnpm run build && vitest run","test:unit":"vitest run --project unit","test:integration":"pnpm run build && vitest run --project integration-no-cow --project integration-cow","test:integration-no-cow":"pnpm run build && vitest run --project integration-no-cow","test:integration-cow":"pnpm run build && vitest run --project integration-cow","dev:install":"pi remove . 2>/dev/null; pi install ./dev",lint:"oxlint","lint:fix":"oxlint --fix",commitlint:"commitlint",release:"semantic-release","release:stage":"npm stage publish","release:approve":"scripts/publish.sh",prepare:"husky"},pi:{image:"https://raw.githubusercontent.com/electric-dragon-80000v/pi-cowboy/main/docs/assets/logo-pi-package-landscape.png",video:"https://github.com/electric-dragon-80000v/pi-cowboy/raw/refs/heads/main/docs/assets/pi-cowboy.mp4",extensions:["./dist/index.js"]},peerDependencies:{"@earendil-works/pi-ai":"*","@earendil-works/pi-coding-agent":"*","@earendil-works/pi-tui":"*",typebox:"*"},devDependencies:{"@commitlint/cli":"^21.2.3","@commitlint/config-conventional":"^21.2.3","@commitlint/types":"^21.2.3","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/exec":"^7.1.0","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/estree":"^1.0.9","@types/mustache":"^4.2.6","@types/node":"^26.6.4","@vitest/coverage-v8":"5.0.3","@vitest/ui":"^5.0.3",esbuild:"^0.28.2",eslint:"^10.12.0","eslint-plugin-import-x":"^4.17.1",husky:"^9.1.7",oxlint:"1.93.0","oxlint-tsgolint":"7.0.2006",prettier:"^3.9.9","semantic-release":"^25.0.9",typescript:"npm:@typescript/typescript6@^6.0.2",vitest:"^5.0.3"},dependencies:{"jsonc-parser":"^3.3.1",mustache:"^4.2.0","smol-toml":"^1.9.0",yaml:"^2.9.1",zod:"^4.6.5"}};var zn=tr.name,As="PI_CODING_AGENT_DIR";function Ss(){let e=process.env[As];return e?v(e):P.join(Vn(),".pi","agent")}r(Ss,"agentDir");function v(e){return e==="~"?Vn():e.startsWith("~/")?P.join(Vn(),e.slice(2)):e}r(v,"expandTilde");function M(e){try{return rr.realpathSync.native(e)}catch{return}}r(M,"canonicalPath");function Qe(){return P.join(Ss(),zn)}r(Qe,"defaultExtensionDir");function sr(){return P.join(Qe(),"worktrees")}r(sr,"defaultWorktreeRoot");function Rs(){return P.join(ks(),"pi-cowboy")}r(Rs,"subagentResultDir");function q(e){return P.join(Rs(),e)}r(q,"subagentResultDirFor");function Qc(e){return P.join(q(e),"result.md")}r(Qc,"subagentResultFileFor");var Is="system.md",Ts="prompt.md";function Zc(e){return P.join(q(e),Is)}r(Zc,"subagentSystemFileFor");var _s="env.sh";function ir(e){return P.join(q(e),_s)}r(ir,"subagentEnvFileFor");function eu(e){return P.join(q(e),Ts)}r(eu,"subagentTaskFileFor");var Yn="cowboy-subagent-";function ye(e){return`${Yn}${e}`}r(ye,"subagentTokenFor");var nu=or(new URL("../agents/",import.meta.url)),tu=or(new URL("../orchestrators/",import.meta.url));function su(e){return{status:"known",available:new Set(e)}}r(su,"probed");function Jn(){return{status:"unknown"}}r(Jn,"unprobed");function Pe(e,n){return n.status==="unknown"||n.available.has(e)}r(Pe,"isAvailable");function iu(e,n){return e.filter(t=>Pe(t,n))}r(iu,"selectable");function ar(e,n){return n.status==="known"&&n.available.has(e)}r(ar,"isProven");var Ze="cow-",Me="copy-on-write",gu=["copy-on-write","checkout"];function fu(e){if(e==="copy-on-write"||e==="checkout")return e}r(fu,"parseWorktreeMaterialization");function ur(e,n){return Pe("copy-on-write",n)?e??Me:"checkout"}r(ur,"resolveWorktreeMaterialization");var en="clean",mu=["dirty","clean"];function yu(e){if(e==="dirty"||e==="clean")return e}r(yu,"parseWorktreeCheckoutType");function hu(e){return e.branch??Q.basename(e.path)}r(hu,"worktreeBranchOf");function Eu(e){if(e==null)return{kind:"new"};if(e==="new"||e==="inherit")return{kind:e};if(typeof e=="object"&&!Array.isArray(e)&&typeof e.path=="string"){let n=e.path.trim();if(n!=="")return{kind:"picked",path:n}}throw new Error('Invalid `worktree`: pass "new", "inherit", or { "path": "/absolute/checkout" }. Nothing was spawned.')}r(Eu,"parseWorktreeRequest");var dr=3,lr=Ce-Ze.length-1-Wt-Bt;function Cs(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}r(Cs,"slugifyWorktreeType");function Os(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(n=>n.length>0)}r(Os,"taskNameWords");function bu(e){let n=Os(e);if(n.length===0)throw new Error("Task name is empty \u2014 provide a short 2-3 word name.");if(n.length>dr)throw new Error(`Task name "${e}" gives the branch name "${n.join("-")}" with ${n.length} words. The limit is ${dr} words.`);let t=n.join("-");if(t.length>lr)throw new Error(`Task name "${e}" gives the branch name "${t}" with ${t.length} characters. The limit is ${lr} characters, because herdr limits agent names to 32 characters.`);return t}r(bu,"buildTaskSlug");function Ps(e,n){return`${Ze}${Cs(e)}-${n}`}r(Ps,"buildWorktreeBranch");function xu(e,n,t){return Q.join(e,Ps(n,t))}r(xu,"buildWorktreePath");function wu(e,n){return e&&e.trim()!==""?Q.isAbsolute(e)?e:Q.resolve(n,e):sr()}r(wu,"resolveWorktreeRoot");function cr(e){return(M(e)??e.replace(/\\/g,"/")).replace(/\/+$/,"")}r(cr,"normalizeRoot");function vu(e,n){return n!==""&&e.startsWith(Ze)&&e.length>n.length&&e.endsWith(`-${n}`)}r(vu,"isSpawnArtifactName");function ku(e,n){let t=cr(e),o=cr(n);return t!==o&&!t.startsWith(`${o}/`)?!1:(t.split("/").filter(Boolean).pop()??"").startsWith(Ze)}r(ku,"isExtensionWorktree");import{getSupportedThinkingLevels as Wc}from"@earendil-works/pi-ai";var nn=class{static{r(this,"RepoLock")}tails=new Map;async run(n,t){let o=(this.tails.get(n)??Promise.resolve()).then(t),s=o.then(()=>{},()=>{});this.tails.set(n,s);try{return await o}finally{this.tails.get(n)===s&&this.tails.delete(n)}}};import*as he from"node:fs";import*as tn from"node:path";function V(e){for(let n of(process.env.PATH??"").split(tn.delimiter)){if(n==="")continue;let t=tn.join(n,e);try{if(!he.statSync(t).isFile())continue;return he.accessSync(t,he.constants.X_OK),t}catch{}}}r(V,"commandPath");function Tu(e){return V(e)??e}r(Tu,"resolveCommand");import{readFile as Xn,readdir as Ms}from"node:fs/promises";import*as He from"node:path";import{z as Ee}from"zod";var pr=3,Hs="sessionDir",fr=Ee.object({type:Ee.string(),text:Ee.string().optional(),thinking:Ee.string().optional()}),Ls=Ee.array(Ee.unknown());function rn(e){return`--${(M(e)??He.resolve(e)).replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}r(rn,"sessionBucketName");async function be(e){let n;try{n=await Xn(He.join(e,"settings.json"),"utf8")}catch{return}let t;try{t=JSON.parse(n)}catch{return}if(y(t))return A(t[Hs])}r(be,"readSessionDirSetting");async function Ns(e,n,t){let o;try{o=await Ms(e,{withFileTypes:!0})}catch{throw new m("session-not-found",`no session record under ${e} for ${t} (subagent ${n})`)}let s=[];for(let i of o){if(!i.isFile()||!i.name.endsWith(".jsonl"))continue;let a=He.join(e,i.name);await Ds(a)===n&&s.push(a)}if(s.length===0)throw new m("session-not-found",`no session record under ${e} for ${t} (subagent ${n})`);if(s.length>1)throw new m("ambiguous-session",`more than one session record under ${e} names subagent ${n}: ${s.join(", ")}`);return s[0]}r(Ns,"findSessionFile");async function Ds(e){let n;try{n=await Xn(e,"utf8")}catch{return}let t;for(let o of n.split(`
2
2
  `)){if(o.trim()==="")continue;let s;try{s=JSON.parse(o)}catch{continue}!y(s)||s.type!=="session_info"||(t=A(s.name))}return t}r(Ds,"readLatestSessionName");async function js(e){let n=await Gs(e),t=!n.endsWith(`
3
3
  `),o=n.split(`
4
4
  `);t||o.pop();let s=$s(o,t,e);return{sessionId:s.header.id,records:Fs(o,s.index,t)}}r(js,"readSessionFile");function $s(e,n,t){for(let o=0;o<e.length;o++){let s=e[o];if(s.trim()==="")continue;let i;try{i=JSON.parse(s)}catch{if(n&&o===e.length-1)break;throw new m("malformed-record",`malformed session record in ${t} at line ${o+1}`)}if(!y(i))throw new m("malformed-record",`malformed session record in ${t} at line ${o+1}`);return{index:o,header:Ws(i,t)}}throw new m("malformed-record",`session record ${t} has no session header`)}r($s,"findSessionHeader");function*Fs(e,n,t){for(let o=0;o<e.length;o++){let s=e[o];if(s.trim()==="")continue;if(o===n){yield x("session",s);continue}let i;try{i=JSON.parse(s)}catch{if(t&&o===e.length-1)break;yield{kind:"unparseable",content:s};continue}if(!y(i)){yield{kind:"unparseable",content:s};continue}yield Ks(i,s)}}r(Fs,"sessionRecords");async function Gs(e){try{return await Xn(e,"utf8")}catch(n){throw new m("unreadable-record",`cannot read session record ${e}: ${h(n)}`)}}r(Gs,"readSessionFileContent");function Ws(e,n){if(e.type!=="session")throw new m("malformed-record",`session record ${n} does not start with a session header`);let t=e.version;if(typeof t!="number"||!Number.isInteger(t))throw new m("malformed-record",`session record ${n} has no numeric version`);if(t!==pr)throw new m("unsupported-version",`session record ${n} uses version ${t}; this export reads version ${pr}`);let o=A(e.id);if(o===void 0)throw new m("missing-session-id",`session record ${n} names no session id`);return{id:o}}r(Ws,"readHeader");function Ks(e,n){if(e.type==="compaction")return Us(e,n);if(e.type!=="message")return x(e.type,n);if(!y(e.message))return{kind:"unparseable",content:n};let t=e.message.role;if(t!=="user"&&t!=="assistant"&&t!=="toolResult")return x(t,n);let o=Ls.safeParse(e.message.content);if(!o.success)return{kind:"unparseable",content:n};if(t==="toolResult")return{kind:"tool-call",content:JSON.stringify(o.data)};let s=gr(o.data,"text");if(s!=="")return{kind:t,content:s};let i=gr(o.data,"thinking");if(i!=="")return{kind:"thinking",content:i};let a=Bs(o.data,"toolCall");return a.length>0?{kind:"tool-call",content:JSON.stringify(a)}:x(t,n)}r(Ks,"readTurn");function Us(e,n){return typeof e.summary!="string"?{kind:"unparseable",content:n}:{kind:"compaction",content:mr(e.summary)}}r(Us,"readCompaction");function gr(e,n){let t=[];for(let o of e){let s=fr.safeParse(o);if(!s.success||s.data.type!==n)continue;let i=n==="thinking"?s.data.thinking??s.data.text:s.data.text;if(i===void 0)continue;let a=mr(i);a!==""&&t.push(a)}return t.join(`
@@ -51,4 +51,4 @@ ${rs(i.content)}`;break}case"thinking":case"tool-call":case"other":break;case"un
51
51
  `).map(t=>{let o=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(t);if(o!==null){let a=o[1];return n===void 0?n=a:a[0]===n[0]&&a.length>=n.length&&o[2].trim()===""&&(n=void 0),t}if(n!==void 0)return t;let s=/^( {0,3})#{1,6}(?=\s|$)/.exec(t);if(s===null)return t;let i=s[1];return`${i}\\${t.slice(i.length)}`}).join(`
52
52
  `)}r(rs,"escapeContentHeadings");async function ay(e,n,t,o){let s=e.get(n);if(s===void 0||!er(s))return{kind:"faulted",fault:{kind:"harness-cannot-export-session",harness:n}};let i;try{i=await s.readHandoverRecords(t)}catch(u){return{kind:"faulted",fault:{kind:"session-export-failed",harness:n,detail:u instanceof Error?u.message:String(u),...u instanceof m?{exportFault:u.fault}:{}}}}if(i.sessionId.trim()==="")return{kind:"faulted",fault:{kind:"session-export-failed",harness:n,detail:"the harness named no session id for the run it exported"}};let a=ec(i),d=a.loss;return d!==void 0&&d.total>0&&d.excluded/d.total>o.maxExcludedRatio?{kind:"faulted",fault:{kind:"session-export-failed",harness:n,detail:Zl(d,o)}}:a.session.trim()===""?{kind:"faulted",fault:{kind:"session-empty",harness:n}}:{kind:"exported",sessionId:a.sessionId,session:a.session,...d===void 0?{}:{loss:d}}}r(ay,"exportRunSession");var nc="<<pi-cowboy-handover",tc=">>";function rc(e){let n=e.map(({harness:t,sessionId:o})=>({harness:t,sessionId:o}));return`${nc} ${JSON.stringify(n)}${tc}`}r(rc,"renderHandoverMarker");function dy(e){return[e.taskSlug===void 0?"You are continuing this task in this workspace.":`You are continuing work on task "${e.taskSlug}" in this workspace.`,`This task was previously handled by another agent harness (${e.sourceName}).`,`The previous run's session id is "${e.current.sessionId}".`,rc([...e.previous,e.current]),"","The session of the previous run is quoted below. Review it together with the current state of the files in this repository, then proceed with the task.","","---","",e.session,""].join(`
53
53
  `)}r(dy,"renderHandoverTask");var os=4;function ge(e){let n=e.indexOf("/"),t=e.indexOf(":"),o=t>0&&(n<0||t<n),s=X,i=e;if(o){if(s=e.slice(0,t),s.trim()==="")return;i=e.slice(t+1)}let a=i.indexOf("/");if(a<0)return i===""?void 0:{kind:"provider",harness:s,provider:i};let d=i.slice(0,a),u=i.slice(a+1);if(!(d===""||u===""))return{kind:"model",harness:s,provider:d,model:u}}r(ge,"parsePoolKey");function is(e,n,t){return`${e}:${n}/${t}`}r(is,"qualifiedModelKey");function as(e,n){return`${e}:${n}`}r(as,"qualifiedProviderKey");function oc(e){let n=ge(e);return n?.kind==="model"?is(n.harness,n.provider,n.model):void 0}r(oc,"modelPoolKeyOf");function sc(e){let n=ge(e);return n?.kind==="provider"?as(n.harness,n.provider):void 0}r(sc,"providerPoolKeyOf");function Pt(e){return Math.max(1,e)}r(Pt,"clampLimit");var ss=class{static{r(this,"ConcurrencyPools")}modelPools=new Map;providerPools=new Map;harnessPools=new Map;globalPool={limit:os,spawned:0};queue=[];reservations=new Map;constructor(n){this.setLimits(n??{default:os,harnesses:{},providers:{},models:{}})}setConcurrency(n){this.setLimits(n),this.drainQueue()}admitSpawn(n,t){let o=this.applicablePools(n);return this.hasRoom(o)?{kind:"start",reservation:o}:(this.queue.push({id:t.id,identity:n,start:t.start}),{kind:"queue"})}reserve(n,t){for(let o of t)o.spawned++;this.reservations.set(n,t)}reacquire(n,t){this.reservations.has(n)||this.reserve(n,this.applicablePools(t))}release(n){let t=this.reservations.get(n);if(t){for(let o of t)o.spawned=Math.max(0,o.spawned-1);this.reservations.delete(n)}this.cancelQueued(n),this.drainQueue()}cancelQueued(n){this.queue=this.queue.filter(t=>t.id!==n)}clearQueue(){this.queue=[]}queuePosition(n){return this.queue.findIndex(t=>t.id===n)+1}setLimits(n){this.globalPool.limit=Pt(n.default),this.syncHarnessPools(n.harnesses),this.syncPools(this.providerPools,n.providers,sc),this.syncPools(this.modelPools,n.models,oc)}syncHarnessPools(n){let t=new Map;for(let[o,s]of Object.entries(n))o.trim()!==""&&typeof s=="number"&&t.set(o,Pt(s));for(let[o,s]of t){let i=this.harnessPools.get(o);i?i.limit=s:this.harnessPools.set(o,{limit:s,spawned:0})}for(let o of this.harnessPools.keys())t.has(o)||this.harnessPools.delete(o)}syncPools(n,t,o){let s=new Map;for(let[i,a]of Object.entries(t)){let d=o(i);d!==void 0&&a!==void 0&&s.set(d,Pt(a))}for(let[i,a]of s){let d=n.get(i);d?d.limit=a:n.set(i,{limit:a,spawned:0})}for(let i of n.keys())s.has(i)||n.delete(i)}applicablePools(n){let t=[];if(n.modelKey){let s=ge(n.modelKey);if(s?.kind==="model"){let i=this.modelPools.get(is(n.harness,s.provider,s.model));i&&t.push(i);let a=this.providerPools.get(as(n.harness,s.provider));a&&t.push(a)}}let o=this.harnessPools.get(n.harness);return o&&t.push(o),t.push(this.globalPool),t}hasRoom(n){return n.every(t=>t.spawned<t.limit)}drainQueue(){let n=[];for(let t of this.queue){let o=this.applicablePools(t.identity);if(!this.hasRoom(o)){n.push(t);continue}t.start(o)}this.queue=n}};var We="defaultModelByHarness",fe="defaultThinkingByHarness",Ie="thinking",Hn=["default","defaultAgentType","defaultOrchestrator","systemPromptMode","includeContextFiles","defaultThinking",fe,Ie,"loadSkillsImplicitly","loadExtensionsImplicitly","disableDefaultAgents","extensionEnabled","showActiveIndicator","grazingEnabled","worktreeRoot","worktreeMaterialization","worktreeCheckoutType","handoverMaxExcludedRatio","harnessType"];import*as N from"node:fs";import*as _e from"node:path";import{z as B}from"zod";function ds(e,n,t){return Jt(e)?qt(e,t)?"reserved":typeof n!="string"?"not-string":Xt(n)?"control":null:"name"}r(ds,"envProblem");function ls(e,n){let t={};for(let[o,s]of Object.entries(e)){if(s===void 0)continue;let i=ds(o,s,n.reserved);if(i!==null){n.report(o,i,s);continue}t[o]=s}return t}r(ls,"sanitizeEnv");function yy(e,n){return e===void 0?n:n===void 0?e:{...e,...n}}r(yy,"mergeEnv");function hy(e){for(let[n,t]of Object.entries(e)){let o=ds(n,t,[]);if(o!==null)throw new Error(`Invalid environment variable ${n}: ${o}`)}return e}r(hy,"trustedEnv");import{z as ic}from"zod";var Mt=ic.number().int().min(1),Te="positive integer";function Ln(e){return Mt.safeParse(e).success}r(Ln,"isConcurrencyLimit");var ac="Set it again in the /cowboy menu, or edit or delete the file to fix it.",Ue="Edit or delete the key in that file to fix it.",dc={schema:B.number().min(0).max(1),expected:"a number from 0 to 1",fix:Ue},Ht={schema:B.union([B.string(),B.null()]),expected:"string or null"},me={schema:B.boolean(),expected:"boolean"},lc={schema:B.enum(["replace","inherit","custom"]),expected:'"replace" | "inherit" | "custom"'},cc={schema:B.enum(["off","minimal","low","medium","high","xhigh","max"]),expected:'"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"'},uc={schema:B.enum(["copy-on-write","checkout"]),expected:'"copy-on-write" | "checkout"'},pc={schema:B.enum(["dirty","clean"]),expected:'"dirty" | "clean"'},us=B.string().min(1).refine(e=>/\S/.test(e)),Ke={schema:us,expected:"non-empty string"},ps=qe.map(e=>`"${e}"`).join(" | "),gc=`an object keyed by a harness id (${ps} or a plugin's), with string or null values`,fc=`an object keyed by a harness id (${ps} or a plugin's), with a non-empty thinking token or null per entry`,mc="an object keyed by an agent type, with a non-empty thinking token or null per entry",yc="non-empty string or null",hc=r(e=>typeof e=="string"||e===null,"isModelKeyOrNull"),Ec=r(e=>e===null||typeof e=="string"&&/\S/.test(e),"isThinkingTokenOrNull"),bc={default:Ht,defaultAgentType:Ke,defaultOrchestrator:Ke,systemPromptMode:lc,includeContextFiles:me,defaultThinking:cc,loadSkillsImplicitly:me,loadExtensionsImplicitly:me,disableDefaultAgents:me,extensionEnabled:me,showActiveIndicator:me,grazingEnabled:me,worktreeRoot:Ke,worktreeMaterialization:uc,worktreeCheckoutType:pc,handoverMaxExcludedRatio:dc,harnessType:Ke};function xc(e){return Array.isArray(e)?"array":e===null?"null":typeof e=="object"?"object":typeof e}r(xc,"describeValue");function Be(e,n,t,o,s){return`[subagents] Incompatible value in ${e}: "${n}" is ${xc(t)}, expected ${o}. ${s}`}r(Be,"incompatibleWarning");function S(e,n,t,o,s=ac){console.warn(Be(e,n,t,o,s))}r(S,"warnIncompatible");var se="object";function Lt(e,n){let t={};if(!y(e))return S(n,"(config)",e,se),t;if(e.agent!==void 0)if(!y(e.agent))S(n,"agent",e.agent,se);else{let o=Sc(e.agent,n);Object.keys(o).length>0&&(t.agent=o)}if(e.concurrency!==void 0){let o=Rc(e.concurrency,n);Object.keys(o).length>0&&(t.concurrency=o)}if(e.harness!==void 0){let o=wc(e.harness,n);o!==void 0&&(t.harness=o)}if(e.multiplexer!==void 0){let o=us.safeParse(e.multiplexer);o.success?t.multiplexer=o.data:S(n,"multiplexer",e.multiplexer,Ke.expected)}return t}r(Lt,"validateRawLayer");function wc(e,n){if(!y(e)){console.warn(Be(n,"harness",e,se,Ue));return}let t={};for(let[o,s]of Object.entries(e))if(s!==void 0){if(!y(s)){console.warn(Be(n,`harness.${o}`,s,se,Ue));continue}t[o]=vc(s,o,n)}return Object.keys(t).length>0?t:void 0}r(wc,"cleanHarnessSections");function vc(e,n,t){if(e.env===void 0)return e;let o=Ac(e.env,n,t),s={...e};return delete s.env,o===void 0?s:{...s,env:o}}r(vc,"cleanHarnessSlice");var kc={name:"a valid environment variable name",reserved:"a variable that is not reserved","not-string":"string",control:"a value without control characters"};function Ac(e,n,t){if(!y(e)){S(t,`harness.${n}.env`,e,se);return}let o=ls(e,{reserved:[],report:r((s,i,a)=>{let d=i==="name"||i==="reserved";S(t,`harness.${n}.env.${s}`,d?s:a,kc[i])},"report")});return Object.keys(o).length>0?o:void 0}r(Ac,"cleanHarnessEnv");function Sc(e,n){let t={};for(let[o,s]of Object.entries(e)){if(s===void 0)continue;if(o===We){let d=cs(s,n,{keyPath:`agent.${o}`,expected:gc,valueExpected:Ht.expected,accepts:hc});d!==void 0&&(t[o]=d);continue}if(o===fe||o===Ie){let d=cs(s,n,{keyPath:`agent.${o}`,expected:o===fe?fc:mc,valueExpected:yc,accepts:Ec});d!==void 0&&(t[o]=d);continue}let i=bc[o]??Ht,a=i.schema.safeParse(s);a.success?t[o]=a.data:S(n,`agent.${o}`,s,i.expected,i.fix)}return t}r(Sc,"cleanAgentEntries");function cs(e,n,{keyPath:t,expected:o,valueExpected:s,accepts:i}){if(!y(e)){S(n,t,e,o);return}let a={};for(let[d,u]of Object.entries(e))if(u!==void 0){if(!/\S/.test(d)){S(n,`${t}.${d}`,d,"non-empty key");continue}i(u)?a[d]=u:S(n,`${t}.${d}`,u,s)}return Object.keys(a).length>0?a:void 0}r(cs,"cleanEntryMap");function Rc(e,n){let t={};if(!y(e))return S(n,"concurrency",e,se),t;e.default!==void 0&&(Ln(e.default)?t.default=e.default:S(n,"concurrency.default",e.default,Te));let o=e.harnesses;if(o!==void 0)if(!y(o))S(n,"concurrency.harnesses",o,se);else{let i={};for(let[a,d]of Object.entries(o)){if(!/\S/.test(a)){S(n,`concurrency.harnesses.${a}`,a,"non-empty harness id");continue}Ln(d)?i[a]=d:S(n,`concurrency.harnesses.${a}`,d,Te)}Object.keys(i).length>0&&(t.harnesses=i)}let s={providers:{level:"provider",expected:'a provider key "provider" or "<harness>:<provider>"'},models:{level:"model",expected:'a model key "provider/model" or "<harness>:<provider>/<model>"'}};for(let i of["providers","models"]){let a=e[i];if(a===void 0)continue;if(!y(a)){S(n,`concurrency.${i}`,a,se);continue}let{level:d,expected:u}=s[i],l={};for(let[c,f]of Object.entries(a)){if(ge(c)?.kind!==d){S(n,`concurrency.${i}.${c}`,c,u);continue}Ln(f)?l[c]=f:S(n,`concurrency.${i}.${c}`,f,Te)}Object.keys(l).length>0&&(t[i]=l)}return t}r(Rc,"cleanConcurrencySection");var ms="config.json";function Ve(){return _e.join(Qe(),ms)}r(Ve,"configPath");function Wy(){return _e.join(Qe(),"prompt.md")}r(Wy,"customPromptPath");var Ic={default:4},Tc={default:null,defaultAgentType:_n,defaultOrchestrator:Cn,systemPromptMode:"replace",includeContextFiles:!0,disableDefaultAgents:!1,extensionEnabled:!0,showActiveIndicator:!0,grazingEnabled:!0,worktreeMaterialization:Me,worktreeCheckoutType:en,handoverMaxExcludedRatio:Mn,harnessType:X},Nt=new Set(["default","defaultThinking",We,fe,Ie]),_c=new Set([We,fe,Ie]);function Dt(e){return Nt.has(e)||!Hn.includes(e)}r(Dt,"isProjectAllowedAgentKey");function ze(e){let n=e?_e.join(e,zn,ms):null,t=e?"absent":"untrusted",o=null,s=!1;return{load:r(()=>{let i=Oc(),a=i.raw;if(s=i.malformed,n){let d=Pc(n);d===null?(o=null,t="absent"):d==="malformed"?(o=null,t="malformed"):(o=d.raw,t="loaded")}else o=null,t="untrusted";return{global:a,project:o,projectStatus:t}},"load"),isGlobalWritable:r(()=>!s,"isGlobalWritable"),paths:r(()=>({global:Ve(),project:n??void 0}),"paths"),saveGlobal:r(i=>{if(s){console.warn("[subagents] Refusing to write global config (malformed); change not saved");return}fs(Ve(),i)},"saveGlobal"),saveProject:r(i=>{if(!n||t==="malformed"||t==="untrusted"){console.warn(`[subagents] Refusing to write project config (${t}); change not saved`);return}fs(n,i)},"saveProject")}}r(ze,"createConfigIO");function ys(e,n){let t={...e.agent};if(n?.agent){for(let[o,s]of Object.entries(n.agent))if(Dt(o)){if(_c.has(o)&&y(t[o])&&y(s)){t[o]={...t[o],...s};continue}t[o]=s}}return{agent:t,concurrency:Cc(e.concurrency,n?.concurrency),multiplexer:e.multiplexer}}r(ys,"mergeLayers");function Cc(...e){let n={},t={},o={},s={};for(let i of e)i&&(i.default!==void 0&&(n.default=i.default),Object.assign(t,i.harnesses??{}),Object.assign(o,i.providers??{}),Object.assign(s,i.models??{}));return Object.keys(t).length>0&&(n.harnesses=t),Object.keys(o).length>0&&(n.providers=o),Object.keys(s).length>0&&(n.models=s),n}r(Cc,"mergeRawConcurrency");function jt(e){return{agent:{...Tc,...e.agent},concurrency:{...Ic,...e.concurrency},multiplexer:e.multiplexer??_t()}}r(jt,"mergeDefaults");function Oc(){let e;try{e=N.readFileSync(Ve(),"utf-8")}catch(t){return t?.code==="ENOENT"?{raw:{},malformed:!1}:gs(t)}let n;try{n=JSON.parse(e)}catch(t){return gs(t)}return{raw:Lt(n,Ve()),malformed:!1}}r(Oc,"readGlobalRaw");function gs(e){return console.warn(`[subagents] Ignoring malformed global config ${Ve()}: ${h(e)}`),{raw:{},malformed:!0}}r(gs,"warnMalformedGlobal");function Pc(e){if(!N.existsSync(e))return null;let n;try{n=N.readFileSync(e,"utf-8")}catch(t){return console.warn(`[subagents] Ignoring malformed project config ${e}: ${h(t)}`),"malformed"}return Mc(n,e)}r(Pc,"readProjectRaw");function Mc(e,n){let t;try{t=JSON.parse(e)}catch(s){return console.warn(`[subagents] Ignoring malformed project config ${n}: ${h(s)}`),"malformed"}if(!y(t))return console.warn(`[subagents] Ignoring malformed project config ${n}: not a JSON object`),"malformed";let o=t;return o.agent!==void 0&&!y(o.agent)?Nn(n,"agent"):o.concurrency!==void 0&&!y(o.concurrency)?Nn(n,"concurrency"):o.concurrency?.providers!==void 0&&!y(o.concurrency.providers)?Nn(n,"concurrency.providers"):o.concurrency?.models!==void 0&&!y(o.concurrency.models)?Nn(n,"concurrency.models"):{raw:Lt(o,n)}}r(Mc,"parseProjectContents");function Nn(e,n){return console.warn(`[subagents] Ignoring malformed project config ${e}: "${n}" is not a JSON object`),"malformed"}r(Nn,"malformedSection");function fs(e,n){let t=e+".tmp";try{N.mkdirSync(_e.dirname(e),{recursive:!0}),N.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),N.renameSync(t,e)}catch(o){console.error(`[subagents] Failed to save config: ${h(o)}`)}}r(fs,"writeJsonAtomic");var Hc=ze();function Lc(e){return e.project?{kind:"present",raw:e.project}:e.projectStatus==="untrusted"||e.projectStatus==="malformed"?{kind:"refused",status:e.projectStatus}:{kind:"creatable"}}r(Lc,"projectLayerFrom");function $t(e){return e.kind==="present"?e.raw:null}r($t,"projectRawOf");var Nc="[subagents] Refusing to write config before the first load; change not saved",Dn=class{static{r(this,"LayeredConfig")}io;files=null;constructor(n=Hc){this.io=n}get paths(){return this.io.paths()}get effective(){let n=this.files;return n===null?jt({}):jt(ys(n.globalRaw,$t(n.projectLayer)))}get global(){return this.files?.globalRaw??{}}get project(){let n=this.files;return n===null?null:$t(n.projectLayer)}get isProjectWritable(){let n=this.files;return n!==null&&n.projectLayer.kind!=="refused"}get isGlobalWritable(){return this.files!==null&&this.io.isGlobalWritable()}setProjectDir(n){this.io=ze(n)}reload(){let n=this.io.load();this.files={globalRaw:n.global,projectLayer:Lc(n)}}mutate(n,t){let o=this.loadedOrWarn();if(o===null)return!1;if(n==="global")return this.globalWritableOrWarn()?(t(o.globalRaw),this.io.saveGlobal(o.globalRaw),!0):!1;let s=Dc(o);return s===null?!1:(t(s),this.io.saveProject(s),!0)}clear(n,t,o){if((n==="session"||n==="all")&&o(),n==="session")return;let s=this.loadedOrWarn();if(s===null)return;(n==="global"||n==="all")&&this.globalWritableOrWarn()&&(t(s.globalRaw),this.io.saveGlobal(s.globalRaw));let i=$t(s.projectLayer);i&&(n==="project"||n==="all")&&(t(i),this.io.saveProject(i))}loadedOrWarn(){return this.files!==null?this.files:(console.warn(Nc),null)}globalWritableOrWarn(){return this.isGlobalWritable?!0:(console.warn("[subagents] Refusing to write global config (malformed); change not saved"),!1)}};function Dc(e){let n=e.projectLayer;if(n.kind==="present")return n.raw;if(n.kind==="refused")return console.warn(`[subagents] Project config target unavailable (${n.status}); change ignored`),null;let t={};return e.projectLayer={kind:"present",raw:t},t}r(Dc,"projectLayerToWrite");var jc=ze();function hs(e){let n=e?.agent;return n?Object.keys(n).some(t=>Dt(t)&&n[t]!==void 0):!1}r(hs,"agentLayerHasModelSettings");function jn(e,n){return e?.agent!=null&&e.agent[n]!==void 0}r(jn,"layerHasAgentKey");function Ye(e,n){return e!=null&&Object.hasOwn(e,n)}r(Ye,"layerCarriesEntry");function $c(e){let n=Yo.safeParse(e);if(!n.success)throw new RangeError(`Invalid pi thinking level ${JSON.stringify(e)}`);return n.data}r($c,"piThinkingLevel");function $n(e){return $(e)?"pi":e}r($n,"thinkingSlot");function Fc(e){return Object.values(e).some(n=>n!=null)}r(Fc,"sessionOverridesHasModelSettings");function Ft(e){return e.default!==void 0||e.harnesses!=null&&Object.keys(e.harnesses).length>0||e.providers!=null&&Object.keys(e.providers).length>0||e.models!=null&&Object.keys(e.models).length>0}r(Ft,"concurrencyLayerHasSettings");var Gc=new Set(Hn.filter(e=>!Nt.has(e)));function Je(e){return typeof e=="string"&&/\S/.test(e)?e:void 0}r(Je,"nonBlankString");function Fn(e){if(!Mt.safeParse(e).success)throw new RangeError(`Invalid concurrency limit ${JSON.stringify(e)}: expected ${Te}.`)}r(Fn,"assertConcurrencyLimit");function Gt(e){return e.defaultModelByHarness??{}}r(Gt,"rawHarnessDefaults");function Es(e){return e.defaultThinkingByHarness??{}}r(Es,"rawThinkingByHarness");function bs(e){return e.thinking??{}}r(bs,"rawThinkingByType");var Gn=class{static{r(this,"ConfigStore")}layers;sessionOverrides={default:null};sessionThinking={};sessionHarnessDefaults={};sessionThinkingDefaults={};sessionConcurrencyLayer={};manager;constructor(n=jc){this.layers=new Dn(n)}setProjectDir(n){this.layers.setProjectDir(n)}get isProjectWritable(){return this.layers.isProjectWritable}get agent(){let n=this.layers.effective.agent;return{defaultModel:n.default,defaultAgentType:n.defaultAgentType??_n,defaultOrchestrator:n.defaultOrchestrator??Cn,systemPromptMode:n.systemPromptMode??"replace",includeContextFiles:n.includeContextFiles??!0,defaultThinking:n.defaultThinking,loadSkillsImplicitly:n.loadSkillsImplicitly??!0,loadExtensionsImplicitly:n.loadExtensionsImplicitly??!0,disableDefaultAgents:n.disableDefaultAgents??!1,extensionEnabled:n.extensionEnabled??!0,showActiveIndicator:n.showActiveIndicator??!0,grazingEnabled:n.grazingEnabled===!0,worktreeRoot:n.worktreeRoot,worktreeMaterialization:n.worktreeMaterialization??Me,worktreeCheckoutType:n.worktreeCheckoutType??en,handoverMaxExcludedRatio:n.handoverMaxExcludedRatio??Mn,harnessType:n.harnessType??X}}get multiplexer(){return this.layers.effective.multiplexer}harnessConfigLayers(){return{global:this.layers.global.harness??{},project:this.layers.project?.harness??{}}}harnessEnv(n){let t=this.layers.global.harness?.[n]?.env;return y(t)?t:void 0}reportHarnessConfigIssue(n,t){let o=this.layers.paths,s=t.layer==="project"?o.project??o.global:o.global;console.warn(Be(s,`harness.${n}${t.keyPath===""?"":`.${t.keyPath}`}`,t.got,t.expected,Ue))}get concurrency(){let n=this.layers.effective.concurrency,t=this.sessionConcurrencyLayer;return{default:t.default??n.default,harnesses:{...n.harnesses,...t.harnesses},providers:{...n.providers,...t.providers},models:{...n.models,...t.models}}}get sessionDefaultModel(){return this.sessionOverrides.default??null}sessionModelOverride(n){return this.sessionOverrides[n]??null}defaultModelForHarness(n){return Je(this.sessionHarnessDefaults[n])??qo(this.layers.effective.agent,n)}sessionThinkingOverride(n){return this.sessionThinking[n]??null}defaultThinkingForHarness(n){return Je(this.sessionThinkingDefaults[$n(n)])??es(this.layers.effective.agent,n)}thinkingFor(n,t,o,s,i){return ns({subagentType:n,agentConfig:t,harnessFamily:s,config:this.layers.effective,harnessDefault:this.defaultThinkingForHarness(o),parentThinking:i,sessionThinking:this.sessionThinking})}configuredHarnessIds(){let n=new Set([this.agent.harnessType]);for(let o of Object.keys(Gt(this.layers.effective.agent)))n.add(o);for(let o of Object.keys(this.concurrency.harnesses))n.add(o);let t=this.harnessConfigLayers();for(let o of Object.keys(t.global))n.add(o);for(let o of Object.keys(t.project))n.add(o);for(let o of[...Object.keys(this.concurrency.providers),...Object.keys(this.concurrency.models)]){let s=ge(o);s!==void 0&&n.add(s.harness)}return[...n]}modelOverrideLevels(n){return{session:this.sessionModelOverride(n)!==null,global:jn(this.layers.global,n),project:jn(this.layers.project,n)}}harnessDefaultModelLevels(n){return{session:Je(this.sessionHarnessDefaults[n])!==void 0,global:Ye(this.layers.global.agent?.defaultModelByHarness,n),project:Ye(this.layers.project?.agent?.defaultModelByHarness,n)}}harnessDefaultThinkingLevels(n){return{session:Je(this.sessionThinkingDefaults[$n(n)])!==void 0,global:this.harnessThinkingAt(this.layers.global,n),project:this.harnessThinkingAt(this.layers.project,n)}}harnessThinkingAt(n,t){return $(t)?jn(n,"defaultThinking"):Ye(n?.agent?.defaultThinkingByHarness,t)}thinkingOverrideLevels(n){return{session:this.sessionThinking[n]!=null,global:Ye(this.layers.global.agent?.thinking,n),project:Ye(this.layers.project?.agent?.thinking,n)}}hasProjectModelKey(n){return jn(this.layers.project,n)}hasProjectThinkingKey(n){return Ge(this.layers.project?.agent?.thinking?.[n])}modelSettingsLevels(){return{session:Fc(this.sessionOverrides)||Object.keys(this.sessionHarnessDefaults).length>0||Object.values(this.sessionThinking).some(n=>n!=null)||Object.values(this.sessionThinkingDefaults).some(n=>Je(n)!==void 0),global:hs(this.layers.global),project:hs(this.layers.project)}}get projectConcurrency(){return{...this.layers.project?.concurrency}}get globalConcurrency(){return{...this.layers.global.concurrency}}get sessionConcurrency(){return{...this.sessionConcurrencyLayer}}concurrencySettingsLevels(){return{session:Ft(this.sessionConcurrencyLayer),global:Ft(this.layers.global.concurrency??{}),project:Ft(this.layers.project?.concurrency??{})}}agentConfigSnapshot(){return this.layers.effective.agent}modelFor(n,t,o,s,i){return Zo({subagentType:n,agentConfig:o,harnessFamily:i,config:this.layers.effective,harnessDefault:this.defaultModelForHarness(s),parentModelId:t,sessionOverrides:this.sessionOverrides})}mutate={agent:{setDefaultModel:r((n,t="global")=>{this.setAgentModelKey("default",n,t)},"setDefaultModel"),setModelOverride:r((n,t,o="global")=>{this.setAgentModelKey(n,t,o)},"setModelOverride"),clearModelOverride:r((n,t="global")=>{this.layers.clear(t,o=>{o.agent&&delete o.agent[n]},()=>{delete this.sessionOverrides[n]})},"clearModelOverride"),clearAllModelOverrides:r((n="global")=>{this.layers.clear(n,t=>this.clearAgentModelKeys(t),()=>{this.sessionOverrides={default:null},this.sessionThinking={},this.sessionHarnessDefaults={},this.sessionThinkingDefaults={}})},"clearAllModelOverrides"),setDefaultAgentType:r(n=>this.setAgentLayerEntry("defaultAgentType",n,"global"),"setDefaultAgentType"),setDefaultOrchestrator:r(n=>this.setAgentLayerEntry("defaultOrchestrator",n,"global"),"setDefaultOrchestrator"),setSystemPromptMode:r(n=>this.setAgentLayerEntry("systemPromptMode",n,"global"),"setSystemPromptMode"),setIncludeContextFiles:r(n=>this.setAgentLayerEntry("includeContextFiles",n,"global"),"setIncludeContextFiles"),setDefaultThinking:r((n,t="global")=>{this.setAgentLayerEntry("defaultThinking",n,t)},"setDefaultThinking"),setLoadSkillsImplicitly:r(n=>this.setAgentLayerEntry("loadSkillsImplicitly",n,"global"),"setLoadSkillsImplicitly"),setLoadExtensionsImplicitly:r(n=>this.setAgentLayerEntry("loadExtensionsImplicitly",n,"global"),"setLoadExtensionsImplicitly"),setDisableDefaultAgents:r(n=>this.setAgentLayerEntry("disableDefaultAgents",n,"global"),"setDisableDefaultAgents"),setExtensionEnabled:r(n=>this.setAgentLayerEntry("extensionEnabled",n,"global"),"setExtensionEnabled"),setShowActiveIndicator:r(n=>this.setAgentLayerEntry("showActiveIndicator",n,"global"),"setShowActiveIndicator"),setGrazingEnabled:r(n=>this.setAgentLayerEntry("grazingEnabled",n,"global"),"setGrazingEnabled"),setWorktreeRoot:r(n=>this.setAgentLayerEntry("worktreeRoot",n,"global"),"setWorktreeRoot"),setWorktreeMaterialization:r(n=>this.setAgentLayerEntry("worktreeMaterialization",n,"global"),"setWorktreeMaterialization"),setWorktreeCheckoutType:r(n=>this.setAgentLayerEntry("worktreeCheckoutType",n,"global"),"setWorktreeCheckoutType"),setHarnessType:r(n=>this.setAgentLayerEntry("harnessType",n,"global"),"setHarnessType"),setHarnessDefaultModel:r((n,t,o="global")=>{if(o==="session"){this.sessionHarnessDefaults[n]=t;return}this.layers.mutate(o,s=>{s.agent??={},s.agent.defaultModelByHarness={...Gt(s.agent),[n]:t}})},"setHarnessDefaultModel"),clearHarnessDefaultModel:r((n,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;let s=Gt(o.agent);delete s[n],Object.keys(s).length===0?delete o.agent.defaultModelByHarness:o.agent.defaultModelByHarness=s},()=>{delete this.sessionHarnessDefaults[n]})},"clearHarnessDefaultModel"),setThinkingOverride:r((n,t,o="global")=>{if(o==="session"){this.sessionThinking[n]=t;return}this.layers.mutate(o,s=>{s.agent??={},s.agent.thinking={...bs(s.agent),[n]:t}})},"setThinkingOverride"),clearThinkingOverride:r((n,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;let s=bs(o.agent);delete s[n],Object.keys(s).length===0?delete o.agent.thinking:o.agent.thinking=s},()=>{delete this.sessionThinking[n]})},"clearThinkingOverride"),setHarnessDefaultThinking:r((n,t,o="global")=>{if(o==="session"){this.sessionThinkingDefaults[$n(n)]=t;return}if($(n)){let s=t===null?void 0:$c(t);this.setAgentLayerEntry("defaultThinking",s,o);return}this.layers.mutate(o,s=>{s.agent??={},s.agent.defaultThinkingByHarness={...Es(s.agent),[n]:t}})},"setHarnessDefaultThinking"),clearHarnessDefaultThinking:r((n,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;if($(n)){delete o.agent.defaultThinking;return}let s=Es(o.agent);delete s[n],Object.keys(s).length===0?delete o.agent.defaultThinkingByHarness:o.agent.defaultThinkingByHarness=s},()=>{delete this.sessionThinkingDefaults[$n(n)]})},"clearHarnessDefaultThinking")},concurrency:{setDefault:r((n,t="global")=>{Fn(n),this.applyConcurrencyWrite(t,o=>{o.default=n})},"setDefault"),setHarness:r((n,t,o="global")=>{Fn(t),this.applyConcurrencyWrite(o,s=>{s.harnesses={...s.harnesses,[n]:t}})},"setHarness"),setProvider:r((n,t,o="global")=>{Fn(t),this.applyConcurrencyWrite(o,s=>{s.providers={...s.providers,[n]:t}})},"setProvider"),setModel:r((n,t,o="global")=>{Fn(t),this.applyConcurrencyWrite(o,s=>{s.models={...s.models,[n]:t}})},"setModel"),removeHarness:r((n,t="global")=>{this.removeConcurrencyEntry("harnesses",n,t)},"removeHarness"),removeProvider:r((n,t="global")=>{this.removeConcurrencyEntry("providers",n,t)},"removeProvider"),removeDefault:r((n="global")=>{this.removeConcurrencyEntry("default",void 0,n)},"removeDefault"),removeModel:r((n,t="global")=>{this.removeConcurrencyEntry("models",n,t)},"removeModel"),clearAll:r((n="global")=>{this.layers.clear(n,t=>{delete t.concurrency},()=>{this.sessionConcurrencyLayer={}}),this.applyConcurrency()},"clearAll")},session:{setOverride:r((n,t)=>{this.sessionOverrides[n]=t},"setOverride"),clearOverride:r(n=>{delete this.sessionOverrides[n]},"clearOverride"),clearAll:r(()=>{this.sessionOverrides={default:null}},"clearAll")}};reload(){this.layers.reload(),this.sessionOverrides={default:null},this.sessionThinking={},this.sessionHarnessDefaults={},this.sessionThinkingDefaults={},this.sessionConcurrencyLayer={},this.applyConcurrency()}setDeps(n){n.manager!==void 0&&(this.manager=n.manager),this.applyConcurrency()}dispose(){this.manager=void 0}setAgentLayerEntry(n,t,o){this.layers.mutate(o,s=>{s.agent??={},t===void 0?delete s.agent[n]:s.agent[n]=t})}setAgentModelKey(n,t,o){if(o==="session"){this.sessionOverrides[n]=t;return}this.setAgentLayerEntry(n,t,o)}applyConcurrencyWrite(n,t){if(n==="session")t(this.sessionConcurrencyLayer);else if(!this.layers.mutate(n,o=>{o.concurrency??={},t(o.concurrency)}))return;this.applyConcurrency()}clearAgentModelKeys(n){if(n.agent)for(let t of Object.keys(n.agent))Gc.has(t)||delete n.agent[t]}removeConcurrencyEntry(n,t,o){let s=r(i=>{if(!i)return;if(n==="default"){delete i.default;return}if(t===void 0)return;if(n==="harnesses"){i.harnesses&&delete i.harnesses[t];return}let a=i[n];a&&delete a[t]},"removeFrom");this.layers.clear(o,i=>s(i.concurrency),()=>s(this.sessionConcurrencyLayer)),this.applyConcurrency()}applyConcurrency(){this.manager?.setConcurrency(this.concurrency)}};var xs={user:"",project:"",shared:""};function Kc(){return{agents:{agents:new Map,scanDirs:xs},orchestrators:{orchestrators:new Map,scanDirs:xs}}}r(Kc,"createSessionTemplates");var p={pi:null,sessionCtx:null,manager:null,store:new Gn,coordinator:null,runtime:null,agentSpawns:new On,repoLock:new nn,sessionTemplates:Kc(),indicatorMarker:null,harnesses:Et(),multiplexers:Ct(),cowAvailability:Jn(),cowAvailabilityClaim:0,harnessAvailability:Jn(),harnessModelCatalog:null,uiFlowClaim:0,uiFlows:new WeakMap};function Uc(){if(p.pi===null)throw new Error("pi instance read before the extension factory bound it");return p.pi}r(Uc,"getPiInstance");function Bc(){if(p.sessionCtx===null)throw new Error("session context read before session_start fired");return p.sessionCtx}r(Bc,"getSessionCtx");function Eh(){if(p.manager===null)throw new Error("agent manager read outside a live session");return p.manager}r(Eh,"getManager");function bh(){return p.manager}r(bh,"getManagerOrNull");function xh(){return p.store}r(xh,"getStore");function wh(){return p.indicatorMarker}r(wh,"getIndicatorMarker");function vh(e){p.indicatorMarker=e}r(vh,"setIndicatorMarker");function kh(){return p.agentSpawns}r(kh,"getAgentSpawns");function Ah(){return p.repoLock}r(Ah,"getRepoLock");function Sh(){if(p.coordinator===null)throw new Error("spawn coordinator read outside a live session");return p.coordinator}r(Sh,"getCoordinator");function Rh(){return p.coordinator}r(Rh,"getCoordinatorOrNull");function Ih(){return p.cowAvailability}r(Ih,"getCowAvailability");function Th(){return p.cowAvailabilityClaim+=1,p.cowAvailabilityClaim}r(Th,"beginCowAvailabilityProbe");function _h(e,n){return e!==p.cowAvailabilityClaim?!1:(p.cowAvailability=n,!0)}r(_h,"setCowAvailability");function Ch(){return p.harnesses}r(Ch,"getHarnessRegistry");function Vc(e){return{getAvailable:r(()=>e.getAvailable().map(n=>({provider:n.provider,id:n.id,thinkingLevels:Wc(n)})),"getAvailable")}}r(Vc,"piModelCatalog");function Oh(){let e=Et(),n=Ct();return p.harnesses=e,p.multiplexers=n,p.harnessModelCatalog=null,{harnesses:e,multiplexers:n}}r(Oh,"installSessionRegistries");function Ph(){return p.harnessAvailability}r(Ph,"getHarnessAvailability");function Mh(e){p.harnessAvailability=e}r(Mh,"setHarnessAvailability");function Hh(){return p.harnessModelCatalog}r(Hh,"getHarnessModelCatalogOrNull");function Lh(){return p.harnessModelCatalog??=wo({registry:p.harnesses,availability:p.harnessAvailability,request:{pi:Uc(),modelCatalog:Vc(Bc().modelRegistry)}}),p.harnessModelCatalog}r(Lh,"getHarnessModelCatalog");function Nh(e){p.harnessModelCatalog=e}r(Nh,"setHarnessModelCatalog");function Dh(){return ur(p.store.agent.worktreeMaterialization,p.cowAvailability)}r(Dh,"getWorktreeMaterialization");function jh(e){p.uiFlowClaim+=1,p.uiFlows.set(e,p.uiFlowClaim)}r(jh,"beginUiFlow");function $h(e){let n=p.uiFlows.get(e);return n===void 0||n===p.uiFlowClaim}r($h,"ownsUiFlow");function Fh(){return p.harnesses.resolve(p.store.agent.harnessType,p.harnessAvailability)}r(Fh,"getHarnessType");function Gh(){return p.runtime}r(Gh,"getRuntime");function Wh(){return p.sessionTemplates}r(Wh,"getSessionTemplates");function Kh(e){p.pi=e}r(Kh,"setPiInstance");function Uh(e){p.sessionCtx=e}r(Uh,"setSessionCtx");function Bh(e){p.manager=e}r(Bh,"setManager");function Vh(e){p.coordinator=e}r(Vh,"setCoordinator");function zh(e){p.runtime=e}r(zh,"setRuntime");function Yh(e){p.sessionTemplates=e}r(Yh,"setSessionTemplates");var zc=new RegExp(`${Yn}([A-Za-z0-9_-]+)`);function Jh(e=process.argv){for(let n of e){let t=zc.exec(n);if(t)return t[1]}}r(Jh,"detectSubagentSpawn");function Zh(e){let n=e.theme.fg("success","\u2713"),t=e.theme.fg("error","\u2717");return{pending:r(o=>e.notify(`${o} \u2026`,"info"),"pending"),succeeded:r((o,s="info")=>e.notify(`${n} ${o}`,s),"succeeded"),failed:r((o,s)=>e.notify(`${t} ${o}: ${h(s)}`,"error"),"failed"),outcome:r((o,s)=>o==="error"?e.notify(`${t} ${s}`,"error"):e.notify(`${n} ${s}`,o==="warning"?"warning":"info"),"outcome")}}r(Zh,"actionReport");export{Ss as a,M as b,sr as c,q as d,Qc as e,Zc as f,ir as g,eu as h,nu as i,tu as j,su as k,Jn as l,Pe as m,iu as n,Me as o,gu as p,fu as q,en as r,mu as s,yu as t,hu as u,Eu as v,Cs as w,bu as x,Ps as y,xu as z,wu as A,vu as B,ku as C,V as D,Tu as E,Z as F,H as G,Sf as H,wo as I,Hf as J,An as K,J as L,Yo as M,_n as N,Cn as O,Yl as P,Jl as Q,Xo as R,Gm as S,Wm as T,Km as U,Um as V,Bm as W,ql as X,Zm as Y,Ql as Z,sy as _,iy as $,ay as aa,dy as ba,ge as ca,ss as da,ls as ea,yy as fa,hy as ga,Wy as ha,Kc as ia,Uc as ja,Bc as ka,Eh as la,bh as ma,xh as na,wh as oa,vh as pa,kh as qa,Ah as ra,Sh as sa,Rh as ta,Ih as ua,Th as va,_h as wa,Ch as xa,Vc as ya,Oh as za,Ph as Aa,Mh as Ba,Hh as Ca,Lh as Da,Nh as Ea,Dh as Fa,jh as Ga,$h as Ha,Fh as Ia,Gh as Ja,Wh as Ka,Kh as La,Uh as Ma,Bh as Na,Vh as Oa,zh as Pa,Yh as Qa,Jh as Ra,Zh as Sa};
54
- //# sourceMappingURL=chunk-FCLYV3G3.js.map
54
+ //# sourceMappingURL=chunk-73OMG4YX.js.map
@@ -1,2 +1,2 @@
1
1
  var N=Object.defineProperty;var t=(e,n)=>N(e,"name",{value:n,configurable:!0});function z(e){return!e||e.length>128||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)}t(z,"isUnsafeName");function C(e){return e.replace(/[\r\n]+/g," ").trim()}t(C,"toSingleLine");function R(e){return new Promise(n=>setTimeout(n,e))}t(R,"sleep");function Z(e){return C(e instanceof Error?e.message:String(e))}t(Z,"errorMessage");function v(e){if(typeof e!="string")return null;let n=e.indexOf("/");return n<=0?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}t(v,"parseModelKey");function J(e,n,r){if(!e)return r;let o=v(e);return o?n.find(o.provider,o.modelId)??r:r}t(J,"findModelInRegistry");function Q(e){if(e)return"model"in e?e.model.id:"harness"in e?e.name:void 0}t(Q,"modelChoiceName");function ee(e){return e!=null&&"key"in e?e.key:void 0}t(ee,"modelChoiceKey");var ne=5e3;function re(e){throw new Error(`Unhandled variant: ${JSON.stringify(e)}`)}t(re,"assertNever");import{randomBytes as w}from"node:crypto";import{Buffer as p}from"buffer";var c="0123456789ABCDEFGHJKMNPQRSTVWXYZ",H="*~$=U",g=class extends Error{static{t(this,"InvalidChecksumCharacterError")}constructor(n){super(n),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},x=class extends Error{static{t(this,"InvalidChecksumError")}constructor(n){super(n),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},y=class{static{t(this,"CrockfordBase32")}static encode(n,r){p.isBuffer(n)?n=p.from(n):n=this.createBuffer(n);let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(n)}let s=[],a=0,i=0;for(let d of n)for(i=i<<8|d,a+=8;a>=5;)s.push(i>>>a-5&31),a-=5;a>0&&s.push(i<<5-a&31);let l=s.map(d=>c.charAt(d)).join("");return u&&(l+=this.computeChecksum(n)),l}static computeChecksum(n){let r=0;for(let o of n)r=(r*256+o)%37;return(c+H).charAt(r)}static decode(n,r){n=n.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(n,r)}let s=null;if(u){if(n.length===0)throw new g("Cannot validate checksum: input is empty");let d=n.charAt(n.length-1);if((c+H).indexOf(d)===-1)throw new g(`Invalid checksum character: ${d}`);s=d,n=n.slice(0,-1)}let a=[],i=0,l=0;for(let d of n){let f=c.indexOf(d);if(f===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);i+=5,i>=8?(i-=8,a.push(l|f>>i),l=f<<8-i&255):l|=f<<8-i}if((l>0||i>=5)&&a.push(l),s!==null){let d=this.computeChecksum(a);if(s!==d)throw new x(`Checksum mismatch: expected '${d}' but found '${s}'`)}return r?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(n){try{return this.decode(n,{checksum:!0}),!0}catch{return!1}}static encodeUlid(n){if(n.length===0)return"";let r=0n;for(let s of n)r=r<<8n|BigInt(s);let o=[];for(;r>0n;){let s=Number(r%32n);o.unshift(c.charAt(s)),r/=32n}let u=Math.ceil(n.length*8/5);return o.join("").padStart(u,"0")}static decodeUlid(n,r){if(n.length===0)return r?.asNumber===!0?0n:p.from([]);let o=0n;for(let i of n){let l=c.indexOf(i);if(l===-1)throw new Error(`Invalid base 32 character found in string: ${i}`);o=o*32n+BigInt(l)}let u=Math.floor(n.length*5/8),s=[],a=o;for(;a>0n;)s.unshift(Number(a&0xffn)),a>>=8n;for(o===0n&&s.push(0);s.length<u;)s.unshift(0);return r?.asNumber===!0?this.asNumber(s):this.asBuffer(s)}static createBuffer(n){if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new Error("Input must be a safe integer");n=BigInt(n)}if(n<0n)throw new Error("Input cannot be a negative number");let r=[];for(;n>0n;)r.unshift(Number(n&0xffn)),n>>=8n;return p.from(r)}static asNumber(n){let r=0n;return n.forEach(o=>{r<<=8n,r|=BigInt(o)}),r}static asBuffer(n){return p.from(n.map(r=>r.toString(16).padStart(2,"0")).join(""),"hex")}};var S="0123456789abcdefghjkmnpqrstvwxyz",I=8,T=5,b=32,E=class extends Error{static{t(this,"SpawnIdExhaustedError")}constructor(n){super(`Could not mint a unique spawn id after ${n} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function O(){return y.encode(w(T)).toLowerCase()}t(O,"generateSpawnId");function le(e,n=O){for(let r=0;r<b;r++){let o=n();if(!e(o))return o}throw new E(b)}t(le,"generateUniqueSpawnId");var D=`[${S}]{${I}}`,A=32,m=9,ge=String(m).length+1;function ye(e,n){if(!Number.isInteger(n)||n<1||n>m)throw new Error(`agent index must be an integer in 1..${m}, got ${String(n)}`);let r=`${e}-${n}`;if(r.length>A)throw new Error(`agent name "${r}" is ${r.length} characters, over herdr's ${A}-character limit`);return r}t(ye,"agentNameWithIndex");function me(e){let n=/^(.*)-(\d+)$/.exec(e);if(n===null)return{base:e,index:1};let r=Number(n[2]);return!Number.isSafeInteger(r)||r<1||r>m?{base:e,index:1}:{base:n[1],index:r}}t(me,"parseAgentName");function he(e,n){return new RegExp(`^cow-${n}-${D}(-\\d+)?$`).test(e)}t(he,"isTaskAgentName");function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}t(L,"isRecord");function xe(e){if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}t(xe,"nonEmpty");var M=["pi","pig","pi-bolt","opencode","codex","claude"],be="pi",q=["pi","pig","pi-bolt"];function Se(e){return q.some(n=>n===e)}t(Se,"isPiFamilyHarness");function Ie(e){return M.find(n=>n===e)}t(Ie,"parseHarnessId");var F=["PATH","HOME","SHELL","PWD","OLDPWD","IFS","CDPATH","GLOBIGNORE","PS1","PS2","PS3","PS4","BASH_ENV","ENV","NODE_OPTIONS","LD_PRELOAD","LD_AUDIT"],B=["DYLD_","HERDR_","COWBOY_"],k=Object.freeze([]),$=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ae(e){return $.test(e)}t(Ae,"isEnvVarName");function Le(e){return new RegExp("\\p{Cc}","u").test(e)}t(Le,"hasControlCharacter");function V(e){return F.includes(e)||B.some(n=>e.startsWith(n))}t(V,"isUniversalReservedEnvVar");function Pe(e,n=k){return V(e)||n.includes(e)}t(Pe,"isReservedEnvVar");function ke(e){return e.reservedEnvVars?.()??k}t(ke,"reservedEnvVarsOf");var _e={pi:["PI_CODING_AGENT_DIR","PI_CODING_AGENT_SESSION_DIR","HERDR_AGENT"],opencode:["OPENCODE_CONFIG_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_CONTENT","OPENCODE_DISABLE_PROJECT_CONFIG","OPENCODE_DISABLE_AUTOUPDATE"],codex:["CODEX_HOME"],claude:["CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_DISABLE_CLAUDE_MDS","ANTHROPIC_API_KEY","COWBOY_API_KEY"]};function Ne(e,n){return{kind:"other",unmappedKind:typeof e=="string"&&e!==""?e:"unknown",content:n}}t(Ne,"otherRecord");function Ce(e){if(!L(e)||typeof e.content!="string")return h(e);let n=e.kind;if(typeof n!="string")return h(e);switch(n){case"user":case"assistant":case"thinking":case"tool-call":case"compaction":case"unparseable":return{kind:n,content:e.content};case"other":return typeof e.unmappedKind=="string"?{kind:n,unmappedKind:e.unmappedKind,content:e.content}:h(e);default:return h(e)}}t(Ce,"readHandoverRecord");function h(e){if(typeof e=="string")return{kind:"unparseable",content:e};try{return{kind:"unparseable",content:JSON.stringify(e)??String(e)}}catch{return{kind:"unparseable",content:String(e)}}}t(h,"unreadableRecord");var P=class extends Error{static{t(this,"SessionExportError")}fault;constructor(n,r){super(r),this.name="SessionExportError",this.fault=n}};function ve(e){return e.kind==="unavailable"?[]:e.entries}t(ve,"modelListEntries");function we(e){return e.kind==="listed"?void 0:e.notice}t(we,"modelListNotice");function Te(e){return e.readHandoverRecords!==void 0}t(Te,"canReadHandoverRecords");function U(e){return`'${e.replaceAll("'","'\\''")}'`}t(U,"singleQuoteShellWord");function qe(e,n){return e===null?n:`( . ${U(e)} && { ${n}; } )`}t(qe,"launchEnvBody");var _=5,G=2e3,W=250;function j(e){let n=e.indexOf("_");return n===-1?e:`${e.slice(0,n+1)}""${e.slice(n+1)}`}t(j,"splitMarker");async function Fe(e,n,r){let o=`${r.commandName}() { : "${r.signature}"; ${r.body}; }`,u=`typeset -f ${r.commandName} 2>/dev/null | grep -q "${r.signature}" && echo ${j(r.readyMarker)}`;for(let s=1;s<=_;s++){if(await e.run(n,o),await e.run(n,u),await K(e,n,r.readyMarker,G)){r.proof!==void 0&&await Y(e,n,r.proof);return}s<_&&await R(W)}throw new Error(`failed to prepare pane ${n}: the ${r.commandName} launcher never landed`)}t(Fe,"installPaneLauncher");async function K(e,n,r,o){try{return await e.waitForOutput(n,r,o),!0}catch{return!1}}t(K,"panePrinted");async function Y(e,n,r){await e.run(n,r.command);try{await e.waitForOutput(n,r.output,r.timeoutMs)}catch{throw new Error(r.failure)}}t(Y,"requirePaneProof");export{t as a,S as b,I as c,O as d,le as e,A as f,m as g,ge as h,ye as i,me as j,he as k,L as l,xe as m,z as n,R as o,Z as p,v as q,J as r,Q as s,ee as t,ne as u,re as v,M as w,be as x,Se as y,Ie as z,Ae as A,Le as B,V as C,Pe as D,ke as E,_e as F,Ne as G,Ce as H,P as I,ve as J,we as K,Te as L,U as M,qe as N,j as O,Fe as P};
2
- //# sourceMappingURL=chunk-YEXMGUZI.js.map
2
+ //# sourceMappingURL=chunk-AOUEQXPY.js.map
@@ -1,2 +1,2 @@
1
- import{Ha as x}from"./chunk-FCLYV3G3.js";import{a as s,q as f,y as C}from"./chunk-YEXMGUZI.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-DD4TYA7R.js.map
1
+ import{Ha as x}from"./chunk-73OMG4YX.js";import{a as s,q as f,y as C}from"./chunk-AOUEQXPY.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-OR6LWM7F.js.map
@@ -1,4 +1,4 @@
1
- import{A as kt,B as bt,C as xt,D as V,J as Q,K as At,M as St,N as Tt,O as X,b as ut,c as pt,e as ht,g as gt,i as mt,k as xe,l as ft,p as yt,u as wt,v as z,w as vt}from"./chunk-ROQJTDCS.js";import{$ as it,A as Qe,Aa as lt,Ca as j,Ga as ct,J as me,Ja as be,L as nt,M as fe,P as ye,Q as rt,S as K,T,U as I,W as ot,_ as st,b as pe,c as je,ja as b,k as L,ka as G,l as We,la as v,m as Ue,n as he,na as w,oa as O,p as Fe,pa as we,qa as ve,sa as at,u as Ke,v as Ge,va as ke,wa as Y,x as Ye,xa as _,y as ze,ya as dt,z as Ve}from"./chunk-FCLYV3G3.js";import{J as et,K as tt,a as r,l as qe,p as $,r as ge,s as Xe,v as Ze,w as F,y as Je}from"./chunk-YEXMGUZI.js";import{visibleWidth as Re}from"@earendil-works/pi-tui";var Ae="\u{1F920}",It="\u{1F404}",mn="\u{1F4A9}",fn=2,yn=1e3,Z=Re(It),wn="76;175;80";function vn(e){return`\x1B[48;2;${wn}m${e}\x1B[49m`}r(vn,"greenBackground");function Ot(e){return e===0?0:Math.max(fn,Math.ceil(Math.sqrt(2*e)))}r(Ot,"pastureEdge");function _t(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(_t,"emptyPasture");function kn(e,t){let n=Ot(e.cows+e.droppings),o=_t(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(kn,"grazedPasture");function J(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(J,"cellsOf");function bn(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(bn,"neighboursOf");function Rt(e,t){return bn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Rt,"openNeighboursOf");function xn(e,t){let n=J(e,"cow").filter(d=>Rt(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Rt(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(xn,"moveHerd");function Et(e,t,n,o){for(let i=0;i<n;i+=1){let a=J(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(Et,"placeAtRandom");function An(e,t,n,o){let i=J(e,"cow"),a=J(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}Et(e,"cow",-s,o),Et(e,"dropping",-d,o)}r(An,"reconcileCounts");function Sn(e,t,n){if(e===null)return kn(t,n);let o=Ot(t.cows+t.droppings),i=_t(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 An(i,t.cows,t.droppings,n),i}r(Sn,"reconcilePasture");var Tn={anchor:"top-right",width:Re(Ae),get offsetX(){return O()?.cowboyOffsetX??0},nonCapturing:!0},Rn={anchor:"top-right",offsetY:1,get width(){return O()?.pastureWidth??0},nonCapturing:!0};function En(e){return e==="cow"?It:e==="dropping"?mn:" ".repeat(Z)}r(En,"cellText");function In(e,t){return e.map(n=>t(n.map(En).join("")))}r(In,"drawnRows");function On(){return ve().list(["spawned"]).length}r(On,"liveAgentCount");function _n(){return ve().list(rt).length}r(_n,"endedAgentCount");function Cn(){return{live:On(),ended:_n()}}r(Cn,"agentCounts");function Pn(){return w().agent.grazingEnabled}r(Pn,"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*Z}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*Z-(t*Z-this.cowboyWidth)}render(){return this.frame(),[Ae]}pastureRows(){return this.frame(),In(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(),yn))}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:xn(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:Sn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Te=class{static{r(this,"PastureView")}render(){return O()?.pastureRows()??[]}invalidate(){}};function Ct(e){Ee(),e.custom(t=>{let n=new Se(t,Cn,Pn,vn,Math.random);return we(n),n},{overlay:!0,overlayOptions:Tn,onHandle:r(t=>O()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Te,{overlay:!0,overlayOptions:Rn,onHandle:r(t=>O()?.attachPasture(t),"onHandle")})}r(Ct,"showExtensionIndicator");function Ee(){let e=O();we(null),e?.dispose()}r(Ee,"hideExtensionIndicator");function ee(){return w().agent.extensionEnabled}r(ee,"isExtensionEnabled");function Mn(){return ee()&&w().agent.showActiveIndicator}r(Mn,"isActiveIndicatorShown");function te(e){Mn()?Ct(e):Ee()}r(te,"syncExtensionIndicator");function po(e,t){w().mutate.agent.setShowActiveIndicator(t),te(e)}r(po,"setShowActiveIndicator");import{Type as E}from"typebox";import{Text as Fr}from"@earendil-works/pi-tui";import{Type as p}from"typebox";var $n="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",Nn=`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.`,Hn=`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.`,Dn=`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.`,Bn='Optional worktree for THIS agent. Omit it, or pass null, for "new": an isolated cow-<task>-<id> worktree, the default. Pass "inherit" to run in the parent session cwd with no worktree of its own, or {"path":"/absolute/checkout"} to run inside an existing worktree of this repository; that checkout is never removed by cleanup. Never pick a target the user did not ask for \u2014 omit the parameter to keep the default.',Ie=p.Union([p.Literal("new"),p.Literal("inherit"),p.Object({path:p.String({description:"Absolute path of an existing git worktree of this repository."})},{additionalProperties:!1}),p.Null()],{description:Bn}),Ln=p.Object({prompt:p.String({description:$n}),task_name:p.String({description:Nn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:Hn})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:Dn})),worktree:p.Optional(Ie)},{additionalProperties:!1,required:["prompt","task_name"]}),N=p.Object({agents:p.Array(Ln,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Oe=Object.values(m),k={type:"json_schema",strict:"prefer"};var _e="_configuredModel",Ce="_configuredThinking";function H(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(H,"readModelKey");function ne(e){return H(e.thinking)??H(e[Ce])}r(ne,"readThinkingRequest");function re(e){let t=H(e.model);if(t)return{source:"call",key:t};let n=H(e[_e]);if(n)return{source:"configured",key:n}}r(re,"readModelRequest");function W(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(W,"withoutModel");function oe(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(oe,"modelChoiceFor");function U(e){return`${e.provider}/${e.id}`}r(U,"modelKey");function jn(e,t){if(t!==void 0&&!fe.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${fe.options.join(", ")}); launching "${U(e)}" with "${t}".`}r(jn,"undeclaredLevelWarning");function Pt(e,t){let n=jn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Pt,"resolvedModel");function Wn(e){return`No API key found for "${e}"`}r(Wn,"missingCredential");function Mt(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:Wn(t.provider)}}r(Mt,"probeCredentials");function Pe(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Pe,"refusal");function Me(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return W(i);let d=Mt(n,o);if(d.verdict!=="unusable")return Pt(o,i);throw new Error(Pe(`The parent session's model "${U(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?ge(e.key,n,void 0):ge(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 W(i)}let s=Mt(n,a);if(s.verdict!=="unusable")return Pt(a,i);throw e.source==="call"?new Error(Pe(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Pe(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(Me,"resolvePiModel");async function Un(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Un,"harnessModels");function qn(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(qn,"undeclaredLevelWarning");async function $t(e,t){if(!e)return W(t.thinking);let n=await Un(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=qn(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($t,"resolveForeignModel");async function se(e,t){let{harness:n}=t;if(Je(n))return Me(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return $t(e,o)}r(se,"resolveSpawnModel");function D(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(D,"resultWithSeverity");function ie(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(ie,"foldSeverity");var $e=`
1
+ import{A as kt,B as bt,C as xt,D as V,J as Q,K as At,M as St,N as Tt,O as X,b as ut,c as pt,e as ht,g as gt,i as mt,k as xe,l as ft,p as yt,u as wt,v as z,w as vt}from"./chunk-Y5BC336I.js";import{$ as it,A as Qe,Aa as lt,Ca as j,Ga as ct,J as me,Ja as be,L as nt,M as fe,P as ye,Q as rt,S as K,T,U as I,W as ot,_ as st,b as pe,c as je,ja as b,k as L,ka as G,l as We,la as v,m as Ue,n as he,na as w,oa as O,p as Fe,pa as we,qa as ve,sa as at,u as Ke,v as Ge,va as ke,wa as Y,x as Ye,xa as _,y as ze,ya as dt,z as Ve}from"./chunk-73OMG4YX.js";import{J as et,K as tt,a as r,l as qe,p as $,r as ge,s as Xe,v as Ze,w as F,y as Je}from"./chunk-AOUEQXPY.js";import{visibleWidth as Re}from"@earendil-works/pi-tui";var Ae="\u{1F920}",It="\u{1F404}",mn="\u{1F4A9}",fn=2,yn=1e3,Z=Re(It),wn="76;175;80";function vn(e){return`\x1B[48;2;${wn}m${e}\x1B[49m`}r(vn,"greenBackground");function Ot(e){return e===0?0:Math.max(fn,Math.ceil(Math.sqrt(2*e)))}r(Ot,"pastureEdge");function _t(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(_t,"emptyPasture");function kn(e,t){let n=Ot(e.cows+e.droppings),o=_t(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(kn,"grazedPasture");function J(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(J,"cellsOf");function bn(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(bn,"neighboursOf");function Rt(e,t){return bn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Rt,"openNeighboursOf");function xn(e,t){let n=J(e,"cow").filter(d=>Rt(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Rt(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(xn,"moveHerd");function Et(e,t,n,o){for(let i=0;i<n;i+=1){let a=J(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(Et,"placeAtRandom");function An(e,t,n,o){let i=J(e,"cow"),a=J(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}Et(e,"cow",-s,o),Et(e,"dropping",-d,o)}r(An,"reconcileCounts");function Sn(e,t,n){if(e===null)return kn(t,n);let o=Ot(t.cows+t.droppings),i=_t(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 An(i,t.cows,t.droppings,n),i}r(Sn,"reconcilePasture");var Tn={anchor:"top-right",width:Re(Ae),get offsetX(){return O()?.cowboyOffsetX??0},nonCapturing:!0},Rn={anchor:"top-right",offsetY:1,get width(){return O()?.pastureWidth??0},nonCapturing:!0};function En(e){return e==="cow"?It:e==="dropping"?mn:" ".repeat(Z)}r(En,"cellText");function In(e,t){return e.map(n=>t(n.map(En).join("")))}r(In,"drawnRows");function On(){return ve().list(["spawned"]).length}r(On,"liveAgentCount");function _n(){return ve().list(rt).length}r(_n,"endedAgentCount");function Cn(){return{live:On(),ended:_n()}}r(Cn,"agentCounts");function Pn(){return w().agent.grazingEnabled}r(Pn,"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*Z}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*Z-(t*Z-this.cowboyWidth)}render(){return this.frame(),[Ae]}pastureRows(){return this.frame(),In(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(),yn))}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:xn(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:Sn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Te=class{static{r(this,"PastureView")}render(){return O()?.pastureRows()??[]}invalidate(){}};function Ct(e){Ee(),e.custom(t=>{let n=new Se(t,Cn,Pn,vn,Math.random);return we(n),n},{overlay:!0,overlayOptions:Tn,onHandle:r(t=>O()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Te,{overlay:!0,overlayOptions:Rn,onHandle:r(t=>O()?.attachPasture(t),"onHandle")})}r(Ct,"showExtensionIndicator");function Ee(){let e=O();we(null),e?.dispose()}r(Ee,"hideExtensionIndicator");function ee(){return w().agent.extensionEnabled}r(ee,"isExtensionEnabled");function Mn(){return ee()&&w().agent.showActiveIndicator}r(Mn,"isActiveIndicatorShown");function te(e){Mn()?Ct(e):Ee()}r(te,"syncExtensionIndicator");function po(e,t){w().mutate.agent.setShowActiveIndicator(t),te(e)}r(po,"setShowActiveIndicator");import{Type as E}from"typebox";import{Text as Fr}from"@earendil-works/pi-tui";import{Type as p}from"typebox";var $n="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",Nn=`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.`,Hn=`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.`,Dn=`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.`,Bn='Optional worktree for THIS agent. Omit it, or pass null, for "new": an isolated cow-<task>-<id> worktree, the default. Pass "inherit" to run in the parent session cwd with no worktree of its own, or {"path":"/absolute/checkout"} to run inside an existing worktree of this repository; that checkout is never removed by cleanup. Never pick a target the user did not ask for \u2014 omit the parameter to keep the default.',Ie=p.Union([p.Literal("new"),p.Literal("inherit"),p.Object({path:p.String({description:"Absolute path of an existing git worktree of this repository."})},{additionalProperties:!1}),p.Null()],{description:Bn}),Ln=p.Object({prompt:p.String({description:$n}),task_name:p.String({description:Nn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:Hn})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:Dn})),worktree:p.Optional(Ie)},{additionalProperties:!1,required:["prompt","task_name"]}),N=p.Object({agents:p.Array(Ln,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Oe=Object.values(m),k={type:"json_schema",strict:"prefer"};var _e="_configuredModel",Ce="_configuredThinking";function H(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(H,"readModelKey");function ne(e){return H(e.thinking)??H(e[Ce])}r(ne,"readThinkingRequest");function re(e){let t=H(e.model);if(t)return{source:"call",key:t};let n=H(e[_e]);if(n)return{source:"configured",key:n}}r(re,"readModelRequest");function W(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(W,"withoutModel");function oe(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(oe,"modelChoiceFor");function U(e){return`${e.provider}/${e.id}`}r(U,"modelKey");function jn(e,t){if(t!==void 0&&!fe.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${fe.options.join(", ")}); launching "${U(e)}" with "${t}".`}r(jn,"undeclaredLevelWarning");function Pt(e,t){let n=jn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Pt,"resolvedModel");function Wn(e){return`No API key found for "${e}"`}r(Wn,"missingCredential");function Mt(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:Wn(t.provider)}}r(Mt,"probeCredentials");function Pe(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Pe,"refusal");function Me(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return W(i);let d=Mt(n,o);if(d.verdict!=="unusable")return Pt(o,i);throw new Error(Pe(`The parent session's model "${U(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?ge(e.key,n,void 0):ge(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 W(i)}let s=Mt(n,a);if(s.verdict!=="unusable")return Pt(a,i);throw e.source==="call"?new Error(Pe(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Pe(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(Me,"resolvePiModel");async function Un(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Un,"harnessModels");function qn(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(qn,"undeclaredLevelWarning");async function $t(e,t){if(!e)return W(t.thinking);let n=await Un(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=qn(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($t,"resolveForeignModel");async function se(e,t){let{harness:n}=t;if(Je(n))return Me(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return $t(e,o)}r(se,"resolveSpawnModel");function D(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(D,"resultWithSeverity");function ie(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(ie,"foldSeverity");var $e=`
2
2
 
3
3
  ---
4
4
 
@@ -10,5 +10,5 @@ ${Zn(u)}`,details:S}}let h=c;if(u.lifecycle.phase==="queued"){let S=v().listAgen
10
10
  `).map(n=>n.trim()).filter(n=>n!==""):[]}r(Rr,"parseConflictFiles");function Er(e,t){return e.includes(`branch "${t}" does not exist`)}r(Er,"isUnknownBranchError");async function Ir(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=G().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 xr(b(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:Ar,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,f)=>{let g=l.trim(),u=`not attempted \u2014 the merge of "${f.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:f,cwd:g}=await c(),u=l.trim();try{let h=await ft(b(),{cwd:g,branch:u,target:a}),y=kr(h.mainRoot,f)?void 0:br(h.mainRoot,f);if(y!==void 0)try{i.ui.notify(y,"warning")}catch{}let A=y!==void 0?`${y}
11
11
  `:"";return h.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${A}"${u}" is already merged into "${h.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:h.target,output:h.output},text:`${A}Merged "${u}" into "${h.target}" in ${h.mainRoot}.`+(h.output?`
12
12
  ${h.output}`:"")}}catch(h){let y=h instanceof Error?h.message:String(h);return Tr(y)?{outcome:{kind:"conflict",branch:u,target:a,files:Rr(y)},text:`"${u}": ${y}`}:Er(y,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${y}`}:{outcome:{kind:"failed",branch:u,error:y},text:`"${u}": ${y}`}}},"handleItem")})}r(Ir,"executeMergeBranchTool");import{Type as de}from"typebox";var Or="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.",_r="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.",Zt=de.Object({agent_ids:de.Array(de.String({minLength:1}),{minItems:1,description:Or}),message:de.String({description:_r})},{additionalProperties:!1,required:["agent_ids","message"]});var Jt={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:Zt,execute:Pr,constrainedSampling:k};function Cr(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(Cr,"steerSeverity");async function Pr(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:Cr,prepare:r(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:r(async s=>{let d=v().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 v().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 f=c!=="spawned"&&d.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:s},text:f?`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(Pr,"executeSteerAgentTool");function ui(e,t,n){return he(e.ids(),t).filter(o=>o!==n)}r(ui,"handoverTargets");function en(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 ${he(t.ids(),n).join(", ")}. Nothing was changed.`}}}r(en,"resolveHandoverTarget");import{Type as x}from"typebox";var Mr="REQUIRED. The id of the SETTLED agent to hand over, as printed by the cowboy_agent spawn result or a completion message. A live agent is refused, never stopped \u2014 stop it with stop_cowboy_agent and hand it over once it has settled.",$r=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${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.`,Nr=`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.`,Hr="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",tn=x.Object({agent_id:x.String({minLength:1,description:Mr}),harness_type:x.String({description:$r}),model:x.Optional(x.Union([x.String(),x.Null()],{description:Nr})),thinking:x.Optional(x.Union([x.String(),x.Null()],{description:Hr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Dr(e,t){let n=en(e.harness_type,_(),lt());if(n.kind==="faulted")return{kind:"faulted",fault:n.fault};let o=n.harness;try{let i=await se(re(e),{harness:o,registry:t.modelRegistry,parent:t.model,thinking:ne(e),listModels:ae(t)});for(let a of i.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:o,modelChoice:oe(i.resolved)}}catch(i){return{kind:"faulted",fault:{kind:"request-refused",detail:$(i)}}}}r(Dr,"resolveIntent");function Br(e,t){return`Agent ${e} ${Lr(t)}`}r(Br,"renderHandoverOutcome");function Lr(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":st(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(Lr,"handoverReport");async function jr(e,t,n,o,i){let a=t.agent_id.trim(),s=await Dr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await v().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return D(it(d),Br(a,d),{agentId:a,outcome:d})}r(jr,"executeHandoverAgentTool");var nn={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:tn,execute:jr,constrainedSampling:k};import{Text as Wr}from"@earendil-works/pi-tui";var Ur={success:"\u2713",warning:"!",error:"\u2717"};function qr(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 Wr(`${n.fg(a,Ur[a])} ${s}`,0,0)}r(qr,"renderCowboyToolResult");function M(e){return{...e,renderResult:qr}}r(M,"withCowboyRenderer");var Kr=Oe;function Gr(e){return q?{...e,worktree:E.Optional(Ie)}:e}r(Gr,"offeredItemProperties");function Yr(e){let t=E.Object(Gr({prompt:N.properties.agents.items.properties.prompt,task_name:N.properties.agents.items.properties.task_name,agent_type:E.Optional(E.Union([E.String(),E.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:N.properties.agents.items.properties.model,harness_type:N.properties.agents.items.properties.harness_type}),{additionalProperties:!1,required:["prompt","task_name"]});return E.Object({agents:E.Array(t,{minItems:1}),run_in_background:N.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Yr,"cowboyAgentsSchemaWithTypes");var zr=q?"Delegate one or more tasks to agents. Each agent gets a fresh pi process and, by default, an isolated worktree \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. Always omit optional parameters the user did not explicitly ask for \u2014 `agent_type`, `model`, `harness_type`, and `worktree` each take this session's configured default when unset, so never guess or fill them in on the user's behalf. When an agent settles, the completion message names its branch when it has one and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.":"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.";function rn(e){let t=Yr(vt()),n={name:m.agent,label:m.agent,description:zr,parameters:t,execute:Lt,constrainedSampling:k};e.registerTool(M(n))}r(rn,"registerAgentTool");function Vr(e,t){w().mutate.agent.setExtensionEnabled(t),t?Qr(e):Xr(e)}r(Vr,"setExtensionEnabled");function Qr(e){let t=b();rn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Kr])]),te(e)}r(Qr,"activateExtension");function Xr(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!Oe.includes(n))),te(e)}r(Xr,"deactivateExtension");function Gi(e){rn(e),e.registerTool(M(jt)),e.registerTool(M(Xt)),e.registerTool(M(Jt)),e.registerTool(M(nn)),e.registerTool(M(Yt)),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 Fr(`${s} ${i}`,0,0)})}r(Gi,"registerTools");var on="cowboy",Zr={wt:"worktree",sp:"spawn",st:"status"};function Yi(e,t){e.registerCommand(on,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Yi,"registerUnavailableCowboyCommand");function zi(e){e.registerCommand(on,{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-H7RSOGDK.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{ct(n);let[o,...i]=t.trim().split(/\s+/),a=Zr[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(ee()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}Vr(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-S5BLHCYS.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!ee()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-H7RSOGDK.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-JXTLTNVP.js");await l(n,s,j()?.options??new Map);return}if(s!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-JXTLTNVP.js");await c(n,j()?.options??new Map)},"handler")})}r(zi,"registerCowboyCommand");import*as sn from"node:fs";import{tmpdir as Jr}from"node:os";import*as le from"node:path";async function an(e,t){try{return await ut(e).probe(t),L(Fe)}catch{return L(["checkout"])}}r(an,"detectCowAvailability");function dn(e){let t=le.resolve(e??je());for(;;){try{if(sn.statSync(t).isDirectory())return t}catch{}let n=le.dirname(t);if(n===t)return Jr();t=n}}r(dn,"probeTargetFor");function eo(e){return(t,n,o)=>e.exec(t,n,o)}r(eo,"execOf");function aa(e){return ln(e,ke())}r(aa,"startCowSupportProbe");function da(e){let t=ke();return Y(t,We()),ln(e,t)}r(da,"refreshCowSupportProbe");function ln(e,t){let n=dn(w().agent.worktreeRoot);return an(eo(e),n).then(o=>{Y(t,o)},()=>{Y(t,L(["checkout"]))})}r(ln,"probe");import cn from"node:fs";var to="/tmp";function no(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(no,"handoverNameField");function un(e){return`${[e.worktree,e.harness,e.sessionId].map(no).join("-")}.md`}r(un,"handoverFileName");function pn(e){return`${to}/${e}`}r(pn,"handoverFilePath");function ro(e){return cn.existsSync(e)}r(ro,"handoverFileExists");function pa(e,t){let n=ro(e);return cn.writeFileSync(e,t,"utf8"),{replaced:n}}r(pa,"writeHandoverFile");import*as hn from"node:path";function fa(e,t){return e===void 0?`main-${t}`:hn.basename(e.path)}r(fa,"exportWorktreeName");function ya(e){return{kind:"prepared",defaultPath:pn(un({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(ya,"handoverExportArtifact");function wa(e){switch(e.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return`is still ${e.status} \u2014 its session cannot be read while the run is in that state. Nothing was changed.`;case"harness-cannot-export-session":return`was not exported: harness "${e.harness}" cannot export its own session, so there is nothing to write.`;case"never-started":return"was not exported: it never started, so there is no session to export.";case"handover-in-progress":return`was not exported: ${e.detail}`;case"session-empty":return`was not exported: harness "${e.harness}" returned an empty session.`;case"session-export-failed":return`was not exported: harness "${e.harness}" could not export its session (${e.detail}).`}}r(wa,"handoverExportFaultReason");function va(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(va,"handoverExportSeverity");export{Ne as a,Xn as b,Zn as c,Rs as d,qt as e,Cs as f,Ps as g,ui as h,Br as i,Ee as j,ee as k,po as l,ro as m,pa as n,fa as o,ya as p,wa as q,va as r,aa as s,da as t,Vr as u,Qr as v,Xr as w,Gi as x,Yi as y,zi as z};
14
- //# sourceMappingURL=chunk-YUOPU3GW.js.map
13
+ `),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Wr(`${n.fg(a,Ur[a])} ${s}`,0,0)}r(qr,"renderCowboyToolResult");function M(e){return{...e,renderResult:qr}}r(M,"withCowboyRenderer");var Kr=Oe;function Gr(e){return q?{...e,worktree:E.Optional(Ie)}:e}r(Gr,"offeredItemProperties");function Yr(e){let t=E.Object(Gr({prompt:N.properties.agents.items.properties.prompt,task_name:N.properties.agents.items.properties.task_name,agent_type:E.Optional(E.Union([E.String(),E.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:N.properties.agents.items.properties.model,harness_type:N.properties.agents.items.properties.harness_type}),{additionalProperties:!1,required:["prompt","task_name"]});return E.Object({agents:E.Array(t,{minItems:1}),run_in_background:N.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Yr,"cowboyAgentsSchemaWithTypes");var zr=q?"Delegate one or more tasks to agents. Each agent gets a fresh pi process and, by default, an isolated worktree \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. Always omit optional parameters the user did not explicitly ask for \u2014 `agent_type`, `model`, `harness_type`, and `worktree` each take this session's configured default when unset, so never guess or fill them in on the user's behalf. When an agent settles, the completion message names its branch when it has one and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.":"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.";function rn(e){let t=Yr(vt()),n={name:m.agent,label:m.agent,description:zr,parameters:t,execute:Lt,constrainedSampling:k};e.registerTool(M(n))}r(rn,"registerAgentTool");function Vr(e,t){w().mutate.agent.setExtensionEnabled(t),t?Qr(e):Xr(e)}r(Vr,"setExtensionEnabled");function Qr(e){let t=b();rn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Kr])]),te(e)}r(Qr,"activateExtension");function Xr(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!Oe.includes(n))),te(e)}r(Xr,"deactivateExtension");function Gi(e){rn(e),e.registerTool(M(jt)),e.registerTool(M(Xt)),e.registerTool(M(Jt)),e.registerTool(M(nn)),e.registerTool(M(Yt)),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 Fr(`${s} ${i}`,0,0)})}r(Gi,"registerTools");var on="cowboy",Zr={wt:"worktree",sp:"spawn",st:"status"};function Yi(e,t){e.registerCommand(on,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Yi,"registerUnavailableCowboyCommand");function zi(e){e.registerCommand(on,{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-NKZSDUHE.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{ct(n);let[o,...i]=t.trim().split(/\s+/),a=Zr[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(ee()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}Vr(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-WLJTYJL2.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!ee()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-NKZSDUHE.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-FKHSUINJ.js");await l(n,s,j()?.options??new Map);return}if(s!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:c}=await import("./menus-FKHSUINJ.js");await c(n,j()?.options??new Map)},"handler")})}r(zi,"registerCowboyCommand");import*as sn from"node:fs";import{tmpdir as Jr}from"node:os";import*as le from"node:path";async function an(e,t){try{return await ut(e).probe(t),L(Fe)}catch{return L(["checkout"])}}r(an,"detectCowAvailability");function dn(e){let t=le.resolve(e??je());for(;;){try{if(sn.statSync(t).isDirectory())return t}catch{}let n=le.dirname(t);if(n===t)return Jr();t=n}}r(dn,"probeTargetFor");function eo(e){return(t,n,o)=>e.exec(t,n,o)}r(eo,"execOf");function aa(e){return ln(e,ke())}r(aa,"startCowSupportProbe");function da(e){let t=ke();return Y(t,We()),ln(e,t)}r(da,"refreshCowSupportProbe");function ln(e,t){let n=dn(w().agent.worktreeRoot);return an(eo(e),n).then(o=>{Y(t,o)},()=>{Y(t,L(["checkout"]))})}r(ln,"probe");import cn from"node:fs";var to="/tmp";function no(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(no,"handoverNameField");function un(e){return`${[e.worktree,e.harness,e.sessionId].map(no).join("-")}.md`}r(un,"handoverFileName");function pn(e){return`${to}/${e}`}r(pn,"handoverFilePath");function ro(e){return cn.existsSync(e)}r(ro,"handoverFileExists");function pa(e,t){let n=ro(e);return cn.writeFileSync(e,t,"utf8"),{replaced:n}}r(pa,"writeHandoverFile");import*as hn from"node:path";function fa(e,t){return e===void 0?`main-${t}`:hn.basename(e.path)}r(fa,"exportWorktreeName");function ya(e){return{kind:"prepared",defaultPath:pn(un({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(ya,"handoverExportArtifact");function wa(e){switch(e.kind){case"agent-unknown":return"not found \u2014 check the id from its spawn or completion result.";case"agent-not-settled":return`is still ${e.status} \u2014 its session cannot be read while the run is in that state. Nothing was changed.`;case"harness-cannot-export-session":return`was not exported: harness "${e.harness}" cannot export its own session, so there is nothing to write.`;case"never-started":return"was not exported: it never started, so there is no session to export.";case"handover-in-progress":return`was not exported: ${e.detail}`;case"session-empty":return`was not exported: harness "${e.harness}" returned an empty session.`;case"session-export-failed":return`was not exported: harness "${e.harness}" could not export its session (${e.detail}).`}}r(wa,"handoverExportFaultReason");function va(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(va,"handoverExportSeverity");export{Ne as a,Xn as b,Zn as c,Rs as d,qt as e,Cs as f,Ps as g,ui as h,Br as i,Ee as j,ee as k,po as l,ro as m,pa as n,fa as o,ya as p,wa as q,va as r,aa as s,da as t,Vr as u,Qr as v,Xr as w,Gi as x,Yi as y,zi as z};
14
+ //# sourceMappingURL=chunk-PU6CJR4Y.js.map
@@ -1,4 +1,4 @@
1
- import{A as et,Aa as Z,D as nt,E as Y,K as rt,Ka as J,M as ot,N as ke,O as F,T as it,b as pe,ea as at,fa as X,i as qe,j as Ke,m as fe,n as Qe,na as j,o as Ye,r as Q,ra as st,s as Xe,u as Ze,w as Je,xa as M,y as me}from"./chunk-FCLYV3G3.js";import{F as tt,a as i,p as W,u as ge,v as he}from"./chunk-YEXMGUZI.js";import*as x from"node:fs";import*as k from"node:path";var hn=`import ctypes, sys
1
+ import{A as et,Aa as Z,D as nt,E as Y,K as rt,Ka as J,M as ot,N as ke,O as F,T as it,b as pe,ea as at,fa as X,i as qe,j as Ke,m as fe,n as Qe,na as j,o as Ye,r as Q,ra as st,s as Xe,u as Ze,w as Je,xa as M,y as me}from"./chunk-73OMG4YX.js";import{F as tt,a as i,p as W,u as ge,v as he}from"./chunk-AOUEQXPY.js";import*as x from"node:fs";import*as k from"node:path";var hn=`import ctypes, sys
2
2
  libc = ctypes.CDLL(None, use_errno=True)
3
3
  # CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
4
4
  if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
@@ -23,4 +23,4 @@ Error: {{error}}{{/error}}{{#has_worktree}}
23
23
  `);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}i(Jn,"describeParseError");var er={label:"File",problem:"was skipped"};async function oe(e,t,n,r,o=er,a){try{await ne.promises.access(e)}catch{return[]}let c=(await ne.promises.readdir(e,{withFileTypes:!0})).filter(l=>l.isFile()&&l.name.endsWith(Xn)),d=[];for(let l of c){let u=_t.join(e,l.name),p;try{p=await ne.promises.readFile(u,"utf-8")}catch{continue}try{let m=t(p),v=a?.(m);if(v!==void 0)throw new Error(v);n(m)&&d.push(m)}catch(m){r?.(`[cowboy] ${o.label} file ${u} ${o.problem}: ${Jn(m)}`,"warning")}}return d}i(oe,"scanTemplateFilesInDir");import{z as P}from"zod";import $t from"mustache";function Wt(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}i(Wt,"worktreeVariables");function tr(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}i(tr,"outcomeVariables");function nr(e){return e?{...Wt(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}i(nr,"settledWorktreeVariables");function rr(e){return e.worktree?{agent_id:e.agentId,...Wt(e.worktree)}:{agent_id:e.agentId}}i(rr,"spawnCueContext");function jo(e){return{...rr(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}i(jo,"queuedCueContext");function Lo(e){let{outcome:t,statusNote:n,worktree:r,multiplexerId:o}=e;return{...tr(t),...n?{status_note:n}:{},...nr(r),...o!=null?{multiplexer_id:o}:{}}}i(Lo,"settledCueContext");var or={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},ir={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},ar={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},sr=Object.keys(or),cr=Object.keys(ir),dr=Object.keys(ar);function Ft(e){switch(e){case"spawned":return sr;case"queued":return cr;case"settled":return dr;default:return}}i(Ft,"cueVariables");var lr={ok:!0},ur="&",pr=new Set(["name",ur,"#","^"]);function Vo(e,t,n){return $t.render(e[t],n,void 0,{escape:i(r=>r==null?"":String(r),"escape")})}i(Vo,"renderCue");function fr(e){let t=e[4];return Array.isArray(t)?t:void 0}i(fr,"spanChildren");function It(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(pr.has(o)&&!t.includes(a))return`unknown variable "{{${a}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let s=fr(r);if(s){let c=It(s,t,n);if(c)return c}}}i(It,"findTemplateProblem");function Dt(e,t){let n=Ft(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let r;try{r=$t.parse(t)}catch(a){return{ok:!1,reason:`unparsable template: ${(a instanceof Error?a.message:String(a)).replace(/\s+/g," ").trim()}`}}let o=It(r,n,e);return o?{ok:!1,reason:o}:lr}i(Dt,"validateCueTemplate");var mr=["spawned","queued","settled"],gr=P.strictObject({spawned:P.string().optional(),queued:P.string().optional(),settled:P.string().optional()}).superRefine((e,t)=>{for(let n of mr){let r=e[n];if(r===void 0)continue;let o=Dt(n,r);o.ok||t.addIssue({code:"custom",message:o.reason,path:[n]})}}),Mt=P.strictObject({name:P.string().optional(),display_name:P.string().optional(),guidance:P.string().optional(),cues:gr.optional()});var hr={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function kr(e){return Mt.parse(re(e))}i(kr,"parseOrchestratorFile");async function z(e,t){return oe(e,kr,n=>n.name,t,hr)}i(z,"scanOrchestratorFilesInDir");function Pe(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,wr(o.get(c.name)??yr(c.name,a),c));return o}i(Pe,"mergeOrchestrators");function yr(e,t){return{...t,name:e,displayName:e}}i(yr,"namedBase");function wr(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(wr,"applyOverride");function G(){return J().orchestrators}i(G,"registry");function si(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);G().orchestrators=n}i(si,"registerOrchestrators");function ci(e,t,n){G().scanDirs={user:e,project:t,shared:n??""}}i(ci,"setOrchestratorScanDirs");async function di(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,r=G().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):z(Ke,n),z(r.user,n),z(r.shared,n),z(r.project,n)]),l=Pe(t?new Map:O,o,[],[]);return Pe(l,a,s,c)}i(di,"scanAndMergeOrchestrators");function Se(e){let{orchestrators:t}=G();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(Se,"resolveOrchestrator");function li(){return[...G().orchestrators.values()].map(e=>e.name)}i(li,"getAvailableOrchestrators");import{z as f}from"zod";var Nt=f.union([f.boolean(),f.array(f.string())]),br={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 ae(e){return f.record(f.string(),f.unknown()).transform((t,n)=>at(t,{reserved:tt[e],report:i((r,o)=>n.addIssue({code:"custom",path:[r],message:br[o]}),"report")}))}i(ae,"envTable");var Bt={model:f.string().optional(),thinking:ot.optional(),extensions:Nt.optional(),skills:Nt.optional(),inlined_skills:f.array(f.string()).optional(),fork:f.boolean().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("pi").optional()},Cr=f.strictObject(Bt),vr=f.strictObject({model:f.string().optional(),variant:f.string().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("opencode").optional()}),xr=f.strictObject({model:f.string().optional(),thinking:f.string().optional(),env:ae("codex").optional()}),Rr=f.strictObject({model:f.string().optional(),thinking:f.string().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("claude").optional()});function _e(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}i(_e,"toToolFilter");function ie(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}i(ie,"nonEmptyEnv");var Tr=f.strictObject({include_context_files:f.boolean().optional(),pi:Cr.optional(),opencode:vr.optional(),codex:xr.optional(),claude:Rr.optional(),...Bt}).transform(({pi:e,opencode:t,codex:n,claude:r,...o})=>{let{model:a,thinking:s,tools:c,exclude_tools:d,env:l,...u}=o,{model:p,thinking:m,tools:v,exclude_tools:D,env:ue,...K}=A(e??{}),{model:R,variant:tn,tools:nn,exclude_tools:rn,env:on,...an}=A(t??{}),{model:sn,thinking:cn,env:dn,...ln}=A(n??{}),{model:un,thinking:pn,tools:fn,exclude_tools:mn,env:gn}=A(r??{}),ze=A({pi:p??a,opencode:R,codex:sn,claude:un}),Ge=A({pi:_e(v??c,D??d),opencode:_e(nn,rn),claude:_e(fn,mn)}),Ue=A({pi:m??s,opencode:tn,codex:cn,claude:pn}),Ve=A({pi:ie(X(l,ue)),opencode:ie(on),codex:ie(dn),claude:ie(gn)});return{...u,...K,...an,...ln,...Object.keys(ze).length>0?{modelsByFamily:ze}:{},...Object.keys(Ge).length>0?{toolsByFamily:Ge}:{},...Object.keys(Ue).length>0?{thinkingByFamily:Ue}:{},...Object.keys(Ve).length>0?{envByFamily:Ve}:{}}}),jt=f.strictObject({name:f.string().optional(),display_name:f.string().optional(),description:f.string().optional(),hidden:f.boolean().optional(),worktree_checkout_type:f.enum(Xe).optional(),system_prompt:f.string().optional(),harness_type:f.string().min(1).optional(),harness:Tr.optional()});function Er(e){return jt.parse(re(e))}i(Er,"parseAgentFile");var Ar={label:"Agent",problem:"is not a valid agent template and was skipped"};async function B(e,t,n){return oe(e,Er,r=>r.name,t,Ar,n)}i(B,"scanAgentFilesInDir");function se(e,t,n,r){let o=new Map;for(let[a,s]of e)o.set(a,{...s});return We(o,t),We(o,n),We(o,r),o}i(se,"mergeAgents");function We(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=Lt(n),s=Or(r.modelsByFamily,a.modelsByFamily),c=Pr(r.toolsByFamily,a.toolsByFamily),d=Sr(r.thinkingByFamily,a.thinkingByFamily),l=_r(r.envByFamily,a.envByFamily);e.set(n.name,{...r,...a,...s?{modelsByFamily:s}:{},...c?{toolsByFamily:c}:{},...d?{thinkingByFamily:d}:{},...l?{envByFamily:l}:{},...o})}else e.set(n.name,{...Wr,...Lt(n)})}}i(We,"mergeAgentOverrides");function Or(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Or,"mergeModelsByFamily");function Pr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Pr,"mergeToolsByFamily");function Sr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Sr,"mergeThinkingByFamily");function _r(e,t){let n={...e};for(let[r,o]of Object.entries(t??{})){let a=r;n[a]=X(n[a],o)}return Object.keys(n).length>0?n:void 0}i(_r,"mergeEnvByFamily");function Lt(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(Lt,"fromTemplate");var Wr={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Fe=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return J().agents}i(S,"registry");function U(e){let t=e.harness_type;if(t===void 0)return;let n=M();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}i(U,"unregisteredHarness");function _i(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[r,o]of Fe)n.set(r,o);for(let[r,o]of e)n.set(r,o);S().agents=n}i(_i,"registerAgents");function Wi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}i(Wi,"setAgentScanDirs");async function Fr(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,r=S().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):B(qe,n,U),B(r.user,n,U),B(r.shared,n,U),B(r.project,n,U)]),l=se(t?new Map:Fe,o,[],[]);return se(l,a,s,c)}i(Fr,"scanAndMerge");async function $r(e,t){let n=await Fr(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 B(e,t?.notify,U),s=se(new Map,[],[],a);for(let[c,d]of s)r.has(c)||(r.set(c,d),o++)}return o}i($r,"discoverNewAgents");function V(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(V,"resolveType");async function Fi(e,t,n){let r=V(e);return r.kind==="not-found"&&(await $r(t,{notify:n}),r=V(e)),r}i(Fi,"resolveTypeOrDiscover");function ce(e){let t=V(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}i(ce,"getAgentConfig");function $i(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}i($i,"getAvailableTypes");function Ii(){return[...S().agents.keys()]}i(Ii,"getAllTypes");function Ht(e,t,n,r){return{skills:e??n,extensions:t??r}}i(Ht,"applyGlobalDefaults");function Di(e,t=!0,n=!0){let r=ce(e);if(r){let{skills:a,extensions:s,...c}=r,d=Ht(a,s,t,n);return{displayName:c.displayName??c.name,description:c.description,...d}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Ht(void 0,void 0,t,n)}}i(Di,"getConfig");function zt(e){return typeof e=="string"&&e!==""?e:void 0}i(zt,"configuredString");function Ir(){let e=zt(j().agent.defaultAgentType);if(e===void 0)return ke;let t=V(e);return t.kind==="resolved"?t.key:ke}i(Ir,"resolveDefaultAgentType");function Dr(){let e=zt(j().agent.defaultOrchestrator);return e===void 0?F:e===F||Se(e)?e:F}i(Dr,"resolveDefaultOrchestratorName");function Ui(e){return typeof e=="string"&&e!==""?e:Ir()}i(Ui,"resolveAgentTypeParam");function Vi(){let e=Dr();return Se(e)??(e===F?O[F]:void 0)??O[F]}i(Vi,"resolveDefaultOrchestrator");function Gt(e){return ce(e)?.worktreeCheckoutType??j().agent.worktreeCheckoutType}i(Gt,"resolveWorktreeCheckoutType");function Ut(e){return typeof e=="string"&&e.trim()!==""?e:void 0}i(Ut,"harnessParam");function qi(e){let t=Ut(e);if(t!==void 0&&M().get(t)!==void 0)return fe(t,Z())?t:void 0}i(qi,"requestedHarnessId");function Ki(e){let t=Ut(e);if(t===void 0)return;let n=M();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=Z();if(!fe(t,r))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${Qe(n.ids(),r).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}i(Ki,"resolveRequestedHarness");function Qi(e,t){if(t!==void 0)return t;let n=ce(e)?.harnessType??j().agent.harnessType;return M().resolve(n,Z())}i(Qi,"resolveHarnessType");function $e(e){return{kind:"recorded",phase:e.lifecycle.phase}}i($e,"recordedSettlement");function Vt(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(Vt,"planRecovered");async function Ie(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(Ie,"assessRemovability");function qt(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 he(e.state)}}i(qt,"recoveryGate");function De(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(De,"recoveryRefusalReason");function q(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(q,"keptReport");function Kt(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(Kt,"ambiguousReport");function Me(e){return e?.force!==void 0?{forced:e.force}:{}}i(Me,"forcedFields");function Qt(e,t,n,r,o,a){return{agentId:e,source:t,outcome:{kind:"torn-down",...Me(a)},branchName:n.kind==="worktree"?n.worktree.branchName:void 0,settlement:r,panes:o.panes,worktree:o.worktree,branch:o.branch}}i(Qt,"assembleReport");function Ji(e){return e.outcome.kind==="refused"&&e.outcome.forceable}i(Ji,"isForceableRefusal");function Ne(e){return e.worktree.kind==="removed"||e.worktree.kind==="absent"?!0:e.worktree.kind==="none"?e.panes.every(t=>t.kind==="closed"):!1}i(Ne,"shouldDropSpawn");function de(e){return e.workspaceId!==void 0?"multiplexer":"git"}i(de,"removalMechanismOf");function Yt(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 he(t.mechanism)}}i(Yt,"paneDispositionFor");var Mr=rt("cleanup");function Nr(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(Nr,"hostRefFor");async function Xt(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(Xt,"removeOwnedTree");async function le(e,t,n){let r=[];for(let o of t)switch(Yt(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(le,"paneOutcomes");async function Br(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(Br,"paneOutcomesForAbsentTree");async function jr(e,t,n){if(t.kind==="no-worktree")return{panes:await le(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 Xt(e,r,n);return a.kind==="removed"?{panes:await le(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 le(e,o,{kind:"retained"}),worktree:a,branch:{kind:"not-applicable"}}}i(jr,"removeResources");function Be(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 Ie(e.isWorktreeDirty,n,r);if(s.kind==="kept")return{kind:"kept",path:r.worktreePath,reason:s.reason};let c=await Xt(e,r,a);if(c.kind==="removal-failed")return c;let d=de(r);await le(e,o,{kind:"removed",mechanism:d,workspaceId:r.workspaceId});let l=await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd});return{kind:"removed",path:r.worktreePath,branchName:r.branchName,via:d,branch:l}}catch(s){return{kind:"removal-failed",path:r.worktreePath,detail:W(s)}}}}}i(Be,"createWorktreeTeardown");async function Lr(e,t,n){if(t.kind!=="worktree"||n===void 0||de(t.worktree)!=="multiplexer")return{kind:"exclusive"};try{let r=await e.otherTenants({workspaceId:n.workspaceId,checkoutPath:t.worktree.worktreePath},n.paneId);return r.length===0?{kind:"exclusive"}:{kind:"shared",tenants:r}}catch(r){return{kind:"unreadable",detail:W(r)}}}i(Lr,"spaceTenancy");function Hr(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(Hr,"environmentPanes");function zr(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(zr,"teardownRuns");function aa(e){let t=Be(e);function n(a,s){return{kind:"discovered",basis:s,deliverable:e.deliverable(a)}}i(n,"recovered");async function r(a,s,c,d){if(c!==void 0){let p=$e(c);return it(c.lifecycle)?{kind:"torn-down",settlement:p}:{kind:"refused",settlement:p,reason:{kind:"agent-active",phase:c.lifecycle.phase},forceable:!1}}if(d?.force!==void 0)return{kind:"torn-down",settlement:n(a,{kind:"forced"})};let l;if(s.pane!==null)try{l=await e.observe(s.pane)}catch(p){let m={kind:"pane-unreadable",detail:W(p)};return{kind:"refused",settlement:n(a,m),reason:De(m),forceable:!0}}let u=qt(l);return u.kind==="allow"?{kind:"torn-down",settlement:n(a,u.basis)}:{kind:"refused",settlement:n(a,u.basis),reason:De(u.basis),forceable:!0}}i(r,"verdictFor");async function o(a,s,c){let d=s.getSpawn(a),l=await e.locate(a,d);if(l.kind==="not-found")throw new Error(`Agent ${a} not found.`);if(l.kind==="ambiguous")return Kt(a,d===void 0?"recovered":"tracked",d===void 0?n(a,{kind:"artifacts-ambiguous"}):$e(d),l.candidates.map(R=>R.worktreePath));let u=Nr(l,e.multiplexer),p=Vt(l,Hr(u,d)),m=await r(a,l,d,c);if(m.kind==="refused")return q(a,l.source,p,m.settlement,{reason:m.reason,forceable:m.forceable});let v=await Lr(e,p,u);if(v.kind!=="exclusive")return q(a,l.source,p,m.settlement,{reason:v.kind==="shared"?{kind:"space-in-use",tenants:v.tenants}:{kind:"unverifiable",detail:`could not check the workspace for other agents (${v.detail})`},forceable:!1});let D=zr(d,l);if(D.length>0)try{await e.teardownEnvironment({subagentId:a,runs:D})}catch(R){Mr.warn("environment teardown failed during cleanup",{spawnId:a,error:W(R)})}if(p.kind==="worktree-unlocatable"){if(p.worktreePath!==null&&!await e.worktreeExists(p.worktreePath)){let R={agentId:a,source:l.source,outcome:{kind:"torn-down",...Me(c)},branchName:p.branchName,settlement:m.settlement,panes:await Br(e,p.panes),worktree:{kind:"absent",path:p.worktreePath},branch:{kind:"not-applicable"}};return Ne(R)&&d!==void 0&&s.dropSpawn(d),R}return q(a,l.source,p,m.settlement,{reason:{kind:"unverifiable",detail:"missing worktree path or repo cwd"},forceable:!1})}if(p.kind==="worktree"){let R=await Ie(e.isWorktreeDirty,c,p.worktree);if(R.kind==="kept")return q(a,l.source,p,m.settlement,{reason:R.reason,forceable:!0})}let ue=await jr(e,p,u),K=Qt(a,l.source,p,m.settlement,ue,c);return Ne(K)&&d!==void 0&&s.dropSpawn(d),K}return i(o,"cleanupAgent"),{...t,cleanupAgent:o}}i(aa,"createCleanup");import*as Zt from"node:path";async function Gr(e,t,n){let r=await ve(e,["rev-parse","--verify","--quiet",`refs/heads/${n}`],t,E);return r===void 0?!0:r.code===0}i(Gr,"branchExisted");async function Jt(e,t){let n=t.branch.trim();if(n==="")throw new h("worktree checkout requires a branch name");let r=await te(e,t.repoCwd),o=Zt.resolve(t.path),a=t.materialization??Ye,s=t.dirtyCheckout??Q,c=await Gr(e,r,n),d=await ve(e,["worktree","add",...Ct(a),"-b",n,o,t.base??"HEAD"],r,E);if(d===void 0||d.code!==0)throw await $(e,r,o),c||await N(e,n,r),new h(d===void 0?`git worktree add for "${n}" could not run (worktree removed)`:`git worktree add for "${n}" failed (worktree removed): ${(d.stderr||d.stdout||`exit ${d.code}`).slice(0,300)}`);let l=await yt(e,["branch","--show-current"],o);if(l!==n)throw await $(e,r,o),await N(e,n,r),new h(l===void 0?`worktree created at ${o} but its branch could not be verified (worktree removed)`:`worktree created at ${o} is on branch "${l||"(detached)"}", not the requested "${n}" (worktree removed). The branch "${l}" still exists.`);let u;try{u=await vt(e,o,a,s)}catch(p){await $(e,r,o),await N(e,n,r);let m=p instanceof Error?p.message:String(p);throw new h(`worktree created but ${a} materialization failed (worktree removed): ${m}`)}if(u.kind==="cow-fallback"){let p=s==="dirty"?" The parent's uncommitted work was not carried over.":"";t.notify?.(`[cowboy] ${u.reason}${p} Nothing is shared with the parent checkout.`,"warning")}return{path:o,branch:n,repoCwd:r,materialization:u}}i(Jt,"createWorktreeCheckout");function Ca(e){return e.kind==="checkout"?e.branch:me(e.taskSlug??Je(e.type),e.id)}i(Ca,"spawnAgentName");function Ur(e){try{let t=_.statSync(e,{bigint:!0});return`${t.dev}:${t.ino}`}catch{return I.resolve(e)}}i(Ur,"canonicalRepoKey");async function va(e){let t=await Le.allocate(e.pi,{naming:{kind:"generated",taskSlug:e.taskSlug??e.agentType,id:e.spawnId},parentCwd:e.parentCwd,worktreeRoot:e.worktreeRoot,materialization:e.materialization,dirtyCheckout:Gt(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(va,"provisionOwnedCheckout");var Le=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:d,host:l}=n,u=r.kind==="generated"?me(r.taskSlug,r.id):r.branch.trim();if(r.kind==="explicit"&&u==="")throw new Error("explicit worktree naming requires a branch name");let p;try{p=await te(t,o)}catch{return d?.("[cowboy] Parent is not inside a git repository \u2014 spawning in the parent cwd without a worktree","warning"),new e(l,{kind:"parent-cwd"},u,!0)}let m=await qr(t,{repoCwd:p,path:I.join(et(a,p),u),branch:u,materialization:s,dirtyCheckout:c,notify:d,host:l});return new e(l,{kind:"worktree",checkout:{path:m.path,branch:m.branch,repoCwd:m.repoCwd},ref:m.ref},u,!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 Be(Yr(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=Vr(o),o}};function Vr(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(Vr,"stateAfterTeardown");async function qr(e,t){let n=I.resolve(t.path);return _.mkdirSync(I.dirname(n),{recursive:!0}),st().run(Ur(t.repoCwd),()=>Qr(e,t.host,{...t,path:n}))}i(qr,"createAdoptedWorktree");async function Kr(e,t,n){let r=await bt(e,t),o=pe(n),a=o===void 0?void 0:r?.find(s=>pe(s.path)===o);if(a!==void 0)return{path:a.path,branch:Ze(a),repoCwd:t,materialization:{kind:"reused"}}}i(Kr,"existingCheckout");async function Qr(e,t,n){let{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:d}=n,l=await Kr(e,r,o),u;if(l!==void 0)u=l;else try{u=await Jt(e,{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:d})}catch(m){throw je(m,await en(e,r,o))}let p;try{p=await t.hostAt({unit:"pane",cwd:u.path,label:a,name:a,checkout:{path:u.path,repoCwd:r,branch:u.branch}})}catch(m){if(l!==void 0)throw je(m,"existing worktree kept");let v=await en(e,r,u.path),D=await N(e,u.branch,r);throw je(m,`${v}. ${He(u.branch,D)}`)}return{path:u.path,branch:u.branch,repoCwd:r,materialization:u.materialization,ref:p}}i(Qr,"adoptWorktree");function Yr(e,t){return{isWorktreeDirty:i(n=>Pt(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 $(e,r,n),!_.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>At(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(Yr,"cleanupDeps");async function en(e,t,n){return await $(e,t,n),_.existsSync(n)?`worktree ${n} NOT removed \u2014 inspect it manually`:`worktree ${n} removed`}i(en,"removeFailedCheckout");function je(e,t){return new Error(`could not create the herdr worktree: ${W(e)}
24
24
 
25
25
  Launch-failure cleanup: ${t}.`)}i(je,"createFailureMessage");function He(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(He,"formatLaunchedBranchOutcome");function xa(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. ${He(e.branchName,e.branch)}.`:`Launch-failure cleanup: worktree ${e.path} removed. ${He(e.branchName,e.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${e.path} KEPT \u2014 ${St(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(xa,"formatLaunchCleanupNote");export{Zr as a,ht as b,b as c,yt as d,L as e,no as f,te as g,$ as h,bt as i,ao as j,xt as k,wo as l,At as m,Pt as n,Ro as o,St as p,Fe as q,_i as r,Wi as s,Fr as t,Fi as u,ce as v,$i as w,Ii as x,Di as y,O as z,rr as A,jo as B,Lo as C,Vo as D,si as E,ci as F,di as G,li as H,Ir as I,Ui as J,Vi as K,Gt as L,qi as M,Ki as N,Qi as O,Ji as P,aa as Q,Ca as R,va as S,Le as T,qr as U,xa as V};
26
- //# sourceMappingURL=chunk-ROQJTDCS.js.map
26
+ //# sourceMappingURL=chunk-Y5BC336I.js.map
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
- import{a as Le,b as Wt,c as Ut,d as Bt,j as Gt,k as U,o as Qt,p as Yt,s as Xt,v as Zt,w as Te,x as en,y as tn,z as nn}from"./chunk-YUOPU3GW.js";import{E as $t,F as Nt,G as qt,O as _t,Q as Kt,R as Vt,S as zt,a as Rt,f as It,g as Q,h as Et,m as Ct,n as Lt,o as Tt,q as Ft,r as Ot,s as jt,t as Ht,v as Mt,y as Dt}from"./chunk-ROQJTDCS.js";import{A as Ze,B as se,Ba as vt,C as et,Ea as St,F as oe,Fa as kt,G as K,I as ot,J as Re,Ja as z,K as L,La as bt,Ma as At,Na as Ee,Oa as Ce,P as W,Pa as ue,Qa as Pt,R as at,Ra as xt,S as dt,Sa as Jt,T as V,U as H,V as lt,W as Ie,a as F,aa as ut,ba as ct,d as Je,da as pt,e as C,ea as gt,f as re,fa as ae,g as Ke,ga as ft,h as ie,ha as ht,ia as mt,ja as E,k as Ve,ka as $,ma as de,na as A,qa as I,ta as le,w as Ye,xa as P,y as Xe,ya as yt,za as wt}from"./chunk-FCLYV3G3.js";import{E as rt,F as it,M as st,a as s,b as ze,c as Qe,n as tt,p as w,t as D,u as nt}from"./chunk-YEXMGUZI.js";import*as M from"node:path";function pe(t,e){let n=t.at(0);if(n)return{kind:"spawn",spawn:n};let r=e.at(0);return r?{kind:"multiplexer",attempt:r}:{kind:"none"}}s(pe,"findTaskDedup");var N=class extends Error{static{s(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,n){let r=e.kind==="spawn",i=r?`agent ${e.spawn.id}`:e.attempt.name,o=r?H(e.spawn.lifecycle):"live";super(`Task "${n}" is already in flight as ${i} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=n,this.dedup=e}},ce=class{constructor(e){this.deps=e}deps;static{s(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let n=e.taskSlug;if(n===void 0)return this.admitOne(e);let i=(this.admissionBySlug.get(n)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(n,i);try{return await i}finally{this.admissionBySlug.get(n)===i&&this.admissionBySlug.delete(n)}}async admitOne(e){if(e.taskSlug){let g=this.deps.listAgents().filter(p=>p.display.taskSlug===e.taskSlug&&dt(p.lifecycle.phase)),m=pe(g,await this.deps.findTaskAttempts(e.taskSlug));if(m.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:m.kind==="spawn"?m.spawn.id:m.attempt.name}}let{type:n,prompt:r,runInBackground:i,signal:o,...a}=e,d={...a,isBackground:i,signal:o},l=this.deps.spawn(n,r,d);return this.deps.getSpawn(l)?.lifecycle.phase==="queued"?{status:"queued",agentId:l,queuePosition:this.deps.queuePosition(l)}:{status:"admitted",agentId:l}}};import rn from"node:fs";var ge=class{constructor(e){this.resultFile=e}resultFile;static{s(this,"FileDeliverable")}async readDeliverable(){try{let e=rn.statSync(this.resultFile).mtimeMs,n=rn.readFileSync(this.resultFile,"utf-8").trim();return n?{content:n,mtime:e}:null}catch{return null}}};import sn from"node:fs";import*as on from"node:path";function Y(t){try{sn.rmSync(on.dirname(t),{recursive:!0,force:!0})}catch{}}s(Y,"removeResultArtifacts");function an(t){try{sn.rmSync(t,{force:!0})}catch{}}s(an,"removeResultFile");import*as B from"node:fs";import*as fe from"node:path";var br=L("assets");async function dn(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}s(dn,"probeList");function Ar(t,e,n){let r=n(e);return t?.find(i=>n(i.path)===r)}s(Ar,"matchWorktree");function ln(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}s(ln,"paneOf");function Pr(t,e,n,r){if(n===void 0)return e??void 0;let i=(t??[]).filter(o=>o.cwd!==void 0&&r(o.cwd)===r(n));return i.length===1?ln(i[0]):e??void 0}s(Pr,"livePaneFor");function Fe(t,e){let n=t?.filter(e)??[];return n.length===1?ln(n[0]):void 0}s(Fe,"solePaneAmong");function xr(t){async function e(){try{return await t.worktreeRoot()}catch{return}}s(e,"root");async function n(l,c){let g=await e(),m=[],p=new Set,h=s(y=>{let f=t.canonicalizePath(y.path);p.has(f)||(p.add(f),m.push(y))},"push");for(let y of c??[]){let f=fe.basename(y.path);se(f,l)&&(g!==void 0&&!et(y.path,g)||h({path:y.path,branch:y.branch!==void 0&&se(y.branch,l)?y.branch:f,workspaceId:y.workspaceId}))}if(m.length>0||g===void 0)return m;for(let y of await t.listRootEntries(g))se(y,l)&&h({path:fe.join(g,y),branch:y});return m}s(n,"discoverCandidates");function r(l){return{worktreePath:l.path,branch:l.branch,workspaceId:l.workspaceId}}s(r,"candidateSummary");async function i(l,c,g,m){let p=c.execution.host,h=c.display.worktree,y=h?.kind==="owned",f=p?{paneId:p.paneId,tabId:p.tabId,workspaceId:p.workspaceId}:null,x="tracked",v=h?.kind==="owned"?h.path:void 0,b=p?.workspaceId;if(v!==void 0){let R=Ar(g,v,t.canonicalizePath);R!==void 0&&(b=R.workspaceId)}let T=f!==null?Pr(m,f,v,t.canonicalizePath)??f:v===void 0?null:Fe(m,R=>R.cwd!==void 0&&t.canonicalizePath(R.cwd)===t.canonicalizePath(v))??null,S=v===void 0?null:{path:v,workspaceId:b,repoCwd:await t.resolveRepoCwd(v)};return{kind:"located",source:x,id:l,branch:h?.branch??Xe(c.display.taskSlug??Ye(c.display.type),c.id),worktreeManaged:y||S!==null,paneCreated:p?.paneCreated===!0,worktree:S,pane:T}}s(i,"locateTracked");async function o(l,c,g){let m=await n(l,c);if(m.length===0)return{kind:"not-found",id:l};if(m.length>1)return{kind:"ambiguous",id:l,candidates:m.map(r)};let p=m[0],h=Fe(g,y=>y.cwd!==void 0&&t.canonicalizePath(y.cwd)===t.canonicalizePath(p.path))??Fe(g,y=>y.workspaceId===p.workspaceId)??null;return{kind:"located",source:"recovered",id:l,branch:p.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:p.path,workspaceId:p.workspaceId,repoCwd:await t.resolveRepoCwd(p.path)},pane:h}}s(o,"locateDiscovered");async function a(l,c){let g=await dn(t.listWorktrees),m=await dn(t.listPlacements),p=g.ok?g.entries:void 0,h=m.ok?m.entries:void 0;return c===void 0?o(l,p,h):i(l,c,p,h)}s(a,"locate");async function d(l,c){let g=await t.listPlacements(),m=l.checkoutPath===void 0?void 0:t.canonicalizePath(l.checkoutPath);return g.filter(p=>p.paneId===c?!1:p.workspaceId===l.workspaceId?!0:m!==void 0&&p.cwd!==void 0&&t.canonicalizePath(p.cwd)===m).map(p=>p.name??p.paneId)}return s(d,"otherTenants"),{multiplexer:t.multiplexer,locate:a,otherTenants:d,observe:s(l=>t.readPane(l.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}s(xr,"createAgentAssets");function he(t,e,n){return xr({multiplexer:n.multiplexer,canonicalizePath:s(r=>n.canonicalizePath(r),"canonicalizePath"),deliverable:s(r=>{let i=C(r);return{path:i,present:B.existsSync(i)}},"deliverable"),listWorktrees:s(()=>n.listWorktrees(),"listWorktrees"),listPlacements:s(()=>n.listPlacements(),"listPlacements"),readPane:s(r=>n.observePane(r),"readPane"),worktreeRoot:s(async()=>{let r=$().cwd;if(!r)return;let i=await Q(t,r).catch(()=>{});return i===void 0?void 0:Ze(A().agent.worktreeRoot,i)},"worktreeRoot"),listRootEntries:s(async r=>{try{return await B.promises.readdir(r)}catch{return[]}},"listRootEntries"),resolveRepoCwd:s(async r=>{try{return await Q(t,r)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:s(r=>Lt(t,r),"isWorktreeDirty"),worktreeExists:s(async r=>B.existsSync(r),"worktreeExists"),removeWorktree:s(r=>e.release(r,"worktree-association"),"removeWorktree"),removeGitWorktree:s(async(r,i)=>(await Et(t,i,r),!B.existsSync(r)),"removeGitWorktree"),deleteBranch:s(r=>Ct(t,r,i=>e.isAttached(i,{repoCwd:r.repoCwd})),"deleteBranch"),closePane:s(async r=>{await e.release(r,"placement")},"closePane"),teardownEnvironment:s(async({subagentId:r,runs:i})=>{let o=P();for(let a of i)try{await o.get(a.harness)?.teardown({pi:t,paneId:a.paneId,cwd:a.cwd,subagentId:r})}catch(d){br.warn("harness teardown failed during environment teardown",{subagentId:r,harness:a.harness,error:w(d)})}},"teardownEnvironment")})}s(he,"createMultiplexerAgentAssets");var j=L("supervisor"),Rr=2e3;function Ir(){let t;return{promise:new Promise(n=>{t=n}),resolve:t}}s(Ir,"deferred");var me=class{constructor(e,n,r={}){this.host=e;this.deliverable=n;this.pollMs=r.pollMs??Rr,this.stopInitiator=r.stopInitiator??"user",this.onFollowUp=r.onFollowUp,this.stopProcess=r.stopProcess??((i,o)=>e.waitUntilGone(i,{timeoutMs:o}))}host;deliverable;static{s(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=Ir();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,n){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:n};try{await this.host.start(n,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(r){throw this.isWatching()&&(this.phase={kind:"idle"}),r}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},j.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),j.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(n=>{j.error("poll loop failed",{errorMessage:w(n)})}),this.settlement.promise}async stop(e){let n=this.phase;if(n.kind!=="watching"||this.outcome!==null)return!1;let{ref:r}=n,i=await this.stopProcess(r,e).catch(o=>(j.debug("stop failed",{errorMessage:w(o)}),!1));return j.debug("stop requested",{paneId:r.paneId,graceMs:e,stopped:i,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),i}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let n=this.phase;n.kind==="watching"&&(j.debug(e,{paneId:n.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,j.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let n=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);n.unref(),this.wakeLoop=()=>{clearTimeout(n),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!Er(this.held,e)){this.held=e,j.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return j.debug("readDeliverable failed",{errorMessage:w(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Er(t,e){return t.content===e.content&&t.mtime===e.mtime}s(Er,"sameReport");function X(t){let e=t.transport.createDeliverable(t.resultFile);return new me(t.host,e,t.supervisorOptions)}s(X,"createPaneSupervisor");function un(t,e){t.host=e}s(un,"placeExecution");function cn(t,e){t.harness=e}s(cn,"engageExecution");function pn(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}s(pn,"endExecutionRun");import He from"node:fs";import _ from"node:path";import{SettingsManager as Vr}from"@earendil-works/pi-coding-agent";import Nr from"node:fs";import{loadProjectContextFiles as qr}from"@earendil-works/pi-coding-agent";function gn(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
2
- `):""}s(gn,"buildOrchestrationGuidance");import{formatSkillsForPrompt as Cr}from"@earendil-works/pi-coding-agent";function Lr(t){let e=t;return e=e.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g,`
1
+ import{a as Te,b as Ut,c as Bt,d as Gt,j as Jt,k as U,o as Yt,p as Xt,s as Zt,v as en,w as Le,x as tn,y as nn,z as rn}from"./chunk-PU6CJR4Y.js";import{E as qt,F as Nt,G as _t,O as Wt,Q as Vt,R as zt,S as Qt,a as It,f as Et,g as Q,h as Ct,m as Tt,n as Lt,o as Ft,q as Ot,r as jt,s as Ht,t as Mt,v as Dt,y as $t}from"./chunk-Y5BC336I.js";import{A as et,B as ie,Ba as St,C as tt,Ea as kt,F as oe,Fa as bt,G as K,I as at,J as xe,Ja as z,K as T,La as At,Ma as Pt,Na as Ee,Oa as Ce,P as W,Pa as ue,Qa as Rt,R as dt,Ra as xt,S as lt,Sa as Kt,T as V,U as H,V as ut,W as Ie,a as F,aa as ct,ba as pt,d as Ke,da as gt,e as C,ea as ht,f as re,fa as ae,g as Ve,ga as ft,h as se,ha as mt,ia as yt,ja as E,k as ze,ka as $,ma as de,na as A,qa as I,ta as le,w as Xe,xa as P,y as Ze,ya as wt,za as vt}from"./chunk-73OMG4YX.js";import{E as st,F as it,M as ot,a as i,b as Qe,c as Ye,n as nt,p as w,t as D,u as rt}from"./chunk-AOUEQXPY.js";import*as M from"node:path";function pe(t,e){let n=t.at(0);if(n)return{kind:"spawn",spawn:n};let r=e.at(0);return r?{kind:"multiplexer",attempt:r}:{kind:"none"}}i(pe,"findTaskDedup");var q=class extends Error{static{i(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,n){let r=e.kind==="spawn",s=r?`agent ${e.spawn.id}`:e.attempt.name,o=r?H(e.spawn.lifecycle):"live";super(`Task "${n}" is already in flight as ${s} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=n,this.dedup=e}},ce=class{constructor(e){this.deps=e}deps;static{i(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let n=e.taskSlug;if(n===void 0)return this.admitOne(e);let s=(this.admissionBySlug.get(n)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(n,s);try{return await s}finally{this.admissionBySlug.get(n)===s&&this.admissionBySlug.delete(n)}}async admitOne(e){if(e.taskSlug){let g=this.deps.listAgents().filter(p=>p.display.taskSlug===e.taskSlug&&lt(p.lifecycle.phase)),m=pe(g,await this.deps.findTaskAttempts(e.taskSlug));if(m.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:m.kind==="spawn"?m.spawn.id:m.attempt.name}}let{type:n,prompt:r,runInBackground:s,signal:o,...a}=e,d={...a,isBackground:s,signal:o},l=this.deps.spawn(n,r,d);return this.deps.getSpawn(l)?.lifecycle.phase==="queued"?{status:"queued",agentId:l,queuePosition:this.deps.queuePosition(l)}:{status:"admitted",agentId:l}}};import sn from"node:fs";var ge=class{constructor(e){this.resultFile=e}resultFile;static{i(this,"FileDeliverable")}async readDeliverable(){try{let e=sn.statSync(this.resultFile).mtimeMs,n=sn.readFileSync(this.resultFile,"utf-8").trim();return n?{content:n,mtime:e}:null}catch{return null}}};import on from"node:fs";import*as an from"node:path";function Y(t){try{on.rmSync(an.dirname(t),{recursive:!0,force:!0})}catch{}}i(Y,"removeResultArtifacts");function dn(t){try{on.rmSync(t,{force:!0})}catch{}}i(dn,"removeResultFile");import*as B from"node:fs";import*as he from"node:path";var br=T("assets");async function ln(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}i(ln,"probeList");function Ar(t,e,n){let r=n(e);return t?.find(s=>n(s.path)===r)}i(Ar,"matchWorktree");function un(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}i(un,"paneOf");function Pr(t,e,n,r){if(n===void 0)return e??void 0;let s=(t??[]).filter(o=>o.cwd!==void 0&&r(o.cwd)===r(n));return s.length===1?un(s[0]):e??void 0}i(Pr,"livePaneFor");function Fe(t,e){let n=t?.filter(e)??[];return n.length===1?un(n[0]):void 0}i(Fe,"solePaneAmong");function Rr(t){async function e(){try{return await t.worktreeRoot()}catch{return}}i(e,"root");async function n(l,c){let g=await e(),m=[],p=new Set,f=i(y=>{let h=t.canonicalizePath(y.path);p.has(h)||(p.add(h),m.push(y))},"push");for(let y of c??[]){let h=he.basename(y.path);ie(h,l)&&(g!==void 0&&!tt(y.path,g)||f({path:y.path,branch:y.branch!==void 0&&ie(y.branch,l)?y.branch:h,workspaceId:y.workspaceId}))}if(m.length>0||g===void 0)return m;for(let y of await t.listRootEntries(g))ie(y,l)&&f({path:he.join(g,y),branch:y});return m}i(n,"discoverCandidates");function r(l){return{worktreePath:l.path,branch:l.branch,workspaceId:l.workspaceId}}i(r,"candidateSummary");async function s(l,c,g,m){let p=c.execution.host,f=c.display.worktree,y=f?.kind==="owned",h=p?{paneId:p.paneId,tabId:p.tabId,workspaceId:p.workspaceId}:null,R="tracked",v=f?.kind==="owned"?f.path:void 0,b=p?.workspaceId;if(v!==void 0){let x=Ar(g,v,t.canonicalizePath);x!==void 0&&(b=x.workspaceId)}let L=h!==null?Pr(m,h,v,t.canonicalizePath)??h:v===void 0?null:Fe(m,x=>x.cwd!==void 0&&t.canonicalizePath(x.cwd)===t.canonicalizePath(v))??null,S=v===void 0?null:{path:v,workspaceId:b,repoCwd:await t.resolveRepoCwd(v)};return{kind:"located",source:R,id:l,branch:f?.branch??Ze(c.display.taskSlug??Xe(c.display.type),c.id),worktreeManaged:y||S!==null,paneCreated:p?.paneCreated===!0,worktree:S,pane:L}}i(s,"locateTracked");async function o(l,c,g){let m=await n(l,c);if(m.length===0)return{kind:"not-found",id:l};if(m.length>1)return{kind:"ambiguous",id:l,candidates:m.map(r)};let p=m[0],f=Fe(g,y=>y.cwd!==void 0&&t.canonicalizePath(y.cwd)===t.canonicalizePath(p.path))??Fe(g,y=>y.workspaceId===p.workspaceId)??null;return{kind:"located",source:"recovered",id:l,branch:p.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:p.path,workspaceId:p.workspaceId,repoCwd:await t.resolveRepoCwd(p.path)},pane:f}}i(o,"locateDiscovered");async function a(l,c){let g=await ln(t.listWorktrees),m=await ln(t.listPlacements),p=g.ok?g.entries:void 0,f=m.ok?m.entries:void 0;return c===void 0?o(l,p,f):s(l,c,p,f)}i(a,"locate");async function d(l,c){let g=await t.listPlacements(),m=l.checkoutPath===void 0?void 0:t.canonicalizePath(l.checkoutPath);return g.filter(p=>p.paneId===c?!1:p.workspaceId===l.workspaceId?!0:m!==void 0&&p.cwd!==void 0&&t.canonicalizePath(p.cwd)===m).map(p=>p.name??p.paneId)}return i(d,"otherTenants"),{multiplexer:t.multiplexer,locate:a,otherTenants:d,observe:i(l=>t.readPane(l.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}i(Rr,"createAgentAssets");function fe(t,e,n){return Rr({multiplexer:n.multiplexer,canonicalizePath:i(r=>n.canonicalizePath(r),"canonicalizePath"),deliverable:i(r=>{let s=C(r);return{path:s,present:B.existsSync(s)}},"deliverable"),listWorktrees:i(()=>n.listWorktrees(),"listWorktrees"),listPlacements:i(()=>n.listPlacements(),"listPlacements"),readPane:i(r=>n.observePane(r),"readPane"),worktreeRoot:i(async()=>{let r=$().cwd;if(!r)return;let s=await Q(t,r).catch(()=>{});return s===void 0?void 0:et(A().agent.worktreeRoot,s)},"worktreeRoot"),listRootEntries:i(async r=>{try{return await B.promises.readdir(r)}catch{return[]}},"listRootEntries"),resolveRepoCwd:i(async r=>{try{return await Q(t,r)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:i(r=>Lt(t,r),"isWorktreeDirty"),worktreeExists:i(async r=>B.existsSync(r),"worktreeExists"),removeWorktree:i(r=>e.release(r,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(r,s)=>(await Ct(t,s,r),!B.existsSync(r)),"removeGitWorktree"),deleteBranch:i(r=>Tt(t,r,s=>e.isAttached(s,{repoCwd:r.repoCwd})),"deleteBranch"),closePane:i(async r=>{await e.release(r,"placement")},"closePane"),teardownEnvironment:i(async({subagentId:r,runs:s})=>{let o=P();for(let a of s)try{await o.get(a.harness)?.teardown({pi:t,paneId:a.paneId,cwd:a.cwd,subagentId:r})}catch(d){br.warn("harness teardown failed during environment teardown",{subagentId:r,harness:a.harness,error:w(d)})}},"teardownEnvironment")})}i(fe,"createMultiplexerAgentAssets");var j=T("supervisor"),xr=2e3;function Ir(){let t;return{promise:new Promise(n=>{t=n}),resolve:t}}i(Ir,"deferred");var me=class{constructor(e,n,r={}){this.host=e;this.deliverable=n;this.pollMs=r.pollMs??xr,this.stopInitiator=r.stopInitiator??"user",this.onFollowUp=r.onFollowUp,this.stopProcess=r.stopProcess??((s,o)=>e.waitUntilGone(s,{timeoutMs:o}))}host;deliverable;static{i(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=Ir();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,n){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:n};try{await this.host.start(n,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(r){throw this.isWatching()&&(this.phase={kind:"idle"}),r}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},j.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),j.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(n=>{j.error("poll loop failed",{errorMessage:w(n)})}),this.settlement.promise}async stop(e){let n=this.phase;if(n.kind!=="watching"||this.outcome!==null)return!1;let{ref:r}=n,s=await this.stopProcess(r,e).catch(o=>(j.debug("stop failed",{errorMessage:w(o)}),!1));return j.debug("stop requested",{paneId:r.paneId,graceMs:e,stopped:s,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),s}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let n=this.phase;n.kind==="watching"&&(j.debug(e,{paneId:n.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,j.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let n=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);n.unref(),this.wakeLoop=()=>{clearTimeout(n),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!Er(this.held,e)){this.held=e,j.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return j.debug("readDeliverable failed",{errorMessage:w(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Er(t,e){return t.content===e.content&&t.mtime===e.mtime}i(Er,"sameReport");function X(t){let e=t.transport.createDeliverable(t.resultFile);return new me(t.host,e,t.supervisorOptions)}i(X,"createPaneSupervisor");function cn(t,e){t.host=e}i(cn,"placeExecution");function pn(t,e){t.harness=e}i(pn,"engageExecution");function gn(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}i(gn,"endExecutionRun");import He from"node:fs";import _ from"node:path";import{SettingsManager as Vr}from"@earendil-works/pi-coding-agent";import qr from"node:fs";import{loadProjectContextFiles as Nr}from"@earendil-works/pi-coding-agent";function hn(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
2
+ `):""}i(hn,"buildOrchestrationGuidance");import{formatSkillsForPrompt as Cr}from"@earendil-works/pi-coding-agent";function Tr(t){let e=t;return e=e.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g,`
3
3
  `),e=e.replace(/\n?(?:The following skills provide[\s\S]*?)?<\s*available_skills\s*>[\s\S]*?<\/\s*available_skills\s*>\n?/g,`
4
4
  `),e=e.replace(/\n?Current date:.*\n?/g,`
5
5
  `),e=e.replace(/\n?Current working directory:.*\n?/g,`
6
6
  `),e=e.replace(/\n{3,}/g,`
7
7
 
8
- `),e.trim()}s(Lr,"stripScaffolding");async function Oe(t,e,n,r,i="replace"){let o=["# Environment",`Working directory: ${e}`,n.isGitRepo?"Git repository: yes":"Not a git repository"];n.isGitRepo&&n.branch&&o.push(`Branch: ${n.branch}`),o.push(`Platform: ${n.platform}`);let a=o.join(`
9
- `),d=!!r?.skillMetas?.length||!!r?.inlinedSkills?.length,l="";if(d){let f=[];if(r?.skillMetas?.length){let v=r.skillMetas.map(S=>({name:S.name,description:S.description,filePath:S.location,baseDir:"",sourceInfo:{},disableModelInvocation:S.disableModelInvocation})),T=Cr(v).match(/<skill>[\s\S]*?<\/skill>/g);T&&f.push(...T)}for(let v of r?.inlinedSkills??[])f.push(`<skill><name>${q(v.name)}</name><description>${q(v.description)}</description><content>${q(v.content)}</content></skill>`);l=`
8
+ `),e.trim()}i(Tr,"stripScaffolding");async function Oe(t,e,n,r,s="replace"){let o=["# Environment",`Working directory: ${e}`,n.isGitRepo?"Git repository: yes":"Not a git repository"];n.isGitRepo&&n.branch&&o.push(`Branch: ${n.branch}`),o.push(`Platform: ${n.platform}`);let a=o.join(`
9
+ `),d=!!r?.skillMetas?.length||!!r?.inlinedSkills?.length,l="";if(d){let h=[];if(r?.skillMetas?.length){let v=r.skillMetas.map(S=>({name:S.name,description:S.description,filePath:S.location,baseDir:"",sourceInfo:{},disableModelInvocation:S.disableModelInvocation})),L=Cr(v).match(/<skill>[\s\S]*?<\/skill>/g);L&&h.push(...L)}for(let v of r?.inlinedSkills??[])h.push(`<skill><name>${N(v.name)}</name><description>${N(v.description)}</description><content>${N(v.content)}</content></skill>`);l=`
10
10
 
11
- ${["The following skills provide specialized instructions for specific tasks.","Use the read tool to load a skill's file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>",...f,"</available_skills>"].join(`
11
+ ${["The following skills provide specialized instructions for specific tasks.","Use the read tool to load a skill's file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>",...h,"</available_skills>"].join(`
12
12
  `)}`}let c=`
13
13
  <agent_instructions>
14
14
  ${t.systemPrompt}
15
- </agent_instructions>`,g="";if(r?.contextFiles?.length){let f=["<project_context>","","Project-specific instructions and guidelines:",""];for(let x of r.contextFiles)f.push(`<project_instructions path="${q(x.path)}">`),f.push(x.content),f.push("</project_instructions>"),f.push("");f.push("</project_context>"),g=`
15
+ </agent_instructions>`,g="";if(r?.contextFiles?.length){let h=["<project_context>","","Project-specific instructions and guidelines:",""];for(let R of r.contextFiles)h.push(`<project_instructions path="${N(R.path)}">`),h.push(R.content),h.push("</project_instructions>"),h.push("");h.push("</project_context>"),g=`
16
16
 
17
- ${f.join(`
18
- `)}`}let m=Tr(t),p=i==="inherit"?r?.parentSystemPrompt:i==="custom"?r?.customSystemPrompt:void 0,h=p&&Lr(p);return{prefix:`${h?`${h}
17
+ ${h.join(`
18
+ `)}`}let m=Lr(t),p=s==="inherit"?r?.parentSystemPrompt:s==="custom"?r?.customSystemPrompt:void 0,f=p&&Tr(p);return{prefix:`${f?`${f}
19
19
 
20
20
  ${a}`:a}${g}`,identity:`${m}
21
- ${c}`,skills:l}}s(Oe,"buildAgentPrompt");function Tr(t){let e=t.displayName?.trim(),n=e?` display_name="${q(e)}"`:"",r=`name="${q(t.name)}"${n}`,i=t.description.trim();return i?`<active_agent ${r}>
22
- ${q(i)}
23
- </active_agent>`:`<active_agent ${r}/>`}s(Tr,"buildActiveAgentTag");function q(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}s(q,"escapeXml");import{existsSync as Fr,readFileSync as Or,realpathSync as jr}from"node:fs";import{homedir as je}from"node:os";import{join as Z,resolve as G}from"node:path";import{loadSkills as Hr,loadSkillsFromDir as fn}from"@earendil-works/pi-coding-agent";function hn(t){let e=G(t),n=Mr(e,fn),r=fn({dir:Z(je(),".agents","skills"),source:"agents"}),i=mn(r.skills,Z(je(),".agents","skills")),o=Hr({cwd:e,agentDir:Z(je(),".pi","agent"),skillPaths:[],includeDefaults:!0}),a=new Set,d=new Set,l=[];for(let c of[...n,...i,...o.skills]){let g=$r(c.filePath);d.has(g)||a.has(c.name)||(a.add(c.name),d.add(g),l.push(c))}return l}s(hn,"loadAllSkills");function Mr(t,e){let n=Dr(t),r=[],i=t;for(;;){let o=Z(i,".agents","skills"),a=e({dir:o,source:"agents"});if(r.push(...mn(a.skills,o)),i===n)break;let d=G(i,"..");if(d===i)break;i=d}return r}s(Mr,"loadAncestorAgentsSkills");function mn(t,e){let n=G(e);return t.filter(r=>G(r.filePath,"..")!==n)}s(mn,"filterRootMdFiles");function Dr(t){let e=G(t);for(;;){if(Fr(Z(e,".git")))return e;let n=G(e,"..");if(n===e)return e;e=n}}s(Dr,"findGitRoot");function $r(t){try{return jr(t)}catch{return t}}s($r,"canonicalizePath");async function yn(t,e){let n=hn(e);return t.map(r=>{if(tt(r))return{name:r,description:"",content:`(Skill "${r}" skipped: name contains path traversal characters)`};let i=n.find(o=>o.name===r);if(!i)return{name:r,description:"",content:`(Skill "${r}" not found in .pi/skills/, .agents/skills/, or global skill locations)`};try{return{name:r,description:i.description,content:Or(i.filePath,"utf-8").trim()}}catch{return{name:r,description:"",content:`(Skill "${r}" not found in .pi/skills/, .agents/skills/, or global skill locations)`}}})}s(yn,"inlineSkills");async function wn(t,e){let n=hn(e);return t.map(r=>{let i=n.find(o=>o.name===r);return i?{name:r,description:i.description,location:i.filePath,disableModelInvocation:i.disableModelInvocation}:{name:r,description:`(Skill "${r}" not found)`,location:"",disableModelInvocation:!1}})}s(wn,"loadSkillMeta");async function vn(t,e,n){try{let r=await t.exec("git",e,{cwd:n,timeout:nt});return r.code===0?r.stdout.trim():null}catch{return null}}s(vn,"execGit");async function _r(t,e){let r=await vn(t,["rev-parse","--is-inside-work-tree"],e)==="true",i=r?await vn(t,["branch","--show-current"],e):null;return{isGitRepo:r,branch:i,platform:process.platform}}s(_r,"detectEnv");async function Wr(t,e,n,r,i,o){let a=ht(),d=r?.includeContextFiles??o,l={};if(i==="inherit")try{l.parentSystemPrompt=t.getSystemPrompt()}catch(c){n(`Failed to get parent system prompt: ${w(c)}. Falling back to replace mode.`)}if(i==="custom")try{let c=Nr.readFileSync(a,"utf-8").trim();c?l.customSystemPrompt=c:n(`Custom prompt file is empty: ${a}. Falling back to replace mode.`)}catch(c){c?.code==="ENOENT"?n(`Custom prompt file not found: ${a}. Falling back to replace mode.`):n(`Failed to read custom prompt file: ${w(c)}. Falling back to replace mode.`)}if(d)try{l.contextFiles=qr({cwd:e,agentDir:F()})}catch{}return l}s(Wr,"resolveSystemPromptSources");async function Ur(t,e,n,r,i,o,a){let d={...a},l=e?.inlinedSkills??[];if(l.length>0&&(d.inlinedSkills=await yn(l,r)),Array.isArray(n.skills)&&(d.skillMetas=await wn(n.skills,r)),e)return await Oe(e,r,i,d,o);let c=Ft.get("general-purpose");if(!c)throw new Error(`No fallback config available for unknown type "${t}"`);return await Oe({...c,name:t},r,i,d,o)}s(Ur,"buildPrompt");function Br(t){return t.filter(e=>!!e?.trim()).join(`
21
+ ${c}`,skills:l}}i(Oe,"buildAgentPrompt");function Lr(t){let e=t.displayName?.trim(),n=e?` display_name="${N(e)}"`:"",r=`name="${N(t.name)}"${n}`,s=t.description.trim();return s?`<active_agent ${r}>
22
+ ${N(s)}
23
+ </active_agent>`:`<active_agent ${r}/>`}i(Lr,"buildActiveAgentTag");function N(t){return t.replace(/</g,"&lt;").replace(/>/g,"&gt;")}i(N,"escapeXml");import{existsSync as Fr,readFileSync as Or,realpathSync as jr}from"node:fs";import{homedir as je}from"node:os";import{join as Z,resolve as G}from"node:path";import{loadSkills as Hr,loadSkillsFromDir as fn}from"@earendil-works/pi-coding-agent";function mn(t){let e=G(t),n=Mr(e,fn),r=fn({dir:Z(je(),".agents","skills"),source:"agents"}),s=yn(r.skills,Z(je(),".agents","skills")),o=Hr({cwd:e,agentDir:Z(je(),".pi","agent"),skillPaths:[],includeDefaults:!0}),a=new Set,d=new Set,l=[];for(let c of[...n,...s,...o.skills]){let g=$r(c.filePath);d.has(g)||a.has(c.name)||(a.add(c.name),d.add(g),l.push(c))}return l}i(mn,"loadAllSkills");function Mr(t,e){let n=Dr(t),r=[],s=t;for(;;){let o=Z(s,".agents","skills"),a=e({dir:o,source:"agents"});if(r.push(...yn(a.skills,o)),s===n)break;let d=G(s,"..");if(d===s)break;s=d}return r}i(Mr,"loadAncestorAgentsSkills");function yn(t,e){let n=G(e);return t.filter(r=>G(r.filePath,"..")!==n)}i(yn,"filterRootMdFiles");function Dr(t){let e=G(t);for(;;){if(Fr(Z(e,".git")))return e;let n=G(e,"..");if(n===e)return e;e=n}}i(Dr,"findGitRoot");function $r(t){try{return jr(t)}catch{return t}}i($r,"canonicalizePath");async function wn(t,e){let n=mn(e);return t.map(r=>{if(nt(r))return{name:r,description:"",content:`(Skill "${r}" skipped: name contains path traversal characters)`};let s=n.find(o=>o.name===r);if(!s)return{name:r,description:"",content:`(Skill "${r}" not found in .pi/skills/, .agents/skills/, or global skill locations)`};try{return{name:r,description:s.description,content:Or(s.filePath,"utf-8").trim()}}catch{return{name:r,description:"",content:`(Skill "${r}" not found in .pi/skills/, .agents/skills/, or global skill locations)`}}})}i(wn,"inlineSkills");async function vn(t,e){let n=mn(e);return t.map(r=>{let s=n.find(o=>o.name===r);return s?{name:r,description:s.description,location:s.filePath,disableModelInvocation:s.disableModelInvocation}:{name:r,description:`(Skill "${r}" not found)`,location:"",disableModelInvocation:!1}})}i(vn,"loadSkillMeta");async function Sn(t,e,n){try{let r=await t.exec("git",e,{cwd:n,timeout:rt});return r.code===0?r.stdout.trim():null}catch{return null}}i(Sn,"execGit");async function _r(t,e){let r=await Sn(t,["rev-parse","--is-inside-work-tree"],e)==="true",s=r?await Sn(t,["branch","--show-current"],e):null;return{isGitRepo:r,branch:s,platform:process.platform}}i(_r,"detectEnv");async function Wr(t,e,n,r,s,o){let a=mt(),d=r?.includeContextFiles??o,l={};if(s==="inherit")try{l.parentSystemPrompt=t.getSystemPrompt()}catch(c){n(`Failed to get parent system prompt: ${w(c)}. Falling back to replace mode.`)}if(s==="custom")try{let c=qr.readFileSync(a,"utf-8").trim();c?l.customSystemPrompt=c:n(`Custom prompt file is empty: ${a}. Falling back to replace mode.`)}catch(c){c?.code==="ENOENT"?n(`Custom prompt file not found: ${a}. Falling back to replace mode.`):n(`Failed to read custom prompt file: ${w(c)}. Falling back to replace mode.`)}if(d)try{l.contextFiles=Nr({cwd:e,agentDir:F()})}catch{}return l}i(Wr,"resolveSystemPromptSources");async function Ur(t,e,n,r,s,o,a){let d={...a},l=e?.inlinedSkills??[];if(l.length>0&&(d.inlinedSkills=await wn(l,r)),Array.isArray(n.skills)&&(d.skillMetas=await vn(n.skills,r)),e)return await Oe(e,r,s,d,o);let c=Ot.get("general-purpose");if(!c)throw new Error(`No fallback config available for unknown type "${t}"`);return await Oe({...c,name:t},r,s,d,o)}i(Ur,"buildPrompt");function Br(t){return t.filter(e=>!!e?.trim()).join(`
24
24
 
25
- `)}s(Br,"joinPromptSections");function Gr(t,e){return t!==null&&t!==""?t:e}s(Gr,"branchName");function Sn(t,e,n,r){let i=t&&e?Gr(n,r):void 0;return i?["","## Worktree branch","",`You are working in a git worktree on branch \`${i}\`.`,"Every commit you make and every merge you run lands on THIS branch \u2014 never on `main` or any other branch.","Do NOT switch branches and do NOT merge into `main` yourself. Report the branch name in your final response so the orchestrator can merge it with the merge_cowboy_branch tool."].join(`
26
- `):""}s(Sn,"buildWorktreeBranchSection");function Jr(){return["## Steering & Mid-Run Instructions","- You may receive additional instructions or steering messages while working (from the user or the orchestrator).","- Always treat mid-run steering and follow-up instructions as having higher priority than your original initial prompt.","- In your final report (written to the result file), you MUST explicitly disclose any steering or direction changes you received during implementation.","- If steering or code review comments caused you to diverge from, modify, or abandon parts of the original goal, clearly explain what changed and why, so the orchestrator understands that the divergence was intentional and requested."].join(`
27
- `)}s(Jr,"buildSteeringInstructions");function Kr(t){return["","## Your report","","When the task is done \u2014 every change committed, every check run \u2014 write your complete final answer, once, to the file:",t,"","That write is your last action. The parent session reads the file as your deliverable as soon as it stops changing, so an edit or a rewrite after it is announced to the parent as a separate report. Verify before you write, not after; then reply with a one-line confirmation."].join(`
28
- `)}s(Kr,"buildResultInstruction");async function kn(t){let{pi:e,ctx:n,cwd:r,notify:i}=t,o=await _r(e,r),a=await Wr(n,r,i,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),d=await Ur(t.type,t.agentConfig,t.config,r,o,t.globalSystemPromptMode,a);return Br([d.prefix,d.identity,d.skills,Sn(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),Jr(),Kr(t.resultFile),gn(t.agentGuidance)])}s(kn,"buildSubagentSystemPrompt");function bn(t,e){let n=Object.entries(e??{});return n.length===0?null:(K(t,`${n.map(([r,i])=>`export ${r}=${st(i)}`).join(`
25
+ `)}i(Br,"joinPromptSections");function Gr(t,e){return t!==null&&t!==""?t:e}i(Gr,"branchName");function kn(t,e,n,r){let s=t&&e?Gr(n,r):void 0;return s?["","## Worktree branch","",`You are working in a git worktree on branch \`${s}\`.`,"Every commit you make and every merge you run lands on THIS branch \u2014 never on `main` or any other branch.","Do NOT switch branches and do NOT merge into `main` yourself. Report the branch name in your final response so the orchestrator can merge it with the merge_cowboy_branch tool."].join(`
26
+ `):""}i(kn,"buildWorktreeBranchSection");function Jr(){return["## Steering & Mid-Run Instructions","- You may receive additional instructions or steering messages while working (from the user or the orchestrator).","- Always treat mid-run steering and follow-up instructions as having higher priority than your original initial prompt.","- In your final report (written to the result file), you MUST explicitly disclose any steering or direction changes you received during implementation.","- If steering or code review comments caused you to diverge from, modify, or abandon parts of the original goal, clearly explain what changed and why, so the orchestrator understands that the divergence was intentional and requested."].join(`
27
+ `)}i(Jr,"buildSteeringInstructions");function Kr(t){return["","## Your report","","When the task is done \u2014 every change committed, every check run \u2014 write your complete final answer, once, to the file:",t,"","That write is your last action. The parent session reads the file as your deliverable as soon as it stops changing, so an edit or a rewrite after it is announced to the parent as a separate report. Verify before you write, not after; then reply with a one-line confirmation."].join(`
28
+ `)}i(Kr,"buildResultInstruction");async function bn(t){let{pi:e,ctx:n,cwd:r,notify:s}=t,o=await _r(e,r),a=await Wr(n,r,s,t.agentConfig,t.globalSystemPromptMode,t.globalIncludeContextFiles),d=await Ur(t.type,t.agentConfig,t.config,r,o,t.globalSystemPromptMode,a);return Br([d.prefix,d.identity,d.skills,kn(t.worktreePath,o.isGitRepo,o.branch,t.expectedBranch),Jr(),Kr(t.resultFile),hn(t.agentGuidance)])}i(bn,"buildSubagentSystemPrompt");function An(t,e){let n=Object.entries(e??{});return n.length===0?null:(K(t,`${n.map(([r,s])=>`export ${r}=${ot(s)}`).join(`
29
29
  `)}
30
- `),t)}s(bn,"stageLaunchEnv");function zr(t,e){let n=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||n.length>0?{kind:"none"}:{kind:"default"}}s(zr,"resolveSkillMode");function Qr(t,e,n){let r=new Map,i=s((o,a)=>{let d=o.toLowerCase(),l=r.get(d);l===void 0?r.set(d,a):l!==a&&r.set(d,null)},"addSource");for(let o of e.packages){let a=typeof o=="string"?o:o.source,d=An(a);d&&i(d,a)}for(let o of e.extensionPaths){let a=An(o);a&&i(a,o)}return t.map(o=>{if(Yr(o)||Xr(o,n))return o;let a=Zr(o),d=r.get(a.toLowerCase());if(d===null)throw new Error(`Extension entry "${o}" is ambiguous in pi settings; more than one source matches its name. The agent did not start.`);if(d===void 0)throw new Error(`Extension entry "${o}" is not in the pi settings and is not an npm:, git:, or path source. The agent did not start.`);return d})}s(Qr,"resolveExtensionSources");function Yr(t){return t.startsWith("npm:")||t.startsWith("git:")}s(Yr,"isPiExtensionSource");function Xr(t,e){return _.isAbsolute(t)?He.existsSync(t):He.existsSync(_.resolve(e,t))}s(Xr,"isExistingPath");function Zr(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}s(Zr,"extensionEntryName");function An(t){let e=t.split("#",1)[0].replace(/[\\/]$/,"");if(!e)return;if(e.startsWith("npm:")){let o=e.slice(4);return(o.startsWith("@")?o.split("/",2).at(1)?.split("@",1)[0]:o.split("@",1)[0])?.toLowerCase()}let n=e.startsWith("git:")?e.slice(4):e,r=_.basename(n),i=_.basename(r,_.extname(r));return i==="index"?_.basename(_.dirname(n))||void 0:i||void 0}s(An,"extensionSourceName");function Pn(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}s(Pn,"notifyLaunchConfigurationError");function ei(t){let e=t,n=e.sessionFile??e.sessionManager?.getSessionFile?.();if(n)return n}s(ei,"resolveParentSessionFile");function xn(t,e){let n=new Set;for(let r of t){if(!r)throw new Error(`Empty entry in ${e} is not supported`);n.add(r)}return[...n]}s(xn,"resolveToolCliEntries");function ti(t,e,n,r){let i=P();switch(i.family(t)){case"pi":return{...e,family:"pi",...n};case"opencode":return{...e,family:"opencode"};case"codex":return{...e,family:"codex",...r};case"claude":return{...e,family:"claude"};case void 0:{if(i.get(t)===void 0)throw new Error(`no harness registered for "${t}"`);return{...e,family:"plugin"}}}}s(ti,"buildLaunchRequest");function ni(t,e){return P().require(t).buildArgs(e)}s(ni,"buildHarnessArgs");function ri(t,e,n,r,i,o,a){let d=ae(e,n),l=d===void 0?void 0:ft(ii(d,i,o,a)),c=Rn(r,"inherited",o,a);return ae(ae(Rn(t,"default",o,a),l),c)}s(ri,"resolveLaunchEnv");function ii(t,e,n,r){let i={};for(let[o,a]of Object.entries(t)){if(!e.includes(o)){i[o]=a;continue}n(`Ignoring environment variable ${o} for ${r}: it is reserved by the ${r} harness and cannot be overridden`)}return i}s(ii,"dropReserved");var si={name:"not a valid environment variable name",reserved:"reserved","not-string":"not a string",control:"carrying a control character"};function Rn(t,e,n,r){if(t===void 0)return;let i=gt(t,{reserved:[],report:s((o,a)=>n(`Ignoring ${e} environment variable ${o} for ${r}: it is ${si[a]} and cannot be carried`),"report")});return Object.keys(i).length===0?void 0:i}s(Rn,"ownEnvOverrides");function oi(t,e){return[...t===void 0?[]:it[t],...e===void 0?[]:rt(e)]}s(oi,"familyReservations");async function In(t,e,n,r,i){let o=A(),a=i.cwd??e.cwd,d=Dt(n,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),l=Mt(n),c=i.harness,g=zr(d.skills,l),m=[],p=s(k=>{m.push(k)},"bufferNotify"),h={kind:"default"};if(d.extensions===!1)h={kind:"none"};else if(Array.isArray(d.extensions))if(d.extensions.length===0)h={kind:"none"};else try{let k=Vr.create(a,F(),{projectTrusted:i.projectTrusted!==!1});h={kind:"paths",paths:Qr(d.extensions,{packages:k.getPackages(),extensionPaths:k.getExtensionPaths()},a)}}catch(k){let xe=k instanceof Error?k.message:String(k);Pn(e,xe)}let y=P().family(c),f={kind:"default"};try{let k=y===void 0?void 0:l?.toolsByFamily?.[y];k?.tools===!1?f={kind:"none"}:Array.isArray(k?.tools)?f={kind:"include",names:xn(k.tools,"tools")}:k?.excludeTools?.length&&(f={kind:"exclude",names:xn(k.excludeTools,"excludeTools")})}catch(k){let xe=k instanceof Error?k.message:String(k);Pn(e,xe)}let x=P().get(c),v=ri(x?.defaultEnv?.(),o.harnessEnv(c),y===void 0?void 0:l?.envByFamily?.[y],x?.inheritedEnv?.(),oi(y,x),p,c),b=i.agentId??"unknown",T=Je(b);oe(T);let S=C(b),R=re(b),ne=ie(b),yr=bn(Ke(b),v),Ue=await kn({pi:t,ctx:e,type:n,agentConfig:l,config:d,cwd:a,globalSystemPromptMode:o.agent.systemPromptMode,globalIncludeContextFiles:o.agent.includeContextFiles,worktreePath:i.worktree?.path,expectedBranch:i.worktree?.branch,agentGuidance:i.agentGuidance,resultFile:S,notify:p});try{K(R,Ue)}catch(k){throw new Error(`cannot write the system prompt file ${R}: ${w(k)}. The agent did not start.`,{cause:k})}if(!He.existsSync(R))throw new Error(`the system prompt file is missing after the write: ${R}. The agent did not start.`);K(ne,r);let Be=i.fork?ei(e):void 0;i.fork&&Be===void 0&&p("Fork session is enabled, but no parent session file is available; launching without --fork");let wr={subagentId:b,systemPromptFile:R,taskFile:ne,resultFile:S,modelKey:D(i.modelChoice)??null,thinking:i.modelChoice?.thinking??null,toolSelection:f,envFile:yr},vr={forkSessionFile:Be??null,skills:g,extensions:h,projectTrusted:i.projectTrusted!==!1},Sr={projectTrusted:i.projectTrusted!==!1},Ge=ti(c,wr,vr,Sr),kr=ni(c,Ge);for(let k of m)e.ui.notify(`[cowboy] ${k}`,"warning");return{name:b,cwd:a,systemPrompt:Ue,piArgs:kr,launch:Ge,harness:c}}s(In,"buildLaunchPlan");var Me="Agent manager disposed before the queued agent could start.";function Cn(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}s(Cn,"createRun");function Ln(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(Ln,"startRun");function Tn(t){return t.shell==="dropped"||t.process.kind!=="launching"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt},shell:t.shell}}s(Tn,"activateRun");function Fn(t,e,n){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"stopped",initiator:e},completedAt:n},shell:t.shell}}s(Fn,"abortQueuedRun");function On(t,e,n){return t.shell!=="held"?t:t.process.kind==="queued"?{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:e},completedAt:n},shell:t.shell}:t.process.kind==="launching"?{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:{kind:"failed",error:e},completedAt:n},shell:t.shell}:t}s(On,"failStart");function ye(t,e,n){return t.shell==="dropped"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:{kind:"settling",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,terminal:e,completedAt:n},shell:"held"}}s(ye,"enterSettling");function jn(t){return t.shell!=="held"||t.process.kind!=="settling"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:t.process.terminal,completedAt:t.process.completedAt},shell:t.shell}}s(jn,"finishSettling");function Hn(t,e){return t.shell!=="held"||t.process.kind!=="settled"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(Hn,"handoverRun");function Mn(t,e){return t.shell!=="held"||t.process.kind!=="settling"&&t.process.kind!=="settled"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}s(Mn,"reviveRun");function Dn(t,e){return{process:{kind:"active",queuedAt:t,startedAt:e},shell:"held"}}s(Dn,"activeRun");function $n(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:Me},completedAt:e},shell:t.shell}}s($n,"disposeQueuedRun");function Nn(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}s(Nn,"disposeLiveRun");function De(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:$e(t,e)}}s(De,"dropRun");function En(t,e,n,{launch:r,retention:i}){let o={phase:"settled",startedAt:t,...r===void 0?{}:{launch:r},...i===void 0?{}:{worktreeRetentionReason:i}};switch(e.kind){case"completed":return{...o,status:"completed",result:e.result,completedAt:n};case"failed":return{...o,status:"error",error:e.error,completedAt:n};case"stopped":return{...o,status:"stopped",completedAt:n,stop:{initiator:e.initiator}}}}s(En,"settledStartedOutcome");function ai(t,e,n,{retention:r}){let i={phase:"never-started",queuedAt:t,...r===void 0?{}:{worktreeRetentionReason:r}};switch(e.kind){case"failed":return{...i,status:"error",error:e.error,completedAt:n};case"stopped":return{...i,status:"stopped",completedAt:n,stop:{initiator:e.initiator}}}}s(ai,"settledNeverStartedOutcome");function di(t,e){switch(t.kind){case"queued":return{phase:"queued",queuedAt:t.queuedAt};case"launching":case"active":return{phase:"spawned",startedAt:t.startedAt,...e.launch===void 0?{}:{launch:e.launch}};case"settling":return En(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?En(t.startedAt,t.terminal,t.completedAt,e):ai(t.queuedAt,t.terminal,t.completedAt,e)}}s(di,"projectProcess");function $e(t,e){return t.shell==="dropped"?t.lifecycle:di(t.process,e)}s($e,"projectLifecycle");import*as qn from"node:fs";import*as _n from"node:path";function Wn(t){let{spawn:e,hostRef:n,transport:r}=t,i=li(e),o=_n.dirname(i.resultFile);oe(o),qn.rmSync(i.resultFile,{force:!0});let a=X({host:r.createHost(E()),resultFile:i.resultFile,supervisorOptions:t.supervisorOptions,transport:r});a.adopt(n),t.attachSupervisor(a,i),t.rebindParentSignal()}s(Wn,"reviveSettledRun");function li(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??C(t.id)}}s(li,"resumeLaunch");var J=L("session");function ui(t,e){let{type:n,options:r}=t;return{id:"",lifecycle:{phase:"queued",queuedAt:Date.now()},display:{type:n,description:r.description,taskSlug:r.taskSlug,invocation:{...r.invocation,runInBackground:r.isBackground??!0},orchestration:r.orchestration,worktree:r.worktree},execution:{promise:e,abortController:new AbortController,host:r.hostRef,modelKey:D(r.modelChoice),history:[]}}}s(ui,"buildAgentSpawn");function ci(t){if(t.shell==="dropped")return;let e=t.process;if(e.kind!=="queued"&&!(e.kind==="settled"&&!e.started))return e.startedAt}s(ci,"startedAtOf");function pi(t){if(t.lifecycle.phase!=="spawned")throw new Error(`agent ${t.id} is not a started run, so it cannot be attached`);return t.lifecycle.startedAt}s(pi,"existingStartedAt");function gi(t){let{lifecycle:e}=t;return e.phase==="queued"||e.phase==="never-started"?e.queuedAt:e.startedAt}s(gi,"existingQueueTime");function fi(t,e){return{pi:E(),ctx:$(),type:t.display.type,prompt:"",options:{spawnId:t.id,description:t.display.description,taskSlug:t.display.taskSlug,orchestration:t.display.orchestration,worktree:t.display.worktree,hostRef:t.execution.host,harness:e}}}s(fi,"attachArgs");var Ne=class{static{s(this,"CompletionGate")}resolve;promise;constructor(){this.promise=new Promise(e=>{this.resolve=e})}open(e){let n=this.resolve;n&&(this.resolve=void 0,n(e))}};function O(t){return{kind:"faulted",fault:t}}s(O,"faulted");var ee=class t{static{s(this,"SubagentSession")}id;args;deps;gate=new Ne;stableSpawn;run;launchState;retention;supervisor;parentBinding;constructor({id:e,args:n,deps:r,existing:i}){if(this.id=e,this.args=n,this.deps=r,i!==void 0){this.stableSpawn=i,this.run=Dn(gi(i),pi(i));return}this.stableSpawn=ui(n,this.gate.promise),this.stableSpawn.id=e;let o=this.stableSpawn.lifecycle;this.run=Cn(o.phase==="queued"?o.queuedAt:Date.now()),I().add(this.stableSpawn),this.bindParentSignal()}static attach(e){let{spawn:n,deps:r}=e,i=n.execution.host;if(i===void 0||n.lifecycle.phase!=="spawned")throw new Error(`agent ${n.id} is not a started run in a known pane, so it cannot be attached`);let o=new t({id:n.id,args:fi(n,e.harness),deps:r,existing:n});n.execution.spawnCtx??=$(),o.launchState=n.lifecycle.launch;let a=X({host:r.transport.createHost(E()),resultFile:o.resultFilePath(),supervisorOptions:o.supervisorOptions(),transport:r.transport});return a.adopt(i),o.beginWatch(a,o.run),o}get spawn(){return this.stableSpawn}get promise(){return this.gate.promise}isQueued(){return this.run.shell==="held"&&this.run.process.kind==="queued"}isLaunching(){return this.run.shell!=="dropped"&&this.run.process.kind==="launching"}isActive(){return this.run.shell!=="dropped"&&this.run.process.kind==="active"}isSettled(){return this.run.shell==="held"&&(this.run.process.kind==="settling"||this.run.process.kind==="settled")}commit(e){this.run=e,this.spawn.lifecycle=$e(e,this.artifacts),I().save(this.spawn)}harnessId(){return this.spawn.execution.harness??this.args.options.harness}get artifacts(){return{launch:this.launchState,retention:this.retention}}start(e){this.isQueued()&&(e&&this.deps.pools.reserve(this.id,e),this.commit(Ln(this.run,Date.now())),this.launch())}rollbackStart(){this.commit(De(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(On(this.run,w(e),Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn)}async steer(e){if(this.isQueued())return{kind:"refused",reason:`agent ${this.id} is queued \u2014 it has no pane yet, so it cannot receive a message. Wait for a concurrency slot (or stop it).`};let n=this.spawn.execution.host;if(!n)return{kind:"refused",reason:this.isLaunching()?`agent ${this.id} is still starting up \u2014 its pane does not exist yet, so it cannot receive a message. Retry in a moment.`:this.spawn.lifecycle.phase==="never-started"?`agent ${this.id} never started, so it has no pane and there is nobody to receive the message.`:`agent ${this.id} has no pane (it was cleaned up), so there is nobody to receive the message.`};let r=this.isSettled(),i=this.harnessId(),o=i===void 0?void 0:P().get(i);if(!o)return{kind:"refused",reason:`agent ${this.id} runs harness "${i??"unknown"}", which this session has not registered, so there is no route to send a message.`};let a;try{a=await o.steer({pi:this.args.pi,pane:this.deps.transport.createPane(E()),paneId:n.paneId,message:e,signal:this.spawn.execution.abortController.signal})}catch(d){a={kind:"not-submitted",detail:w(d)}}if(a.kind==="not-submitted")return{kind:"refused",reason:`the message could not be delivered to agent ${this.id} \u2014 ${a.detail}`};if(r)try{this.revive(n)}catch(d){return{kind:"delivered-not-revived",reason:`the message reached its pane, but the agent could not be revived: ${w(d)}. No completion message will arrive \u2014 read the pane for the result.`}}return{kind:"delivered"}}revive(e){Wn({spawn:this.spawn,hostRef:e,transport:this.deps.transport,supervisorOptions:this.supervisorOptions(),attachSupervisor:s((n,r)=>{this.launchState=r,this.retention=void 0,this.beginWatch(n,Mn(this.run,Date.now()))},"attachSupervisor"),rebindParentSignal:s(()=>this.bindParentSignal(),"rebindParentSignal")})}beginWatch(e,n){this.supervisor!==e&&this.supervisor?.detach(),this.deps.pools.reacquire(this.id,{harness:this.harnessId()??this.args.options.harness,modelKey:this.spawn.execution.modelKey}),this.supervisor=e,n!==this.run&&this.commit(n),e.watch().then(r=>this.applySupervisorOutcome(e,r)).catch(r=>{J.warn("run watch failed",{spawnId:this.id,detail:w(r)})})}async abort(e){let n=this.isLaunching()||this.isActive(),r=this.run;return J.debug("abort requested",{initiator:e,process:r.shell==="dropped"?"dropped":r.process.kind,shell:r.shell,stopIssued:n}),this.isQueued()?(this.deps.pools.cancelQueued(this.id),this.commit(Fn(this.run,e??"agent",Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn),!0):!this.isLaunching()&&!this.isActive()||(this.spawn.execution.abortController.abort(),await this.stopPaneProcess(),!this.isLaunching()&&!this.isActive())?!1:(this.commit(ye(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}readTarget(){let e=this.spawn.execution.harness,n=this.spawn.execution.host,r=ci(this.run);return e===void 0||n===void 0||r===void 0?O({kind:"never-started"}):{kind:"ready",from:e,ref:n,cwd:this.args.options.worktree?.path??this.args.ctx.cwd,startedAt:r}}handoverSource(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settled")return O({kind:"agent-not-settled",status:H(this.spawn.lifecycle)});if(!e.process.started)return O({kind:"never-started"});let n=this.readTarget();return n.kind==="faulted"?n:{...n,settled:e}}exportSource(){let e=this.run;return e.shell!=="held"?O({kind:"agent-not-settled",status:H(this.spawn.lifecycle)}):e.process.kind==="queued"||e.process.kind==="settled"&&!e.process.started?O({kind:"never-started"}):this.readTarget()}async readRunSession(e){return await ut(P(),e.from,{pi:this.args.pi,subagentId:this.id,paneId:e.ref.paneId,cwd:e.cwd,startedAt:e.startedAt,staged:{systemPromptFile:re(this.id),taskFile:ie(this.id),resultFile:C(this.id)}},{maxExcludedRatio:A().agent.handoverMaxExcludedRatio})}handoverTask(e,n,r){return ct({taskSlug:this.spawn.display.taskSlug,sourceName:P().displayName(e.from),previous:this.spawn.execution.history.map(({harness:i,sessionId:o})=>({harness:i,sessionId:o})),current:{harness:e.from,sessionId:n},session:r})}async handover(e){let n=this.handoverSource();if(n.kind==="faulted")return n;let{from:r,ref:i,cwd:o,settled:a}=n,d=await this.readRunSession(n);if(d.kind==="faulted")return d;if(this.run!==a)return O({kind:"agent-not-settled",status:H(this.spawn.lifecycle)});let l;try{l=await this.stopHarnessProcess(i,12e3)}catch(g){return O({kind:"stop-failed",detail:w(g)})}if(!l)return O({kind:"stop-failed",detail:"the source process did not confirm it was gone"});this.supervisor?.detach(),this.supervisor=void 0;try{await P().require(r).teardown({pi:this.args.pi,paneId:i.paneId,cwd:o,subagentId:this.id})}catch(g){return O({kind:"launch-failed",detail:`source harness teardown failed: ${w(g)}`})}an(this.resultFilePath());let c=this.handoverTask(n,d.sessionId,d.session);if(pn(this.spawn.execution,{harness:r,host:i,cwd:o,sessionId:d.sessionId,startedAt:n.startedAt,endedAt:Date.now()}),this.args.prompt=c,this.args.options.harness=e.harness,this.args.options.modelChoice=e.modelChoice,this.launchState=void 0,this.retention=void 0,this.deps.pools.reacquire(this.id,{harness:e.harness,modelKey:D(e.modelChoice)}),this.commit(Hn(this.run,Date.now())),this.bindParentSignal(),await this.launch({kind:"handover"}),!this.isActive()){let g=this.spawn.lifecycle;return O({kind:"launch-failed",detail:g.phase==="settled"&&g.status==="error"?g.error:"the next run did not start"})}return{kind:"handed-over",from:r,to:e.harness,...d.loss===void 0?{}:{loss:d.loss}}}async exportHandover(){let e=this.exportSource();if(e.kind==="faulted")return e;let n=await this.readRunSession(e);return n.kind==="faulted"?n:Yt({worktree:Qt(this.spawn.display.worktree,this.spawn.id),harness:e.from,sessionId:n.sessionId,text:this.handoverTask(e,n.sessionId,n.session),...n.loss===void 0?{}:{loss:n.loss}})}drop(){this.commit(De(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,Y(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit($n(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(Nn(this.run)),this.gate.open("")),this.supervisor?.abandon(),this.supervisor=void 0,this.detachParentBinding()}async launch(e={kind:"spawn"}){let n={kind:"none"},r={kind:"none"},i={confirmed:!0},o;try{let a=this.deps.transport.createHost(this.args.pi),d=this.deps.transport.createPane(this.args.pi),{pi:l,ctx:c,type:g,prompt:m,options:p}=this.args,h=e.kind==="spawn"?p.hostRef:void 0;if(e.kind==="spawn"&&!h&&p.worktree?.kind==="owned"){let S;try{S=await zt({pi:l,host:a,parentCwd:c.cwd,spawnId:this.spawn.id,agentType:g,taskSlug:p.taskSlug,worktreeRoot:A().agent.worktreeRoot,materialization:kt(),notify:s((R,ne)=>c.ui.notify(R,ne),"notify")})}catch(R){throw p.worktree=void 0,this.spawn.display.worktree=void 0,R}p.worktree=S.kind==="owned"?{kind:"owned",...S.worktree}:void 0,this.spawn.display.worktree=p.worktree,h=S.kind==="owned"?S.hostRef:void 0}let y=Vt(p.worktree===void 0?{kind:"parent-cwd",type:g,taskSlug:p.taskSlug,id:this.id}:{kind:"checkout",branch:p.worktree.branch}),f=await In(l,c,g,m,{agentId:this.id,harness:p.harness,modelChoice:p.modelChoice,fork:p.fork,cwd:p.worktree?.path,projectTrusted:p.projectTrusted,description:p.description,worktree:p.worktree,agentGuidance:p.orchestration.guidance}),x={resultFile:f.launch.resultFile};this.launchState=x,o=f.cwd;let v=P(),b=v.require(f.harness);if(!h){let S=p.worktree;h=await a.hostAt({unit:"pane",cwd:f.cwd,label:p.taskSlug??g,name:y,...S===void 0?{}:{checkout:{path:S.path,repoCwd:await Q(l,S.path),branch:S.branch}}})}if(n={kind:"held",host:a,ref:h},!this.isLaunching())return;un(this.spawn.execution,h),cn(this.spawn.execution,f.harness),await b.prepare({pi:l,pane:d,paneId:h.paneId,cwd:f.cwd,launch:f.launch,config:v.config(f.harness)});let T=X({host:a,resultFile:x.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=T,await T.start({name:h.name,cwd:f.cwd,piArgs:f.piArgs,agentMultiplexerKind:b.agentMultiplexerKind,taskSlug:p.taskSlug},h),!this.isLaunching()||this.launchAborted())return;if(b.postStart)try{await b.postStart({pi:l,pane:d,paneId:h.paneId,cwd:f.cwd,launch:f.launch,config:v.config(f.harness),signal:this.spawn.execution.abortController.signal})}catch(S){throw this.launchAborted()||(i.confirmed=await T.stop(2e3),i.confirmed||(n={kind:"committed"})),S}if(n={kind:"committed"},!this.isLaunching()||this.launchAborted())return;this.beginWatch(T,Tn(this.run))}catch(a){r={kind:"failed",error:a}}finally{n.kind==="held"&&await n.host.release(n.ref,"placement").catch(()=>{})}if(r.kind==="failed"&&this.isLaunching()){let a=this.spawn.execution.harness;if(a!==void 0&&i.confirmed)try{await P().require(a).teardown({pi:this.args.pi,paneId:this.spawn.execution.host?.paneId??null,cwd:o??null,subagentId:this.spawn.id})}catch(d){J.warn("harness teardown failed after a failed launch",{spawnId:this.spawn.id,harness:a,error:w(d)})}this.commit(ye(this.run,{kind:"failed",error:w(r.error)},Date.now())),await this.settle()}}launchAborted(){return this.spawn.execution.abortController.signal.aborted}supervisorOptions(){return{stopInitiator:"agent",stopProcess:s((e,n)=>this.stopHarnessProcess(e,n),"stopProcess"),onFollowUp:s(e=>this.deps.onFollowUpResult(this.spawn,e),"onFollowUp")}}async stopHarnessProcess(e,n){let r=this.spawn.execution.harness??this.args.options.harness;try{await P().require(r).stop({pi:this.args.pi,pane:this.deps.transport.createPane(this.args.pi),paneId:e.paneId})}catch(i){J.debug("harness stop failed",{harness:r,paneId:e.paneId,detail:w(i)})}return this.deps.transport.createHost(this.args.pi).waitUntilGone(e,{timeoutMs:n})}resultFilePath(){return this.launchState?.resultFile??C(this.id)}async applySupervisorOutcome(e,n){if(!(!this.isActive()||this.supervisor!==e))switch(J.debug("outcome mapped",{kind:n.kind}),n.kind){case"completed":{this.commit(ye(this.run,{kind:"completed",result:n.deliverable||""},Date.now())),await this.settle();return}case"stopped":await this.abort(n.initiator)}}async stopPaneProcess(){let e=this.supervisor;if(e){this.supervisor=void 0,await e.stop(2e3);return}let n=this.spawn.execution.host;n&&await this.stopHarnessProcess(n,12e3)}settleChain=Promise.resolve();async settle(){if(this.run.shell!=="held"||this.run.process.kind!=="settling")return;let e=this.settleChain,n,r=new Promise(i=>{n=i});this.settleChain=r,await e;try{await this.runSettlePass()}finally{n()}}async runSettlePass(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settling")return;let n=lt(this.spawn.lifecycle),r=await this.readWorktreeRetention();this.deps.pools.release(this.id),this.deps.onRunEnded(this.spawn),this.run===e&&this.detachParentBinding(),this.gate.open(n),this.run===e&&(this.retention=r??void 0,this.commit(jn(this.run)))}async readWorktreeRetention(){let e=this.spawn.display.worktree;return e?.kind!=="owned"?null:Tt(E(),e.path)}detachParentBinding(){let e=this.parentBinding;e&&(this.parentBinding=void 0,e.signal.removeEventListener("abort",e.handler))}bindParentSignal(){if(this.parentBinding)return;let e=this.args.options.signal;if(!e||e.aborted)return;let n=s(()=>{J.debug("parent signal fired",{initiator:"user"}),this.abort("user")},"handler");e.addEventListener("abort",n,{once:!0}),this.parentBinding={signal:e,handler:n}}};function Bn(t){return{createHost:s(()=>t.host,"createHost"),createPane:s(()=>t.pane,"createPane"),createPlacements:s(()=>t.placements,"createPlacements"),createDeliverable:s(e=>new ge(e),"createDeliverable")}}s(Bn,"createAgentManagerTransport");var qe=L("manager");function Un(t){return{kind:"faulted",fault:{kind:"request-refused",detail:t}}}s(Un,"handoverRefused");function hi(t){if(t.outcome.kind==="refused"){let e=t.outcome.reason;return e.kind==="dirty"||e.kind==="unverifiable"?e:void 0}if(t.worktree.kind==="removal-failed")return{kind:"unverifiable",detail:`the removal was not confirmed (${t.worktree.detail})`}}s(hi,"retentionForReport");var we=class{constructor(e,n){this.transport=n;this.pools=e,this.registry=new ce({listAgents:s(()=>this.listAgents(W),"listAgents"),spawn:s((r,i,o)=>this.spawn(E(),$(),r,i,o),"spawn"),getSpawn:s(r=>this.getSpawn(r),"getSpawn"),findTaskAttempts:s(r=>this.transport.createHost(E()).findAttempts(r),"findTaskAttempts"),queuePosition:s(r=>this.pools.queuePosition(r),"queuePosition")})}transport;static{s(this,"AgentManager")}sessions=new Map;onComplete;onFollowUp;teardowns=new Map;handovers=new Map;pools;registry;getRegistry(){return this.registry}attachLiveSpawns(){for(let e of I().list(["spawned"]))this.sessions.has(e.id)||this.attachSpawn(e)}attachSpawn(e){let n=e.execution.harness;if(n===void 0||e.execution.host===void 0)return;let r;try{r=ee.attach({spawn:e,harness:n,deps:{transport:this.transport,pools:this.pools,onRunEnded:s(i=>this.notifyComplete(i),"onRunEnded"),onFollowUpResult:s((i,o)=>this.notifyFollowUp(i,o),"onFollowUpResult")}})}catch(i){qe.warn("spawn could not be attached",{spawnId:e.id,detail:w(i)});return}return this.sessions.set(e.id,r),r}setConcurrency(e){this.pools.setConcurrency(e)}setOnComplete(e){this.onComplete=e}setOnFollowUp(e){this.onFollowUp=e}mintSpawnId(){return I().mint()}spawn(e,n,r,i,o){let a=o.spawnId,{requestedHarness:d,...l}=o,c={...l,harness:_t(r,d)},g={pi:e,ctx:n,type:r,prompt:i,options:c},m=this.pools.admitSpawn({harness:c.harness,modelKey:D(c.modelChoice)},{id:a,start:s(h=>this.startSession(a,g,h),"start")}),p;try{p=new ee({id:a,args:g,deps:{transport:this.transport,pools:this.pools,onRunEnded:s(h=>this.notifyComplete(h),"onRunEnded"),onFollowUpResult:s((h,y)=>this.notifyFollowUp(h,y),"onFollowUpResult")}})}catch(h){throw this.pools.release(a),h}if(this.sessions.set(a,p),c.signal?.aborted)return p.abort("user"),a;if(m.kind==="queue")return a;try{p.start(m.reservation)}catch(h){throw p.rollbackStart(),this.pools.release(a),this.sessions.delete(a),I().drop(a),h}return a}startSession(e,n,r){let i=this.sessions.get(e);if(!i||!i.isQueued())return!1;try{i.start(r)}catch(o){i.settleStartFailure(o)}return!0}async steer(e,n){if(this.handovers.has(e))return{kind:"refused",reason:"it is being handed over to another harness \u2014 wait for the handover to finish before steering it."};if(this.teardowns.has(e))return{kind:"refused",reason:"it is being cleaned up, so its worktree is on its way out \u2014 wait for the report before steering it."};let r=this.sessions.get(e);return r?r.steer(n):{kind:"refused",reason:"no live session tracks it \u2014 check the id from its spawn or completion result (a cleaned-up agent is gone for good)."}}isHandingOver(e){return this.handovers.has(e)}async handover(e,n){if(this.teardowns.has(e))return Un("it is being cleaned up \u2014 wait for the cleanup report before handing it over.");if(this.handovers.has(e))return Un("a handover is already in progress \u2014 wait for it to finish.");let r=this.sessions.get(e);if(!r)return{kind:"faulted",fault:{kind:"agent-unknown"}};let i=r.handover(n);this.handovers.set(e,i);try{return await i}finally{this.handovers.get(e)===i&&this.handovers.delete(e)}}async exportHandover(e){if(this.handovers.has(e))return{kind:"faulted",fault:{kind:"handover-in-progress",detail:"a handover is already in progress \u2014 wait for it to finish before exporting it."}};let n=this.sessions.get(e);return n?n.exportHandover():{kind:"faulted",fault:{kind:"agent-unknown"}}}getSpawn(e){return I().get(e)}assets(){let e=E();return he(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=at){return I().list(e).sort((n,r)=>Ie(r.lifecycle)-Ie(n.lifecycle))}async abort(e,n){return await this.sessions.get(e)?.abort(n)??!1}notifyComplete(e){try{this.onComplete?.(e)}catch(n){qe.warn("completion notification failed",{spawnId:e.id,detail:w(n)})}}notifyFollowUp(e,n){try{this.onFollowUp?.(e,n)}catch(r){qe.warn("follow-up notification failed",{spawnId:e.id,detail:w(r)})}}recordRetention(e,n){let r=e.lifecycle;V(r)&&(r.worktreeRetentionReason=n,I().save(e))}dropSpawn(e){this.sessions.get(e.id)?.drop(),this.sessions.delete(e.id),Y(C(e.id)),I().drop(e.id)}async cleanup(e,n){let r=this.runCleanup(e,this.teardowns.get(e),n);this.teardowns.set(e,r);try{return await r}finally{this.teardowns.get(e)===r&&this.teardowns.delete(e)}}async runCleanup(e,n,r){await n?.catch(()=>{}),await this.handovers.get(e)?.catch(()=>{}),le()?.dropNudge(e);let i=this.getSpawn(e)!==void 0,o=await Kt(this.assets()).cleanupAgent(e,{getSpawn:s(d=>this.getSpawn(d),"getSpawn"),dropSpawn:s(d=>this.dropSpawn(d),"dropSpawn")},r),a=this.getSpawn(e);if(a!==void 0){let d=hi(o);d!==void 0&&this.recordRetention(a,d)}return i&&o.outcome.kind==="torn-down"&&Y(C(e)),o}dispose(){this.pools.clearQueue();for(let e of this.sessions.values())e.settleForDispose();this.sessions.clear()}};var mi=200,ve=class{static{s(this,"SpawnCoordinator")}manager;pendingNudges=new Set;pendingFollowUps=new Map;nudgeTimer=null;disposed=!1;registry;constructor(e){this.manager=e,this.registry=e.getRegistry()}async spawn(e,n){let r=await this.registry.admit(n);if(r.status==="rejected")throw await this.inFlightError(n.taskSlug,r);let i=r.agentId,o=this.manager.getSpawn(i);return o.execution.spawnCtx=e,this.announceSpawn(e,o),n.runInBackground||await o.execution.promise,{agentId:i,spawn:o}}announceSpawn(e,n){if(!e.hasUI)return;let r=n.lifecycle;if(V(r))return;let i=r.phase==="queued"?"Queued":"Spawned";Jt(e.ui).succeeded(`${i} agent ${n.id} (${n.display.type})`)}async inFlightError(e,n){let r=this.manager.getSpawn(n.conflictingId);if(r)return new N({kind:"spawn",spawn:r},e);let i=await z().host.findAttempts(e),o=pe([],i);if(o.kind!=="none")return new N(o,e);let a={name:n.conflictingId};return new N({kind:"multiplexer",attempt:a},e)}dropNudge(e){this.pendingNudges.delete(e),this.pendingFollowUps.delete(e)}scheduleNudge(e){this.pendingNudges.add(e),this.ensureNudgeTimer()}onAgentFollowUp(e,n){Gn(e)&&(this.pendingFollowUps.set(e.id,n),this.ensureNudgeTimer())}ensureNudgeTimer(){this.nudgeTimer||(this.nudgeTimer=setTimeout(()=>{this.nudgeTimer=null;let e=[...this.pendingNudges];this.pendingNudges.clear();let n=[...this.pendingFollowUps];this.pendingFollowUps.clear();for(let r of e)this.emitIndividualNudge(r);for(let[r,i]of n)this.emitFollowUp(r,i)},mi))}onAgentComplete(e){Gn(e)&&(yi(e)||this.scheduleNudge(e.id))}dispose(){this.nudgeTimer&&(clearTimeout(this.nudgeTimer),this.nudgeTimer=null),this.pendingNudges.clear(),this.pendingFollowUps.clear(),this.disposed=!0}emitFollowUp(e,n){if(this.disposed||!U())return;let r=E(),i=this.manager.getSpawn(e);if(!i)return;let o=Le(i,{includeRunInfo:!0,includeStatus:!0}),a=`[Cowboy agent "${i.display.type}" ${i.id} reported again after settling]`;try{r.sendMessage({customType:"subagent-result",content:`${a}
30
+ `),t)}i(An,"stageLaunchEnv");function zr(t,e){let n=e?.inlinedSkills??[];return t===!1||Array.isArray(t)||n.length>0?{kind:"none"}:{kind:"default"}}i(zr,"resolveSkillMode");function Qr(t,e,n){let r=new Map,s=i((o,a)=>{let d=o.toLowerCase(),l=r.get(d);l===void 0?r.set(d,a):l!==a&&r.set(d,null)},"addSource");for(let o of e.packages){let a=typeof o=="string"?o:o.source,d=Pn(a);d&&s(d,a)}for(let o of e.extensionPaths){let a=Pn(o);a&&s(a,o)}return t.map(o=>{if(Yr(o)||Xr(o,n))return o;let a=Zr(o),d=r.get(a.toLowerCase());if(d===null)throw new Error(`Extension entry "${o}" is ambiguous in pi settings; more than one source matches its name. The agent did not start.`);if(d===void 0)throw new Error(`Extension entry "${o}" is not in the pi settings and is not an npm:, git:, or path source. The agent did not start.`);return d})}i(Qr,"resolveExtensionSources");function Yr(t){return t.startsWith("npm:")||t.startsWith("git:")}i(Yr,"isPiExtensionSource");function Xr(t,e){return _.isAbsolute(t)?He.existsSync(t):He.existsSync(_.resolve(e,t))}i(Xr,"isExistingPath");function Zr(t){let e=t.indexOf("/");return(e===-1?t:t.slice(0,e)).toLowerCase()}i(Zr,"extensionEntryName");function Pn(t){let e=t.split("#",1)[0].replace(/[\\/]$/,"");if(!e)return;if(e.startsWith("npm:")){let o=e.slice(4);return(o.startsWith("@")?o.split("/",2).at(1)?.split("@",1)[0]:o.split("@",1)[0])?.toLowerCase()}let n=e.startsWith("git:")?e.slice(4):e,r=_.basename(n),s=_.basename(r,_.extname(r));return s==="index"?_.basename(_.dirname(n))||void 0:s||void 0}i(Pn,"extensionSourceName");function Rn(t,e){throw t.ui.notify(`[cowboy] ${e}`,"error"),new Error(e)}i(Rn,"notifyLaunchConfigurationError");function es(t){let e=t,n=e.sessionFile??e.sessionManager?.getSessionFile?.();if(n)return n}i(es,"resolveParentSessionFile");function xn(t,e){let n=new Set;for(let r of t){if(!r)throw new Error(`Empty entry in ${e} is not supported`);n.add(r)}return[...n]}i(xn,"resolveToolCliEntries");function ts(t,e,n,r){let s=P();switch(s.family(t)){case"pi":return{...e,family:"pi",...n};case"opencode":return{...e,family:"opencode"};case"codex":return{...e,family:"codex",...r};case"claude":return{...e,family:"claude"};case void 0:{if(s.get(t)===void 0)throw new Error(`no harness registered for "${t}"`);return{...e,family:"plugin"}}}}i(ts,"buildLaunchRequest");function ns(t,e){return P().require(t).buildArgs(e)}i(ns,"buildHarnessArgs");function rs(t,e,n,r,s,o,a){let d=ae(e,n),l=d===void 0?void 0:ft(ss(d,s,o,a)),c=In(r,"inherited",o,a);return ae(ae(In(t,"default",o,a),l),c)}i(rs,"resolveLaunchEnv");function ss(t,e,n,r){let s={};for(let[o,a]of Object.entries(t)){if(!e.includes(o)){s[o]=a;continue}n(`Ignoring environment variable ${o} for ${r}: it is reserved by the ${r} harness and cannot be overridden`)}return s}i(ss,"dropReserved");var is={name:"not a valid environment variable name",reserved:"reserved","not-string":"not a string",control:"carrying a control character"};function In(t,e,n,r){if(t===void 0)return;let s=ht(t,{reserved:[],report:i((o,a)=>n(`Ignoring ${e} environment variable ${o} for ${r}: it is ${is[a]} and cannot be carried`),"report")});return Object.keys(s).length===0?void 0:s}i(In,"ownEnvOverrides");function os(t,e){return[...t===void 0?[]:it[t],...e===void 0?[]:st(e)]}i(os,"familyReservations");async function En(t,e,n,r,s){let o=A(),a=s.cwd??e.cwd,d=$t(n,o.agent.loadSkillsImplicitly,o.agent.loadExtensionsImplicitly),l=Dt(n),c=s.harness,g=zr(d.skills,l),m=[],p=i(k=>{m.push(k)},"bufferNotify"),f={kind:"default"};if(d.extensions===!1)f={kind:"none"};else if(Array.isArray(d.extensions))if(d.extensions.length===0)f={kind:"none"};else try{let k=Vr.create(a,F(),{projectTrusted:s.projectTrusted!==!1});f={kind:"paths",paths:Qr(d.extensions,{packages:k.getPackages(),extensionPaths:k.getExtensionPaths()},a)}}catch(k){let Re=k instanceof Error?k.message:String(k);Rn(e,Re)}let y=P().family(c),h={kind:"default"};try{let k=y===void 0?void 0:l?.toolsByFamily?.[y];k?.tools===!1?h={kind:"none"}:Array.isArray(k?.tools)?h={kind:"include",names:xn(k.tools,"tools")}:k?.excludeTools?.length&&(h={kind:"exclude",names:xn(k.excludeTools,"excludeTools")})}catch(k){let Re=k instanceof Error?k.message:String(k);Rn(e,Re)}let R=P().get(c),v=rs(R?.defaultEnv?.(),o.harnessEnv(c),y===void 0?void 0:l?.envByFamily?.[y],R?.inheritedEnv?.(),os(y,R),p,c),b=s.agentId??"unknown",L=Ke(b);oe(L);let S=C(b),x=re(b),ne=se(b),yr=An(Ve(b),v),Be=await bn({pi:t,ctx:e,type:n,agentConfig:l,config:d,cwd:a,globalSystemPromptMode:o.agent.systemPromptMode,globalIncludeContextFiles:o.agent.includeContextFiles,worktreePath:s.worktree?.path,expectedBranch:s.worktree?.branch,agentGuidance:s.agentGuidance,resultFile:S,notify:p});try{K(x,Be)}catch(k){throw new Error(`cannot write the system prompt file ${x}: ${w(k)}. The agent did not start.`,{cause:k})}if(!He.existsSync(x))throw new Error(`the system prompt file is missing after the write: ${x}. The agent did not start.`);K(ne,r);let Ge=s.fork?es(e):void 0;s.fork&&Ge===void 0&&p("Fork session is enabled, but no parent session file is available; launching without --fork");let wr={subagentId:b,systemPromptFile:x,taskFile:ne,resultFile:S,modelKey:D(s.modelChoice)??null,thinking:s.modelChoice?.thinking??null,toolSelection:h,envFile:yr},vr={forkSessionFile:Ge??null,skills:g,extensions:f,projectTrusted:s.projectTrusted!==!1},Sr={projectTrusted:s.projectTrusted!==!1},Je=ts(c,wr,vr,Sr),kr=ns(c,Je);for(let k of m)e.ui.notify(`[cowboy] ${k}`,"warning");return{name:b,cwd:a,systemPrompt:Be,piArgs:kr,launch:Je,harness:c}}i(En,"buildLaunchPlan");var Me="Agent manager disposed before the queued agent could start.";function De(t){return{process:{kind:"queued",queuedAt:t},shell:"held"}}i(De,"createRun");function Tn(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(Tn,"startRun");function Ln(t){return t.shell==="dropped"||t.process.kind!=="launching"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt},shell:t.shell}}i(Ln,"activateRun");function Fn(t,e,n){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"stopped",initiator:e},completedAt:n},shell:t.shell}}i(Fn,"abortQueuedRun");function On(t,e,n){return t.shell!=="held"?t:t.process.kind==="queued"?{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:e},completedAt:n},shell:t.shell}:t.process.kind==="launching"?{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:{kind:"failed",error:e},completedAt:n},shell:t.shell}:t}i(On,"failStart");function ye(t,e,n){return t.shell==="dropped"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:{kind:"settling",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,terminal:e,completedAt:n},shell:"held"}}i(ye,"enterSettling");function jn(t){return t.shell!=="held"||t.process.kind!=="settling"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,startedAt:t.process.startedAt,started:!0,terminal:t.process.terminal,completedAt:t.process.completedAt},shell:t.shell}}i(jn,"finishSettling");function Hn(t,e){return t.shell!=="held"||t.process.kind!=="settled"?t:{process:{kind:"launching",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(Hn,"handoverRun");function Mn(t,e){return t.shell!=="held"||t.process.kind!=="settling"&&t.process.kind!=="settled"?t:{process:{kind:"active",queuedAt:t.process.queuedAt,startedAt:e},shell:t.shell}}i(Mn,"reviveRun");function as(t,e){return{process:{kind:"active",queuedAt:t,startedAt:e},shell:"held"}}i(as,"activeRun");function Dn(t){switch(t.phase){case"queued":return De(t.queuedAt);case"spawned":return as(t.startedAt,t.startedAt);case"settled":{let e=t.status==="completed"?{kind:"completed",result:t.result}:t.status==="error"?{kind:"failed",error:t.error}:{kind:"stopped",initiator:t.stop.initiator};return{process:{kind:"settled",queuedAt:t.startedAt,startedAt:t.startedAt,started:!0,terminal:e,completedAt:t.completedAt},shell:"held"}}case"never-started":{let e=t.status==="error"?{kind:"failed",error:t.error}:{kind:"stopped",initiator:t.stop.initiator};return{process:{kind:"settled",queuedAt:t.queuedAt,started:!1,terminal:e,completedAt:t.completedAt},shell:"held"}}}}i(Dn,"restoreRun");function $n(t,e){return t.shell!=="held"||t.process.kind!=="queued"?t:{process:{kind:"settled",queuedAt:t.process.queuedAt,started:!1,terminal:{kind:"failed",error:Me},completedAt:e},shell:t.shell}}i($n,"disposeQueuedRun");function qn(t){return t.shell!=="held"||t.process.kind!=="launching"&&t.process.kind!=="active"?t:{process:t.process,shell:"disposed"}}i(qn,"disposeLiveRun");function $e(t,e){return t.shell==="dropped"?t:{shell:"dropped",lifecycle:qe(t,e)}}i($e,"dropRun");function Cn(t,e,n,{launch:r,retention:s}){let o={phase:"settled",startedAt:t,...r===void 0?{}:{launch:r},...s===void 0?{}:{worktreeRetentionReason:s}};switch(e.kind){case"completed":return{...o,status:"completed",result:e.result,completedAt:n};case"failed":return{...o,status:"error",error:e.error,completedAt:n};case"stopped":return{...o,status:"stopped",completedAt:n,stop:{initiator:e.initiator}}}}i(Cn,"settledStartedOutcome");function ds(t,e,n,{retention:r}){let s={phase:"never-started",queuedAt:t,...r===void 0?{}:{worktreeRetentionReason:r}};switch(e.kind){case"failed":return{...s,status:"error",error:e.error,completedAt:n};case"stopped":return{...s,status:"stopped",completedAt:n,stop:{initiator:e.initiator}}}}i(ds,"settledNeverStartedOutcome");function ls(t,e){switch(t.kind){case"queued":return{phase:"queued",queuedAt:t.queuedAt};case"launching":case"active":return{phase:"spawned",startedAt:t.startedAt,...e.launch===void 0?{}:{launch:e.launch}};case"settling":return Cn(t.startedAt,t.terminal,t.completedAt,e);case"settled":return t.started?Cn(t.startedAt,t.terminal,t.completedAt,e):ds(t.queuedAt,t.terminal,t.completedAt,e)}}i(ls,"projectProcess");function qe(t,e){return t.shell==="dropped"?t.lifecycle:ls(t.process,e)}i(qe,"projectLifecycle");import*as Nn from"node:fs";import*as _n from"node:path";function Wn(t){let{spawn:e,hostRef:n,transport:r}=t,s=us(e),o=_n.dirname(s.resultFile);oe(o),Nn.rmSync(s.resultFile,{force:!0});let a=X({host:r.createHost(E()),resultFile:s.resultFile,supervisorOptions:t.supervisorOptions,transport:r});a.adopt(n),t.attachSupervisor(a,s),t.rebindParentSignal()}i(Wn,"reviveSettledRun");function us(t){let{lifecycle:e}=t;return{resultFile:(e.phase==="settled"?e.launch:void 0)?.resultFile??C(t.id)}}i(us,"resumeLaunch");var J=T("session");function cs(t,e){let{type:n,options:r}=t;return{id:"",lifecycle:{phase:"queued",queuedAt:Date.now()},display:{type:n,description:r.description,taskSlug:r.taskSlug,invocation:{...r.invocation,runInBackground:r.isBackground??!0},orchestration:r.orchestration,worktree:r.worktree},execution:{promise:e,abortController:new AbortController,host:r.hostRef,modelKey:D(r.modelChoice),history:[]}}}i(cs,"buildAgentSpawn");function ps(t){if(t.shell==="dropped")return;let e=t.process;if(e.kind!=="queued"&&!(e.kind==="settled"&&!e.started))return e.startedAt}i(ps,"startedAtOf");function gs(t,e){return{pi:E(),ctx:$(),type:t.display.type,prompt:"",options:{spawnId:t.id,description:t.display.description,taskSlug:t.display.taskSlug,orchestration:t.display.orchestration,worktree:t.display.worktree,hostRef:t.execution.host,harness:e}}}i(gs,"attachArgs");var Ne=class{static{i(this,"CompletionGate")}resolve;promise;constructor(){this.promise=new Promise(e=>{this.resolve=e})}open(e){let n=this.resolve;n&&(this.resolve=void 0,n(e))}};function O(t){return{kind:"faulted",fault:t}}i(O,"faulted");var ee=class t{static{i(this,"SubagentSession")}id;args;deps;gate=new Ne;stableSpawn;run;launchState;retention;supervisor;parentBinding;constructor({id:e,args:n,deps:r,existing:s}){if(this.id=e,this.args=n,this.deps=r,s!==void 0){let a=Dn(s.lifecycle);if(a===void 0)throw new Error(`agent ${s.id}'s recorded lifecycle cannot be restored`);this.stableSpawn=s,this.run=a;return}this.stableSpawn=cs(n,this.gate.promise),this.stableSpawn.id=e;let o=this.stableSpawn.lifecycle;this.run=De(o.phase==="queued"?o.queuedAt:Date.now()),I().add(this.stableSpawn),this.bindParentSignal()}static attach(e){let{spawn:n,deps:r}=e,s=n.execution.host;if(n.lifecycle.phase==="spawned"&&s===void 0)throw new Error(`agent ${n.id} is in flight but names no pane, so it cannot be attached`);let o=new t({id:n.id,args:gs(n,e.harness),deps:r,existing:n});if(n.execution.spawnCtx??=$(),o.launchState="launch"in n.lifecycle?n.lifecycle.launch:void 0,o.retention="worktreeRetentionReason"in n.lifecycle?n.lifecycle.worktreeRetentionReason:void 0,o.isActive()&&s!==void 0){let a=X({host:r.transport.createHost(E()),resultFile:o.resultFilePath(),supervisorOptions:o.supervisorOptions(),transport:r.transport});a.adopt(s),o.beginWatch(a,o.run)}return o}get spawn(){return this.stableSpawn}get promise(){return this.gate.promise}isQueued(){return this.run.shell==="held"&&this.run.process.kind==="queued"}isLaunching(){return this.run.shell!=="dropped"&&this.run.process.kind==="launching"}isActive(){return this.run.shell!=="dropped"&&this.run.process.kind==="active"}isSettled(){return this.run.shell==="held"&&(this.run.process.kind==="settling"||this.run.process.kind==="settled")}commit(e){this.run=e,this.spawn.lifecycle=qe(e,this.artifacts),I().save(this.spawn)}harnessId(){return this.spawn.execution.harness??this.args.options.harness}get artifacts(){return{launch:this.launchState,retention:this.retention}}start(e){this.isQueued()&&(e&&this.deps.pools.reserve(this.id,e),this.commit(Tn(this.run,Date.now())),this.launch())}rollbackStart(){this.commit($e(this.run,this.artifacts)),this.detachParentBinding(),this.gate.open("")}settleStartFailure(e){this.commit(On(this.run,w(e),Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn)}async steer(e){if(this.isQueued())return{kind:"refused",reason:`agent ${this.id} is queued \u2014 it has no pane yet, so it cannot receive a message. Wait for a concurrency slot (or stop it).`};let n=this.spawn.execution.host;if(!n)return{kind:"refused",reason:this.isLaunching()?`agent ${this.id} is still starting up \u2014 its pane does not exist yet, so it cannot receive a message. Retry in a moment.`:this.spawn.lifecycle.phase==="never-started"?`agent ${this.id} never started, so it has no pane and there is nobody to receive the message.`:`agent ${this.id} has no pane (it was cleaned up), so there is nobody to receive the message.`};let r=this.isSettled();r&&this.renewAbortController();let s=this.harnessId(),o=s===void 0?void 0:P().get(s);if(!o)return{kind:"refused",reason:`agent ${this.id} runs harness "${s??"unknown"}", which this session has not registered, so there is no route to send a message.`};let a;try{a=await o.steer({pi:this.args.pi,pane:this.deps.transport.createPane(E()),paneId:n.paneId,message:e,signal:this.spawn.execution.abortController.signal,staged:this.stagedPaths()})}catch(d){a={kind:"not-submitted",detail:w(d)}}if(a.kind==="not-submitted")return{kind:"refused",reason:`the message could not be delivered to agent ${this.id} \u2014 ${a.detail}`};if(r)try{this.revive(n)}catch(d){return{kind:"delivered-not-revived",reason:`the message reached its pane, but the agent could not be revived: ${w(d)}. No completion message will arrive \u2014 read the pane for the result.`}}return{kind:"delivered"}}revive(e){Wn({spawn:this.spawn,hostRef:e,transport:this.deps.transport,supervisorOptions:this.supervisorOptions(),attachSupervisor:i((n,r)=>{this.launchState=r,this.retention=void 0,this.beginWatch(n,Mn(this.run,Date.now()))},"attachSupervisor"),rebindParentSignal:i(()=>this.bindParentSignal(),"rebindParentSignal")})}beginWatch(e,n){this.supervisor!==e&&this.supervisor?.detach(),this.deps.pools.reacquire(this.id,{harness:this.harnessId()??this.args.options.harness,modelKey:this.spawn.execution.modelKey}),this.supervisor=e,n!==this.run&&this.commit(n),e.watch().then(r=>this.applySupervisorOutcome(e,r)).catch(r=>{J.warn("run watch failed",{spawnId:this.id,detail:w(r)})})}async abort(e){let n=this.isLaunching()||this.isActive(),r=this.run;return J.debug("abort requested",{initiator:e,process:r.shell==="dropped"?"dropped":r.process.kind,shell:r.shell,stopIssued:n}),this.isQueued()?(this.deps.pools.cancelQueued(this.id),this.commit(Fn(this.run,e??"agent",Date.now())),this.detachParentBinding(),this.gate.open(""),this.deps.onRunEnded(this.spawn),!0):!this.isLaunching()&&!this.isActive()||(this.spawn.execution.abortController.abort(),await this.stopPaneProcess(),!this.isLaunching()&&!this.isActive())?!1:(this.commit(ye(this.run,{kind:"stopped",initiator:e??"agent"},Date.now())),await this.settle(),!0)}readTarget(){let e=this.spawn.execution.harness,n=this.spawn.execution.host,r=ps(this.run);return e===void 0||n===void 0||r===void 0?O({kind:"never-started"}):{kind:"ready",from:e,ref:n,cwd:this.args.options.worktree?.path??this.args.ctx.cwd,startedAt:r}}handoverSource(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settled")return O({kind:"agent-not-settled",status:H(this.spawn.lifecycle)});if(!e.process.started)return O({kind:"never-started"});let n=this.readTarget();return n.kind==="faulted"?n:{...n,settled:e}}exportSource(){let e=this.run;return e.shell!=="held"?O({kind:"agent-not-settled",status:H(this.spawn.lifecycle)}):e.process.kind==="queued"||e.process.kind==="settled"&&!e.process.started?O({kind:"never-started"}):this.readTarget()}stagedPaths(){return{systemPromptFile:re(this.id),taskFile:se(this.id),resultFile:C(this.id)}}async readRunSession(e){return await ct(P(),e.from,{pi:this.args.pi,subagentId:this.id,paneId:e.ref.paneId,cwd:e.cwd,startedAt:e.startedAt,staged:this.stagedPaths()},{maxExcludedRatio:A().agent.handoverMaxExcludedRatio})}handoverTask(e,n,r){return pt({taskSlug:this.spawn.display.taskSlug,sourceName:P().displayName(e.from),previous:this.spawn.execution.history.map(({harness:s,sessionId:o})=>({harness:s,sessionId:o})),current:{harness:e.from,sessionId:n},session:r})}async handover(e){let n=this.handoverSource();if(n.kind==="faulted")return n;let{from:r,ref:s,cwd:o,settled:a}=n,d=await this.readRunSession(n);if(d.kind==="faulted")return d;if(this.run!==a)return O({kind:"agent-not-settled",status:H(this.spawn.lifecycle)});let l;try{l=await this.stopHarnessProcess(s,12e3)}catch(g){return O({kind:"stop-failed",detail:w(g)})}if(!l)return O({kind:"stop-failed",detail:"the source process did not confirm it was gone"});this.supervisor?.detach(),this.supervisor=void 0;try{await P().require(r).teardown({pi:this.args.pi,paneId:s.paneId,cwd:o,subagentId:this.id})}catch(g){return O({kind:"launch-failed",detail:`source harness teardown failed: ${w(g)}`})}dn(this.resultFilePath());let c=this.handoverTask(n,d.sessionId,d.session);if(gn(this.spawn.execution,{harness:r,host:s,cwd:o,sessionId:d.sessionId,startedAt:n.startedAt,endedAt:Date.now()}),this.args.prompt=c,this.args.options.harness=e.harness,this.args.options.modelChoice=e.modelChoice,this.launchState=void 0,this.retention=void 0,this.deps.pools.reacquire(this.id,{harness:e.harness,modelKey:D(e.modelChoice)}),this.commit(Hn(this.run,Date.now())),this.renewAbortController(),this.bindParentSignal(),await this.launch({kind:"handover"}),!this.isActive()){let g=this.spawn.lifecycle;return O({kind:"launch-failed",detail:g.phase==="settled"&&g.status==="error"?g.error:"the next run did not start"})}return{kind:"handed-over",from:r,to:e.harness,...d.loss===void 0?{}:{loss:d.loss}}}async exportHandover(){let e=this.exportSource();if(e.kind==="faulted")return e;let n=await this.readRunSession(e);return n.kind==="faulted"?n:Xt({worktree:Yt(this.spawn.display.worktree,this.spawn.id),harness:e.from,sessionId:n.sessionId,text:this.handoverTask(e,n.sessionId,n.session),...n.loss===void 0?{}:{loss:n.loss}})}drop(){this.commit($e(this.run,this.artifacts)),this.supervisor?.detach(),this.supervisor=void 0,Y(this.resultFilePath()),this.detachParentBinding(),this.gate.open("")}settleForDispose(){this.isQueued()?(this.commit($n(this.run,Date.now())),this.gate.open("")):(this.isLaunching()||this.isActive())&&(this.commit(qn(this.run)),this.gate.open("")),this.supervisor?.abandon(),this.supervisor=void 0,this.detachParentBinding()}async launch(e={kind:"spawn"}){let n={kind:"none"},r={kind:"none"},s={confirmed:!0},o;try{let a=this.deps.transport.createHost(this.args.pi),d=this.deps.transport.createPane(this.args.pi),{pi:l,ctx:c,type:g,prompt:m,options:p}=this.args,f=e.kind==="spawn"?p.hostRef:void 0;if(e.kind==="spawn"&&!f&&p.worktree?.kind==="owned"){let S;try{S=await Qt({pi:l,host:a,parentCwd:c.cwd,spawnId:this.spawn.id,agentType:g,taskSlug:p.taskSlug,worktreeRoot:A().agent.worktreeRoot,materialization:bt(),notify:i((x,ne)=>c.ui.notify(x,ne),"notify")})}catch(x){throw p.worktree=void 0,this.spawn.display.worktree=void 0,x}p.worktree=S.kind==="owned"?{kind:"owned",...S.worktree}:void 0,this.spawn.display.worktree=p.worktree,f=S.kind==="owned"?S.hostRef:void 0}let y=zt(p.worktree===void 0?{kind:"parent-cwd",type:g,taskSlug:p.taskSlug,id:this.id}:{kind:"checkout",branch:p.worktree.branch}),h=await En(l,c,g,m,{agentId:this.id,harness:p.harness,modelChoice:p.modelChoice,fork:p.fork,cwd:p.worktree?.path,projectTrusted:p.projectTrusted,description:p.description,worktree:p.worktree,agentGuidance:p.orchestration.guidance}),R={resultFile:h.launch.resultFile};this.launchState=R,o=h.cwd;let v=P(),b=v.require(h.harness);if(!f){let S=p.worktree;f=await a.hostAt({unit:"pane",cwd:h.cwd,label:p.taskSlug??g,name:y,...S===void 0?{}:{checkout:{path:S.path,repoCwd:await Q(l,S.path),branch:S.branch}}})}if(n={kind:"held",host:a,ref:f},!this.isLaunching())return;cn(this.spawn.execution,f),pn(this.spawn.execution,h.harness),await b.prepare({pi:l,pane:d,paneId:f.paneId,cwd:h.cwd,launch:h.launch,config:v.config(h.harness)});let L=X({host:a,resultFile:R.resultFile,supervisorOptions:this.supervisorOptions(),transport:this.deps.transport});if(this.supervisor=L,await L.start({name:f.name,cwd:h.cwd,piArgs:h.piArgs,agentMultiplexerKind:b.agentMultiplexerKind,taskSlug:p.taskSlug},f),!this.isLaunching()||this.launchAborted())return;if(b.postStart)try{await b.postStart({pi:l,pane:d,paneId:f.paneId,cwd:h.cwd,launch:h.launch,config:v.config(h.harness),signal:this.spawn.execution.abortController.signal})}catch(S){throw this.launchAborted()||(s.confirmed=await L.stop(2e3),s.confirmed||(n={kind:"committed"})),S}if(n={kind:"committed"},!this.isLaunching()||this.launchAborted())return;this.beginWatch(L,Ln(this.run))}catch(a){r={kind:"failed",error:a}}finally{n.kind==="held"&&await n.host.release(n.ref,"placement").catch(()=>{})}if(r.kind==="failed"&&this.isLaunching()){let a=this.spawn.execution.harness;if(a!==void 0&&s.confirmed)try{await P().require(a).teardown({pi:this.args.pi,paneId:this.spawn.execution.host?.paneId??null,cwd:o??null,subagentId:this.spawn.id})}catch(d){J.warn("harness teardown failed after a failed launch",{spawnId:this.spawn.id,harness:a,error:w(d)})}this.commit(ye(this.run,{kind:"failed",error:w(r.error)},Date.now())),await this.settle()}}launchAborted(){return this.spawn.execution.abortController.signal.aborted}renewAbortController(){this.spawn.execution.abortController=new AbortController}supervisorOptions(){return{stopInitiator:"agent",stopProcess:i((e,n)=>this.stopHarnessProcess(e,n),"stopProcess"),onFollowUp:i(e=>this.deps.onFollowUpResult(this.spawn,e),"onFollowUp")}}async stopHarnessProcess(e,n){let r=this.spawn.execution.harness??this.args.options.harness;try{await P().require(r).stop({pi:this.args.pi,pane:this.deps.transport.createPane(this.args.pi),paneId:e.paneId,staged:this.stagedPaths()})}catch(s){J.debug("harness stop failed",{harness:r,paneId:e.paneId,detail:w(s)})}return this.deps.transport.createHost(this.args.pi).waitUntilGone(e,{timeoutMs:n})}resultFilePath(){return this.launchState?.resultFile??C(this.id)}async applySupervisorOutcome(e,n){if(!(!this.isActive()||this.supervisor!==e))switch(J.debug("outcome mapped",{kind:n.kind}),n.kind){case"completed":{this.commit(ye(this.run,{kind:"completed",result:n.deliverable||""},Date.now())),await this.settle();return}case"stopped":await this.abort(n.initiator)}}async stopPaneProcess(){let e=this.supervisor;if(e){this.supervisor=void 0,await e.stop(2e3);return}let n=this.spawn.execution.host;n&&await this.stopHarnessProcess(n,12e3)}settleChain=Promise.resolve();async settle(){if(this.run.shell!=="held"||this.run.process.kind!=="settling")return;let e=this.settleChain,n,r=new Promise(s=>{n=s});this.settleChain=r,await e;try{await this.runSettlePass()}finally{n()}}async runSettlePass(){let e=this.run;if(e.shell!=="held"||e.process.kind!=="settling")return;let n=ut(this.spawn.lifecycle),r=await this.readWorktreeRetention();this.deps.pools.release(this.id),this.deps.onRunEnded(this.spawn),this.run===e&&this.detachParentBinding(),this.gate.open(n),this.run===e&&(this.retention=r??void 0,this.commit(jn(this.run)))}async readWorktreeRetention(){let e=this.spawn.display.worktree;return e?.kind!=="owned"?null:Ft(E(),e.path)}detachParentBinding(){let e=this.parentBinding;e&&(this.parentBinding=void 0,e.signal.removeEventListener("abort",e.handler))}bindParentSignal(){if(this.parentBinding)return;let e=this.args.options.signal;if(!e||e.aborted)return;let n=i(()=>{J.debug("parent signal fired",{initiator:"user"}),this.abort("user")},"handler");e.addEventListener("abort",n,{once:!0}),this.parentBinding={signal:e,handler:n}}};function Bn(t){return{createHost:i(()=>t.host,"createHost"),createPane:i(()=>t.pane,"createPane"),createPlacements:i(()=>t.placements,"createPlacements"),createDeliverable:i(e=>new ge(e),"createDeliverable")}}i(Bn,"createAgentManagerTransport");var _e=T("manager");function Un(t){return{kind:"faulted",fault:{kind:"request-refused",detail:t}}}i(Un,"handoverRefused");function hs(t){if(t.outcome.kind==="refused"){let e=t.outcome.reason;return e.kind==="dirty"||e.kind==="unverifiable"?e:void 0}if(t.worktree.kind==="removal-failed")return{kind:"unverifiable",detail:`the removal was not confirmed (${t.worktree.detail})`}}i(hs,"retentionForReport");var we=class{constructor(e,n){this.transport=n;this.pools=e,this.registry=new ce({listAgents:i(()=>this.listAgents(W),"listAgents"),spawn:i((r,s,o)=>this.spawn(E(),$(),r,s,o),"spawn"),getSpawn:i(r=>this.getSpawn(r),"getSpawn"),findTaskAttempts:i(r=>this.transport.createHost(E()).findAttempts(r),"findTaskAttempts"),queuePosition:i(r=>this.pools.queuePosition(r),"queuePosition")})}transport;static{i(this,"AgentManager")}sessions=new Map;onComplete;onFollowUp;teardowns=new Map;handovers=new Map;pools;registry;getRegistry(){return this.registry}attachSpawns(){let e={transport:this.transport,pools:this.pools,onRunEnded:i(n=>this.notifyComplete(n),"onRunEnded"),onFollowUpResult:i((n,r)=>this.notifyFollowUp(n,r),"onFollowUpResult")};for(let n of I().list()){if(this.sessions.has(n.id))continue;let r=n.execution.harness;if(r!==void 0)try{this.sessions.set(n.id,ee.attach({spawn:n,harness:r,deps:e}))}catch(s){_e.warn("spawn could not be attached",{spawnId:n.id,detail:w(s)})}}}setConcurrency(e){this.pools.setConcurrency(e)}setOnComplete(e){this.onComplete=e}setOnFollowUp(e){this.onFollowUp=e}mintSpawnId(){return I().mint()}spawn(e,n,r,s,o){let a=o.spawnId,{requestedHarness:d,...l}=o,c={...l,harness:Wt(r,d)},g={pi:e,ctx:n,type:r,prompt:s,options:c},m=this.pools.admitSpawn({harness:c.harness,modelKey:D(c.modelChoice)},{id:a,start:i(f=>this.startSession(a,g,f),"start")}),p;try{p=new ee({id:a,args:g,deps:{transport:this.transport,pools:this.pools,onRunEnded:i(f=>this.notifyComplete(f),"onRunEnded"),onFollowUpResult:i((f,y)=>this.notifyFollowUp(f,y),"onFollowUpResult")}})}catch(f){throw this.pools.release(a),f}if(this.sessions.set(a,p),c.signal?.aborted)return p.abort("user"),a;if(m.kind==="queue")return a;try{p.start(m.reservation)}catch(f){throw p.rollbackStart(),this.pools.release(a),this.sessions.delete(a),I().drop(a),f}return a}startSession(e,n,r){let s=this.sessions.get(e);if(!s||!s.isQueued())return!1;try{s.start(r)}catch(o){s.settleStartFailure(o)}return!0}async steer(e,n){if(this.handovers.has(e))return{kind:"refused",reason:"it is being handed over to another harness \u2014 wait for the handover to finish before steering it."};if(this.teardowns.has(e))return{kind:"refused",reason:"it is being cleaned up, so its worktree is on its way out \u2014 wait for the report before steering it."};let r=this.sessions.get(e);return r?r.steer(n):{kind:"refused",reason:"no live session tracks it \u2014 check the id from its spawn or completion result (a cleaned-up agent is gone for good)."}}isHandingOver(e){return this.handovers.has(e)}async handover(e,n){if(this.teardowns.has(e))return Un("it is being cleaned up \u2014 wait for the cleanup report before handing it over.");if(this.handovers.has(e))return Un("a handover is already in progress \u2014 wait for it to finish.");let r=this.sessions.get(e);if(!r)return{kind:"faulted",fault:{kind:"agent-unknown"}};let s=r.handover(n);this.handovers.set(e,s);try{return await s}finally{this.handovers.get(e)===s&&this.handovers.delete(e)}}async exportHandover(e){if(this.handovers.has(e))return{kind:"faulted",fault:{kind:"handover-in-progress",detail:"a handover is already in progress \u2014 wait for it to finish before exporting it."}};let n=this.sessions.get(e);return n?n.exportHandover():{kind:"faulted",fault:{kind:"agent-unknown"}}}getSpawn(e){return I().get(e)}assets(){let e=E();return fe(e,this.transport.createHost(e),this.transport.createPlacements(e))}async locate(e){return this.assets().locate(e,this.getSpawn(e))}listAgents(e=dt){return I().list(e).sort((n,r)=>Ie(r.lifecycle)-Ie(n.lifecycle))}async abort(e,n){return await this.sessions.get(e)?.abort(n)??!1}notifyComplete(e){try{this.onComplete?.(e)}catch(n){_e.warn("completion notification failed",{spawnId:e.id,detail:w(n)})}}notifyFollowUp(e,n){try{this.onFollowUp?.(e,n)}catch(r){_e.warn("follow-up notification failed",{spawnId:e.id,detail:w(r)})}}recordRetention(e,n){let r=e.lifecycle;V(r)&&(r.worktreeRetentionReason=n,I().save(e))}dropSpawn(e){this.sessions.get(e.id)?.drop(),this.sessions.delete(e.id),Y(C(e.id)),I().drop(e.id)}async cleanup(e,n){let r=this.runCleanup(e,this.teardowns.get(e),n);this.teardowns.set(e,r);try{return await r}finally{this.teardowns.get(e)===r&&this.teardowns.delete(e)}}async runCleanup(e,n,r){await n?.catch(()=>{}),await this.handovers.get(e)?.catch(()=>{}),le()?.dropNudge(e);let s=this.getSpawn(e)!==void 0,o=await Vt(this.assets()).cleanupAgent(e,{getSpawn:i(d=>this.getSpawn(d),"getSpawn"),dropSpawn:i(d=>this.dropSpawn(d),"dropSpawn")},r),a=this.getSpawn(e);if(a!==void 0){let d=hs(o);d!==void 0&&this.recordRetention(a,d)}return s&&o.outcome.kind==="torn-down"&&Y(C(e)),o}dispose(){this.pools.clearQueue();for(let e of this.sessions.values())e.settleForDispose();this.sessions.clear()}};var fs=200,ve=class{static{i(this,"SpawnCoordinator")}manager;pendingNudges=new Set;pendingFollowUps=new Map;nudgeTimer=null;disposed=!1;registry;constructor(e){this.manager=e,this.registry=e.getRegistry()}async spawn(e,n){let r=await this.registry.admit(n);if(r.status==="rejected")throw await this.inFlightError(n.taskSlug,r);let s=r.agentId,o=this.manager.getSpawn(s);return o.execution.spawnCtx=e,this.announceSpawn(e,o),n.runInBackground||await o.execution.promise,{agentId:s,spawn:o}}announceSpawn(e,n){if(!e.hasUI)return;let r=n.lifecycle;if(V(r))return;let s=r.phase==="queued"?"Queued":"Spawned";Kt(e.ui).succeeded(`${s} agent ${n.id} (${n.display.type})`)}async inFlightError(e,n){let r=this.manager.getSpawn(n.conflictingId);if(r)return new q({kind:"spawn",spawn:r},e);let s=await z().host.findAttempts(e),o=pe([],s);if(o.kind!=="none")return new q(o,e);let a={name:n.conflictingId};return new q({kind:"multiplexer",attempt:a},e)}dropNudge(e){this.pendingNudges.delete(e),this.pendingFollowUps.delete(e)}scheduleNudge(e){this.pendingNudges.add(e),this.ensureNudgeTimer()}onAgentFollowUp(e,n){Gn(e)&&(this.pendingFollowUps.set(e.id,n),this.ensureNudgeTimer())}ensureNudgeTimer(){this.nudgeTimer||(this.nudgeTimer=setTimeout(()=>{this.nudgeTimer=null;let e=[...this.pendingNudges];this.pendingNudges.clear();let n=[...this.pendingFollowUps];this.pendingFollowUps.clear();for(let r of e)this.emitIndividualNudge(r);for(let[r,s]of n)this.emitFollowUp(r,s)},fs))}onAgentComplete(e){Gn(e)&&(ms(e)||this.scheduleNudge(e.id))}dispose(){this.nudgeTimer&&(clearTimeout(this.nudgeTimer),this.nudgeTimer=null),this.pendingNudges.clear(),this.pendingFollowUps.clear(),this.disposed=!0}emitFollowUp(e,n){if(this.disposed||!U())return;let r=E(),s=this.manager.getSpawn(e);if(!s)return;let o=Te(s,{includeRunInfo:!0,includeStatus:!0}),a=`[Cowboy agent "${s.display.type}" ${s.id} reported again after settling]`;try{r.sendMessage({customType:"subagent-result",content:`${a}
31
31
 
32
- ${n}`,details:o,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let d=i.execution.spawnCtx;if(d)try{d.ui.notify(`${a} New report available`,"info")}catch{}}}emitIndividualNudge(e){if(this.disposed||!U())return;let n=E(),r=this.manager.getSpawn(e);if(!r)return;let i=Le(r,{includeRunInfo:!0,includeStatus:!0});try{n.sendMessage({customType:"subagent-result",content:`${Wt(r)}
32
+ ${n}`,details:o,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let d=s.execution.spawnCtx;if(d)try{d.ui.notify(`${a} New report available`,"info")}catch{}}}emitIndividualNudge(e){if(this.disposed||!U())return;let n=E(),r=this.manager.getSpawn(e);if(!r)return;let s=Te(r,{includeRunInfo:!0,includeStatus:!0});try{n.sendMessage({customType:"subagent-result",content:`${Ut(r)}
33
33
 
34
- ${Ut(r)}`,details:i,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let o=r.execution.spawnCtx;if(o)try{o.ui.notify(`[Cowboy agent "${r.display.type}" ${H(r.lifecycle)}] Result available`,"info")}catch{}}}};function Gn(t){return t.display.invocation?.runInBackground??!0}s(Gn,"isBackgroundRun");function yi(t){let e=t.lifecycle;return V(e)&&e.status==="stopped"&&e.stop.initiator==="user"}s(yi,"stoppedByUser");import*as Xn from"node:fs";import{pathToFileURL as Ai}from"node:url";import*as Qn from"node:path";import{DefaultPackageManager as Si,SettingsManager as ki}from"@earendil-works/pi-coding-agent";import*as Jn from"node:fs";import*as Kn from"node:path";import{z as Se}from"zod";var Vn="pi-cowboy",wi="pi-cowboy-",vi=Se.object({name:Se.string().startsWith(wi),[Vn]:Se.object({plugin:Se.string().min(1)})});function zn(t){let e;try{e=Jn.readFileSync(Kn.join(t,"package.json"),"utf-8")}catch{return}let n;try{n=JSON.parse(e)}catch{return}let r=vi.safeParse(n);if(r.success)return{name:r.data.name,entry:r.data[Vn].plugin}}s(zn,"readPluginManifest");function bi(t){let e=new Map;for(let n of t){if(n.installedPath===void 0)continue;let r=zn(n.installedPath);r!==void 0&&(e.has(r.name)||e.set(r.name,{name:r.name,source:n.source,root:n.installedPath,entry:Qn.resolve(n.installedPath,r.entry)}))}return[...e.values()].sort((n,r)=>n.name.localeCompare(r.name))}s(bi,"pluginsAmong");async function Yn(t){let e=new Si({cwd:t,agentDir:F(),settingsManager:ki.create(t,F())});return bi(e.listConfiguredPackages())}s(Yn,"discoverPluginPackages");function Zn(t){let e=null,n=null,r=null;async function i(o,a,d){let l=r;l!==null&&(await l,r===l&&(r=null));let c=[],g=[],m=[],p;try{p=await Yn(a)}catch(f){d(`[cowboy] installed plugins could not be discovered and were skipped: ${w(f)}`,"warning"),p=[]}for(let f of p){let x=g.length;try{let v=await Ri(f,o,a,t,b=>g.push(b));v!==void 0&&c.push(v),m.push(f.name)}catch(v){for(let b of g.splice(x).reverse())b();d(`[cowboy] plugin "${f.name}" (${f.source}) could not load and was skipped: ${w(v)}`,"warning")}}let h,y={loaded:m,dispose:s(()=>(h??=(async()=>{e===y&&(e=null);for(let f=c.pop();f!==void 0;f=c.pop())try{await f()}catch(x){d(`[cowboy] a plugin disposer failed: ${w(x)}`,"warning")}for(let f=g.pop();f!==void 0;f=g.pop())f()})(),r=h,h),"dispose")};return e=y,n=null,y}return s(i,"startLoad"),{load(o,a,d){return e!==null?Promise.resolve(e):(n??=i(o,a,d),n)}}}s(Zn,"createPluginLoader");function Pi(t){try{return`?v=${Xn.statSync(t).mtimeMs}`}catch{return""}}s(Pi,"cacheBust");function xi(t,e,n,r){return{pi:t,cwd:e,registerHarness:s(i=>{let o=n.harnesses.register(i);return o&&r(()=>n.harnesses.unregister(i.id)),o},"registerHarness"),deriveHarness:s(i=>{let o=n.harnesses.derive(i);return o&&r(()=>n.harnesses.unregister(i.id)),o},"deriveHarness"),getHarness:s(i=>n.harnesses.get(i),"getHarness"),registerMultiplexer:s(i=>{let o=n.multiplexers.register(i);return o&&r(()=>n.multiplexers.unregister(i.id)),o},"registerMultiplexer")}}s(xi,"pluginApi");async function Ri(t,e,n,r,i){let o=xi(e,n,r,i),d=(await import(`${Ai(t.entry).href}${Pi(t.entry)}`)).default;if(typeof d!="function")throw new Error(`entry module ${t.entry} has no default-export factory`);let l=await d(o);return typeof l=="function"?l:void 0}s(Ri,"loadOne");function Ii(){let t=[],e=[];for(let n of P().ids()){let r=Ei(n);r.status==="available"?t.push(n):r.notice!==void 0&&e.push(r.notice)}return{availability:Ve(t),notices:e}}s(Ii,"probeHarnessAvailability");function Ei(t){try{return P().require(t).availability()}catch(e){return{status:"unavailable",notice:`[cowboy] the "${t}" harness could not answer for itself and is not offered: ${w(e)}`}}}s(Ei,"askAvailability");function er(){let t=Ii();return vt(t.availability),t}s(er,"startHarnessAvailabilityProbe");import*as be from"node:path";import{z as u}from"zod";function Ci(t){return"launch"in t&&t.launch!==void 0?{...t,launch:{...t.launch}}:{...t}}s(Ci,"copyLifecycle");function nr(t){let e={type:t.display.type,description:t.display.description,...t.display.taskSlug===void 0?{}:{taskSlug:t.display.taskSlug},orchestration:Li(t.display.orchestration),...t.display.invocation===void 0?{}:{invocation:{...t.display.invocation}},...t.display.worktree===void 0?{}:{worktree:{...t.display.worktree}}},n=t.execution.host;return{v:1,id:t.id,lifecycle:Ci(t.lifecycle),display:e,execution:{...n===void 0?{}:{host:{...n}},...t.execution.harness===void 0?{}:{harness:t.execution.harness},...t.execution.modelKey===void 0?{}:{modelKey:t.execution.modelKey},history:t.execution.history.map(r=>({harness:r.harness,host:{...r.host},cwd:r.cwd,sessionId:r.sessionId,startedAt:r.startedAt,endedAt:r.endedAt}))}}}s(nr,"encodeSpawnRecord");function Li(t){return{name:t.name,...t.displayName===void 0?{}:{displayName:t.displayName},cues:{spawned:t.cues.spawned,queued:t.cues.queued,settled:t.cues.settled},guidance:t.guidance}}s(Li,"copyOrchestration");function rr(t,e){return{v:1,kind:"forgotten",spawnId:t,at:e}}s(rr,"encodeForget");function Ae(t){let e=t.execution.host;return{id:t.id,lifecycle:t.lifecycle,display:{type:t.display.type,description:t.display.description,orchestration:t.display.orchestration,...t.display.taskSlug===void 0?{}:{taskSlug:t.display.taskSlug},...t.display.invocation===void 0?{}:{invocation:t.display.invocation},...t.display.worktree===void 0?{}:{worktree:t.display.worktree}},execution:{promise:Promise.resolve(""),abortController:new AbortController,history:t.execution.history.map(n=>({...n,host:{...n.host}})),...e===void 0?{}:{host:{...e}},...t.execution.harness===void 0?{}:{harness:t.execution.harness},...t.execution.modelKey===void 0?{}:{modelKey:t.execution.modelKey}}}}s(Ae,"spawnFromRecord");var ir=u.string().regex(new RegExp(`^[${ze}]{${Qe}}$`),"not a spawn id"),sr=u.string().min(1).refine(t=>be.isAbsolute(t),"not an absolute path").refine(t=>!t.split(be.sep).includes(".."),"a path may not traverse upwards"),ke=u.object({resultFile:sr}),te=u.union([u.object({kind:u.literal("dirty")}),u.object({kind:u.literal("unverifiable"),detail:u.string()})]),tr=u.object({initiator:u.enum(["user","agent"])}),Ti=u.union([u.object({phase:u.literal("queued"),queuedAt:u.number()}),u.object({phase:u.literal("spawned"),startedAt:u.number(),launch:ke.optional()}),u.object({phase:u.literal("settled"),startedAt:u.number(),launch:ke.optional(),worktreeRetentionReason:te.optional(),status:u.literal("completed"),result:u.string(),completedAt:u.number()}),u.object({phase:u.literal("settled"),startedAt:u.number(),launch:ke.optional(),worktreeRetentionReason:te.optional(),status:u.literal("error"),error:u.string(),completedAt:u.number()}),u.object({phase:u.literal("settled"),startedAt:u.number(),launch:ke.optional(),worktreeRetentionReason:te.optional(),status:u.literal("stopped"),completedAt:u.number(),stop:tr}),u.object({phase:u.literal("never-started"),queuedAt:u.number(),worktreeRetentionReason:te.optional(),status:u.literal("error"),error:u.string(),completedAt:u.number()}),u.object({phase:u.literal("never-started"),queuedAt:u.number(),worktreeRetentionReason:te.optional(),status:u.literal("stopped"),completedAt:u.number(),stop:tr})]),or=u.object({multiplexer:u.string().min(1),name:u.string(),paneId:u.string().min(1),tabId:u.string().optional(),workspaceId:u.string(),paneCreated:u.boolean()}),Fi=u.object({harness:u.string().min(1),host:or,cwd:u.string().nullable(),sessionId:u.string(),startedAt:u.number(),endedAt:u.number()}),Oi=u.object({kind:u.enum(["owned","picked"]),path:sr,branch:u.string()}),ji=u.object({modelName:u.string().optional(),thinkingLevel:u.string().optional(),runInBackground:u.boolean().optional(),fork:u.boolean().optional()}),Hi=u.object({spawned:u.string(),queued:u.string(),settled:u.string()}),Mi=u.object({name:u.string(),displayName:u.string().optional(),cues:Hi,guidance:u.string()}),Di=u.object({v:u.literal(1),id:ir,lifecycle:Ti,display:u.object({type:u.string(),description:u.string(),taskSlug:u.string().optional(),orchestration:Mi,invocation:ji.optional(),worktree:Oi.optional()}),execution:u.object({host:or.optional(),harness:u.string().min(1).optional(),modelKey:u.string().min(1).optional(),history:u.array(Fi)})}),$i=u.union([u.object({v:u.literal(1),kind:u.literal("spawn"),at:u.number(),record:Di}),u.object({v:u.literal(1),kind:u.literal("forgotten"),spawnId:ir,at:u.number()})]);function ar(t){let e=$i.safeParse(t);return e.success?e.data:null}s(ar,"decodeJournalEntry");var Pe=L("adoption"),Ni="The session was reloaded before the queued agent could start.";function qi(t,e){if(t.lifecycle.phase!=="queued")return t;let{queuedAt:n}=t.lifecycle;return{...t,lifecycle:{phase:"never-started",queuedAt:n,status:"error",error:Ni,completedAt:e}}}s(qi,"demoteQueued");function _i(t,e,n,r){return{...t,lifecycle:{phase:"settled",startedAt:e.startedAt,...e.launch===void 0?{}:{launch:e.launch},status:"error",error:n,completedAt:r}}}s(_i,"settleRecord");async function Wi(t,e,n){let r=qi(t,n);return r!==t?{kind:"restored",record:r,writeBack:!0}:Ui(t)?Bi(t,e,n):{kind:"restored",record:t,writeBack:!1}}s(Wi,"decide");function Ui(t){return t.lifecycle.phase==="spawned"}s(Ui,"isInFlight");async function Bi(t,e,n){let r=await e.verdictOf(t);switch(r.kind){case"adopt-live":return{kind:"restored",record:t,writeBack:!1};case"forget":return{kind:"dropped"};case"settle":return{kind:"restored",record:_i(t,t.lifecycle,r.reason,n),writeBack:!0}}}s(Bi,"verifyInFlight");function Gi(t,e){let n=t.display.taskSlug;if(n===void 0)return;let r=e.store.list(W).find(i=>i.id!==t.id&&i.display.taskSlug===n&&i.lifecycle.phase!=="never-started");r!==void 0&&(Pe.warn("restored run shares a task slug with a tracked one",{spawnId:t.id,otherId:r.id,taskSlug:n}),e.notify?.(`Cowboy restored agent ${t.id}, and agent ${r.id} is already tracked for task "${n}". Both are listed; that task cannot take a new agent until one of them is stopped or cleaned up.`,"warning"))}s(Gi,"reportSlugCollision");async function dr(t){let{journal:e,store:n}=t,r;try{let l=e.replay();l.unreadable>0&&(Pe.warn("unreadable spawn journal entries",{count:l.unreadable}),t.notify?.(`Cowboy could not read ${l.unreadable} recorded agent${l.unreadable===1?"":"s"} from this session; ${l.unreadable===1?"it is":"they are"} not listed.`,"warning")),r=l.records}catch(l){Pe.warn("spawn replay failed",{detail:w(l)}),t.notify?.("Cowboy could not read its recorded agents from this session; any still running are not listed.","warning"),r=[]}let i=new Set(r.map(l=>l.id)),o=Date.now(),a=r.filter(l=>n.get(l.id)===void 0),d=await Promise.allSettled(a.map(l=>Wi(l,t,o)));for(let[l,c]of a.entries())try{let g=d[l];if(g.status==="rejected")throw g.reason;let m=g.value;if(m.kind==="dropped"){e.forget(c.id);continue}let p=Ae(m.record);n.add(p),m.writeBack&&e.record(p),Gi(p,t)}catch(g){Pe.warn("spawn record could not be restored",{spawnId:c.id,detail:w(g)}),t.notify?.(`Cowboy could not restore agent ${c.id} from this session; it is no longer listed.`,"warning")}for(let l of n.list())i.has(l.id)||e.record(l)}s(dr,"adoptSpawnRecords");var Ji=L("journal"),We="pi-cowboy.spawn-journal";function Ki(t){return typeof t=="object"&&t!==null&&t.type==="custom"&&t.customType===We}s(Ki,"isJournalEntry");function lr(t){return JSON.stringify(_e(t))}s(lr,"signature");function _e(t){if(Array.isArray(t))return t.map(_e);if(t===null||typeof t!="object")return t;let e=t,n={};for(let r of Object.keys(e).sort())n[r]=_e(e[r]);return n}s(_e,"canonical");function ur(t){let e=s(()=>t.now?.()??Date.now(),"now"),n=!1,r=!1,i=new Map;function o(a){if(!n)try{t.append(a)}catch(d){r||(r=!0,Ji.warn("spawn journal write failed",{detail:w(d)}),t.notify?.("Cowboy could not record its running agents in this session, so a reload may forget them. The agents themselves are unaffected.","warning"))}}return s(o,"append"),{record(a){let d=nr(a),l=lr(d);i.get(d.id)!==l&&(i.set(d.id,l),o({v:1,kind:"spawn",at:e(),record:d}))},forget(a){i.delete(a),o(rr(a,e()))},replay(){let a=new Map,d=0;for(let l of t.readBranch()){if(!Ki(l))continue;let c=ar(l.data);if(c===null){d+=1;continue}if(c.kind==="forgotten"){a.delete(c.spawnId),i.delete(c.spawnId);continue}a.set(c.record.id,c.record),i.set(c.record.id,lr(c.record))}return{records:[...a.values()],unreadable:d}},detach(){n=!0}}}s(ur,"createSpawnJournal");var Vi="the process is gone, but its worktree and branch remain";function cr(t){let e=!1;async function n(i){try{return await t.locate(i.id,Ae(i))}catch{return{kind:"not-found",id:i.id}}}s(n,"locate");function r(i){e||(e=!0,t.notify?.(`Cowboy found more than one set of artifacts for agent ${i.id}, so it cannot tell whether that agent is still running. It is listed, but may be stale.`,"warning"))}return s(r,"reportAmbiguity"),{async verdict(i){let o=await n(i);if(o.kind==="ambiguous")return r(i),{kind:"adopt-live"};let a=i.execution.host;if(a===void 0)return{kind:"adopt-live"};let d;try{d=await t.observe(a)}catch{return{kind:"adopt-live"}}return d!==void 0?{kind:"adopt-live"}:o.kind==="not-found"?{kind:"forget"}:{kind:"settle",reason:Vi}}}}s(cr,"createSpawnVerification");async function pr(t,e,n){let r=s((d,l)=>{e.hasUI&&e.ui.notify(d,l)},"notify"),i=ur({append:s(d=>t.appendEntry(We,d),"append"),readBranch:s(()=>e.sessionManager.getBranch(),"readBranch"),notify:r}),o=he(t,n.host,n.placements),a=cr({locate:s((d,l)=>o.locate(d,l),"locate"),observe:s(d=>o.observe(d),"observe"),notify:r});return await dr({journal:i,store:I(),verdictOf:s(d=>a.verdict(d),"verdictOf"),notify:r}),I().setObserver(i),{dispose(){I().clearObserver(i),i.detach()}}}s(pr,"bindSessionSpawnJournal");async function gr(t,e){let n=wt(),r=await Zn(n).load(t,e.cwd,(g,m)=>{e.hasUI&&e.ui.notify(g,m)}),i=A();n.harnesses.validateConfigs(i.harnessConfigLayers(),(g,m)=>i.reportHarnessConfigIssue(g,m)),zi(e,n);let o=n.multiplexers.hosting();if(o.length===0)return{kind:"unhosted",plugins:r,reason:Re};let a=n.multiplexers.runtime(t,A().multiplexer);if(!o.includes(a.multiplexer))return{kind:"unhosted",plugins:r,reason:Re};ue(a);let d=await pr(t,e,a),l=er();if(e.hasUI)for(let g of l.notices)e.ui.notify(g,"warning");let c=ot({registry:n.harnesses,availability:l.availability,request:{pi:t,modelCatalog:yt(e.modelRegistry)}});return St(c),c.warm(),{kind:"hosted",plugins:r,runtime:a,journal:d}}s(gr,"startSessionRuntime");function zi(t,e){if(!t.hasUI)return;let n=A(),r=new Set(e.harnesses.ids()),i=n.configuredHarnessIds().filter(o=>!r.has(o)).map(o=>`harness "${o}"`);e.multiplexers.has(n.multiplexer)||i.push(`multiplexer "${n.multiplexer}"`),i.length!==0&&t.ui.notify(`[cowboy] nothing registered for ${i.join(", ")}; those settings are ignored and the launch falls back to the default.`,"warning")}s(zi,"reportUnregisteredConfig");function Qi(t){if(!de()){let e=new we(new pt(A().concurrency),Bn(t));Ee(e),A().setDeps({manager:e});let n=new ve(e);Ce(n),e.setOnComplete(r=>{n.onAgentComplete(r)}),e.setOnFollowUp((r,i)=>{n.onAgentFollowUp(r,i)})}}s(Qi,"wireManagerAndCoordinator");async function Yi(t){let e=F(),n=M.join(e,"agents"),r=t.isProjectTrusted(),i=r?M.join(t.cwd,".agents","agents"):"",o=r?M.join(t.cwd,".pi","agents"):"";jt(n,o,i);let a=A().agent.disableDefaultAgents,d=await Ht({disableDefaultAgents:a,notify:s((l,c)=>{t.ui.notify(l,c)},"notify")});Ot(d,{disableDefaultAgents:a})}s(Yi,"scanAndRegisterAgents");async function Xi(t){let e=F(),n=M.join(e,"orchestrators"),r=t.isProjectTrusted(),i=r?M.join(t.cwd,".agents","orchestrators"):"",o=r?M.join(t.cwd,".pi","orchestrators"):"";Nt(n,o,i);let a=await qt({notify:s((d,l)=>{t.ui.notify(d,l)},"notify")});$t(a)}s(Xi,"scanAndRegisterOrchestrators");async function Zi(t){Pt(mt());let e=t.isProjectTrusted()?M.join(t.cwd,".pi"):void 0;A().setProjectDir(e),A().reload()}s(Zi,"loadSessionConfig");async function es(t){await Yi(t),await Xi(t)}s(es,"scanSessionTemplates");function fr(t){t.on("tool_call",Bt);let e=null,n=null;t.on("session_start",async(r,i)=>{At(i),await Zi(i);let o=await gr(t,i);if(e=o.plugins,o.kind==="hosted"&&(n=o.journal),o.kind==="unhosted"){Te(i.ui),i.hasUI&&U()&&i.ui.notify(o.reason,"warning");return}await es(i),Qi(o.runtime),de()?.attachLiveSpawns(),await Xt(t),U()?Zt(i.ui):(Te(i.ui),i.hasUI&&i.ui.notify("Cowboy extension is disabled \u2014 its tools are not loaded. Run /cowboy enable to turn it back on.","info"))}),t.on("session_shutdown",async(r,i)=>{let o=de();if(o){let c=o.listAgents(W);c.length>0&&i.hasUI&&i.ui.notify(`${c.length} subagent pane(s) left running in their panes (tracking stopped for the previous session)`,"warning")}le()?.dispose(),Ce(null),A().dispose(),o?.dispose(),Ee(null);let a=n;n=null,a?.dispose(),Gt();let d=e;e=null;let l=z();await d?.dispose(),z()===l&&ue(null)}),process.on("exit",()=>{try{process.stderr.write("\x1B[?2026l\x1B[?25h\x1B[0m")}catch{}})}s(fr,"setupEventListeners");var hr="pi-cowboy needs a git repository: this directory is not inside one, so pi-cowboy stays inactive";function mr(t,e){t.on("session_start",async(n,r)=>{r.hasUI&&r.ui.notify(e,"warning")})}s(mr,"reportInactive");function ts(t){if(xt()!==void 0)return;let e=Rt();if(e!==void 0){mr(t,e);return}if(!It(process.cwd())){mr(t,hr),tn(t,hr);return}bt(t),en(t),nn(t),fr(t)}s(ts,"default");export{ts as default};
34
+ ${Bt(r)}`,details:s,display:!0},{deliverAs:"followUp",triggerTurn:!0})}catch{let o=r.execution.spawnCtx;if(o)try{o.ui.notify(`[Cowboy agent "${r.display.type}" ${H(r.lifecycle)}] Result available`,"info")}catch{}}}};function Gn(t){return t.display.invocation?.runInBackground??!0}i(Gn,"isBackgroundRun");function ms(t){let e=t.lifecycle;return V(e)&&e.status==="stopped"&&e.stop.initiator==="user"}i(ms,"stoppedByUser");import*as Xn from"node:fs";import{pathToFileURL as bs}from"node:url";import*as Qn from"node:path";import{DefaultPackageManager as vs,SettingsManager as Ss}from"@earendil-works/pi-coding-agent";import*as Jn from"node:fs";import*as Kn from"node:path";import{z as Se}from"zod";var Vn="pi-cowboy",ys="pi-cowboy-",ws=Se.object({name:Se.string().startsWith(ys),[Vn]:Se.object({plugin:Se.string().min(1)})});function zn(t){let e;try{e=Jn.readFileSync(Kn.join(t,"package.json"),"utf-8")}catch{return}let n;try{n=JSON.parse(e)}catch{return}let r=ws.safeParse(n);if(r.success)return{name:r.data.name,entry:r.data[Vn].plugin}}i(zn,"readPluginManifest");function ks(t){let e=new Map;for(let n of t){if(n.installedPath===void 0)continue;let r=zn(n.installedPath);r!==void 0&&(e.has(r.name)||e.set(r.name,{name:r.name,source:n.source,root:n.installedPath,entry:Qn.resolve(n.installedPath,r.entry)}))}return[...e.values()].sort((n,r)=>n.name.localeCompare(r.name))}i(ks,"pluginsAmong");async function Yn(t){let e=new vs({cwd:t,agentDir:F(),settingsManager:Ss.create(t,F())});return ks(e.listConfiguredPackages())}i(Yn,"discoverPluginPackages");function Zn(t){let e=null,n=null,r=null;async function s(o,a,d){let l=r;l!==null&&(await l,r===l&&(r=null));let c=[],g=[],m=[],p;try{p=await Yn(a)}catch(h){d(`[cowboy] installed plugins could not be discovered and were skipped: ${w(h)}`,"warning"),p=[]}for(let h of p){let R=g.length;try{let v=await Rs(h,o,a,t,b=>g.push(b));v!==void 0&&c.push(v),m.push(h.name)}catch(v){for(let b of g.splice(R).reverse())b();d(`[cowboy] plugin "${h.name}" (${h.source}) could not load and was skipped: ${w(v)}`,"warning")}}let f,y={loaded:m,dispose:i(()=>(f??=(async()=>{e===y&&(e=null);for(let h=c.pop();h!==void 0;h=c.pop())try{await h()}catch(R){d(`[cowboy] a plugin disposer failed: ${w(R)}`,"warning")}for(let h=g.pop();h!==void 0;h=g.pop())h()})(),r=f,f),"dispose")};return e=y,n=null,y}return i(s,"startLoad"),{load(o,a,d){return e!==null?Promise.resolve(e):(n??=s(o,a,d),n)}}}i(Zn,"createPluginLoader");function As(t){try{return`?v=${Xn.statSync(t).mtimeMs}`}catch{return""}}i(As,"cacheBust");function Ps(t,e,n,r){return{pi:t,cwd:e,registerHarness:i(s=>{let o=n.harnesses.register(s);return o&&r(()=>n.harnesses.unregister(s.id)),o},"registerHarness"),deriveHarness:i(s=>{let o=n.harnesses.derive(s);return o&&r(()=>n.harnesses.unregister(s.id)),o},"deriveHarness"),getHarness:i(s=>n.harnesses.get(s),"getHarness"),registerMultiplexer:i(s=>{let o=n.multiplexers.register(s);return o&&r(()=>n.multiplexers.unregister(s.id)),o},"registerMultiplexer")}}i(Ps,"pluginApi");async function Rs(t,e,n,r,s){let o=Ps(e,n,r,s),d=(await import(`${bs(t.entry).href}${As(t.entry)}`)).default;if(typeof d!="function")throw new Error(`entry module ${t.entry} has no default-export factory`);let l=await d(o);return typeof l=="function"?l:void 0}i(Rs,"loadOne");function xs(){let t=[],e=[];for(let n of P().ids()){let r=Is(n);r.status==="available"?t.push(n):r.notice!==void 0&&e.push(r.notice)}return{availability:ze(t),notices:e}}i(xs,"probeHarnessAvailability");function Is(t){try{return P().require(t).availability()}catch(e){return{status:"unavailable",notice:`[cowboy] the "${t}" harness could not answer for itself and is not offered: ${w(e)}`}}}i(Is,"askAvailability");function er(){let t=xs();return St(t.availability),t}i(er,"startHarnessAvailabilityProbe");import*as be from"node:path";import{z as u}from"zod";function Es(t){return"launch"in t&&t.launch!==void 0?{...t,launch:{...t.launch}}:{...t}}i(Es,"copyLifecycle");function nr(t){let e={type:t.display.type,description:t.display.description,...t.display.taskSlug===void 0?{}:{taskSlug:t.display.taskSlug},orchestration:Cs(t.display.orchestration),...t.display.invocation===void 0?{}:{invocation:{...t.display.invocation}},...t.display.worktree===void 0?{}:{worktree:{...t.display.worktree}}},n=t.execution.host;return{v:1,id:t.id,lifecycle:Es(t.lifecycle),display:e,execution:{...n===void 0?{}:{host:{...n}},...t.execution.harness===void 0?{}:{harness:t.execution.harness},...t.execution.modelKey===void 0?{}:{modelKey:t.execution.modelKey},history:t.execution.history.map(r=>({harness:r.harness,host:{...r.host},cwd:r.cwd,sessionId:r.sessionId,startedAt:r.startedAt,endedAt:r.endedAt}))}}}i(nr,"encodeSpawnRecord");function Cs(t){return{name:t.name,...t.displayName===void 0?{}:{displayName:t.displayName},cues:{spawned:t.cues.spawned,queued:t.cues.queued,settled:t.cues.settled},guidance:t.guidance}}i(Cs,"copyOrchestration");function rr(t,e){return{v:1,kind:"forgotten",spawnId:t,at:e}}i(rr,"encodeForget");function Ae(t){let e=t.execution.host;return{id:t.id,lifecycle:t.lifecycle,display:{type:t.display.type,description:t.display.description,orchestration:t.display.orchestration,...t.display.taskSlug===void 0?{}:{taskSlug:t.display.taskSlug},...t.display.invocation===void 0?{}:{invocation:t.display.invocation},...t.display.worktree===void 0?{}:{worktree:t.display.worktree}},execution:{promise:Promise.resolve(""),abortController:new AbortController,history:t.execution.history.map(n=>({...n,host:{...n.host}})),...e===void 0?{}:{host:{...e}},...t.execution.harness===void 0?{}:{harness:t.execution.harness},...t.execution.modelKey===void 0?{}:{modelKey:t.execution.modelKey}}}}i(Ae,"spawnFromRecord");var sr=u.string().regex(new RegExp(`^[${Qe}]{${Ye}}$`),"not a spawn id"),ir=u.string().min(1).refine(t=>be.isAbsolute(t),"not an absolute path").refine(t=>!t.split(be.sep).includes(".."),"a path may not traverse upwards"),ke=u.object({resultFile:ir}),te=u.union([u.object({kind:u.literal("dirty")}),u.object({kind:u.literal("unverifiable"),detail:u.string()})]),tr=u.object({initiator:u.enum(["user","agent"])}),Ts=u.union([u.object({phase:u.literal("queued"),queuedAt:u.number()}),u.object({phase:u.literal("spawned"),startedAt:u.number(),launch:ke.optional()}),u.object({phase:u.literal("settled"),startedAt:u.number(),launch:ke.optional(),worktreeRetentionReason:te.optional(),status:u.literal("completed"),result:u.string(),completedAt:u.number()}),u.object({phase:u.literal("settled"),startedAt:u.number(),launch:ke.optional(),worktreeRetentionReason:te.optional(),status:u.literal("error"),error:u.string(),completedAt:u.number()}),u.object({phase:u.literal("settled"),startedAt:u.number(),launch:ke.optional(),worktreeRetentionReason:te.optional(),status:u.literal("stopped"),completedAt:u.number(),stop:tr}),u.object({phase:u.literal("never-started"),queuedAt:u.number(),worktreeRetentionReason:te.optional(),status:u.literal("error"),error:u.string(),completedAt:u.number()}),u.object({phase:u.literal("never-started"),queuedAt:u.number(),worktreeRetentionReason:te.optional(),status:u.literal("stopped"),completedAt:u.number(),stop:tr})]),or=u.object({multiplexer:u.string().min(1),name:u.string(),paneId:u.string().min(1),tabId:u.string().optional(),workspaceId:u.string(),paneCreated:u.boolean()}),Ls=u.object({harness:u.string().min(1),host:or,cwd:u.string().nullable(),sessionId:u.string(),startedAt:u.number(),endedAt:u.number()}),Fs=u.object({kind:u.enum(["owned","picked"]),path:ir,branch:u.string()}),Os=u.object({modelName:u.string().optional(),thinkingLevel:u.string().optional(),runInBackground:u.boolean().optional(),fork:u.boolean().optional()}),js=u.object({spawned:u.string(),queued:u.string(),settled:u.string()}),Hs=u.object({name:u.string(),displayName:u.string().optional(),cues:js,guidance:u.string()}),Ms=u.object({v:u.literal(1),id:sr,lifecycle:Ts,display:u.object({type:u.string(),description:u.string(),taskSlug:u.string().optional(),orchestration:Hs,invocation:Os.optional(),worktree:Fs.optional()}),execution:u.object({host:or.optional(),harness:u.string().min(1).optional(),modelKey:u.string().min(1).optional(),history:u.array(Ls)})}),Ds=u.union([u.object({v:u.literal(1),kind:u.literal("spawn"),at:u.number(),record:Ms}),u.object({v:u.literal(1),kind:u.literal("forgotten"),spawnId:sr,at:u.number()})]);function ar(t){let e=Ds.safeParse(t);return e.success?e.data:null}i(ar,"decodeJournalEntry");var Pe=T("adoption"),$s="The session was reloaded before the queued agent could start.";function qs(t,e){if(t.lifecycle.phase!=="queued")return t;let{queuedAt:n}=t.lifecycle;return{...t,lifecycle:{phase:"never-started",queuedAt:n,status:"error",error:$s,completedAt:e}}}i(qs,"demoteQueued");function Ns(t,e,n,r){return{...t,lifecycle:{phase:"settled",startedAt:e.startedAt,...e.launch===void 0?{}:{launch:e.launch},status:"error",error:n,completedAt:r}}}i(Ns,"settleRecord");async function _s(t,e,n){let r=qs(t,n);return r!==t?{kind:"restored",record:r,writeBack:!0}:Ws(t)?Us(t,e,n):{kind:"restored",record:t,writeBack:!1}}i(_s,"decide");function Ws(t){return t.lifecycle.phase==="spawned"}i(Ws,"isInFlight");async function Us(t,e,n){let r=await e.verdictOf(t);switch(r.kind){case"adopt-live":return{kind:"restored",record:t,writeBack:!1};case"forget":return{kind:"dropped"};case"settle":return{kind:"restored",record:Ns(t,t.lifecycle,r.reason,n),writeBack:!0}}}i(Us,"verifyInFlight");function Bs(t,e){let n=t.display.taskSlug;if(n===void 0)return;let r=e.store.list(W).find(s=>s.id!==t.id&&s.display.taskSlug===n&&s.lifecycle.phase!=="never-started");r!==void 0&&(Pe.warn("restored run shares a task slug with a tracked one",{spawnId:t.id,otherId:r.id,taskSlug:n}),e.notify?.(`Cowboy restored agent ${t.id}, and agent ${r.id} is already tracked for task "${n}". Both are listed; that task cannot take a new agent until one of them is stopped or cleaned up.`,"warning"))}i(Bs,"reportSlugCollision");async function dr(t){let{journal:e,store:n}=t,r;try{let l=e.replay();l.unreadable>0&&(Pe.warn("unreadable spawn journal entries",{count:l.unreadable}),t.notify?.(`Cowboy could not read ${l.unreadable} recorded agent${l.unreadable===1?"":"s"} from this session; ${l.unreadable===1?"it is":"they are"} not listed.`,"warning")),r=l.records}catch(l){Pe.warn("spawn replay failed",{detail:w(l)}),t.notify?.("Cowboy could not read its recorded agents from this session; any still running are not listed.","warning"),r=[]}let s=new Set(r.map(l=>l.id)),o=Date.now(),a=r.filter(l=>n.get(l.id)===void 0),d=await Promise.allSettled(a.map(l=>_s(l,t,o)));for(let[l,c]of a.entries())try{let g=d[l];if(g.status==="rejected")throw g.reason;let m=g.value;if(m.kind==="dropped"){e.forget(c.id);continue}let p=Ae(m.record);n.add(p),m.writeBack&&e.record(p),Bs(p,t)}catch(g){Pe.warn("spawn record could not be restored",{spawnId:c.id,detail:w(g)}),t.notify?.(`Cowboy could not restore agent ${c.id} from this session; it is no longer listed.`,"warning")}for(let l of n.list())s.has(l.id)||e.record(l)}i(dr,"adoptSpawnRecords");var Gs=T("journal"),Ue="pi-cowboy.spawn-journal";function Js(t){return typeof t=="object"&&t!==null&&t.type==="custom"&&t.customType===Ue}i(Js,"isJournalEntry");function lr(t){return JSON.stringify(We(t))}i(lr,"signature");function We(t){if(Array.isArray(t))return t.map(We);if(t===null||typeof t!="object")return t;let e=t,n={};for(let r of Object.keys(e).sort())n[r]=We(e[r]);return n}i(We,"canonical");function ur(t){let e=i(()=>t.now?.()??Date.now(),"now"),n=!1,r=!1,s=new Map;function o(a){if(!n)try{t.append(a)}catch(d){r||(r=!0,Gs.warn("spawn journal write failed",{detail:w(d)}),t.notify?.("Cowboy could not record its running agents in this session, so a reload may forget them. The agents themselves are unaffected.","warning"))}}return i(o,"append"),{record(a){let d=nr(a),l=lr(d);s.get(d.id)!==l&&(s.set(d.id,l),o({v:1,kind:"spawn",at:e(),record:d}))},forget(a){s.delete(a),o(rr(a,e()))},replay(){let a=new Map,d=0;for(let l of t.readBranch()){if(!Js(l))continue;let c=ar(l.data);if(c===null){d+=1;continue}if(c.kind==="forgotten"){a.delete(c.spawnId),s.delete(c.spawnId);continue}a.set(c.record.id,c.record),s.set(c.record.id,lr(c.record))}return{records:[...a.values()],unreadable:d}},detach(){n=!0}}}i(ur,"createSpawnJournal");var Ks="the process is gone, but its worktree and branch remain";function cr(t){let e=!1;async function n(s){try{return await t.locate(s.id,Ae(s))}catch{return{kind:"not-found",id:s.id}}}i(n,"locate");function r(s){e||(e=!0,t.notify?.(`Cowboy found more than one set of artifacts for agent ${s.id}, so it cannot tell whether that agent is still running. It is listed, but may be stale.`,"warning"))}return i(r,"reportAmbiguity"),{async verdict(s){let o=await n(s);if(o.kind==="ambiguous")return r(s),{kind:"adopt-live"};let a=s.execution.host;if(a===void 0)return{kind:"adopt-live"};let d;try{d=await t.observe(a)}catch{return{kind:"adopt-live"}}return d!==void 0?{kind:"adopt-live"}:o.kind==="not-found"?{kind:"forget"}:{kind:"settle",reason:Ks}}}}i(cr,"createSpawnVerification");async function pr(t,e,n){let r=i((d,l)=>{e.hasUI&&e.ui.notify(d,l)},"notify"),s=ur({append:i(d=>t.appendEntry(Ue,d),"append"),readBranch:i(()=>e.sessionManager.getBranch(),"readBranch"),notify:r}),o=fe(t,n.host,n.placements),a=cr({locate:i((d,l)=>o.locate(d,l),"locate"),observe:i(d=>o.observe(d),"observe"),notify:r});return await dr({journal:s,store:I(),verdictOf:i(d=>a.verdict(d),"verdictOf"),notify:r}),I().setObserver(s),{dispose(){I().clearObserver(s),s.detach()}}}i(pr,"bindSessionSpawnJournal");async function gr(t,e){let n=vt(),r=await Zn(n).load(t,e.cwd,(g,m)=>{e.hasUI&&e.ui.notify(g,m)}),s=A();n.harnesses.validateConfigs(s.harnessConfigLayers(),(g,m)=>s.reportHarnessConfigIssue(g,m)),Vs(e,n);let o=n.multiplexers.hosting();if(o.length===0)return{kind:"unhosted",plugins:r,reason:xe};let a=n.multiplexers.runtime(t,A().multiplexer);if(!o.includes(a.multiplexer))return{kind:"unhosted",plugins:r,reason:xe};ue(a);let d=await pr(t,e,a),l=er();if(e.hasUI)for(let g of l.notices)e.ui.notify(g,"warning");let c=at({registry:n.harnesses,availability:l.availability,request:{pi:t,modelCatalog:wt(e.modelRegistry)}});return kt(c),c.warm(),{kind:"hosted",plugins:r,runtime:a,journal:d}}i(gr,"startSessionRuntime");function Vs(t,e){if(!t.hasUI)return;let n=A(),r=new Set(e.harnesses.ids()),s=n.configuredHarnessIds().filter(o=>!r.has(o)).map(o=>`harness "${o}"`);e.multiplexers.has(n.multiplexer)||s.push(`multiplexer "${n.multiplexer}"`),s.length!==0&&t.ui.notify(`[cowboy] nothing registered for ${s.join(", ")}; those settings are ignored and the launch falls back to the default.`,"warning")}i(Vs,"reportUnregisteredConfig");function zs(t){if(!de()){let e=new we(new gt(A().concurrency),Bn(t));Ee(e),A().setDeps({manager:e});let n=new ve(e);Ce(n),e.setOnComplete(r=>{n.onAgentComplete(r)}),e.setOnFollowUp((r,s)=>{n.onAgentFollowUp(r,s)})}}i(zs,"wireManagerAndCoordinator");async function Qs(t){let e=F(),n=M.join(e,"agents"),r=t.isProjectTrusted(),s=r?M.join(t.cwd,".agents","agents"):"",o=r?M.join(t.cwd,".pi","agents"):"";Ht(n,o,s);let a=A().agent.disableDefaultAgents,d=await Mt({disableDefaultAgents:a,notify:i((l,c)=>{t.ui.notify(l,c)},"notify")});jt(d,{disableDefaultAgents:a})}i(Qs,"scanAndRegisterAgents");async function Ys(t){let e=F(),n=M.join(e,"orchestrators"),r=t.isProjectTrusted(),s=r?M.join(t.cwd,".agents","orchestrators"):"",o=r?M.join(t.cwd,".pi","orchestrators"):"";Nt(n,o,s);let a=await _t({notify:i((d,l)=>{t.ui.notify(d,l)},"notify")});qt(a)}i(Ys,"scanAndRegisterOrchestrators");async function Xs(t){Rt(yt());let e=t.isProjectTrusted()?M.join(t.cwd,".pi"):void 0;A().setProjectDir(e),A().reload()}i(Xs,"loadSessionConfig");async function Zs(t){await Qs(t),await Ys(t)}i(Zs,"scanSessionTemplates");function hr(t){t.on("tool_call",Gt);let e=null,n=null;t.on("session_start",async(r,s)=>{Pt(s),await Xs(s);let o=await gr(t,s);if(e=o.plugins,o.kind==="hosted"&&(n=o.journal),o.kind==="unhosted"){Le(s.ui),s.hasUI&&U()&&s.ui.notify(o.reason,"warning");return}await Zs(s),zs(o.runtime),de()?.attachSpawns(),await Zt(t),U()?en(s.ui):(Le(s.ui),s.hasUI&&s.ui.notify("Cowboy extension is disabled \u2014 its tools are not loaded. Run /cowboy enable to turn it back on.","info"))}),t.on("session_shutdown",async(r,s)=>{let o=de();if(o){let c=o.listAgents(W);c.length>0&&s.hasUI&&s.ui.notify(`${c.length} subagent pane(s) left running in their panes (tracking stopped for the previous session)`,"warning")}le()?.dispose(),Ce(null),A().dispose(),o?.dispose(),Ee(null);let a=n;n=null,a?.dispose(),Jt();let d=e;e=null;let l=z();await d?.dispose(),z()===l&&ue(null)}),process.on("exit",()=>{try{process.stderr.write("\x1B[?2026l\x1B[?25h\x1B[0m")}catch{}})}i(hr,"setupEventListeners");var fr="pi-cowboy needs a git repository: this directory is not inside one, so pi-cowboy stays inactive";function mr(t,e){t.on("session_start",async(n,r)=>{r.hasUI&&r.ui.notify(e,"warning")})}i(mr,"reportInactive");function ei(t){if(xt()!==void 0)return;let e=It();if(e!==void 0){mr(t,e);return}if(!Et(process.cwd())){mr(t,fr),nn(t,fr);return}At(t),tn(t),rn(t),hr(t)}i(ei,"default");export{ei as default};
35
35
  //# sourceMappingURL=index.js.map
@@ -1,3 +1,3 @@
1
- import{a as M,b as y}from"./chunk-F45A7CCD.js";import{U as H,d as g,g as R,j as P}from"./chunk-ROQJTDCS.js";import{b as S,o as D}from"./chunk-DD4TYA7R.js";import{A,Fa as T,Ja as v,Sa as _,ja as x,na as I,s as u,t as E}from"./chunk-FCLYV3G3.js";import{a as t,f as b,p as N}from"./chunk-YEXMGUZI.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=b,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout";case"reused":return"reused (the checkout already existed)"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out";case"reused":return"nothing: the existing checkout was reused exactly as it was"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
1
+ import{a as M,b as y}from"./chunk-2RG6EJRC.js";import{U as H,d as g,g as R,j as P}from"./chunk-Y5BC336I.js";import{b as S,o as D}from"./chunk-OR6LWM7F.js";import{A,Fa as T,Ja as v,Sa as _,ja as x,na as I,s as u,t as E}from"./chunk-73OMG4YX.js";import{a as t,f as b,p as N}from"./chunk-AOUEQXPY.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=b,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout";case"reused":return"reused (the checkout already existed)"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out";case"reused":return"nothing: the existing checkout was reused exactly as it was"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
2
2
  `)}t(Y,"describeCreatedWorktree");async function J(e,r,o,a){if($.existsSync(a))return`Cannot create the worktree: ${a} already exists. Pick another name.`;if(await g(e,["rev-parse","--verify","--quiet",`refs/heads/${o}`],r)!==void 0)return`Cannot create the worktree: the branch "${o}" already exists. Pick another name.`}t(J,"describeCollision");async function ue(e,r){let o=new S(e),a=t((n,i)=>e.ui.notify(n,i),"notify"),s=await o.open(({theme:n,close:i})=>new y(L({prefill:r,notify:a,onDone:t(m=>i(m),"onDone"),onCancel:t(()=>i(),"onCancel")}),{title:"Worktree Name",theme:n,passthroughKeys:!0}));if(s===void 0)return;let p=I(),c=x();if(!await P(c,e.cwd)){a("Cannot create a worktree: this session is not inside a git repository.","error");return}let d;try{d=await R(c,e.cwd)}catch(n){a(`Cannot create a worktree: ${N(n)}`,"error");return}let G=await g(c,["status","--porcelain"],d)==="",k=p.agent.worktreeCheckoutType;if(!G){let n=await o.open(({theme:i,close:m})=>{let h=new X(u.map(l=>({value:l,label:l,description:q[l]})),u.length,D(i));return h.setSelectedIndex(u.indexOf(p.agent.worktreeCheckoutType)),h.onSelect=l=>m(E(l.value)),h.onCancel=()=>m(),new y(h,{title:"Worktree Checkout",theme:i,onCancel:t(()=>m(),"onCancel")})});if(n===void 0)return;k=n}let w=z.join(A(p.agent.worktreeRoot,d),s),C=await J(c,d,s,w);if(C!==void 0){a(C,"error");return}let f=_(e.ui);f.pending(`Creating worktree ${s}`);let W;try{W=await H(c,{repoCwd:d,path:w,branch:s,materialization:T(),dirtyCheckout:k,notify:a,host:v().host})}catch(n){f.failed("Worktree creation failed",n);return}f.succeeded(Y(W,k))}t(ue,"showWorktreeCommandMenu");export{ue as showWorktreeCommandMenu};
3
- //# sourceMappingURL=menu-worktree-command-S5BLHCYS.js.map
3
+ //# sourceMappingURL=menu-worktree-command-WLJTYJL2.js.map
@@ -1,4 +1,4 @@
1
- import{e as _e,f as rn,g as ot,h as on,i as sn,l as an,m as mn,n as pn,q as Ae,r as Ke,t as fn,u as gn}from"./chunk-YUOPU3GW.js";import{a as We,b as N}from"./chunk-F45A7CCD.js";import{H as Qt,I as en,K as tn,L as nn,O as oe,P as dn,T as cn,V as un,i as Yt,j as Xt,v as z,w as Fe,x as Zt,z as Jt}from"./chunk-ROQJTDCS.js";import{a as fe,b as K,c as ie,d as se,e as ge,f as he,g as X,h as Ne,i as it,j as De,k as Oe,l as D,m as ln,n as B,o as Z,p as Ve,q as Me}from"./chunk-DD4TYA7R.js";import{$ as Gt,Aa as re,Da as Ut,Fa as He,H as ee,Ia as zt,Ja as je,M as Pt,N as Ht,O as jt,R as Ee,S as ae,Sa as Y,T as Re,U as Ft,V as _t,W as Nt,X as Dt,Y as Vt,Z as Wt,_ as Kt,a as St,c as kt,ca as Pe,ha as nt,ja as de,ka as pe,la as qt,m as tt,ma as J,n as we,na as E,p as wt,q as Tt,s as Ot,sa as Bt,t as Mt,u as At,ua as rt,xa as _}from"./chunk-FCLYV3G3.js";import{J as Et,K as Rt,L as Le,a as t,f as Ct,p as me,q as It,r as Te,s as xt,w as $t,y as ne,z as Lt}from"./chunk-YEXMGUZI.js";import{SettingsList as sr}from"@earendil-works/pi-tui";import{SettingsManager as lr}from"@earendil-works/pi-coding-agent";async function hn(e,n){return lr.create(e,n??St()).getDefaultThinkingLevel()}t(hn,"getPiDefaultThinkingLevel");import{SettingsList as yr}from"@earendil-works/pi-tui";var dr={queued:{icon:"\u25C6",color:"accent"},spawned:{icon:"\u25C8",color:"accent"},completed:{icon:"\u2713",color:"success"},error:{icon:"\u2717",color:"error"},stopped:{icon:"\u25A0",color:"dim"}};function yn(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=dr[e];return n.fg(o.color,o.icon)}t(yn,"statusIcon");function st(e){if(!Number.isFinite(e)||e<1e3)return"<1s";let n=Math.floor(e/1e3),o=Math.floor(n/3600),r=Math.floor(n%3600/60),s=n%60,i=[];return o>0&&i.push(`${o}h`),r>0&&i.push(`${r}m`),(s>0||i.length===0)&&i.push(`${s}s`),i.join(" ")}t(st,"formatMs");function vn(e){let n=z(e);return n?.displayName??n?.name??"Agent"}t(vn,"getDisplayName");function le(e){return`${e.fg("accent","\u2022")} `}t(le,"agentBulletPrefix");function bn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(bn,"truncatePath");function Ge(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(Ge,"formatSlotLimit");function Sn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:s,harnessDefaultFor:i,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:c}=e,u=new Map;for(let d of n){let h=o[d],{model:C,source:m}=Dt({subagentType:d,harnessFamily:l(d),agentConfig:h,config:{agent:r},harnessDefault:i(d),parentModelId:c,sessionOverrides:s});if(!at(s,r,d,e.sessionThinking))continue;let k=m==="session-per-type"||m==="session-default"?"[session]":a(d)?"[project]":"",{level:f,source:w}=lt({type:d,agentConfig:h,harnessFamily:l(d),config:r,harnessDefault:e.harnessDefaultThinkingFor(d),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),g=w==="session-per-type"?" [session]":w==="parent"?" [parent]":w==="config-per-type"&&e.hasProjectThinkingKey(d)?" [project]":"",b=u.get(C)??[];b.push({type:d,thinking:f,thinkingTag:g,tag:k}),u.set(C,b)}return[...u.entries()].sort((d,h)=>d[0]===h[0]?0:d[0]===null?-1:h[0]===null?1:d[0]<h[0]?-1:1).map(([d,h])=>({modelId:d,rows:h}))}t(Sn,"buildModelGroups");function at(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(at,"hasExplicitPerTypeOverride");function lt(e){let n=Wt({subagentType:e.type,harnessFamily:e.harnessFamily,agentConfig:e.agentConfig,config:{agent:e.config},harnessDefault:e.harnessDefault,parentThinking:e.parentThinking,sessionThinking:e.sessionThinking});return n!==void 0?{level:n.value,source:n.source}:{level:e.harnessFamily==="pi"?Vt:null,source:void 0}}t(lt,"displayedThinking");import{SettingsList as mr}from"@earendil-works/pi-tui";import{matchesKey as Ie,SelectList as cr,truncateToWidth as ur}from"@earendil-works/pi-tui";function kn(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],s=B(new cr(r,5,Z(e.theme)));return s.onSelect=i=>{i.value==="Yes"?(e.onConfirm(),o("Yes")):o()},s.onCancel=()=>o(),s}}t(kn,"createConfirmSubmenu");function ye(e){return se({invalidate(){},render(o){let r=Math.max(0,o-4),s=t(l=>` ${ur(l,r,"...",!0)}`,"line"),i=[s(e.theme.bold(e.message))];if(e.detail)for(let l of e.detail.split(`
1
+ import{e as _e,f as rn,g as ot,h as on,i as sn,l as an,m as mn,n as pn,q as Ae,r as Ke,t as fn,u as gn}from"./chunk-PU6CJR4Y.js";import{a as We,b as N}from"./chunk-2RG6EJRC.js";import{H as Qt,I as en,K as tn,L as nn,O as oe,P as dn,T as cn,V as un,i as Yt,j as Xt,v as z,w as Fe,x as Zt,z as Jt}from"./chunk-Y5BC336I.js";import{a as fe,b as K,c as ie,d as se,e as ge,f as he,g as X,h as Ne,i as it,j as De,k as Oe,l as D,m as ln,n as B,o as Z,p as Ve,q as Me}from"./chunk-OR6LWM7F.js";import{$ as Gt,Aa as re,Da as Ut,Fa as He,H as ee,Ia as zt,Ja as je,M as Pt,N as Ht,O as jt,R as Ee,S as ae,Sa as Y,T as Re,U as Ft,V as _t,W as Nt,X as Dt,Y as Vt,Z as Wt,_ as Kt,a as St,c as kt,ca as Pe,ha as nt,ja as de,ka as pe,la as qt,m as tt,ma as J,n as we,na as E,p as wt,q as Tt,s as Ot,sa as Bt,t as Mt,u as At,ua as rt,xa as _}from"./chunk-73OMG4YX.js";import{J as Et,K as Rt,L as Le,a as t,f as Ct,p as me,q as It,r as Te,s as xt,w as $t,y as ne,z as Lt}from"./chunk-AOUEQXPY.js";import{SettingsList as sr}from"@earendil-works/pi-tui";import{SettingsManager as lr}from"@earendil-works/pi-coding-agent";async function hn(e,n){return lr.create(e,n??St()).getDefaultThinkingLevel()}t(hn,"getPiDefaultThinkingLevel");import{SettingsList as yr}from"@earendil-works/pi-tui";var dr={queued:{icon:"\u25C6",color:"accent"},spawned:{icon:"\u25C8",color:"accent"},completed:{icon:"\u2713",color:"success"},error:{icon:"\u2717",color:"error"},stopped:{icon:"\u25A0",color:"dim"}};function yn(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=dr[e];return n.fg(o.color,o.icon)}t(yn,"statusIcon");function st(e){if(!Number.isFinite(e)||e<1e3)return"<1s";let n=Math.floor(e/1e3),o=Math.floor(n/3600),r=Math.floor(n%3600/60),s=n%60,i=[];return o>0&&i.push(`${o}h`),r>0&&i.push(`${r}m`),(s>0||i.length===0)&&i.push(`${s}s`),i.join(" ")}t(st,"formatMs");function vn(e){let n=z(e);return n?.displayName??n?.name??"Agent"}t(vn,"getDisplayName");function le(e){return`${e.fg("accent","\u2022")} `}t(le,"agentBulletPrefix");function bn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(bn,"truncatePath");function Ge(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(Ge,"formatSlotLimit");function Sn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:s,harnessDefaultFor:i,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:c}=e,u=new Map;for(let d of n){let h=o[d],{model:C,source:m}=Dt({subagentType:d,harnessFamily:l(d),agentConfig:h,config:{agent:r},harnessDefault:i(d),parentModelId:c,sessionOverrides:s});if(!at(s,r,d,e.sessionThinking))continue;let k=m==="session-per-type"||m==="session-default"?"[session]":a(d)?"[project]":"",{level:f,source:w}=lt({type:d,agentConfig:h,harnessFamily:l(d),config:r,harnessDefault:e.harnessDefaultThinkingFor(d),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),g=w==="session-per-type"?" [session]":w==="parent"?" [parent]":w==="config-per-type"&&e.hasProjectThinkingKey(d)?" [project]":"",b=u.get(C)??[];b.push({type:d,thinking:f,thinkingTag:g,tag:k}),u.set(C,b)}return[...u.entries()].sort((d,h)=>d[0]===h[0]?0:d[0]===null?-1:h[0]===null?1:d[0]<h[0]?-1:1).map(([d,h])=>({modelId:d,rows:h}))}t(Sn,"buildModelGroups");function at(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(at,"hasExplicitPerTypeOverride");function lt(e){let n=Wt({subagentType:e.type,harnessFamily:e.harnessFamily,agentConfig:e.agentConfig,config:{agent:e.config},harnessDefault:e.harnessDefault,parentThinking:e.parentThinking,sessionThinking:e.sessionThinking});return n!==void 0?{level:n.value,source:n.source}:{level:e.harnessFamily==="pi"?Vt:null,source:void 0}}t(lt,"displayedThinking");import{SettingsList as mr}from"@earendil-works/pi-tui";import{matchesKey as Ie,SelectList as cr,truncateToWidth as ur}from"@earendil-works/pi-tui";function kn(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],s=B(new cr(r,5,Z(e.theme)));return s.onSelect=i=>{i.value==="Yes"?(e.onConfirm(),o("Yes")):o()},s.onCancel=()=>o(),s}}t(kn,"createConfirmSubmenu");function ye(e){return se({invalidate(){},render(o){let r=Math.max(0,o-4),s=t(l=>` ${ur(l,r,"...",!0)}`,"line"),i=[s(e.theme.bold(e.message))];if(e.detail)for(let l of e.detail.split(`
2
2
  `))i.push(s(l));return i.push(s(e.theme.fg("dim","Y yes \xB7 N no"))),i},handleInput(o){if(Ie(o,"y")||Ie(o,"shift+y")){e.onYes();return}(Ie(o,"n")||Ie(o,"shift+n")||Ie(o,"escape"))&&e.onNo()}})}t(ye,"createKeyConfirm");var pr={session:{label:"Session",setDescription:"Not saved",clearDescription:"Removes from the session"},global:{label:"Global",setDescription:"Saves to the global config file",clearDescription:"Removes from the global config file"},project:{label:"Project",setDescription:"Saves to the project config file",clearDescription:"Removes from the project config file"}};function dt(e,n){let o=pr[e];return{id:e,label:o.label,currentValue:"",description:n?o.clearDescription:o.setDescription}}t(dt,"levelItem");function ve(e){let n=[];return e.offered.session&&n.push(dt("session",e.clearMode===!0)),e.offered.global&&n.push(dt("global",e.clearMode===!0)),e.offered.project&&n.push(dt("project",e.clearMode===!0)),e.includeClear&&n.push({id:"clear",label:"Clear...",currentValue:""}),e.includeAll&&n.push({id:"all",label:"All levels",currentValue:""}),n}t(ve,"buildLevelItems");function te(e){return(n,o)=>{let r=e.items.map(i=>({...i,submenu:t((l,a)=>{let c=e.onPick(i.id,a,()=>o());return c||(a(i.id),ie)},"submenu")})),s=B(new mr(r,r.length,D(e.theme),(i,l)=>o(l),()=>o()));return se(s)}}t(te,"createLevelPickerSubmenu");function qe(e){let n=e.availableLevels,o=e.includeAll===!0,r=(e.includeSession??!0)&&(!n||n.session),s=!n||n.global,i=e.projectOffered&&(!n||n.project),l=[r,s,i].filter(Boolean).length,a=e.showClear===!0?e.onClear:void 0,c=ve({offered:{session:r,global:s,project:i},clearMode:o,includeClear:a!==void 0,includeAll:n?l>=2:e.includeAll===!0});return te({theme:e.theme,items:c,onPick:t((u,d)=>u==="clear"?be({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,availableLevels:e.availableLevels,onClear:t(h=>a?.(h),"onClear")})("",d):e.onPick(u,d),"onPick")})}t(qe,"createTargetSelectSubmenu");function be(e){return qe({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,includeAll:!0,availableLevels:e.availableLevels,onPick:t(n=>e.onClear(n),"onPick")})}t(be,"createClearPickerSubmenu");function Be(e){return(n,o)=>qe({theme:e.theme,projectOffered:e.projectOffered,includeAll:!0,availableLevels:e.availableLevels,onPick:t((r,s)=>kn({message:e.message(r),theme:e.theme,onConfirm:t(()=>e.onConfirm(r),"onConfirm")})(n,s),"onPick")})(n,o)}t(Be,"createClearAllSubmenu");import{Input as Cn}from"@earendil-works/pi-tui";function ct(e,n){let o=n.min??1,r=t(i=>i===0?"\u2265 0":`\u2265 ${i}`,"fmtLabel"),s=t(i=>e.ui.notify(i,"error"),"onError");return(i,l)=>{let a=new Cn;return a.setValue(i),a.onSubmit=c=>{let u=c.trim();if(!u||/^unlimited$/i.test(u))switch(n.kind){case"required":s(`Invalid value \u2014 must be a number ${r(o)}`);return;case"defaulted":n.onValid?.(n.default),l(String(n.default));return;case"optional":n.onEmpty?.(),l("");return}let d=ln(u,o);if(d===void 0){s(`Invalid value \u2014 must be a number ${r(o)}`);return}n.onValid?.(d),l(String(d))},a.onEscape=()=>l(),a}}t(ct,"createNumericSubmenu");function Se(e,n){return(o,r)=>{let s=new Cn;return s.setValue(o),s.onSubmit=i=>{let l=i.trim();if(!l){if(n?.required){e.ui.notify("Cannot be empty","error");return}r();return}r(l)},s.onEscape=()=>r(),s}}t(Se,"createInputSubmenu");var wn="__custom__",ke="__none__";function fr(e,n){let o=[];if(e.kind!=="none"){for(let r of e.levels)o.push({id:r,label:r==="off"?"Off":r.charAt(0).toUpperCase()+r.slice(1),currentValue:n===r?"(current)":""});e.kind==="advisory"&&o.push({id:wn,label:"Custom token...",currentValue:"",description:"A level or variant this harness advertises beyond its own list."})}return o.push({id:ke,label:"None",currentValue:n===null?"(current)":"",description:"Use the template, configured default, or parent session's level."}),o}t(fr,"valueItems");function Tn(e){return te({theme:e.theme,items:fr(e.offering,e.current),onPick:t((n,o)=>{if(n===wn)return Se(e.ctx)(e.current??"",r=>{if(r===void 0){o();return}e.onPick(r),o(r)});e.onPick(n===ke?null:n)},"onPick")})}t(Tn,"createThinkingValuePicker");function ze(e,n,o,r){return n.length>0?{}:{loadModelOptions:t(async()=>{let s=await Ut().list(e),i=Rt(s);return i!==void 0&&r?.(i,"warning"),Et(s).map(l=>l.key)},"loadModelOptions"),requestRender:o}}t(ze,"deferredModelList");var Ue=class{constructor(n){this.cancel=n}cancel;static{t(this,"LoadingModels")}focused=!0;render(){return["Loading models\u2026"]}invalidate(){}handleInput(n){(n==="\x1B"||n==="")&&this.cancel()}};function On(e){let n=e.currentModel??null,o=e.showClear===!0?e.onClear:void 0;return te({theme:e.theme,items:ve({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:o!==void 0}),onPick:t((r,s,i)=>{if(r==="clear")return be({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(u=>o?.(u),"onClear")})("",s);let l=r,a=t(u=>new fe(it(u,n,e.mergedModels),n,{onSelect:t(d=>{e.onSet(l,d),d==null?i():s(d)},"onSelect"),onCancel:t(()=>s(),"onCancel")},e.theme),"select");if(e.loadModelOptions===void 0)return a(e.modelOptions);let c=new ge(new Ue(s));return e.loadModelOptions().then(u=>{c.activate(a(u)),e.requestRender?.()}),c},"onPick")})}t(On,"createModelSelectSubmenu");function Mn(e){let n=e.currentModel??null;return te({theme:e.theme,items:ve({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:e.showClear}),onPick:t((o,r,s)=>{if(o==="clear")return be({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(c=>e.onClear(c),"onClear")})("",r);let i=o,l,a=t(c=>new fe(it(c,n,e.mergedModels),n,{onSelect:t(u=>{if(u==null){e.onClear(i),s();return}let d=e.offeringFor(u);if(d.kind==="none"){e.onSet(i,u,null),r(u);return}l.activate(Tn({theme:e.theme,ctx:e.ctx,offering:d,current:e.currentThinking,onPick:t(h=>e.onSet(i,u,h),"onPick")})("",r))},"onSelect"),onCancel:t(()=>r(),"onCancel")},e.theme),"dialog");return e.loadModelOptions===void 0?(l=new ge(a(e.modelOptions)),l):(l=new ge(new Ue(r)),e.loadModelOptions().then(c=>{l.activate(a(c)),e.requestRender?.()}),l)},"onPick")})}t(Mn,"createModelThinkingSubmenu");import{getSupportedThinkingLevels as gr}from"@earendil-works/pi-ai";function Ye(e){let{harnessId:n,modelKey:o,entries:r,piModel:s}=e;if(ne(n))return s===void 0?{kind:"advisory",levels:[]}:s.reasoning?{kind:"closed",levels:gr(s)}:{kind:"none"};if(o==="")return hr(r);let i=r.find(l=>l.key===o);return i===void 0?{kind:"advisory",levels:[]}:i.thinkingLevels.kind==="advisory"?{kind:"advisory",levels:i.thinkingLevels.levels}:i.thinkingLevels.levels.length===0?{kind:"none"}:{kind:"closed",levels:i.thinkingLevels.levels}}t(Ye,"thinkingOfferingFor");function hr(e){let n=[...new Set(e.flatMap(r=>r.thinkingLevels.levels))],o=e.length===0||e.some(r=>r.thinkingLevels.kind==="advisory");return n.length===0&&!o?{kind:"none"}:o?{kind:"advisory",levels:n}:{kind:"closed",levels:n}}t(hr,"unionThinkingOffering");function An(e){return Ye({harnessId:e.harnessId,modelKey:e.modelKey??"",entries:e.entries.get(e.harnessId)??[],piModel:Te(e.modelKey??"",e.registry,e.parentModel)})}t(An,"thinkingOfferingForModel");function Xe(e){let n=e.model??"(none)",o=e.thinking??"(none)",r=e.model?e.modelTag:"",s=e.thinking?e.thinkingTag:"";return r!==""&&r===s?`${n} \xB7 ${o}${s}`:`${n}${r} \xB7 ${o}${s}`}t(Xe,"pairedRow");function Ze(e,n){return e?" [session]":n?" [project]":""}t(Ze,"layerTag");function ut(e,n){return n===null?"":Ze(e.session,e.project)}t(ut,"thinkingTagOf");function In(e,n,o,r){if(o===null){e.mutate.agent.clearHarnessDefaultThinking(n,r);return}r!=="session"&&ne(n)&&!Pt.safeParse(o).success||e.mutate.agent.setHarnessDefaultThinking(n,o,r)}t(In,"writeHarnessDefaultThinking");function vr(e,n,o,r){o===null?e.mutate.agent.clearThinkingOverride(n,r):e.mutate.agent.setThinkingOverride(n,o,r)}t(vr,"writeTypeThinking");function br(e){return _().runnable(e).filter(n=>!ne(n))}t(br,"harnessDefaultRowIds");function Sr(e){let n=br(re());return se(kr(e,n))}t(Sr,"buildModelSettingsScreen");function kr(e,n){let{ctx:o,store:r,theme:s,harnessModelOptions:i,requestRender:l,piDefaultThinking:a,close:c}=e,u,d=t(m=>{let k=[],f=r.isProjectWritable,w=t((y,P)=>o.ui.notify(y,P),"notify"),g=pe(),b=g.model??o.model,O=b?`${b.provider}/${b.id}`:null,R=g.thinkingLevel??null,F=r.agentConfigSnapshot(),$=De(F),H=t(()=>{u?.(d(m))},"refresh"),G=t(y=>P=>An({harnessId:y,modelKey:P,entries:i,registry:g.modelRegistry,parentModel:b}),"offeringFor"),W=t(y=>{let P={session:y.modelLevels.session||y.thinkingLevels.session,global:y.modelLevels.global||y.thinkingLevels.global,project:y.modelLevels.project||y.thinkingLevels.project};return Mn({modelOptions:y.modelOptions,...ze(y.harnessId,y.modelOptions,l,w),mergedModels:y.mergedModels,projectOffered:f,theme:m,ctx:o,currentModel:y.model,currentThinking:y.thinking,showClear:P.session||P.global||P.project,availableLevels:P,offeringFor:G(y.harnessId),onSet:t((I,q,V)=>{y.write(I,q,V),w(`${y.label} set to ${q} \xB7 ${V??"(none)"} (${I})`,"info")},"onSet"),onClear:t(I=>{y.clear(I),w(`${y.label} cleared (${I})`,"info"),H()},"onClear")})},"pairSubmenu"),v=F.default,p=r.modelOverrideLevels("default"),S=r.harnessDefaultThinkingLevels("pi"),T=r.defaultThinkingForHarness("pi"),M=r.sessionDefaultModel??v;k.push({id:"defaultModel",label:"Pi Default Model",currentValue:Xe({model:M,modelTag:Ze(p.session,r.hasProjectModelKey("default")),thinking:T,thinkingTag:ut(S,T)}),description:"Default model and thinking level applied when no session, per-type, or template override is set.",submenu:W({label:"Pi Default Model",harnessId:"pi",modelOptions:ee(i,"pi"),mergedModels:Oe("pi",$),model:M,thinking:T,modelLevels:p,thinkingLevels:S,write:t((y,P,I)=>{r.mutate.agent.setModelOverride("default",P,y),In(r,"pi",I,y)},"write"),clear:t(y=>{r.mutate.agent.clearModelOverride("default",y),r.mutate.agent.clearHarnessDefaultThinking("pi",y)},"clear")})});for(let y of n){let P=`${_().displayName(y)} Default Model`,I=r.harnessDefaultModelLevels(y),q=r.harnessDefaultThinkingLevels(y),V=r.defaultThinkingForHarness(y);k.push({id:`harness:${y}`,label:P,currentValue:Xe({model:r.defaultModelForHarness(y),modelTag:Ze(I.session,I.project),thinking:V,thinkingTag:ut(q,V)}),description:`Default model and thinking level applied to agents launched under ${y} when no session, per-type, or template override is set.`,submenu:W({label:P,harnessId:y,modelOptions:ee(i,y),mergedModels:[],model:r.defaultModelForHarness(y),thinking:V,modelLevels:I,thinkingLevels:q,write:t((Q,et,ar)=>{r.mutate.agent.setHarnessDefaultModel(y,et,Q),In(r,y,ar,Q)},"write"),clear:t(Q=>{r.mutate.agent.clearHarnessDefaultModel(y,Q),r.mutate.agent.clearHarnessDefaultThinking(y,Q)},"clear")})})}let A=Zt(),x={default:r.sessionDefaultModel},L={};for(let y of A)x[y]=r.sessionModelOverride(y),L[y]=z(y);let j={};for(let y of A)j[y]=r.sessionThinkingOverride(y);let U=Sn({types:A,agentConfigs:L,config:F,sessionOverrides:x,sessionThinking:j,harnessDefaultFor:t(y=>r.defaultModelForHarness(oe(y)),"harnessDefaultFor"),harnessDefaultThinkingFor:t(y=>{let P=oe(y),I=r.defaultThinkingForHarness(P);return I!==null?I:ne(P)&&R===null?a??null:null},"harnessDefaultThinkingFor"),harnessFamilyFor:t(y=>_().family(oe(y)),"harnessFamilyFor"),hasProjectModelKey:t(y=>r.hasProjectModelKey(y),"hasProjectModelKey"),hasProjectThinkingKey:t(y=>r.hasProjectThinkingKey(y),"hasProjectThinkingKey"),parentModelId:O,parentThinking:R}),xe=t((y,P,I,q)=>W({label:y,harnessId:P,modelOptions:ee(i,P),mergedModels:Oe(P,$),model:I,thinking:q,modelLevels:r.modelOverrideLevels(y),thinkingLevels:r.thinkingOverrideLevels(y),write:t((V,Q,et)=>{r.mutate.agent.setModelOverride(y,Q,V),vr(r,y,et,V)},"write"),clear:t(V=>{r.mutate.agent.clearModelOverride(y,V),r.mutate.agent.clearThinkingOverride(y,V)},"clear")}),"typeSubmenu");for(let y of U){k.push({id:X,label:" ",currentValue:""}),k.push(he(m,y.modelId??"(no model)"));let P=Math.max(...y.rows.map(I=>`${I.thinking??"(none)"}${I.thinkingTag}`.length));for(let I of y.rows){let q=oe(I.type),V=`${I.thinking??"(none)"}${I.thinkingTag}`,Q=I.thinking!==null&&I.thinkingTag.trim()===I.tag.trim()?"":I.tag;k.push({id:`type:${I.type}`,label:`${le(m)}${I.type}`,currentValue:`${V.padEnd(P)} ${Q}`.trimEnd(),description:`Model and thinking level for the ${I.type} agent type.`,submenu:xe(I.type,q,y.modelId,I.thinking)})}}k.push({id:X,label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",currentValue:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});let vt=A.filter(y=>!at(x,F,y,j));vt.length>0&&k.push({id:"overrideType",label:"Override another type...",currentValue:"",description:"Configure model and thinking level overrides for an agent type currently using inherited defaults.",submenu:t((y,P)=>Ve(vt.map(I=>({value:I,label:`${le(m)}${I}`})),{onSelect:t(I=>{if(I==null)return P();let q=oe(I),V=z(I),Q=r.modelFor(I,O,V,q,_().family(q));return xe(I,q,Q,lt({type:I,agentConfig:V,harnessFamily:_().family(q),config:F,harnessDefault:r.defaultThinkingForHarness(q),parentThinking:R??void 0,sessionThinking:j}).level)("",P)},"onSelect"),onCancel:t(()=>P(),"onCancel")},m),"submenu")}),k.push({id:X,label:" ",currentValue:""});let bt=r.modelSettingsLevels(),$e={...bt,project:bt.project&&f};return($e.session||$e.global||$e.project)&&k.push({id:"clearAll",label:"Clear all model and thinking overrides...",currentValue:"",description:"Remove model and thinking level overrides across a selected configuration layer (session, global, project, or all).",submenu:Be({theme:m,projectOffered:f,availableLevels:$e,message:t(y=>`Clear all model and thinking overrides at the ${y} level?`,"message"),onConfirm:t(y=>{r.mutate.agent.clearAllModelOverrides(y),w(`Model and thinking overrides cleared (${y})`,"info")},"onConfirm")})}),k},"buildItems"),h=new yr(d(s),15,D(s),(m,k)=>u?.(d(s)),c),C=new N(h,{title:"Model Settings",theme:s,onCancel:c,onRebuild:t(m=>{u=m},"onRebuild")});return se(C)}t(kr,"buildModelSettingsList");function xn(e){let{ctx:n,store:o,theme:r,harnessModelOptions:s,requestRender:i,piDefaultThinking:l}=e,a=t(()=>{let c=o.modelOverrideLevels("default"),u=o.harnessDefaultThinkingLevels("pi"),d=o.defaultThinkingForHarness("pi");return Xe({model:o.sessionDefaultModel??o.agentConfigSnapshot().default,modelTag:Ze(c.session,o.hasProjectModelKey("default")),thinking:d,thinkingTag:ut(u,d)})},"defaultDisplay");return{id:"modelOverrides",label:"Model overrides",currentValue:a(),description:"Pi's default model and thinking level, plus per-harness and per-type overrides; opens the model settings screen.",submenu:t((c,u)=>Sr({ctx:n,store:o,theme:r,harnessModelOptions:s,requestRender:i,piDefaultThinking:l,close:t(()=>u(a()),"close")}),"submenu")}}t(xn,"buildModelOverridesRow");import{SettingsList as $n}from"@earendil-works/pi-tui";function Ln(e,n){return e==="pi"?n:`${e}:${n}`}t(Ln,"qualifiedKey");function Je(e){let n=new Map;for(let o of e){let r=Pe(o)?.harness??"pi",s=n.get(r);s?s.push(o):n.set(r,[o])}return n}t(Je,"groupKeysByHarness");function wr(e,n){let o=[...e];for(let r of n.keys())o.includes(r)||o.push(r);return o}t(wr,"sectionHarnesses");async function En(e,n){let o=[...n.keys()],r=t((i,l)=>{let a=[],c=i.isProjectWritable,u=t((v,p,S)=>p==="default"?v.default!==void 0:S===void 0?!1:p==="harnesses"?v.harnesses?.[S]!==void 0:v[p]?.[S]!==void 0,"layerHas"),d=t((v,p)=>({session:u(i.sessionConcurrency,v,p),global:u(i.globalConcurrency,v,p),project:u(i.projectConcurrency,v,p)}),"entryLevels"),h=t((v,p)=>u(i.sessionConcurrency,v,p)?" [session]":u(i.projectConcurrency,v,p)?" [project]":"","limitTag"),C=t((v,p)=>(S,T)=>qe({theme:l,projectOffered:c,onPick:t((M,A)=>ct(e,{kind:"optional",min:1,onValid:t(x=>p(M,x),"onValid")})(v,A),"onPick")})(S,T),"targetThenValueSubmenu"),m=t((v,p,S,T)=>(M,A)=>{let x=ve({offered:{session:!0,global:!0,project:c},includeClear:T.session||T.global||T.project});return te({theme:l,items:x,onPick:t((L,j)=>{if(L==="clear")return be({theme:l,projectOffered:c,availableLevels:T,onClear:S})("",j);let U=L;return ct(e,{kind:"optional",min:1,onValid:t(xe=>p(U,xe),"onValid")})(String(v),j)},"onPick")})(M,A)},"limitSubmenu"),k=t(v=>(p,S)=>{let T=t(()=>v(),"buildFresh"),M,A=B(new $n(T(),15,D(l),(x,L)=>{let j=M,U=T();j.items=U,j.filteredItems=U,j.submenuComponent=null,j.selectedIndex=0},()=>S("closed")));return M=A,Ne(M),se(A)},"nestedListSubmenu"),f=t(v=>{let p=E(),S=p.concurrency.harnesses[v],T=_().displayName(v),M=`Concurrent agents of every model launched under ${v}.`;if(S===void 0)return{id:`harness:${v}`,label:T,currentValue:"unset",description:M,submenu:C("",(x,L)=>{E().mutate.concurrency.setHarness(v,L,x),e.ui.notify(`${v} concurrency set to ${L} (${x})`,"info")})};let A=u(p.sessionConcurrency,"harnesses",v)?" [session]":u(p.projectConcurrency,"harnesses",v)?" [project]":"";return{id:`harness:${v}`,label:T,currentValue:Ge(S,A),description:M,submenu:m(S,(x,L)=>{E().mutate.concurrency.setHarness(v,L,x),e.ui.notify(`${T} concurrency set to ${L} (${x})`,"info")},x=>{E().mutate.concurrency.removeHarness(v,x),e.ui.notify(`Removed per-harness limit for ${v} (${x})`,"info")},{session:u(p.sessionConcurrency,"harnesses",v),global:u(p.globalConcurrency,"harnesses",v),project:u(p.projectConcurrency,"harnesses",v)})}},"harnessLimitRow"),w=t(()=>{let v=E(),p=[...o];for(let S of Object.keys(v.concurrency.harnesses))S.trim()!==""&&!p.includes(S)&&p.push(S);return p.map(S=>f(S))},"harnessListItems"),g=t(v=>{let p=ee(n,v);return[...new Set(p.map(S=>It(S)?.provider).filter(S=>S!==void 0))].sort()},"providerOptionsFor"),b=t((v,p)=>{let S=E(),T=S.concurrency.providers[p],M=`Concurrent slots reserved for agents under ${v} using the ${Pe(p)?.provider??p} provider.`;if(T===void 0)return{id:`provider:${p}`,label:p,currentValue:"unset",description:M,submenu:C("",(x,L)=>{E().mutate.concurrency.setProvider(p,L,x),e.ui.notify(`${p} concurrency set to ${L} (${x})`,"info")})};let A=u(S.sessionConcurrency,"providers",p)?" [session]":u(S.projectConcurrency,"providers",p)?" [project]":"";return{id:`provider:${p}`,label:p,currentValue:Ge(T,A),description:M,submenu:m(T,(x,L)=>{E().mutate.concurrency.setProvider(p,L,x),e.ui.notify(`${p} concurrency set to ${L} (${x})`,"info")},x=>{E().mutate.concurrency.removeProvider(p,x),e.ui.notify(`Removed per-provider limit for ${p} (${x})`,"info")},{session:u(S.sessionConcurrency,"providers",p),global:u(S.globalConcurrency,"providers",p),project:u(S.projectConcurrency,"providers",p)})}},"providerLimitRow"),O=t(v=>{let p=E(),S=Je(Object.keys(p.concurrency.providers)).get(v)??[],T=g(v).map(A=>Ln(v,A));return[...new Set([...T,...S])].sort().map(A=>b(v,A))},"providerListItems"),R=t((v,p)=>{let S=E(),T=S.concurrency.models[p],M=Pe(p),A=M?.kind==="model"?M.model:p,x=`Concurrent slots reserved for agents under ${v} using the ${A} model.`;if(T===void 0)return{id:`model:${p}`,label:p,currentValue:"unset",description:x,submenu:C("",(j,U)=>{E().mutate.concurrency.setModel(p,U,j),e.ui.notify(`${p} concurrency set to ${U} (${j})`,"info")})};let L=u(S.sessionConcurrency,"models",p)?" [session]":u(S.projectConcurrency,"models",p)?" [project]":"";return{id:`model:${p}`,label:p,currentValue:Ge(T,L),description:x,submenu:m(T,(j,U)=>{E().mutate.concurrency.setModel(p,U,j),e.ui.notify(`${p} concurrency set to ${U} (${j})`,"info")},j=>{E().mutate.concurrency.removeModel(p,j),e.ui.notify(`Removed per-model limit for ${p} (${j})`,"info")},{session:u(S.sessionConcurrency,"models",p),global:u(S.globalConcurrency,"models",p),project:u(S.projectConcurrency,"models",p)})}},"modelLimitRow"),F=t(v=>{let p=E(),S=Je(Object.keys(p.concurrency.models)).get(v)??[],T=ee(n,v).map(A=>Ln(v,A));return[...new Set([...T,...S])].sort().map(A=>R(v,A))},"modelListItems"),$=t(v=>{let p=E(),S=Je(Object.keys(v==="providers"?p.concurrency.providers:p.concurrency.models));return wr(o,S).filter(T=>{let M=(S.get(T)??[]).length>0;return v==="providers"?M||g(T).length>0:M||ee(n,T).length>0}).map(T=>({id:`${v}-harness:${T}`,label:_().displayName(T),currentValue:"",description:v==="providers"?`Provider limits under ${T}.`:`Model limits under ${T}.`,submenu:k(()=>v==="providers"?O(T):F(T))}))},"harnessPickerItems"),H=i.concurrency.default;a.push({id:"defaultConcurrency",label:"Default concurrency limit",currentValue:`${H}${h("default")}`,description:"Concurrent agents, whatever harness, provider, or model they use.",submenu:m(H,(v,p)=>{i.mutate.concurrency.setDefault(p,v),e.ui.notify(`Default concurrency set to ${p} (${v})`,"info")},v=>{i.mutate.concurrency.removeDefault(v),e.ui.notify(`Removed default concurrency limit (${v})`,"info")},d("default"))}),a.push({id:"harnessLimits",label:"Per-harness limits",currentValue:"",description:"Cap how many agents run at once under a single harness.",submenu:k(w)}),a.push({id:"providerLimits",label:"Per-provider limits",currentValue:"",description:"Cap how many agents run at once for a single provider.",submenu:k(()=>$("providers"))}),a.push({id:"modelLimits",label:"Per-model limits",currentValue:"",description:"Cap how many agents run at once for a single model.",submenu:k(()=>$("models"))});let G=i.concurrencySettingsLevels(),W={...G,project:G.project&&c};return(W.session||W.global||W.project)&&a.push({id:"resetAll",label:"Clear all concurrency limits...",currentValue:"",description:"Remove concurrency overrides at the chosen level (session, global, project, or all).",submenu:Be({theme:l,projectOffered:c,availableLevels:W,message:t(v=>`Clear all concurrency limits at the ${v} level?`,"message"),onConfirm:t(v=>{i.mutate.concurrency.clearAll(v),e.ui.notify(`Concurrency limits cleared (${v})`,"info")},"onConfirm")})}),a},"buildItems"),s;await new K(e).open(({theme:i,close:l})=>{let a=t(()=>s?.(r(E(),i)),"triggerRebuild"),c=E(),u=r(c,i),d=new $n(u,15,D(i),(h,C)=>a(),l);return new N(d,{title:"Concurrency Settings",theme:i,onCancel:l,onRebuild:t(h=>{s=h},"onRebuild")})})}t(En,"showConcurrencySettingsMenu");import{matchesKey as ce,SelectList as pt,truncateToWidth as _n,visibleWidth as Qe}from"@earendil-works/pi-tui";import{SelectList as Tr}from"@earendil-works/pi-tui";async function Rn(e,n){let o=J();if(!o)return e.map(s=>({id:s,kind:"error",error:"manager unavailable"}));let r=[];for(let s of e)try{r.push({id:s,kind:"report",report:await o.cleanup(s,n(s))})}catch(i){r.push({id:s,kind:"error",error:me(i)})}return r}t(Rn,"runCleanupPass");function mt(e,n){let o=Y(e.ui);for(let r of n)r.kind==="report"?o.succeeded(rn(r.report),ot(r.report)?"warning":"info"):o.failed(`Failed to clean up agent ${r.id}`,r.error)}t(mt,"reportCleanupOutcomes");function Pn(e){return e.outcome.kind==="refused"?e.outcome.reason:void 0}t(Pn,"refusalReason");function Or(e){return e.worktree.kind==="kept"?e.worktree.path??void 0:void 0}t(Or,"refusalWorktreePath");function Mr(e){switch(e.kind){case"dirty":return"It has uncommitted changes";case"unverifiable":return`Its state could not be verified (${e.detail})`;case"recovered-refusal":return"Herdr still reports it at work";default:return _e(e)}}t(Mr,"offerReason");function Ar(e,n){return{invalidate(){},render:t(()=>[` ${e.fg("dim",n)}`],"render")}}t(Ar,"progressBody");function Ir(e,n,o,r){let s=[{value:"force",label:"Force",description:n},{value:"cancel",label:"Cancel",description:"Keep the worktree and its changes"}],i=B(new Tr(s,6,Z(e)));return i.onSelect=l=>l.value==="force"?o():r(),i.onCancel=r,i}t(Ir,"forceOfferList");function Hn(e){let{ctx:n,theme:o,view:r,refresh:s,close:i,requestRender:l}=e,a=t(d=>{r.activate(d),l()},"show"),c=t((d,h,C,m)=>{let k=d.length===1;a(ye({theme:o,message:k?`Force cleanup of agent ${d[0]}?`:`Force cleanup of ${d.length} agents?`,detail:[...C,"",k?"This DELETES its worktree and anything uncommitted in it.":"This DELETES their worktrees and anything uncommitted in them."].join(`
3
3
  `),onNo:m,onYes:t(()=>{i(),Y(n.ui).pending(`Forcing cleanup of ${Me(d)}`),(async()=>{let f=await Rn(d,w=>{let g=h.get(w);return{force:g?{reason:g}:{}}});mt(n,f)})()},"onYes")}))},"askForceConfirm"),u=t(d=>{let h=new Map;for(let{id:b,report:O}of d){let R=Pn(O);R&&h.set(b,R)}let C=[...h.keys()],m=C.length===1,k=d.map(({id:b,report:O})=>{let R=Pn(O),F=R?m?_e(R):`${b}: ${_e(R)}`:`${b}: kept`,$=Or(O);return $?`${F} (${$})`:F}),f=h.get(C[0]??""),w=m?`Clean up agent ${C[0]} anyway? ${f?Mr(f):"kept"}.`:`Clean up ${C.length} agents anyway?`,g=t(()=>{mt(n,d),s()},"backOut");a(Ir(o,w,()=>c(C,h,k,g),g))},"offerForce");return d=>{a(Ar(o,`Cleaning up ${Me(d)}\u2026`)),(async()=>{let h=await Rn(d,()=>{}),C=h.filter(f=>f.kind==="report"&&dn(f.report)),m=new Set(C.map(f=>f.id));if(mt(n,h.filter(f=>!m.has(f.id))),C.length>0){u(C);return}h.some(f=>f.kind==="error"||ot(f.report))?s():i()})()}}t(Hn,"createStatusCleanup");import{copyToClipboard as xr}from"@earendil-works/pi-coding-agent";import{SelectList as $r}from"@earendil-works/pi-tui";function jn(e){let{ctx:n,theme:o,view:r,close:s,requestRender:i}=e,l=Y(n.ui),a=t(f=>{r.activate(f),i()},"show"),c=t(f=>f.loss===void 0?"":Kt(f.loss),"lossClause"),u=t((f,w,g)=>{try{pn(g,w.text)}catch(b){l.failed(`Failed to export agent ${f.id} to ${g}`,b),h(f,w,g);return}l.outcome(Ke(w),`Exported handover for agent ${f.id} to ${g}.${c(w)}`),s()},"writeTo"),d=t((f,w,g)=>{if(!mn(g)){u(f,w,g);return}a(ye({theme:o,message:`Overwrite ${g}?`,detail:"A file already exists there. Y replaces it with the current export; Esc keeps the existing file.",onYes:t(()=>u(f,w,g),"onYes"),onNo:t(()=>h(f,w,g),"onNo")}))},"confirmOverwrite"),h=t((f,w,g)=>{a(We({prefill:g,notify:t((b,O)=>n.ui.notify(b,O),"notify"),validate:t(b=>b===""?"empty":null,"validate"),describeProblem:t(()=>"The export needs a file path.","describeProblem"),onDone:t(b=>d(f,w,b),"onDone"),onCancel:t(()=>k(f),"onCancel")}))},"showPathField"),C=t((f,w)=>{(async()=>{try{await xr(w.text)}catch(g){l.failed(`Failed to export agent ${f.id} to the clipboard`,g);return}l.outcome(Ke(w),`Exported handover for agent ${f.id} to the clipboard.${c(w)}`),s()})()},"copyToClipboardAndReport"),m=t((f,w)=>{let g=J();if(!g){l.failed(`Failed to export agent ${f.id}`,"manager unavailable");return}l.pending(`Reading the handover for agent ${f.id}`),(async()=>{let b=await g.exportHandover(f.id);if(b.kind==="faulted"){l.outcome(Ke(b),`Agent ${f.id} ${Ae(b.fault)}`);return}w(b)})()},"readExport"),k=t(f=>{let w=[{value:"clipboard",label:"Export to clipboard",description:"Copy this run's handover text to the clipboard"},{value:"file",label:"Export to file",description:"Write the handover text to a file you choose"}],g=B(new $r(w,10,Z(o)));g.onSelect=b=>{if(b.value==="clipboard"){m(f,O=>C(f,O));return}m(f,O=>h(f,O,O.defaultPath))},g.onCancel=()=>s(),a(g)},"showChoice");return k}t(jn,"createStatusExport");import{SelectList as Lr}from"@earendil-works/pi-tui";function Fn(e){let{ctx:n,theme:o,view:r,close:s,requestRender:i,backToActions:l}=e,a=Y(n.ui),c=t(m=>{r.activate(m),i()},"show"),u=t((m,k)=>{s(),a.outcome("warning",`Agent ${m.id} ${k}`)},"refuse"),d=t((m,k)=>{let f=J();if(s(),!f){a.failed(`Failed to hand agent ${m.id} over to ${k}`,"manager unavailable");return}a.pending(`Handing agent ${m.id} over to ${k}`),(async()=>{let w=await f.handover(m.id,{harness:k});a.outcome(Gt(w),sn(m.id,w))})()},"runHandover"),h=t((m,k)=>{let f=_(),w=on(f,re(),k).map(b=>({value:`harness:${b}`,label:`Hand over to ${f.displayName(b)}`,description:`Launch the next run of this agent under ${f.displayName(b)}`}));if(w.length===0){u(m,"was not handed over: no other harness can take it over.");return}let g=B(new Lr(w,10,Z(o)));g.onSelect=b=>{d(m,b.value.slice(8))},g.onCancel=()=>s(),c(g)},"openSubmenu"),C=t((m,k)=>{c(ye({theme:o,message:`Agent ${m.id} is still running.`,detail:`pi-cowboy will need to stop it before it can be handed over. Proceed?
4
4
 
@@ -8,4 +8,4 @@ You have been invoked to handle a specific task autonomously`,"utf-8"),e.ui.noti
8
8
  `,1)[0]??"").slice(0,zr),R=Bt(),F=tn();try{await R.spawn(o,{spawnId:f,type:h.type,requestedHarness:h.harness,prompt:m,description:O,orchestration:F,modelChoice:h.modelChoice,worktree:b,hostRef:w?.hostRef,projectTrusted:w?.projectTrusted,invocation:{...zn(h.modelChoice),runInBackground:h.runInBackground,fork:h.fork},runInBackground:h.runInBackground,fork:h.fork})}catch($){let H=`Spawn failed: ${$ instanceof Error?$.message:String($)}`;if(!w){e.ui.notify(H,"error");return}let G=await w.teardown(k);e.ui.notify(`${H}
9
9
 
10
10
  ${un(G)}`,"error")}},"launch"),a=await or(e,n);if(a===void 0)return;let c=new K(e),u;if(a.worktreeChoice.kind==="new"){let h=await nr(c,(C,m)=>e.ui.notify(C,m));if(h===void 0)return;u={kind:"new",branch:h}}else u=a.worktreeChoice;let d=await c.open(({tui:h,theme:C,keybindings:m,close:k})=>new N(rr({prefill:"",onDone:t(f=>k(f),"onDone"),onCancel:t(()=>k(),"onCancel"),tui:h,theme:C,keybindings:m}),{title:"Agent Prompt (optional)",theme:C,passthroughKeys:!0}));d!==void 0&&await l(a,u,d)}t(ir,"showSpawnAgentMenu");async function Yr(e){return await new K(e).open(({theme:n,close:o})=>{let r=t(u=>o(u),"handOff"),s=E(),i=s.agent.showActiveIndicator,l=s.agent.grazingEnabled,a=[Ce("concurrency","Concurrency Settings","Set per-model slot limits",r),Ce("spawnoptions","Agent behavior","spawn defaults, results delivery, output, tools, worktrees",r),Ce("systemprompt","System prompt","Prompt mode, AGENTS.md, skills, extensions",r),{id:"showActiveIndicator",label:"Show cowboy \u{1F920}",currentValue:i?"ON":"OFF",values:["ON","OFF"]},{id:"grazingEnabled",label:"Grazing \u{1F404}",currentValue:l?"ON":"OFF",values:["ON","OFF"]}],c=new sr(a,10,D(n),(u,d)=>{u==="showActiveIndicator"?an(e.ui,d==="ON"):u==="grazingEnabled"&&s.mutate.agent.setGrazingEnabled(d==="ON")},o);return new N(c,{title:"Settings",theme:n,onCancel:o})})}t(Yr,"showSettingsList");async function Xr(e,n){for(;;){let o=await Yr(e);if(o===void 0)return;switch(o){case"concurrency":await En(e,n);break;case"spawnoptions":await Kn(e);break;case"systemprompt":await Bn(e);break}}}t(Xr,"showSettingsMenu");async function Zr(e,n,o){switch(n){case"status":await Vn(e);break;case"spawn":await ir(e,o);break;case"settings":await Xr(e,o);break}}t(Zr,"showAgentsActionMenu");function Ce(e,n,o,r){return{id:e,label:n,description:o,currentValue:"",submenu:t(()=>(r(e),ie),"submenu")}}t(Ce,"handOffRow");async function Jr(e,n){let o=await hn(e.cwd),r;return await new K(e).open(({tui:s,theme:i,close:l})=>{let a=t(d=>l(d),"handOff"),c=t(()=>{let d=E(),h=t((k,f)=>e.ui.notify(k,f),"notify"),C=d.agent.extensionEnabled,m={id:"extensionEnabled",label:"Enabled",currentValue:C?"ON":"OFF",values:["ON","OFF"],description:C?"Unload the cowboy tools and stop subagent-result notifications. Persisted; active agents keep working.":"cowboy tools are unloaded and the rest of this menu is hidden. Active agents keep working."};return C?[xn({ctx:e,store:d,theme:i,harnessModelOptions:n,requestRender:t(()=>s.requestRender(),"requestRender"),piDefaultThinking:o}),qn({store:d,theme:i,notify:h}),Gn({store:d,theme:i,notify:h}),Ce("status","Status","List spawned, queued and settled agents",a),Ce("spawn","Spawn agent","Manually spawn a new agent",a),Ce("settings","Settings","Concurrency, agent behavior, and system prompt settings",a),m]:[m]},"buildItems"),u=new sr(c(),10,D(i),(d,h)=>{let C=d==="extensionEnabled";if(C){let m=h==="ON";gn(e.ui,m),e.ui.notify(m?"pi-cowboy enabled":"pi-cowboy disabled","info")}r?.(c(),C?"extensionEnabled":void 0)},l);return new N(u,{title:"Agents",theme:i,onCancel:l,onRebuild:t(d=>{r=d},"onRebuild")})})}t(Jr,"showAgentsMainList");async function il(e,n){for(;;){let o=await Jr(e,n);if(o===void 0)return;await Zr(e,o,n)}}t(il,"showAgentsMainMenu");export{Zr as showAgentsActionMenu,il as showAgentsMainMenu,Xr as showSettingsMenu,ir as showSpawnAgentMenu};
11
- //# sourceMappingURL=menus-JXTLTNVP.js.map
11
+ //# sourceMappingURL=menus-FKHSUINJ.js.map
@@ -1,2 +1,2 @@
1
- import{a as E,b as R,i as A}from"./chunk-DD4TYA7R.js";import{ja as v,ka as u,na as c,xa as S,ya as k}from"./chunk-FCLYV3G3.js";import{J as h,K as C,a as s,q as w,r as m}from"./chunk-YEXMGUZI.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
- //# sourceMappingURL=model-picker-H7RSOGDK.js.map
1
+ import{a as E,b as R,i as A}from"./chunk-OR6LWM7F.js";import{ja as v,ka as u,na as c,xa as S,ya as k}from"./chunk-73OMG4YX.js";import{J as h,K as C,a as s,q as w,r as m}from"./chunk-AOUEQXPY.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
+ //# sourceMappingURL=model-picker-NKZSDUHE.js.map
@@ -1,2 +1,2 @@
1
- import{C as e,D as s,E as r,F as n,G as t,J as o,K as a,M as i,N as H}from"../chunk-YEXMGUZI.js";export{n as RESERVED_ENV_VARS_BY_FAMILY,s as isReservedEnvVar,e as isUniversalReservedEnvVar,H as launchEnvBody,o as modelListEntries,a as modelListNotice,t as otherRecord,r as reservedEnvVarsOf,i as singleQuoteShellWord};
1
+ import{C as e,D as s,E as r,F as n,G as t,J as o,K as a,M as i,N as H}from"../chunk-AOUEQXPY.js";export{n as RESERVED_ENV_VARS_BY_FAMILY,s as isReservedEnvVar,e as isUniversalReservedEnvVar,H as launchEnvBody,o as modelListEntries,a as modelListNotice,t as otherRecord,r as reservedEnvVarsOf,i as singleQuoteShellWord};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cowboy",
3
- "version": "0.36.0",
3
+ "version": "0.36.2",
4
4
  "type": "module",
5
5
  "packageManager": "pnpm@12.9.1",
6
6
  "description": "🤠 Agent orchestrator for pi. It can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents and handover sessions in between them. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",