pi-cowboy 0.22.1 → 0.22.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.
@@ -1,22 +1,20 @@
1
1
  name = "Explore"
2
2
  display_name = "Explore"
3
- description = "Fast codebase exploration agent (read-only)"
3
+ description = "Fast codebase exploration agent (no code modifications)"
4
4
 
5
5
  system_prompt = '''
6
- # CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
6
+ # CRITICAL: NO CODEBASE MODIFICATIONS
7
7
 
8
8
  You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
9
- Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
9
+ Your role is to search and analyze existing code. If other instructions direct you to write non-code files (such as deliverables or reports), follow those, but never edit or modify the codebase.
10
10
 
11
11
  You are STRICTLY PROHIBITED from:
12
12
 
13
- - Creating new files
14
- - Modifying existing files
15
- - Deleting files
16
- - Moving or copying files
17
- - Creating temporary files anywhere, including /tmp
18
- - Using redirect operators (>, >>, |) or heredocs to write to files
19
- - Running ANY commands that change system state
13
+ - Creating new codebase files
14
+ - Modifying existing codebase files
15
+ - Deleting, moving, or copying codebase files
16
+ - Using redirect operators (>, >>, |) or heredocs to write to repository files
17
+ - Running ANY commands that change codebase or system state
20
18
 
21
19
  Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
22
20
 
@@ -37,4 +35,4 @@ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find,
37
35
  - Be thorough and precise'''
38
36
 
39
37
  [harness.pi]
40
- tools = ["read", "bash", "grep", "find"]
38
+ tools = ["read", "write", "bash", "grep", "find"]
@@ -1,4 +1,4 @@
1
- import{a as r,c as Xn,d as m,j as Re,k as Ce,l as k,m as cn,n as Jn,o as qn,q as Qn,t as Pe,u as Zn,v as T,w as I,x as et,y as R}from"./chunk-254PTGN5.js";import*as q from"node:path";import*as tt from"node:fs";import{homedir as dn,tmpdir as eo}from"node:os";import*as v from"node:path";import{fileURLToPath as rt}from"node:url";var nt={name:"pi-cowboy",version:"0.22.1",type:"module",packageManager:"pnpm@12.9.1",description:"Agent orchestrator for pi: can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents. 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/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.88.0","oxlint-tsgolint":"7.0.2004",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 un=nt.name,no="PI_CODING_AGENT_DIR";function to(){let n=process.env[no];return n?pn(n):v.join(dn(),".pi","agent")}r(to,"agentDir");function pn(n){return n==="~"?dn():n.startsWith("~/")?v.join(dn(),n.slice(2)):n}r(pn,"expandTilde");function V(n){try{return tt.realpathSync.native(n)}catch{return}}r(V,"canonicalPath");function Se(){return v.join(to(),un)}r(Se,"defaultExtensionDir");function ot(){return v.join(Se(),"worktrees")}r(ot,"defaultWorktreeRoot");function ro(){return v.join(eo(),"pi-cowboy")}r(ro,"subagentResultDir");function L(n){return v.join(ro(),n)}r(L,"subagentResultDirFor");function ga(n){return v.join(L(n),"result.md")}r(ga,"subagentResultFileFor");var oo="system.md",io="prompt.md";function fa(n){return v.join(L(n),oo)}r(fa,"subagentSystemFileFor");var so="env.sh";function ma(n){return v.join(L(n),so)}r(ma,"subagentEnvFileFor");function ya(n){return v.join(L(n),io)}r(ya,"subagentTaskFileFor");var gn="cowboy-subagent-";function X(n){return`${gn}${n}`}r(X,"subagentTokenFor");var ha=rt(new URL("../agents/",import.meta.url)),ba=rt(new URL("../orchestrators/",import.meta.url));function va(n){return{status:"known",available:new Set(n)}}r(va,"probed");function fn(){return{status:"unknown"}}r(fn,"unprobed");function le(n,e){return e.status==="unknown"||e.available.has(n)}r(le,"isAvailable");function wa(n,e){return n.filter(t=>le(t,e))}r(wa,"selectable");function it(n,e){return e.status==="known"&&e.available.has(n)}r(it,"isProven");import{randomBytes as ao}from"node:crypto";import{Buffer as ce}from"buffer";var J="0123456789ABCDEFGHJKMNPQRSTVWXYZ",st="*~$=U",Oe=class extends Error{static{r(this,"InvalidChecksumCharacterError")}constructor(e){super(e),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},mn=class extends Error{static{r(this,"InvalidChecksumError")}constructor(e){super(e),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},_e=class{static{r(this,"CrockfordBase32")}static encode(e,t){ce.isBuffer(e)?e=ce.from(e):e=this.createBuffer(e);let o=t?.variant??"crockford",i=t?.checksum??!1;if(o==="ulid"){if(i)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(e)}let s=[],a=0,l=0;for(let d of e)for(l=l<<8|d,a+=8;a>=5;)s.push(l>>>a-5&31),a-=5;a>0&&s.push(l<<5-a&31);let u=s.map(d=>J.charAt(d)).join("");return i&&(u+=this.computeChecksum(e)),u}static computeChecksum(e){let t=0;for(let o of e)t=(t*256+o)%37;return(J+st).charAt(t)}static decode(e,t){e=e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let o=t?.variant??"crockford",i=t?.checksum??!1;if(o==="ulid"){if(i)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(e,t)}let s=null;if(i){if(e.length===0)throw new Oe("Cannot validate checksum: input is empty");let d=e.charAt(e.length-1);if((J+st).indexOf(d)===-1)throw new Oe(`Invalid checksum character: ${d}`);s=d,e=e.slice(0,-1)}let a=[],l=0,u=0;for(let d of e){let p=J.indexOf(d);if(p===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);l+=5,l>=8?(l-=8,a.push(u|p>>l),u=p<<8-l&255):u|=p<<8-l}if((u>0||l>=5)&&a.push(u),s!==null){let d=this.computeChecksum(a);if(s!==d)throw new mn(`Checksum mismatch: expected '${d}' but found '${s}'`)}return t?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(e){try{return this.decode(e,{checksum:!0}),!0}catch{return!1}}static encodeUlid(e){if(e.length===0)return"";let t=0n;for(let s of e)t=t<<8n|BigInt(s);let o=[];for(;t>0n;){let s=Number(t%32n);o.unshift(J.charAt(s)),t/=32n}let i=Math.ceil(e.length*8/5);return o.join("").padStart(i,"0")}static decodeUlid(e,t){if(e.length===0)return t?.asNumber===!0?0n:ce.from([]);let o=0n;for(let l of e){let u=J.indexOf(l);if(u===-1)throw new Error(`Invalid base 32 character found in string: ${l}`);o=o*32n+BigInt(u)}let i=Math.floor(e.length*5/8),s=[],a=o;for(;a>0n;)s.unshift(Number(a&0xffn)),a>>=8n;for(o===0n&&s.push(0);s.length<i;)s.unshift(0);return t?.asNumber===!0?this.asNumber(s):this.asBuffer(s)}static createBuffer(e){if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("Input must be a safe integer");e=BigInt(e)}if(e<0n)throw new Error("Input cannot be a negative number");let t=[];for(;e>0n;)t.unshift(Number(e&0xffn)),e>>=8n;return ce.from(t)}static asNumber(e){let t=0n;return e.forEach(o=>{t<<=8n,t|=BigInt(o)}),t}static asBuffer(e){return ce.from(e.map(t=>t.toString(16).padStart(2,"0")).join(""),"hex")}};var lt="0123456789abcdefghjkmnpqrstvwxyz",Me=8,lo=5,at=32,yn=class extends Error{static{r(this,"SpawnIdExhaustedError")}constructor(e){super(`Could not mint a unique spawn id after ${e} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function hn(){return _e.encode(ao(lo)).toLowerCase()}r(hn,"generateSpawnId");function ct(n,e=hn){for(let t=0;t<at;t++){let o=e();if(!n(o))return o}throw new yn(at)}r(ct,"generateUniqueSpawnId");var Le="cow-",de="copy-on-write",Ha=["copy-on-write","checkout"];function Na(n){if(n==="copy-on-write"||n==="checkout")return n}r(Na,"parseWorktreeMaterialization");function gt(n,e){return le("copy-on-write",e)?n??de:"checkout"}r(gt,"resolveWorktreeMaterialization");var He="clean",Da=["dirty","clean"];function ja(n){if(n==="dirty"||n==="clean")return n}r(ja,"parseWorktreeCheckoutType");var dt=3,co=32,ut=co-Le.length-1-Me;function uo(n){return n.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}r(uo,"slugifyWorktreeType");function po(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(e=>e.length>0)}r(po,"taskNameWords");function Fa(n){let e=po(n);if(e.length===0)throw new Error("Task name is empty \u2014 provide a short 2-3 word name.");if(e.length>dt)throw new Error(`Task name "${n}" gives the branch name "${e.join("-")}" with ${e.length} words. The limit is ${dt} words.`);let t=e.join("-");if(t.length>ut)throw new Error(`Task name "${n}" gives the branch name "${t}" with ${t.length} characters. The limit is ${ut} characters, because herdr limits agent names to 32 characters.`);return t}r(Fa,"buildTaskSlug");function go(n,e){return`${Le}${uo(n)}-${e}`}r(go,"buildWorktreeBranch");function $a(n,e,t){return q.join(n,go(e,t))}r($a,"buildWorktreePath");function Ka(n,e){return n&&n.trim()!==""?q.isAbsolute(n)?n:q.resolve(e,n):ot()}r(Ka,"resolveWorktreeRoot");function pt(n){return(V(n)??n.replace(/\\/g,"/")).replace(/\/+$/,"")}r(pt,"normalizeRoot");function Wa(n,e){return e!==""&&n.startsWith(Le)&&n.length>e.length&&n.endsWith(`-${e}`)}r(Wa,"isSpawnArtifactName");function Ga(n,e){let t=pt(n),o=pt(e);return t!==o&&!t.startsWith(`${o}/`)?!1:(t.split("/").filter(Boolean).pop()??"").startsWith(Le)}r(Ga,"isExtensionWorktree");import{getSupportedThinkingLevels as ia}from"@earendil-works/pi-ai";var Ne=class{static{r(this,"RepoLock")}tails=new Map;async run(e,t){let o=(this.tails.get(e)??Promise.resolve()).then(t),i=o.then(()=>{},()=>{});this.tails.set(e,i);try{return await o}finally{this.tails.get(e)===i&&this.tails.delete(e)}}};import*as Q from"node:fs";import*as De from"node:path";function P(n){for(let e of(process.env.PATH??"").split(De.delimiter)){if(e==="")continue;let t=De.join(e,n);try{if(!Q.statSync(t).isFile())continue;return Q.accessSync(t,Q.constants.X_OK),t}catch{}}}r(P,"commandPath");function Va(n){return P(n)??n}r(Va,"resolveCommand");function bn(n){let e=["--system-prompt",n.systemPromptFile,"--append-system-prompt",X(n.subagentId),"--name",n.subagentId,"--no-context-files"];n.modelKey!==null&&e.push("--model",n.modelKey),n.thinking!==null&&e.push("--thinking",n.thinking),n.forkSessionFile!==null&&e.push("--fork",n.forkSessionFile);let t=n.toolSelection;if(t.kind==="none"?e.push("--no-tools"):t.kind==="include"?e.push("--tools",t.names.join(",")):t.kind==="exclude"&&e.push("--exclude-tools",t.names.join(",")),n.skills.kind==="none"&&e.push("--no-skills"),n.extensions.kind==="none")e.push("--no-extensions");else if(n.extensions.kind==="paths"){e.push("--no-extensions");for(let o of n.extensions.paths)e.push("-e",o)}return e.push(n.projectTrusted?"--approve":"--no-approve"),e.push(`@${n.taskFile}`),e}r(bn,"buildPiLaunchArgs");var En=r(async({modelCatalog:n})=>({kind:"listed",entries:n.getAvailable().map(e=>({key:`${e.provider}/${e.id}`,thinkingLevels:{kind:"closed",levels:e.thinkingLevels}}))}),"piFamilyListModels");function je(n){return{agentMultiplexerKind:"pi",availability:r(()=>P(n.binary)===void 0?{status:"unavailable"}:{status:"available"},"availability"),buildArgs:bn,listModels:En,prefetchModels:r(()=>{},"prefetchModels"),teardown:r(async()=>{},"teardown"),async prepare({pane:e,paneId:t,launch:o}){await R(e,t,{commandName:"pi",body:`export HERDR_AGENT=pi; ${I(o.envFile,`${n.binary} "$@"`)}`,signature:n.signature,readyMarker:n.readyMarker})}}}r(je,"createPiCompatibleHarness");var ft=je({binary:"pig",signature:"PIG_LAUNCHER_8f9a2b",readyMarker:"PIG_VERIFIED"});var mt=je({binary:"pi-bolt",signature:"PI_BOLT_LAUNCHER_5e1c7a",readyMarker:"PI_BOLT_VERIFIED"});import{z as S}from"zod";var Fe=["agent","agents","autoupdate","experimental","instructions","mode","permission","permissions","plugin","plugins","policies","reference","references","skills","tools","update"],fo=new Set(Fe),mo=`one of: ${Fe.join(", ")}`;function yo(n){return fo.has(n)}r(yo,"isOpencodeConfigIncludeRoot");var yt={scope:"global",parse({global:n},e){let t=[];if(n===void 0)return{configInclude:t};let o=n.configInclude;if(o===void 0)return{configInclude:t};if(!Array.isArray(o))return e({layer:"global",keyPath:"configInclude",got:o,expected:"array of root keys"}),{configInclude:t};for(let[i,s]of o.entries()){if(typeof s!="string"||!yo(s)){e({layer:"global",keyPath:`configInclude[${i}]`,got:s,expected:mo});continue}t.includes(s)||t.push(s)}return{configInclude:t}}};import _t from"node:fs";import*as Mt from"node:path";import ho from"node:fs";import*as An from"node:path";import{stringify as bo}from"yaml";import $e from"node:fs";var ht=448,bt=384;function Z(n){$e.mkdirSync(n,{recursive:!0,mode:ht}),$e.chmodSync(n,ht)}r(Z,"ensureResultDir");function H(n,e){$e.writeFileSync(n,e,{encoding:"utf-8",mode:bt}),$e.chmodSync(n,bt)}r(H,"writeResultFile");var Et="question";function N(n,e){return{action:n,resource:"*",effect:e}}r(N,"rule");function At(n){switch(n.kind){case"default":return[N("*","allow"),N(Et,"deny")];case"none":return[N("*","deny")];case"include":return[N("*","deny"),...n.names.map(e=>N(e,"allow"))];case"exclude":return[N("*","allow"),N(Et,"deny"),...n.names.map(e=>N(e,"deny"))]}}r(At,"opencodePermissions");var vt="agent",Eo=".md";function Ao(n){return bo({description:X(n.subagentId),mode:"primary",permissions:At(n.toolSelection)},{lineWidth:0})}r(Ao,"frontmatter");function vo(n){return`---
1
+ import{a as r,c as Xn,d as m,j as Re,k as Ce,l as k,m as cn,n as Jn,o as qn,q as Qn,t as Pe,u as Zn,v as T,w as I,x as et,y as R}from"./chunk-254PTGN5.js";import*as q from"node:path";import*as tt from"node:fs";import{homedir as dn,tmpdir as eo}from"node:os";import*as v from"node:path";import{fileURLToPath as rt}from"node:url";var nt={name:"pi-cowboy",version:"0.22.2",type:"module",packageManager:"pnpm@12.9.1",description:"Agent orchestrator for pi: can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents. 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.89.0","oxlint-tsgolint":"7.0.2004",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 un=nt.name,no="PI_CODING_AGENT_DIR";function to(){let n=process.env[no];return n?pn(n):v.join(dn(),".pi","agent")}r(to,"agentDir");function pn(n){return n==="~"?dn():n.startsWith("~/")?v.join(dn(),n.slice(2)):n}r(pn,"expandTilde");function V(n){try{return tt.realpathSync.native(n)}catch{return}}r(V,"canonicalPath");function Se(){return v.join(to(),un)}r(Se,"defaultExtensionDir");function ot(){return v.join(Se(),"worktrees")}r(ot,"defaultWorktreeRoot");function ro(){return v.join(eo(),"pi-cowboy")}r(ro,"subagentResultDir");function L(n){return v.join(ro(),n)}r(L,"subagentResultDirFor");function ga(n){return v.join(L(n),"result.md")}r(ga,"subagentResultFileFor");var oo="system.md",io="prompt.md";function fa(n){return v.join(L(n),oo)}r(fa,"subagentSystemFileFor");var so="env.sh";function ma(n){return v.join(L(n),so)}r(ma,"subagentEnvFileFor");function ya(n){return v.join(L(n),io)}r(ya,"subagentTaskFileFor");var gn="cowboy-subagent-";function X(n){return`${gn}${n}`}r(X,"subagentTokenFor");var ha=rt(new URL("../agents/",import.meta.url)),ba=rt(new URL("../orchestrators/",import.meta.url));function va(n){return{status:"known",available:new Set(n)}}r(va,"probed");function fn(){return{status:"unknown"}}r(fn,"unprobed");function le(n,e){return e.status==="unknown"||e.available.has(n)}r(le,"isAvailable");function wa(n,e){return n.filter(t=>le(t,e))}r(wa,"selectable");function it(n,e){return e.status==="known"&&e.available.has(n)}r(it,"isProven");import{randomBytes as ao}from"node:crypto";import{Buffer as ce}from"buffer";var J="0123456789ABCDEFGHJKMNPQRSTVWXYZ",st="*~$=U",Oe=class extends Error{static{r(this,"InvalidChecksumCharacterError")}constructor(e){super(e),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},mn=class extends Error{static{r(this,"InvalidChecksumError")}constructor(e){super(e),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},_e=class{static{r(this,"CrockfordBase32")}static encode(e,t){ce.isBuffer(e)?e=ce.from(e):e=this.createBuffer(e);let o=t?.variant??"crockford",i=t?.checksum??!1;if(o==="ulid"){if(i)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(e)}let s=[],a=0,l=0;for(let d of e)for(l=l<<8|d,a+=8;a>=5;)s.push(l>>>a-5&31),a-=5;a>0&&s.push(l<<5-a&31);let u=s.map(d=>J.charAt(d)).join("");return i&&(u+=this.computeChecksum(e)),u}static computeChecksum(e){let t=0;for(let o of e)t=(t*256+o)%37;return(J+st).charAt(t)}static decode(e,t){e=e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let o=t?.variant??"crockford",i=t?.checksum??!1;if(o==="ulid"){if(i)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(e,t)}let s=null;if(i){if(e.length===0)throw new Oe("Cannot validate checksum: input is empty");let d=e.charAt(e.length-1);if((J+st).indexOf(d)===-1)throw new Oe(`Invalid checksum character: ${d}`);s=d,e=e.slice(0,-1)}let a=[],l=0,u=0;for(let d of e){let p=J.indexOf(d);if(p===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);l+=5,l>=8?(l-=8,a.push(u|p>>l),u=p<<8-l&255):u|=p<<8-l}if((u>0||l>=5)&&a.push(u),s!==null){let d=this.computeChecksum(a);if(s!==d)throw new mn(`Checksum mismatch: expected '${d}' but found '${s}'`)}return t?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(e){try{return this.decode(e,{checksum:!0}),!0}catch{return!1}}static encodeUlid(e){if(e.length===0)return"";let t=0n;for(let s of e)t=t<<8n|BigInt(s);let o=[];for(;t>0n;){let s=Number(t%32n);o.unshift(J.charAt(s)),t/=32n}let i=Math.ceil(e.length*8/5);return o.join("").padStart(i,"0")}static decodeUlid(e,t){if(e.length===0)return t?.asNumber===!0?0n:ce.from([]);let o=0n;for(let l of e){let u=J.indexOf(l);if(u===-1)throw new Error(`Invalid base 32 character found in string: ${l}`);o=o*32n+BigInt(u)}let i=Math.floor(e.length*5/8),s=[],a=o;for(;a>0n;)s.unshift(Number(a&0xffn)),a>>=8n;for(o===0n&&s.push(0);s.length<i;)s.unshift(0);return t?.asNumber===!0?this.asNumber(s):this.asBuffer(s)}static createBuffer(e){if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error("Input must be a safe integer");e=BigInt(e)}if(e<0n)throw new Error("Input cannot be a negative number");let t=[];for(;e>0n;)t.unshift(Number(e&0xffn)),e>>=8n;return ce.from(t)}static asNumber(e){let t=0n;return e.forEach(o=>{t<<=8n,t|=BigInt(o)}),t}static asBuffer(e){return ce.from(e.map(t=>t.toString(16).padStart(2,"0")).join(""),"hex")}};var lt="0123456789abcdefghjkmnpqrstvwxyz",Me=8,lo=5,at=32,yn=class extends Error{static{r(this,"SpawnIdExhaustedError")}constructor(e){super(`Could not mint a unique spawn id after ${e} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function hn(){return _e.encode(ao(lo)).toLowerCase()}r(hn,"generateSpawnId");function ct(n,e=hn){for(let t=0;t<at;t++){let o=e();if(!n(o))return o}throw new yn(at)}r(ct,"generateUniqueSpawnId");var Le="cow-",de="copy-on-write",Ha=["copy-on-write","checkout"];function Na(n){if(n==="copy-on-write"||n==="checkout")return n}r(Na,"parseWorktreeMaterialization");function gt(n,e){return le("copy-on-write",e)?n??de:"checkout"}r(gt,"resolveWorktreeMaterialization");var He="clean",Da=["dirty","clean"];function ja(n){if(n==="dirty"||n==="clean")return n}r(ja,"parseWorktreeCheckoutType");var dt=3,co=32,ut=co-Le.length-1-Me;function uo(n){return n.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}r(uo,"slugifyWorktreeType");function po(n){return n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(e=>e.length>0)}r(po,"taskNameWords");function Fa(n){let e=po(n);if(e.length===0)throw new Error("Task name is empty \u2014 provide a short 2-3 word name.");if(e.length>dt)throw new Error(`Task name "${n}" gives the branch name "${e.join("-")}" with ${e.length} words. The limit is ${dt} words.`);let t=e.join("-");if(t.length>ut)throw new Error(`Task name "${n}" gives the branch name "${t}" with ${t.length} characters. The limit is ${ut} characters, because herdr limits agent names to 32 characters.`);return t}r(Fa,"buildTaskSlug");function go(n,e){return`${Le}${uo(n)}-${e}`}r(go,"buildWorktreeBranch");function $a(n,e,t){return q.join(n,go(e,t))}r($a,"buildWorktreePath");function Ka(n,e){return n&&n.trim()!==""?q.isAbsolute(n)?n:q.resolve(e,n):ot()}r(Ka,"resolveWorktreeRoot");function pt(n){return(V(n)??n.replace(/\\/g,"/")).replace(/\/+$/,"")}r(pt,"normalizeRoot");function Wa(n,e){return e!==""&&n.startsWith(Le)&&n.length>e.length&&n.endsWith(`-${e}`)}r(Wa,"isSpawnArtifactName");function Ga(n,e){let t=pt(n),o=pt(e);return t!==o&&!t.startsWith(`${o}/`)?!1:(t.split("/").filter(Boolean).pop()??"").startsWith(Le)}r(Ga,"isExtensionWorktree");import{getSupportedThinkingLevels as ia}from"@earendil-works/pi-ai";var Ne=class{static{r(this,"RepoLock")}tails=new Map;async run(e,t){let o=(this.tails.get(e)??Promise.resolve()).then(t),i=o.then(()=>{},()=>{});this.tails.set(e,i);try{return await o}finally{this.tails.get(e)===i&&this.tails.delete(e)}}};import*as Q from"node:fs";import*as De from"node:path";function P(n){for(let e of(process.env.PATH??"").split(De.delimiter)){if(e==="")continue;let t=De.join(e,n);try{if(!Q.statSync(t).isFile())continue;return Q.accessSync(t,Q.constants.X_OK),t}catch{}}}r(P,"commandPath");function Va(n){return P(n)??n}r(Va,"resolveCommand");function bn(n){let e=["--system-prompt",n.systemPromptFile,"--append-system-prompt",X(n.subagentId),"--name",n.subagentId,"--no-context-files"];n.modelKey!==null&&e.push("--model",n.modelKey),n.thinking!==null&&e.push("--thinking",n.thinking),n.forkSessionFile!==null&&e.push("--fork",n.forkSessionFile);let t=n.toolSelection;if(t.kind==="none"?e.push("--no-tools"):t.kind==="include"?e.push("--tools",t.names.join(",")):t.kind==="exclude"&&e.push("--exclude-tools",t.names.join(",")),n.skills.kind==="none"&&e.push("--no-skills"),n.extensions.kind==="none")e.push("--no-extensions");else if(n.extensions.kind==="paths"){e.push("--no-extensions");for(let o of n.extensions.paths)e.push("-e",o)}return e.push(n.projectTrusted?"--approve":"--no-approve"),e.push(`@${n.taskFile}`),e}r(bn,"buildPiLaunchArgs");var En=r(async({modelCatalog:n})=>({kind:"listed",entries:n.getAvailable().map(e=>({key:`${e.provider}/${e.id}`,thinkingLevels:{kind:"closed",levels:e.thinkingLevels}}))}),"piFamilyListModels");function je(n){return{agentMultiplexerKind:"pi",availability:r(()=>P(n.binary)===void 0?{status:"unavailable"}:{status:"available"},"availability"),buildArgs:bn,listModels:En,prefetchModels:r(()=>{},"prefetchModels"),teardown:r(async()=>{},"teardown"),async prepare({pane:e,paneId:t,launch:o}){await R(e,t,{commandName:"pi",body:`export HERDR_AGENT=pi; ${I(o.envFile,`${n.binary} "$@"`)}`,signature:n.signature,readyMarker:n.readyMarker})}}}r(je,"createPiCompatibleHarness");var ft=je({binary:"pig",signature:"PIG_LAUNCHER_8f9a2b",readyMarker:"PIG_VERIFIED"});var mt=je({binary:"pi-bolt",signature:"PI_BOLT_LAUNCHER_5e1c7a",readyMarker:"PI_BOLT_VERIFIED"});import{z as S}from"zod";var Fe=["agent","agents","autoupdate","experimental","instructions","mode","permission","permissions","plugin","plugins","policies","reference","references","skills","tools","update"],fo=new Set(Fe),mo=`one of: ${Fe.join(", ")}`;function yo(n){return fo.has(n)}r(yo,"isOpencodeConfigIncludeRoot");var yt={scope:"global",parse({global:n},e){let t=[];if(n===void 0)return{configInclude:t};let o=n.configInclude;if(o===void 0)return{configInclude:t};if(!Array.isArray(o))return e({layer:"global",keyPath:"configInclude",got:o,expected:"array of root keys"}),{configInclude:t};for(let[i,s]of o.entries()){if(typeof s!="string"||!yo(s)){e({layer:"global",keyPath:`configInclude[${i}]`,got:s,expected:mo});continue}t.includes(s)||t.push(s)}return{configInclude:t}}};import _t from"node:fs";import*as Mt from"node:path";import ho from"node:fs";import*as An from"node:path";import{stringify as bo}from"yaml";import $e from"node:fs";var ht=448,bt=384;function Z(n){$e.mkdirSync(n,{recursive:!0,mode:ht}),$e.chmodSync(n,ht)}r(Z,"ensureResultDir");function H(n,e){$e.writeFileSync(n,e,{encoding:"utf-8",mode:bt}),$e.chmodSync(n,bt)}r(H,"writeResultFile");var Et="question";function N(n,e){return{action:n,resource:"*",effect:e}}r(N,"rule");function At(n){switch(n.kind){case"default":return[N("*","allow"),N(Et,"deny")];case"none":return[N("*","deny")];case"include":return[N("*","deny"),...n.names.map(e=>N(e,"allow"))];case"exclude":return[N("*","allow"),N(Et,"deny"),...n.names.map(e=>N(e,"deny"))]}}r(At,"opencodePermissions");var vt="agent",Eo=".md";function Ao(n){return bo({description:X(n.subagentId),mode:"primary",permissions:At(n.toolSelection)},{lineWidth:0})}r(Ao,"frontmatter");function vo(n){return`---
2
2
  ${Ao(n)}---
3
3
 
4
4
  ${n.systemPrompt}`}r(vo,"opencodeAgentMarkdown");function wt(n,e){return An.join(n,vt,`${e}${Eo}`)}r(wt,"definitionFile");function xt(n,e){Z(An.join(n,vt)),H(wt(n,e.subagentId),vo(e))}r(xt,"writeAgentDefinition");function kt(n,e){try{ho.rmSync(wt(n,e),{force:!0})}catch{}}r(kt,"removeAgentDefinition");import Tt from"node:fs";import{homedir as It}from"node:os";import*as E from"node:path";import{parse as xo}from"jsonc-parser";var wo=`[${lt}]{${Me}}`;function vn(n,e){return new RegExp(`^cow-${e}-${wo}$`).test(n)}r(vn,"isTaskAgentName");function y(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}r(y,"isRecord");var Rt=["opencode.json","opencode.jsonc"],Ct="explicit-config.json";function ko(){let n=xn("XDG_CONFIG_HOME")??E.join(It(),".config");return xn("OPENCODE_CONFIG_DIR")??E.join(n,"opencode")}r(ko,"userOpencodeConfigDir");function Pt(n){let e=ko(),t=new Map;for(let o of Rt){let i=E.join(e,o),s=St(i);s!==void 0&&t.set(o,Ot(s,n.configInclude,i))}return Co(n.configDir,t),To(n.configDir,n.configInclude)}r(Pt,"writeUserOpencodeConfig");function To(n,e){let t=xn("OPENCODE_CONFIG");if(t===void 0)return;let o=St(t);if(o===void 0)return;let i=E.join(n,Ct);return H(i,`${JSON.stringify(Ot(o,e,t),null,2)}
@@ -7,4 +7,4 @@ ${n.systemPrompt}`}r(vo,"opencodeAgentMarkdown");function wt(n,e){return An.join
7
7
  `}r(hi,"settingsJson");function bi(n){let e=V(n)??n;return`${JSON.stringify({hasCompletedOnboarding:!0,projects:{[e]:{hasTrustDialogAccepted:!0}}},null,2)}
8
8
  `}r(bi,"stateJson");function zt(n){let e=Yt(n.subagentId);return Z(e),H(ue.join(e,Bt),hi()),H(ue.join(e,yi),bi(n.cwd)),e}r(zt,"writeClaudeStaging");function Vt(n){try{fi.rmSync(Yt(n),{recursive:!0,force:!0})}catch{}}r(Vt,"removeClaudeStaging");var Ai=15e3,Tn="claude",vi="CLAUDE_LAUNCHER_3f7a1d",wi="CLAUDE_VERIFIED",xi="CLAUDE_STAGED";function ki(){return process.env.CLAUDE_SECURESTORAGE_CONFIG_DIR??process.env.CLAUDE_CONFIG_DIR??""}r(ki,"parentCredentialStore");function Ti(n){let e=ki();switch(n){case"darwin":return e;case"linux":{let t=e===""?ee.join(Ei(),".claude"):pn(e);return ee.isAbsolute(t)?t:ee.resolve(t)}default:return e}}r(Ti,"spawnCredentialStore");function Ii(n,e,t,o){let i=$(pe(n)),s=$(`${pe(n)}.tmp`);return[`if [ -n "\${ANTHROPIC_API_KEY:-}" ]; then export COWBOY_API_KEY="$ANTHROPIC_API_KEY"; unset ANTHROPIC_API_KEY; else grep -v '"apiKeyHelper"' ${i} > ${s} && mv ${s} ${i}; fi`,`export CLAUDE_SECURESTORAGE_CONFIG_DIR=${$(t)}`,`export CLAUDE_CONFIG_DIR=${$(n)}`,"export CLAUDE_CODE_DISABLE_CLAUDE_MDS=1",I(o,`command claude "$@" -- "$(cat ${$(e)})"`)].join("; ")}r(Ii,"launcherBody");function $(n){return`'${n.replaceAll("'","'\\''")}'`}r($,"singleQuote");function Ri(n,e){return{command:`test -r ${$(pe(n))} && test -r ${$(e)} && (unset -f ${Tn}; command -v ${Tn} >/dev/null) && echo CLAUDE_""STAGED`,output:xi,timeoutMs:Ai,failure:`failed to prepare the pane: the pane never proved it can see the staged claude state \u2014 the settings ${pe(n)}, the task ${e}, or the claude binary on its PATH. The agent did not start.`}}r(Ri,"stagedProof");function Ci(n){let e="anthropic/";return n.startsWith(e)?n.slice(e.length):n}r(Ci,"claudeModelName");function Pi(n){switch(n.toolSelection.kind){case"default":return[];case"none":return["--tools",""];case"include":return["--tools",n.toolSelection.names.join(",")];case"exclude":return["--disallowedTools",n.toolSelection.names.join(",")]}}r(Pi,"toolArgs");var Si=["low","medium","high","xhigh","max"],ge={kind:"closed",levels:Si},Oi=[{key:"anthropic/haiku",label:"haiku",thinkingLevels:ge},{key:"anthropic/sonnet",label:"sonnet",thinkingLevels:ge},{key:"anthropic/opus",label:"opus",thinkingLevels:ge},{key:"anthropic/fable",label:"fable",thinkingLevels:ge},{key:"anthropic/mythos",label:"mythos",thinkingLevels:ge}],Xt={agentMultiplexerKind:"claude",availability:r(()=>P("claude")===void 0?{status:"unavailable"}:{status:"available"},"availability"),async prepare({pane:n,paneId:e,cwd:t,launch:o}){let i=zt({subagentId:o.subagentId,cwd:t});await R(n,e,{commandName:Tn,body:Ii(i,o.taskFile,Ti(process.platform),o.envFile),signature:vi,readyMarker:wi,proof:Ri(i,o.taskFile)})},buildArgs(n){let e=["--system-prompt-file",n.systemPromptFile,"--append-system-prompt",X(n.subagentId),"-n",n.subagentId,"--dangerously-skip-permissions","--setting-sources","user","--strict-mcp-config"];return n.modelKey!==null&&e.push("--model",Ci(n.modelKey)),n.thinking!==null&&e.push("--effort",n.thinking),e.push(...Pi(n)),e},listModels:r(()=>Promise.resolve({kind:"listed",entries:Oi}),"listModels"),prefetchModels:r(n=>{},"prefetchModels"),teardown:r(async({subagentId:n})=>{Vt(n)},"teardown")};var _i="PI_ENV_LAUNCHER_4c7d19",Mi="PI_ENV_VERIFIED",Li={agentMultiplexerKind:"pi",availability:r(()=>({status:"available"}),"availability"),async prepare({pane:n,paneId:e,launch:t}){t.envFile!==null&&await R(n,e,{commandName:"pi",body:I(t.envFile,'command pi "$@"'),signature:_i,readyMarker:Mi})},buildArgs:bn,listModels:En,prefetchModels:r(()=>{},"prefetchModels"),teardown:r(async()=>{},"teardown")},K={pi:Li,pig:ft,"pi-bolt":mt,opencode:Kt,codex:Ut,claude:Xt},Hi={pi:"Pi",pig:"PiG","pi-bolt":"Pi-Bolt",opencode:"OpenCode",codex:"Codex",claude:"Claude"},Ni={pi:"pi",pig:"pi","pi-bolt":"pi",opencode:"opencode",codex:"codex",claude:"claude"};function Jt(n,e,t){switch(n){case"pi":return t(K.pi,ne(e,"pi"));case"pig":return t(K.pig,ne(e,"pi"));case"pi-bolt":return t(K["pi-bolt"],ne(e,"pi"));case"opencode":return t(K.opencode,ne(e,"opencode"));case"codex":return t(K.codex,ne(e,"codex"));case"claude":return t(K.claude,ne(e,"claude"));default:return Re(n)}}r(Jt,"withBuiltin");function ne(n,e){if(n.family!==e)throw new Error(`a "${n.family}" launch reached the "${e}" harness`);return n}r(ne,"familyRequest");function Di(n){let e=K[n];return{id:n,displayName:Hi[n],config:e.config,agentMultiplexerKind:e.agentMultiplexerKind,availability:r(()=>e.availability(),"availability"),prepare:r(t=>Jt(n,t.launch,(o,i)=>o.prepare({pi:t.pi,pane:t.pane,paneId:t.paneId,cwd:t.cwd,launch:i,config:t.config})),"prepare"),buildArgs:r(t=>Jt(n,t,(o,i)=>o.buildArgs(i)),"buildArgs"),teardown:r(t=>e.teardown(t),"teardown"),listModels:r(t=>e.listModels(t),"listModels"),prefetchModels:r(t=>e.prefetchModels(t),"prefetchModels")}}r(Di,"wrapBuiltin");function ji(n){return{...n,listModels:r(async e=>{let t=await n.listModels(e);return t.kind==="unavailable"?t:{...t,entries:t.entries.map(o=>({...o,thinkingLevels:Fi(o.thinkingLevels)}))}},"listModels")}}r(ji,"withOneLevelShape");function Fi(n){return $i(n)?{kind:"closed",levels:n}:n}r(Fi,"foldLevels");function $i(n){return Array.isArray(n)}r($i,"isFlatLevels");function In(){let n=new Map(Ce.map(i=>[i,Di(i)])),e=new Set,t=new Map,o={register(i){let s=cn(i.id)!==void 0?"a built-in harness owns that id":n.has(i.id)?"another plugin already registered that id in this load":void 0;return s!==void 0?(console.warn(`[subagents] Ignoring harness "${i.id}": ${s}`),!1):(n.set(i.id,ji(i)),e.add(i.id),!0)},unregister(i){e.has(i)&&(n.delete(i),e.delete(i),t.delete(i))},ids(){return[...n.keys()]},get(i){return n.get(i)},validateConfigs(i,s){for(let[a,l]of n){let u=l.config;if(u===void 0)continue;let d=u.scope==="project"?i.project[a]:void 0;try{t.set(a,u.parse({global:i.global[a],project:d},p=>s(a,p)))}catch(p){n.delete(a),e.delete(a),t.delete(a),console.warn(`[subagents] Disabling harness "${a}": its configuration codec failed to parse it (${m(p)}).`)}}},require(i){let s=n.get(i);if(s===void 0)throw new Error(`no harness registered for "${i}"`);return s},displayName(i){return n.get(i)?.displayName??i},runnable(i){return o.ids().filter(s=>k(s)||it(s,i))},config(i){return t.get(i)},resolve(i,s){return n.has(i)&&le(i,s)?i:"pi"},async listModelOptions(i,s){let a=await Promise.all(o.runnable(s).map(async d=>{try{return{id:d,list:await o.require(d).listModels(i)}}catch(p){return{id:d,list:{kind:"unavailable",notice:`Could not list the ${o.displayName(d)} models (${m(p)}).`}}}})),l=new Map(a.map(d=>[d.id,Pe(d.list)])),u=a.flatMap(d=>{let p=Zn(d.list);return p===void 0?[]:[p]});return{options:l,notices:u}}};return o}r(In,"createHarnessRegistry");function Rn(n){let e=cn(n);return e===void 0?void 0:Ni[e]}r(Rn,"harnessFamilyOf");function Ic(n,e){return(n.get(e)??[]).map(t=>t.key)}r(Ic,"modelKeysOf");var C="herdr",Ki=[C],Wi="HERDR_ENV";function Gi(n){return n===C?process.env[Wi]==="1":Re(n)}r(Gi,"isHosting");function Cn(n){return Gi(n)}r(Cn,"multiplexerHosts");function qt(){return Ki.find(Cn)}r(qt,"getHostMultiplexer");var Sc="pi-cowboy launches agents in panes, so it runs only inside a multiplexer it can detect. None hosting this process is registered \u2014 run pi inside herdr, or install a plugin multiplexer for the multiplexer you run pi inside.";var f=class extends Error{constructor(t,o){super(t);this.code=o;this.name="HerdrError"}code;static{r(this,"HerdrError")}},Ui=["pane_not_found"],Bi=["tab_not_found"],Yi=["agent_not_found","agent_name_not_found"];function Pn(n){return n instanceof f&&n.code!==void 0&&Ui.includes(n.code)}r(Pn,"isPaneGoneError");function Qt(n){return n instanceof f&&n.code!==void 0&&Bi.includes(n.code)}r(Qt,"isTabGoneError");function Sn(n){return n instanceof f&&n.code!==void 0&&Yi.includes(n.code)}r(Sn,"isAgentGoneError");function O(n){return n instanceof f?n.code:void 0}r(O,"herdrErrorCode");var A=class{constructor(e){this.pi=e}pi;static{r(this,"HerdrTransport")}async call(e,t){let o=await this.exec(e,t);if(!o)return;let i;try{i=JSON.parse(o)}catch{throw new f(`herdr ${e.join(" ")} printed no JSON result envelope: ${o.slice(0,500)}`,void 0)}return i.result}async exec(e,t){let o=await this.pi.exec("herdr",e,{timeout:t?.timeoutMs??6e4}),i=o.stdout.trim(),s=o.stderr.trim();if(o.code!==0){let a=zi(s),l=a===void 0?Xi(Vi(s,i),e.join(" "),o.code):a.message??`herdr reported ${a.code??"an error"}`;throw new f(l.slice(0,500),a?.code)}return i}};function zi(n){let e;try{e=JSON.parse(n)}catch{return}let t=h(e,"error");return t===void 0?void 0:{code:g(t,"code"),message:g(t,"message")}}r(zi,"parseFailure");function Vi(n,e){return n!==""?n:e===""?void 0:e}r(Vi,"printedText");function Xi(n,e,t){return n===void 0?`herdr ${e} exited ${t} without printing anything`:`herdr ${e} exited ${t}: ${n}`}r(Xi,"printedFailure");function h(n,e){if(!n||typeof n!="object")return;let t=n[e];return t&&typeof t=="object"?t:void 0}r(h,"objectField");function g(n,e){if(!n||typeof n!="object")return;let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}r(g,"strField");function Zt(n,e){if(!n||typeof n!="object")return;let t=n[e];return typeof t=="boolean"?t:void 0}r(Zt,"boolField");async function er(n,e,t){let o=new A(n),i=t?.timeoutMs===void 0?void 0:{timeoutMs:t.timeoutMs};return o.call(e,i)}r(er,"runHerdr");function te(n){return{kind:"settled",value:n}}r(te,"settled");function Ue(){return{kind:"keep-polling"}}r(Ue,"keepPolling");async function Be(n,e){let t=e.timeoutMs===void 0?void 0:Date.now()+e.timeoutMs,o=0;for(;;){if(e.signal?.aborted)return;o+=1;let i=await n(o);if(i.kind==="settled")return i.value;if(i.kind==="abandoned"||e.maxAttempts!==void 0&&o>=e.maxAttempts||t!==void 0&&Date.now()>=t)return;let{intervalMs:s}=e;await Xn(typeof s=="function"?s(o):s)}}r(Be,"pollUntil");import{appendFileSync as Ji,mkdirSync as qi}from"node:fs";import{join as nr}from"node:path";import{CONFIG_DIR_NAME as Qi}from"@earendil-works/pi-coding-agent";var On=["debug","info","warn","error"],Zi=ns(process.env.PI_COWBOY_LOG_LEVEL),tr=nr(process.cwd(),Qi),es=nr(tr,"pi-cowboy.log");function ze(n){function e(s,a){Ye("debug",n,s,a)}r(e,"debug");function t(s,a){Ye("info",n,s,a)}r(t,"info");function o(s,a){Ye("warn",n,s,a)}r(o,"warn");function i(s,a){Ye("error",n,s,a)}return r(i,"error"),{debug:e,info:t,warn:o,error:i}}r(ze,"createLogger");function ns(n){let e=n?.toLowerCase();return e&&On.includes(e)?e:"info"}r(ns,"parseLevel");function Ye(n,e,t,o){if(On.indexOf(n)<On.indexOf(Zi))return;let i=o===void 0?"":ts(o),s=`${new Date().toISOString()} ${n.toUpperCase().padEnd(5)} [${e}] ${t}${i}
9
9
  `;try{qi(tr,{recursive:!0}),Ji(es,s,"utf8")}catch{}}r(Ye,"write");function ts(n){let e=[];for(let t of Object.keys(n)){let o;try{o=n[t]}catch(s){o=`unserializable: ${String(s)}`}let i;try{i=JSON.stringify(o)??String(o)}catch{try{i=String(o)}catch{i="[unserializable]"}}e.push(`${t}=${i}`)}return e.length===0?"":` ${e.join(" ")}`}r(ts,"serializeData");var re=ze("herdr.panes"),oe=15e3,fe=class{constructor(e){this.transport=e}transport;static{r(this,"HerdrPanes")}async createAgentTab(e){let t=["tab","create","--workspace",e.workspaceId,"--cwd",e.cwd,"--label",e.label,"--no-focus"],o=await this.transport.call(t),i=g(h(o,"tab"),"tab_id"),s=g(h(o,"root_pane"),"pane_id");if(!i||!s)throw new f(`herdr tab create returned no tab/pane ids (${JSON.stringify(o).slice(0,300)})`,void 0);return{tabId:i,paneId:s}}async closePane(e){try{await this.transport.call(["pane","close",e],{timeoutMs:oe})}catch(t){if(Pn(t)){re.debug("pane already gone",{paneId:e});return}re.warn("pane close failed",{paneId:e,code:O(t),detail:m(t)})}}async renamePane(e,t){let o=["pane","rename",e];t.kind==="clear"?o.push("--clear"):o.push(t.label);try{await this.transport.call(o,{timeoutMs:oe})}catch(i){if(Pn(i)){re.debug("pane already gone",{paneId:e});return}re.warn("pane rename failed",{paneId:e,code:O(i),detail:m(i)})}}async renameTab(e,t){try{await this.transport.call(["tab","rename",e,t],{timeoutMs:oe})}catch(o){if(Qt(o)){re.debug("tab already gone",{tabId:e});return}re.warn("tab rename failed",{tabId:e,code:O(o),detail:m(o)})}}async focusTab(e){await this.transport.call(["tab","focus",e],{timeoutMs:oe})}async runInPane(e,t){await this.transport.call(["pane","run",e,t],{timeoutMs:oe})}async waitForPaneOutput(e,t,o){await this.transport.call(["pane","wait-output","--match",t,"--timeout",String(o),e],{timeoutMs:o+oe})}};function G(n){return new fe(new A(n))}r(G,"paneNamespace");async function rr(n,e){return G(n).createAgentTab(e)}r(rr,"createAgentTab");async function or(n,e){return G(n).closePane(e)}r(or,"closePane");async function ir(n,e,t){return G(n).renamePane(e,t)}r(ir,"renamePane");async function sr(n,e,t){return G(n).renameTab(e,t)}r(sr,"renameTab");async function ar(n,e){return G(n).focusTab(e)}r(ar,"focusTab");async function lr(n,e,t){return G(n).runInPane(e,t)}r(lr,"runInPane");async function cr(n,e,t,o){return G(n).waitForPaneOutput(e,t,o)}r(cr,"waitForPaneOutput");import*as gr from"node:path";var me=ze("herdr.agents"),dr=5e3,ur=5,rs=500,os=3e4,Ve=15e3,U=class{constructor(e){this.transport=e}transport;static{r(this,"HerdrAgents")}async startAgent(e){let t;if(await Be(async()=>{try{return await this.transport.call(["agent","start",e.name,"--kind",e.agentMultiplexerKind,"--pane",e.paneId,"--timeout",String(dr),"--",...e.piArgs],{timeoutMs:dr+os}),te(!0)}catch(s){if(is(s))return te(!0);if(t=as(s),!ss(s)){if(await this.paneHostsAgent(e.paneId))return te(!0);throw t}return Ue()}},{intervalMs:r(s=>rs*s,"intervalMs"),maxAttempts:ur})||await this.paneHostsAgent(e.paneId))return;let i=t instanceof Error?t.message:String(t);throw new f(`herdr agent start failed after ${ur} attempts (the target pane never became an available shell): ${i}`,t instanceof f?t.code:void 0)}async paneHostsAgent(e){try{let t=await this.getAgentInfo(e,{timeoutMs:Ve});return t!==void 0&&t.paneId===e}catch(t){return me.debug("agent start probe failed",{paneId:e,code:O(t)}),!1}}async listAgentRecords(){let e=await this.transport.call(["agent","list"]),t=Array.isArray(e)?e:h(e,"agents");if(!Array.isArray(t))throw new f(`herdr agent list returned no agents array: ${JSON.stringify(e).slice(0,300)}`,void 0);let o=[];for(let i of t){let s=pr(i);s&&o.push(s)}return o}async getAgentInfo(e,t){try{let o=await this.transport.call(["agent","get",e],t),i=pr(h(o,"agent")??o);if(!i){me.debug("herdr record rejected",{target:e,result:o});return}return{...i,name:i.name??e}}catch(o){if(Sn(o)){me.debug("agent not found",{target:e,code:o.code});return}throw o}}async findTaskAttempts(e){let t;try{t=await this.listAgentRecords()}catch{return[]}let o=[];for(let i of t){if(i.name!==void 0&&vn(i.name,e)){o.push({name:i.name});continue}if(i.cwd===void 0)continue;let s=gr.basename(i.cwd);vn(s,e)&&o.push({name:s})}return o}async sendKeys(e,t){await this.transport.call(["agent","send-keys",e,...t],{timeoutMs:Ve})}async submitPrompt(e,t){await this.transport.call(["agent","prompt",e,t],{timeoutMs:Ve})}async interruptAgent(e){try{await this.transport.call(["agent","send-keys",e,"ctrl+c"],{timeoutMs:Ve})}catch(t){if(Sn(t)){me.debug("interrupt skipped: agent already gone",{name:e});return}me.warn("agent interrupt failed",{name:e,code:O(t),detail:m(t)})}}};function is(n){return n instanceof f?n.code==="cli:agent:start:timeout"||n.code==="agent_not_ready"?!0:/timed out waiting for agent startup/i.test(n.message):!1}r(is,"isNonFatalStartError");function ss(n){return n instanceof f?n.code==="agent_pane_unavailable"||n.code==="agent_pane_busy"?!0:/is not an available shell/i.test(n.message):!1}r(ss,"isTransientAgentStartError");function as(n){return!(n instanceof f)||n.code===void 0?n:new f(`${n.message} (herdr code: ${n.code})`,n.code)}r(as,"withHerdrCode");function pr(n){if(!n||typeof n!="object")return;let e=n,t=g(e,"pane_id");if(!t)return;let o=g(e,"agent_status");return{name:g(e,"name")??g(e,"agent_name"),state:o??"unknown",workspaceId:g(e,"workspace_id"),tabId:g(e,"tab_id"),cwd:g(e,"cwd"),paneId:t,interactiveReady:e.interactive_ready===!0}}r(pr,"parseAgentInfo");function ye(n){return new U(new A(n))}r(ye,"agentNamespace");async function fr(n,e){return ye(n).startAgent(e)}r(fr,"startAgent");async function mr(n){return ye(n).listAgentRecords()}r(mr,"listAgentRecords");async function _n(n,e){return ye(n).getAgentInfo(e)}r(_n,"getAgentInfo");async function yr(n,e){return ye(n).findTaskAttempts(e)}r(yr,"findTaskAttempts");async function hr(n,e,t){return ye(n).submitPrompt(e,t)}r(hr,"submitAgentPrompt");var ls=15e3,cs=3e4,he=class{constructor(e){this.transport=e}transport;static{r(this,"HerdrWorktrees")}async removeHerdrWorktree(e){try{return await this.transport.call(["worktree","remove","--workspace",e,"--force"],{timeoutMs:cs}),!0}catch{return!1}}async listWorktrees(e){let t=["worktree","list"];e&&t.push("--cwd",e);let o=await this.transport.call(t,{timeoutMs:ls}),i=h(o,"worktrees");if(!Array.isArray(i))throw new f(`herdr worktree list returned no worktrees array: ${JSON.stringify(o).slice(0,300)}`,void 0);let s=[];for(let a of i){let l=g(a,"path");l!==void 0&&s.push({path:l,label:g(a,"label"),isLinkedWorktree:Zt(a,"is_linked_worktree")??!1,openWorkspaceId:g(a,"open_workspace_id"),branch:g(a,"branch")})}return s}};function be(n){return V(n)??n.replace(/\\/g,"/")}r(be,"normalizeHerdrPath");function br(n){let e=new A(n);return new he(e)}r(br,"worktreeNamespace");async function Mn(n,e){return br(n).removeHerdrWorktree(e)}r(Mn,"removeHerdrWorktree");async function Ln(n,e){return br(n).listWorktrees(e)}r(Ln,"listWorktrees");var Hn=class{static{r(this,"HerdrClient")}panes;agents;worktrees;transport;constructor(e){this.transport=new A(e),this.panes=new fe(this.transport),this.agents=new U(this.transport),this.worktrees=new he(this.transport)}async getCurrentWorkspaceId(){let e=await this.transport.call(["pane","current","--current"]),t=g(h(e,"pane"),"workspace_id");if(t===void 0)throw new f("could not determine the current herdr workspace (not inside herdr?)",void 0);return t}};async function Er(n){return new Hn(n).getCurrentWorkspaceId()}r(Er,"getCurrentWorkspaceId");var ds=8e3,us=15e3,ps=1e3,Nn=class{constructor(e){this.agents=e}agents;static{r(this,"HerdrAgentStopper")}async stopAgentAndWait(e,t){let o=t?.interruptGraceMs??ds,i=t?.confirmMs??us;return await this.agents.interruptAgent(e),await this.waitUntilAgentGone(e,o)?!0:this.waitUntilAgentGone(e,i)}async waitUntilAgentGone(e,t){return await Be(async()=>{try{if(!await this.agents.getAgentInfo(e))return te(!0)}catch{}return Ue()},{intervalMs:ps,timeoutMs:t})??!1}};function gs(n){let e=new A(n);return new Nn(new U(e))}r(gs,"createHerdrAgentStopper");async function Ar(n,e,t){return gs(n).stopAgentAndWait(e,t)}r(Ar,"stopAgentAndWait");var vr="\u{1F404}";function Dn(n){return n===""?vr:`${vr} ${n}`}r(Dn,"markedLabel");async function wr(n,e,t){await ir(n,e,{kind:"label",label:Dn(t)})}r(wr,"nameSubagentPane");async function fs(n,e,t){await sr(n,e,Dn(t))}r(fs,"nameAdoptedTab");function ms(n){return{focus:r(async e=>{if(e.tabId===void 0)throw new f(`cannot focus pane ${e.paneId}: the address carries no tab id`,void 0);await ar(n,e.tabId)},"focus")}}r(ms,"createHerdrView");function ys(n){return{hostAt:r(async e=>{if(e.checkout){let{path:i,repoCwd:s,branch:a}=e.checkout,l=await er(n,["worktree","open","--cwd",s,"--path",i,"--label",a,"--no-focus"],{timeoutMs:6e4}),u=g(h(l,"worktree"),"path"),d=g(h(l,"workspace"),"workspace_id"),p=g(h(l,"tab"),"tab_id"),F=g(h(l,"root_pane"),"pane_id"),qr=g(h(l,"worktree"),"branch");if(!u||!d||!p||!F||qr!==a){let Qr=(d===void 0?!0:await Mn(n,d))?"":` A herdr workspace, tab and pane for this worktree may still exist (workspace ${d}); close it with \`herdr worktree remove --workspace ${d} --force\`.`;throw new f(`herdr worktree open for ${i} did not adopt "${a}": ${JSON.stringify(l).slice(0,300)}.${Qr}`,void 0)}return await wr(n,F,e.label),await fs(n,p,e.label),{multiplexer:C,name:e.name??e.label,paneId:F,tabId:p,workspaceId:d,paneCreated:!1}}let t=await Er(n),o=await rr(n,{workspaceId:t,cwd:e.cwd,label:Dn(e.label)});return await wr(n,o.paneId,e.label),{multiplexer:C,name:e.name??e.label,paneId:o.paneId,tabId:o.tabId,workspaceId:t,paneCreated:!0}},"hostAt"),start:r((e,t)=>fr(n,{name:t.name,paneId:e.paneId,piArgs:t.piArgs,agentMultiplexerKind:t.agentMultiplexerKind}),"start"),observe:r(async e=>{let t=await _n(n,e.paneId);if(t)return{state:t.state}},"observe"),stop:r((e,t)=>Ar(n,e.paneId,{interruptGraceMs:t?.interruptGraceMs,confirmMs:t?.confirmMs}),"stop"),release:r(async(e,t)=>t==="worktree-association"?Mn(n,e.workspaceId):(e.paneCreated&&await or(n,e.paneId),!0),"release"),isAttached:r(async(e,t)=>(await Ln(n,t?.repoCwd)).some(i=>be(i.path)===be(e)),"isAttached"),findAttempts:r(e=>yr(n,e),"findAttempts"),deliver:r(async(e,t)=>{try{return await hr(n,e.paneId,t),{kind:"submitted"}}catch(o){let i=O(o);return{kind:"not-submitted",detail:`the agent's pane did not take the message (${i===void 0?"":`${i}: `}${m(o)}); nothing was submitted.`}}},"deliver")}}r(ys,"createHerdrHost");function hs(n){return{kind:C,run:r((e,t)=>lr(n,e,t),"run"),waitForOutput:r((e,t,o)=>cr(n,e,t,o),"waitForOutput")}}r(hs,"createHerdrPane");function bs(n,e){return{multiplexer:e,canonicalizePath:r(t=>be(t),"canonicalizePath"),listWorktrees:r(async()=>(await Ln(n)).map(t=>({path:be(t.path),label:t.label,branch:t.branch,workspaceId:t.openWorkspaceId})),"listWorktrees"),listPlacements:r(async()=>(await mr(n)).map(t=>({name:t.name,state:t.state,workspaceId:t.workspaceId,tabId:t.tabId,cwd:t.cwd,paneId:t.paneId})),"listPlacements"),observePane:r(async t=>{let o=await _n(n,t);return o===void 0?void 0:{state:o.state}},"observePane")}}r(bs,"createHerdrPlacements");function xr(n){return{host:ys(n),view:ms(n),pane:hs(n),placements:bs(n,C),multiplexer:C}}r(xr,"createHerdrRuntime");var _=C;function jn(){return qt()??_}r(jn,"defaultMultiplexer");function Fn(){let n=new Map,e=new Set;n.set(_,{id:_,hosts:r(()=>Cn(_),"hosts"),create:xr});let t=r(s=>{try{return s.hosts()}catch(a){return console.warn(`[subagents] multiplexer "${s.id}" could not answer whether it hosts this process: ${m(a)}`),!1}},"hostsProcess"),o=r((s,a)=>{try{return n.get(s)?.create(a)}catch(l){console.warn(`[subagents] multiplexer "${s}" failed to start: ${m(l)}`);return}},"build"),i={register(s){let a=s.id===_?"the built-in multiplexer owns that id":n.has(s.id)?"another plugin already registered that id in this load":void 0;return a!==void 0?(console.warn(`[subagents] Ignoring multiplexer "${s.id}": ${a}`),!1):(n.set(s.id,s),e.add(s.id),!0)},unregister(s){e.has(s)&&(n.delete(s),e.delete(s))},has(s){return n.has(s)},hosting(){return[...n.values()].filter(t).map(s=>s.id)},resolveId(s){let a=i.hosting();return a.includes(s)?s:a[0]??jn()},runtime(s,a){let l=i.resolveId(a),u=o(l,s);if(u!==void 0)return u;if(l===_)throw new Error(`the built-in multiplexer "${l}" produced no runtime`);console.warn(`[subagents] multiplexer "${l}" produced no runtime; falling back to "${_}"`);let d=o(_,s);if(d===void 0)throw new Error(`the built-in multiplexer "${_}" produced no runtime`);return d}};return i}r(Fn,"createMultiplexerRegistry");import{z as Es}from"zod";var kr=Es.enum(["off","minimal","low","medium","high","xhigh","max"]),Je="general-purpose",qe="default",Xe={queued:!1,spawned:!1,settled:!0,"never-started":!0};function Tr(n){return Object.keys(Xe).filter(e=>Xe[e]===n)}r(Tr,"phasesWhere");var As=Tr(!1),vs=Tr(!0),Ir=[...As,...vs];function ws(n){return Xe[n]}r(ws,"isEndedPhase");function Dd(n){return!Xe[n]}r(Dd,"isActivePhase");function jd(n){return ws(n.phase)}r(jd,"hasOutcome");function Fd(n){switch(n.phase){case"queued":return"queued";case"spawned":return"spawned";case"settled":case"never-started":return n.status}}r(Fd,"lifecycleStatus");function $d(n){return n.phase==="settled"&&n.status==="completed"?n.result:""}r($d,"lifecycleResult");function Kd(n){switch(n.phase){case"queued":case"never-started":return n.queuedAt;case"spawned":case"settled":return n.startedAt}}r(Kd,"lifecycleStartTime");var $n=class extends Error{static{r(this,"SpawnIdCollisionError")}spawnId;constructor(e){super(`Spawn id ${e} is already registered \u2014 an id belongs to exactly one spawn from creation until its explicit drop.`),this.name="SpawnIdCollisionError",this.spawnId=e}},Qe=class{static{r(this,"AgentSpawnStore")}spawns=new Map;add(e){if(this.spawns.has(e.id))throw new $n(e.id);this.spawns.set(e.id,e)}mint(e=hn){return ct(t=>this.spawns.has(t),e)}get(e){return this.spawns.get(e)}drop(e){this.spawns.delete(e)}list(e=Ir){return[...this.spawns.values()].filter(t=>e.includes(t.lifecycle.phase))}};function Rr(n,e){if(k(e))return n.default??null;let t=n.defaultModelByHarness?.[e];return Ee(t)?t:null}r(Rr,"harnessDefaultModel");function Cr(n){for(let[e,t]of n)if(Ee(t))return{value:t,source:e}}r(Cr,"firstResolved");function xs(n){let{subagentType:e,agentConfig:t,harnessFamily:o,config:i,harnessDefault:s,parentModelId:a,sessionOverrides:l}=n,u=o===void 0?void 0:t?.modelsByFamily?.[o],d=[["session-per-type",l?.[e]],["config-per-type",i.agent[e]],["agent-template",u],["session-default",o==="pi"?l?.default:void 0],["harness-default",s]],p=Cr(d);return p?{model:p.value,source:p.source}:{model:o==="pi"?a:null,source:"parent"}}r(xs,"resolveModelSource");function Pr(n){return xs(n).model}r(Pr,"resolveModel");function Sr(n,e){let t=k(e)?n.defaultThinking:n.defaultThinkingByHarness?.[e];return Ee(t)?t:null}r(Sr,"harnessDefaultThinking");var Xd="medium";function ks(n){let{subagentType:e,agentConfig:t,harnessFamily:o,config:i,harnessDefault:s,parentThinking:a,sessionThinking:l}=n,u=o===void 0?void 0:t?.thinkingByFamily?.[o];return Cr([["session-per-type",l?.[e]],["config-per-type",i.agent.thinking?.[e]],["agent-template",u],["harness-default",s],["parent",o==="pi"?a:void 0]])}r(ks,"resolveThinkingSource");function Or(n){return ks(n)?.value}r(Or,"resolveThinking");function Ee(n){return typeof n=="string"&&n.length>0}r(Ee,"isNamedValue");var _r=4;function B(n){let e=n.indexOf("/"),t=n.indexOf(":"),o=t>0&&(e<0||t<e),i="pi",s=n;if(o){if(i=n.slice(0,t),i.trim()==="")return;s=n.slice(t+1)}let a=s.indexOf("/");if(a<0)return s===""?void 0:{kind:"provider",harness:i,provider:s};let l=s.slice(0,a),u=s.slice(a+1);if(!(l===""||u===""))return{kind:"model",harness:i,provider:l,model:u}}r(B,"parsePoolKey");function Lr(n,e,t){return`${n}:${e}/${t}`}r(Lr,"qualifiedModelKey");function Hr(n,e){return`${n}:${e}`}r(Hr,"qualifiedProviderKey");function Ts(n){let e=B(n);return e?.kind==="model"?Lr(e.harness,e.provider,e.model):void 0}r(Ts,"modelPoolKeyOf");function Is(n){let e=B(n);return e?.kind==="provider"?Hr(e.harness,e.provider):void 0}r(Is,"providerPoolKeyOf");function Kn(n){return Math.max(1,n)}r(Kn,"clampLimit");var Mr=class{static{r(this,"ConcurrencyPools")}modelPools=new Map;providerPools=new Map;harnessPools=new Map;globalPool={limit:_r,spawned:0};queue=[];reservations=new Map;constructor(e){this.setLimits(e??{default:_r,harnesses:{},providers:{},models:{}})}setConcurrency(e){this.setLimits(e),this.drainQueue()}admitSpawn(e,t){let o=this.applicablePools(e);return this.hasRoom(o)?{kind:"start",reservation:o}:(this.queue.push({id:t.id,identity:e,start:t.start}),{kind:"queue"})}reserve(e,t){for(let o of t)o.spawned++;this.reservations.set(e,t)}reacquire(e,t){this.reservations.has(e)||this.reserve(e,this.applicablePools(t))}release(e){let t=this.reservations.get(e);if(t){for(let o of t)o.spawned=Math.max(0,o.spawned-1);this.reservations.delete(e)}this.cancelQueued(e),this.drainQueue()}cancelQueued(e){this.queue=this.queue.filter(t=>t.id!==e)}clearQueue(){this.queue=[]}queuePosition(e){return this.queue.findIndex(t=>t.id===e)+1}setLimits(e){this.globalPool.limit=Kn(e.default),this.syncHarnessPools(e.harnesses),this.syncPools(this.providerPools,e.providers,Is),this.syncPools(this.modelPools,e.models,Ts)}syncHarnessPools(e){let t=new Map;for(let[o,i]of Object.entries(e))o.trim()!==""&&typeof i=="number"&&t.set(o,Kn(i));for(let[o,i]of t){let s=this.harnessPools.get(o);s?s.limit=i:this.harnessPools.set(o,{limit:i,spawned:0})}for(let o of this.harnessPools.keys())t.has(o)||this.harnessPools.delete(o)}syncPools(e,t,o){let i=new Map;for(let[s,a]of Object.entries(t)){let l=o(s);l!==void 0&&a!==void 0&&i.set(l,Kn(a))}for(let[s,a]of i){let l=e.get(s);l?l.limit=a:e.set(s,{limit:a,spawned:0})}for(let s of e.keys())i.has(s)||e.delete(s)}applicablePools(e){let t=[];if(e.modelKey){let i=B(e.modelKey);if(i?.kind==="model"){let s=this.modelPools.get(Lr(e.harness,i.provider,i.model));s&&t.push(s);let a=this.providerPools.get(Hr(e.harness,i.provider));a&&t.push(a)}}let o=this.harnessPools.get(e.harness);return o&&t.push(o),t.push(this.globalPool),t}hasRoom(e){return e.every(t=>t.spawned<t.limit)}drainQueue(){let e=[];for(let t of this.queue){let o=this.applicablePools(t.identity);if(!this.hasRoom(o)){e.push(t);continue}t.start(o)}this.queue=e}};var Ae="defaultModelByHarness",Y="defaultThinkingByHarness",ie="thinking",Ze=["default","defaultAgentType","defaultOrchestrator","systemPromptMode","includeContextFiles","defaultThinking",Y,ie,"loadSkillsImplicitly","loadExtensionsImplicitly","disableDefaultAgents","extensionEnabled","showActiveIndicator","grazingEnabled","worktreeRoot","worktreeMaterialization","worktreeCheckoutType","harnessType"];import*as x from"node:fs";import*as ae from"node:path";import{z as M}from"zod";function Nr(n,e,t){return Jn(n)?Qn(n,t)?"reserved":typeof e!="string"?"not-string":qn(e)?"control":null:"name"}r(Nr,"envProblem");function Dr(n,e){let t={};for(let[o,i]of Object.entries(n)){if(i===void 0)continue;let s=Nr(o,i,e.reserved);if(s!==null){e.report(o,s,i);continue}t[o]=i}return t}r(Dr,"sanitizeEnv");function ru(n,e){return n===void 0?e:e===void 0?n:{...n,...e}}r(ru,"mergeEnv");function ou(n){for(let[e,t]of Object.entries(n)){let o=Nr(e,t,[]);if(o!==null)throw new Error(`Invalid environment variable ${e}: ${o}`)}return n}r(ou,"trustedEnv");import{z as Rs}from"zod";var Wn=Rs.number().int().min(1),se="positive integer";function en(n){return Wn.safeParse(n).success}r(en,"isConcurrencyLimit");var Gn={schema:M.union([M.string(),M.null()]),expected:"string or null"},z={schema:M.boolean(),expected:"boolean"},Cs={schema:M.enum(["replace","inherit","custom"]),expected:'"replace" | "inherit" | "custom"'},Ps={schema:M.enum(["off","minimal","low","medium","high","xhigh","max"]),expected:'"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"'},Ss={schema:M.enum(["copy-on-write","checkout"]),expected:'"copy-on-write" | "checkout"'},Os={schema:M.enum(["dirty","clean"]),expected:'"dirty" | "clean"'},Fr=M.string().min(1).refine(n=>/\S/.test(n)),ve={schema:Fr,expected:"non-empty string"},$r=Ce.map(n=>`"${n}"`).join(" | "),_s=`an object keyed by a harness id (${$r} or a plugin's), with string or null values`,Ms=`an object keyed by a harness id (${$r} or a plugin's), with a non-empty thinking token or null per entry`,Ls="an object keyed by an agent type, with a non-empty thinking token or null per entry",Hs="non-empty string or null",Ns=r(n=>typeof n=="string"||n===null,"isModelKeyOrNull"),Ds=r(n=>n===null||typeof n=="string"&&/\S/.test(n),"isThinkingTokenOrNull"),js={default:Gn,defaultAgentType:ve,defaultOrchestrator:ve,systemPromptMode:Cs,includeContextFiles:z,defaultThinking:Ps,loadSkillsImplicitly:z,loadExtensionsImplicitly:z,disableDefaultAgents:z,extensionEnabled:z,showActiveIndicator:z,grazingEnabled:z,worktreeRoot:ve,worktreeMaterialization:Ss,worktreeCheckoutType:Os,harnessType:ve};function Fs(n){return Array.isArray(n)?"array":n===null?"null":typeof n=="object"?"object":typeof n}r(Fs,"describeValue");var $s="Set it again in the /cowboy menu, or edit or delete the file to fix it.",nn="Edit or delete the key in that file to fix it.";function we(n,e,t,o,i){return`[subagents] Incompatible value in ${n}: "${e}" is ${Fs(t)}, expected ${o}. ${i}`}r(we,"incompatibleWarning");function b(n,e,t,o){console.warn(we(n,e,t,o,$s))}r(b,"warnIncompatible");var j="object";function Un(n,e){let t={};if(!y(n))return b(e,"(config)",n,j),t;if(n.agent!==void 0)if(!y(n.agent))b(e,"agent",n.agent,j);else{let o=Bs(n.agent,e);Object.keys(o).length>0&&(t.agent=o)}if(n.concurrency!==void 0){let o=Ys(n.concurrency,e);Object.keys(o).length>0&&(t.concurrency=o)}if(n.harness!==void 0){let o=Ks(n.harness,e);o!==void 0&&(t.harness=o)}if(n.multiplexer!==void 0){let o=Fr.safeParse(n.multiplexer);o.success?t.multiplexer=o.data:b(e,"multiplexer",n.multiplexer,ve.expected)}return t}r(Un,"validateRawLayer");function Ks(n,e){if(!y(n)){console.warn(we(e,"harness",n,j,nn));return}let t={};for(let[o,i]of Object.entries(n))if(i!==void 0){if(!y(i)){console.warn(we(e,`harness.${o}`,i,j,nn));continue}t[o]=Ws(i,o,e)}return Object.keys(t).length>0?t:void 0}r(Ks,"cleanHarnessSections");function Ws(n,e,t){if(n.env===void 0)return n;let o=Us(n.env,e,t),i={...n};return delete i.env,o===void 0?i:{...i,env:o}}r(Ws,"cleanHarnessSlice");var Gs={name:"a valid environment variable name",reserved:"a variable that is not reserved","not-string":"string",control:"a value without control characters"};function Us(n,e,t){if(!y(n)){b(t,`harness.${e}.env`,n,j);return}let o=Dr(n,{reserved:[],report:r((i,s,a)=>{let l=s==="name"||s==="reserved";b(t,`harness.${e}.env.${i}`,l?i:a,Gs[s])},"report")});return Object.keys(o).length>0?o:void 0}r(Us,"cleanHarnessEnv");function Bs(n,e){let t={};for(let[o,i]of Object.entries(n)){if(i===void 0)continue;if(o===Ae){let l=jr(i,e,{keyPath:`agent.${o}`,expected:_s,valueExpected:Gn.expected,accepts:Ns});l!==void 0&&(t[o]=l);continue}if(o===Y||o===ie){let l=jr(i,e,{keyPath:`agent.${o}`,expected:o===Y?Ms:Ls,valueExpected:Hs,accepts:Ds});l!==void 0&&(t[o]=l);continue}let s=js[o]??Gn,a=s.schema.safeParse(i);a.success?t[o]=a.data:b(e,`agent.${o}`,i,s.expected)}return t}r(Bs,"cleanAgentEntries");function jr(n,e,{keyPath:t,expected:o,valueExpected:i,accepts:s}){if(!y(n)){b(e,t,n,o);return}let a={};for(let[l,u]of Object.entries(n))if(u!==void 0){if(!/\S/.test(l)){b(e,`${t}.${l}`,l,"non-empty key");continue}s(u)?a[l]=u:b(e,`${t}.${l}`,u,i)}return Object.keys(a).length>0?a:void 0}r(jr,"cleanEntryMap");function Ys(n,e){let t={};if(!y(n))return b(e,"concurrency",n,j),t;n.default!==void 0&&(en(n.default)?t.default=n.default:b(e,"concurrency.default",n.default,se));let o=n.harnesses;if(o!==void 0)if(!y(o))b(e,"concurrency.harnesses",o,j);else{let s={};for(let[a,l]of Object.entries(o)){if(!/\S/.test(a)){b(e,`concurrency.harnesses.${a}`,a,"non-empty harness id");continue}en(l)?s[a]=l:b(e,`concurrency.harnesses.${a}`,l,se)}Object.keys(s).length>0&&(t.harnesses=s)}let i={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 s of["providers","models"]){let a=n[s];if(a===void 0)continue;if(!y(a)){b(e,`concurrency.${s}`,a,j);continue}let{level:l,expected:u}=i[s],d={};for(let[p,F]of Object.entries(a)){if(B(p)?.kind!==l){b(e,`concurrency.${s}.${p}`,p,u);continue}en(F)?d[p]=F:b(e,`concurrency.${s}.${p}`,F,se)}Object.keys(d).length>0&&(t[s]=d)}return t}r(Ys,"cleanConcurrencySection");var Gr="config.json";function xe(){return ae.join(Se(),Gr)}r(xe,"configPath");function Cu(){return ae.join(Se(),"prompt.md")}r(Cu,"customPromptPath");var zs={default:4},Vs={default:null,defaultAgentType:Je,defaultOrchestrator:qe,systemPromptMode:"replace",includeContextFiles:!0,disableDefaultAgents:!1,extensionEnabled:!0,showActiveIndicator:!0,grazingEnabled:!0,worktreeMaterialization:de,worktreeCheckoutType:He,harnessType:"pi"},Bn=new Set(["default","defaultThinking",Ae,Y,ie]),Xs=new Set([Ae,Y,ie]);function Yn(n){return Bn.has(n)||!Ze.includes(n)}r(Yn,"isProjectAllowedAgentKey");function ke(n){let e=n?ae.join(n,un,Gr):null,t=n?"absent":"untrusted",o=null,i=!1;return{load:r(()=>{let s=qs(),a=s.raw;if(i=s.malformed,e){let l=Qs(e);l===null?(o=null,t="absent"):l==="malformed"?(o=null,t="malformed"):(o=l.raw,t="loaded")}else o=null,t="untrusted";return{global:a,project:o,projectStatus:t}},"load"),isGlobalWritable:r(()=>!i,"isGlobalWritable"),paths:r(()=>({global:xe(),project:e??void 0}),"paths"),saveGlobal:r(s=>{if(i){console.warn("[subagents] Refusing to write global config (malformed); change not saved");return}Wr(xe(),s)},"saveGlobal"),saveProject:r(s=>{if(!e||t==="malformed"||t==="untrusted"){console.warn(`[subagents] Refusing to write project config (${t}); change not saved`);return}Wr(e,s)},"saveProject")}}r(ke,"createConfigIO");function Ur(n,e){let t={...n.agent};if(e?.agent){for(let[o,i]of Object.entries(e.agent))if(Yn(o)){if(Xs.has(o)&&y(t[o])&&y(i)){t[o]={...t[o],...i};continue}t[o]=i}}return{agent:t,concurrency:Js(n.concurrency,e?.concurrency),multiplexer:n.multiplexer}}r(Ur,"mergeLayers");function Js(...n){let e={},t={},o={},i={};for(let s of n)s&&(s.default!==void 0&&(e.default=s.default),Object.assign(t,s.harnesses??{}),Object.assign(o,s.providers??{}),Object.assign(i,s.models??{}));return Object.keys(t).length>0&&(e.harnesses=t),Object.keys(o).length>0&&(e.providers=o),Object.keys(i).length>0&&(e.models=i),e}r(Js,"mergeRawConcurrency");function Br(n){return{agent:{...Vs,...n.agent},concurrency:{...zs,...n.concurrency},multiplexer:n.multiplexer??jn()}}r(Br,"mergeDefaults");function qs(){let n;try{n=x.readFileSync(xe(),"utf-8")}catch(t){return t?.code==="ENOENT"?{raw:{},malformed:!1}:Kr(t)}let e;try{e=JSON.parse(n)}catch(t){return Kr(t)}return{raw:Un(e,xe()),malformed:!1}}r(qs,"readGlobalRaw");function Kr(n){return console.warn(`[subagents] Ignoring malformed global config ${xe()}: ${m(n)}`),{raw:{},malformed:!0}}r(Kr,"warnMalformedGlobal");function Qs(n){if(!x.existsSync(n))return null;let e;try{e=x.readFileSync(n,"utf-8")}catch(t){return console.warn(`[subagents] Ignoring malformed project config ${n}: ${m(t)}`),"malformed"}return Zs(e,n)}r(Qs,"readProjectRaw");function Zs(n,e){let t;try{t=JSON.parse(n)}catch(i){return console.warn(`[subagents] Ignoring malformed project config ${e}: ${m(i)}`),"malformed"}if(!y(t))return console.warn(`[subagents] Ignoring malformed project config ${e}: not a JSON object`),"malformed";let o=t;return o.agent!==void 0&&!y(o.agent)?tn(e,"agent"):o.concurrency!==void 0&&!y(o.concurrency)?tn(e,"concurrency"):o.concurrency?.providers!==void 0&&!y(o.concurrency.providers)?tn(e,"concurrency.providers"):o.concurrency?.models!==void 0&&!y(o.concurrency.models)?tn(e,"concurrency.models"):{raw:Un(o,e)}}r(Zs,"parseProjectContents");function tn(n,e){return console.warn(`[subagents] Ignoring malformed project config ${n}: "${e}" is not a JSON object`),"malformed"}r(tn,"malformedSection");function Wr(n,e){let t=n+".tmp";try{x.mkdirSync(ae.dirname(n),{recursive:!0}),x.writeFileSync(t,JSON.stringify(e,null,2),"utf-8"),x.renameSync(t,n)}catch(o){console.error(`[subagents] Failed to save config: ${m(o)}`)}}r(Wr,"writeJsonAtomic");var ea=ke();function Yr(n){return n.project?{kind:"present",raw:n.project}:n.projectStatus==="untrusted"||n.projectStatus==="malformed"?{kind:"refused",status:n.projectStatus}:{kind:"creatable"}}r(Yr,"projectLayerFrom");var rn=class{static{r(this,"LayeredConfig")}io;globalRaw;projectLayer;constructor(e=ea){this.io=e;let t=e.load();this.globalRaw=t.global,this.projectLayer=Yr(t)}get paths(){return this.io.paths()}get effective(){return Br(Ur(this.globalRaw,this.project))}get global(){return this.globalRaw}get project(){return this.projectLayer.kind==="present"?this.projectLayer.raw:null}get isProjectWritable(){return this.projectLayer.kind!=="refused"}get isGlobalWritable(){return this.io.isGlobalWritable()}setProjectDir(e){this.io=ke(e)}reload(){let e=this.io.load();this.globalRaw=e.global,this.projectLayer=Yr(e)}mutate(e,t){if(e==="global"&&!this.globalWritableOrWarn())return!1;let o=e==="global"?this.global:this.projectLayerToWrite();return o===null?!1:(t(o),e==="global"?this.io.saveGlobal(o):this.io.saveProject(o),!0)}clear(e,t,o){(e==="session"||e==="all")&&o(),(e==="global"||e==="all")&&this.globalWritableOrWarn()&&(t(this.globalRaw),this.io.saveGlobal(this.globalRaw));let i=this.project;i&&(e==="project"||e==="all")&&(t(i),this.io.saveProject(i))}globalWritableOrWarn(){return this.isGlobalWritable?!0:(console.warn("[subagents] Refusing to write global config (malformed); change not saved"),!1)}projectLayerToWrite(){let e=this.projectLayer;if(e.kind==="present")return e.raw;if(e.kind==="refused")return console.warn(`[subagents] Project config target unavailable (${e.status}); change ignored`),null;let t={};return this.projectLayer={kind:"present",raw:t},t}};var na=ke();function zr(n){let e=n?.agent;return e?Object.keys(e).some(t=>Yn(t)&&e[t]!==void 0):!1}r(zr,"agentLayerHasModelSettings");function on(n,e){return n?.agent!=null&&n.agent[e]!==void 0}r(on,"layerHasAgentKey");function Te(n,e){return n!=null&&Object.hasOwn(n,e)}r(Te,"layerCarriesEntry");function ta(n){let e=kr.safeParse(n);if(!e.success)throw new RangeError(`Invalid pi thinking level ${JSON.stringify(n)}`);return e.data}r(ta,"piThinkingLevel");function sn(n){return k(n)?"pi":n}r(sn,"thinkingSlot");function ra(n){return Object.values(n).some(e=>e!=null)}r(ra,"sessionOverridesHasModelSettings");function zn(n){return n.default!==void 0||n.harnesses!=null&&Object.keys(n.harnesses).length>0||n.providers!=null&&Object.keys(n.providers).length>0||n.models!=null&&Object.keys(n.models).length>0}r(zn,"concurrencyLayerHasSettings");var oa=new Set(Ze.filter(n=>!Bn.has(n)));function Ie(n){return typeof n=="string"&&/\S/.test(n)?n:void 0}r(Ie,"nonBlankString");function an(n){if(!Wn.safeParse(n).success)throw new RangeError(`Invalid concurrency limit ${JSON.stringify(n)}: expected ${se}.`)}r(an,"assertConcurrencyLimit");function Vn(n){return n.defaultModelByHarness??{}}r(Vn,"rawHarnessDefaults");function Vr(n){return n.defaultThinkingByHarness??{}}r(Vr,"rawThinkingByHarness");function Xr(n){return n.thinking??{}}r(Xr,"rawThinkingByType");var ln=class{static{r(this,"ConfigStore")}layers;sessionOverrides={default:null};sessionThinking={};sessionHarnessDefaults={};sessionThinkingDefaults={};sessionConcurrencyLayer={};manager;constructor(e=na){this.layers=new rn(e)}setProjectDir(e){this.layers.setProjectDir(e)}get isProjectWritable(){return this.layers.isProjectWritable}get agent(){let e=this.layers.effective.agent;return{defaultModel:e.default,defaultAgentType:e.defaultAgentType??Je,defaultOrchestrator:e.defaultOrchestrator??qe,systemPromptMode:e.systemPromptMode??"replace",includeContextFiles:e.includeContextFiles??!0,defaultThinking:e.defaultThinking,loadSkillsImplicitly:e.loadSkillsImplicitly??!0,loadExtensionsImplicitly:e.loadExtensionsImplicitly??!0,disableDefaultAgents:e.disableDefaultAgents??!1,extensionEnabled:e.extensionEnabled??!0,showActiveIndicator:e.showActiveIndicator??!0,grazingEnabled:e.grazingEnabled===!0,worktreeRoot:e.worktreeRoot,worktreeMaterialization:e.worktreeMaterialization??de,worktreeCheckoutType:e.worktreeCheckoutType??He,harnessType:e.harnessType??"pi"}}get multiplexer(){return this.layers.effective.multiplexer}harnessConfigLayers(){return{global:this.layers.global.harness??{},project:this.layers.project?.harness??{}}}harnessEnv(e){let t=this.layers.global.harness?.[e]?.env;return y(t)?t:void 0}reportHarnessConfigIssue(e,t){let o=this.layers.paths,i=t.layer==="project"?o.project??o.global:o.global;console.warn(we(i,`harness.${e}${t.keyPath===""?"":`.${t.keyPath}`}`,t.got,t.expected,nn))}get concurrency(){let e=this.layers.effective.concurrency,t=this.sessionConcurrencyLayer;return{default:t.default??e.default,harnesses:{...e.harnesses,...t.harnesses},providers:{...e.providers,...t.providers},models:{...e.models,...t.models}}}get sessionDefaultModel(){return this.sessionOverrides.default??null}sessionModelOverride(e){return this.sessionOverrides[e]??null}defaultModelForHarness(e){return Ie(this.sessionHarnessDefaults[e])??Rr(this.layers.effective.agent,e)}sessionThinkingOverride(e){return this.sessionThinking[e]??null}defaultThinkingForHarness(e){return Ie(this.sessionThinkingDefaults[sn(e)])??Sr(this.layers.effective.agent,e)}thinkingFor(e,t,o,i){return Or({subagentType:e,agentConfig:t,harnessFamily:Rn(o),config:this.layers.effective,harnessDefault:this.defaultThinkingForHarness(o),parentThinking:i,sessionThinking:this.sessionThinking})}configuredHarnessIds(){let e=new Set([this.agent.harnessType]);for(let o of Object.keys(Vn(this.layers.effective.agent)))e.add(o);for(let o of Object.keys(this.concurrency.harnesses))e.add(o);let t=this.harnessConfigLayers();for(let o of Object.keys(t.global))e.add(o);for(let o of Object.keys(t.project))e.add(o);for(let o of[...Object.keys(this.concurrency.providers),...Object.keys(this.concurrency.models)]){let i=B(o);i!==void 0&&e.add(i.harness)}return[...e]}modelOverrideLevels(e){return{session:this.sessionModelOverride(e)!==null,global:on(this.layers.global,e),project:on(this.layers.project,e)}}harnessDefaultModelLevels(e){return{session:Ie(this.sessionHarnessDefaults[e])!==void 0,global:Te(this.layers.global.agent?.defaultModelByHarness,e),project:Te(this.layers.project?.agent?.defaultModelByHarness,e)}}harnessDefaultThinkingLevels(e){return{session:Ie(this.sessionThinkingDefaults[sn(e)])!==void 0,global:this.harnessThinkingAt(this.layers.global,e),project:this.harnessThinkingAt(this.layers.project,e)}}harnessThinkingAt(e,t){return k(t)?on(e,"defaultThinking"):Te(e?.agent?.defaultThinkingByHarness,t)}thinkingOverrideLevels(e){return{session:this.sessionThinking[e]!=null,global:Te(this.layers.global.agent?.thinking,e),project:Te(this.layers.project?.agent?.thinking,e)}}hasProjectModelKey(e){return on(this.layers.project,e)}hasProjectThinkingKey(e){return Ee(this.layers.project?.agent?.thinking?.[e])}modelSettingsLevels(){return{session:ra(this.sessionOverrides)||Object.keys(this.sessionHarnessDefaults).length>0||Object.values(this.sessionThinking).some(e=>e!=null)||Object.values(this.sessionThinkingDefaults).some(e=>Ie(e)!==void 0),global:zr(this.layers.global),project:zr(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:zn(this.sessionConcurrencyLayer),global:zn(this.layers.global.concurrency??{}),project:zn(this.layers.project?.concurrency??{})}}agentConfigSnapshot(){return this.layers.effective.agent}modelFor(e,t,o,i){return Pr({subagentType:e,agentConfig:o,harnessFamily:Rn(i),config:this.layers.effective,harnessDefault:this.defaultModelForHarness(i),parentModelId:t,sessionOverrides:this.sessionOverrides})}mutate={agent:{setDefaultModel:r((e,t="global")=>{this.setAgentModelKey("default",e,t)},"setDefaultModel"),setModelOverride:r((e,t,o="global")=>{this.setAgentModelKey(e,t,o)},"setModelOverride"),clearModelOverride:r((e,t="global")=>{this.layers.clear(t,o=>{o.agent&&delete o.agent[e]},()=>{delete this.sessionOverrides[e]})},"clearModelOverride"),clearAllModelOverrides:r((e="global")=>{this.layers.clear(e,t=>this.clearAgentModelKeys(t),()=>{this.sessionOverrides={default:null},this.sessionThinking={},this.sessionHarnessDefaults={},this.sessionThinkingDefaults={}})},"clearAllModelOverrides"),setDefaultAgentType:r(e=>this.setAgentLayerEntry("defaultAgentType",e,"global"),"setDefaultAgentType"),setDefaultOrchestrator:r(e=>this.setAgentLayerEntry("defaultOrchestrator",e,"global"),"setDefaultOrchestrator"),setSystemPromptMode:r(e=>this.setAgentLayerEntry("systemPromptMode",e,"global"),"setSystemPromptMode"),setIncludeContextFiles:r(e=>this.setAgentLayerEntry("includeContextFiles",e,"global"),"setIncludeContextFiles"),setDefaultThinking:r((e,t="global")=>{this.setAgentLayerEntry("defaultThinking",e,t)},"setDefaultThinking"),setLoadSkillsImplicitly:r(e=>this.setAgentLayerEntry("loadSkillsImplicitly",e,"global"),"setLoadSkillsImplicitly"),setLoadExtensionsImplicitly:r(e=>this.setAgentLayerEntry("loadExtensionsImplicitly",e,"global"),"setLoadExtensionsImplicitly"),setDisableDefaultAgents:r(e=>this.setAgentLayerEntry("disableDefaultAgents",e,"global"),"setDisableDefaultAgents"),setExtensionEnabled:r(e=>this.setAgentLayerEntry("extensionEnabled",e,"global"),"setExtensionEnabled"),setShowActiveIndicator:r(e=>this.setAgentLayerEntry("showActiveIndicator",e,"global"),"setShowActiveIndicator"),setGrazingEnabled:r(e=>this.setAgentLayerEntry("grazingEnabled",e,"global"),"setGrazingEnabled"),setWorktreeRoot:r(e=>this.setAgentLayerEntry("worktreeRoot",e,"global"),"setWorktreeRoot"),setWorktreeMaterialization:r(e=>this.setAgentLayerEntry("worktreeMaterialization",e,"global"),"setWorktreeMaterialization"),setWorktreeCheckoutType:r(e=>this.setAgentLayerEntry("worktreeCheckoutType",e,"global"),"setWorktreeCheckoutType"),setHarnessType:r(e=>this.setAgentLayerEntry("harnessType",e,"global"),"setHarnessType"),setHarnessDefaultModel:r((e,t,o="global")=>{if(o==="session"){this.sessionHarnessDefaults[e]=t;return}this.layers.mutate(o,i=>{i.agent??={},i.agent.defaultModelByHarness={...Vn(i.agent),[e]:t}})},"setHarnessDefaultModel"),clearHarnessDefaultModel:r((e,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;let i=Vn(o.agent);delete i[e],Object.keys(i).length===0?delete o.agent.defaultModelByHarness:o.agent.defaultModelByHarness=i},()=>{delete this.sessionHarnessDefaults[e]})},"clearHarnessDefaultModel"),setThinkingOverride:r((e,t,o="global")=>{if(o==="session"){this.sessionThinking[e]=t;return}this.layers.mutate(o,i=>{i.agent??={},i.agent.thinking={...Xr(i.agent),[e]:t}})},"setThinkingOverride"),clearThinkingOverride:r((e,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;let i=Xr(o.agent);delete i[e],Object.keys(i).length===0?delete o.agent.thinking:o.agent.thinking=i},()=>{delete this.sessionThinking[e]})},"clearThinkingOverride"),setHarnessDefaultThinking:r((e,t,o="global")=>{if(o==="session"){this.sessionThinkingDefaults[sn(e)]=t;return}if(k(e)){let i=t===null?void 0:ta(t);this.setAgentLayerEntry("defaultThinking",i,o);return}this.layers.mutate(o,i=>{i.agent??={},i.agent.defaultThinkingByHarness={...Vr(i.agent),[e]:t}})},"setHarnessDefaultThinking"),clearHarnessDefaultThinking:r((e,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;if(k(e)){delete o.agent.defaultThinking;return}let i=Vr(o.agent);delete i[e],Object.keys(i).length===0?delete o.agent.defaultThinkingByHarness:o.agent.defaultThinkingByHarness=i},()=>{delete this.sessionThinkingDefaults[sn(e)]})},"clearHarnessDefaultThinking")},concurrency:{setDefault:r((e,t="global")=>{an(e),this.applyConcurrencyWrite(t,o=>{o.default=e})},"setDefault"),setHarness:r((e,t,o="global")=>{an(t),this.applyConcurrencyWrite(o,i=>{i.harnesses={...i.harnesses,[e]:t}})},"setHarness"),setProvider:r((e,t,o="global")=>{an(t),this.applyConcurrencyWrite(o,i=>{i.providers={...i.providers,[e]:t}})},"setProvider"),setModel:r((e,t,o="global")=>{an(t),this.applyConcurrencyWrite(o,i=>{i.models={...i.models,[e]:t}})},"setModel"),removeHarness:r((e,t="global")=>{this.removeConcurrencyEntry("harnesses",e,t)},"removeHarness"),removeProvider:r((e,t="global")=>{this.removeConcurrencyEntry("providers",e,t)},"removeProvider"),removeDefault:r((e="global")=>{this.removeConcurrencyEntry("default",void 0,e)},"removeDefault"),removeModel:r((e,t="global")=>{this.removeConcurrencyEntry("models",e,t)},"removeModel"),clearAll:r((e="global")=>{this.layers.clear(e,t=>{delete t.concurrency},()=>{this.sessionConcurrencyLayer={}}),this.applyConcurrency()},"clearAll")},session:{setOverride:r((e,t)=>{this.sessionOverrides[e]=t},"setOverride"),clearOverride:r(e=>{delete this.sessionOverrides[e]},"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(e){e.manager!==void 0&&(this.manager=e.manager),this.applyConcurrency()}dispose(){this.manager=void 0}setAgentLayerEntry(e,t,o){this.layers.mutate(o,i=>{i.agent??={},t===void 0?delete i.agent[e]:i.agent[e]=t})}setAgentModelKey(e,t,o){if(o==="session"){this.sessionOverrides[e]=t;return}this.setAgentLayerEntry(e,t,o)}applyConcurrencyWrite(e,t){if(e==="session")t(this.sessionConcurrencyLayer);else if(!this.layers.mutate(e,o=>{o.concurrency??={},t(o.concurrency)}))return;this.applyConcurrency()}clearAgentModelKeys(e){if(e.agent)for(let t of Object.keys(e.agent))oa.has(t)||delete e.agent[t]}removeConcurrencyEntry(e,t,o){let i=r(s=>{if(!s)return;if(e==="default"){delete s.default;return}if(t===void 0)return;if(e==="harnesses"){s.harnesses&&delete s.harnesses[t];return}let a=s[e];a&&delete a[t]},"removeFrom");this.layers.clear(o,s=>i(s.concurrency),()=>i(this.sessionConcurrencyLayer)),this.applyConcurrency()}applyConcurrency(){this.manager?.setConcurrency(this.concurrency)}};var Jr={user:"",project:"",shared:""};function sa(){return{agents:{agents:new Map,scanDirs:Jr},orchestrators:{orchestrators:new Map,scanDirs:Jr}}}r(sa,"createSessionTemplates");var c={pi:null,sessionCtx:null,manager:null,store:new ln,coordinator:null,runtime:null,agentSpawns:new Qe,repoLock:new Ne,sessionTemplates:sa(),indicatorMarker:null,harnesses:In(),multiplexers:Fn(),cowAvailability:fn(),cowAvailabilityClaim:0,harnessAvailability:fn(),uiFlowClaim:0,uiFlows:new WeakMap};function rp(){if(c.pi===null)throw new Error("pi instance read before the extension factory bound it");return c.pi}r(rp,"getPiInstance");function op(){if(c.sessionCtx===null)throw new Error("session context read before session_start fired");return c.sessionCtx}r(op,"getSessionCtx");function ip(){if(c.manager===null)throw new Error("agent manager read outside a live session");return c.manager}r(ip,"getManager");function sp(){return c.manager}r(sp,"getManagerOrNull");function ap(){return c.store}r(ap,"getStore");function lp(){return c.indicatorMarker}r(lp,"getIndicatorMarker");function cp(n){c.indicatorMarker=n}r(cp,"setIndicatorMarker");function dp(){return c.agentSpawns}r(dp,"getAgentSpawns");function up(){return c.repoLock}r(up,"getRepoLock");function pp(){if(c.coordinator===null)throw new Error("spawn coordinator read outside a live session");return c.coordinator}r(pp,"getCoordinator");function gp(){return c.coordinator}r(gp,"getCoordinatorOrNull");function fp(){return c.cowAvailability}r(fp,"getCowAvailability");function mp(){return c.cowAvailabilityClaim+=1,c.cowAvailabilityClaim}r(mp,"beginCowAvailabilityProbe");function yp(n,e){return n!==c.cowAvailabilityClaim?!1:(c.cowAvailability=e,!0)}r(yp,"setCowAvailability");function hp(){return c.harnesses}r(hp,"getHarnessRegistry");function bp(n){return{getAvailable:r(()=>n.getAvailable().map(e=>({provider:e.provider,id:e.id,thinkingLevels:ia(e)})),"getAvailable")}}r(bp,"piModelCatalog");function Ep(){let n=In(),e=Fn();return c.harnesses=n,c.multiplexers=e,{harnesses:n,multiplexers:e}}r(Ep,"installSessionRegistries");function Ap(){return c.harnessAvailability}r(Ap,"getHarnessAvailability");function vp(n){c.harnessAvailability=n}r(vp,"setHarnessAvailability");function wp(){return gt(c.store.agent.worktreeMaterialization,c.cowAvailability)}r(wp,"getWorktreeMaterialization");function xp(n){c.uiFlowClaim+=1,c.uiFlows.set(n,c.uiFlowClaim)}r(xp,"beginUiFlow");function kp(n){let e=c.uiFlows.get(n);return e===void 0||e===c.uiFlowClaim}r(kp,"ownsUiFlow");function Tp(){return c.harnesses.resolve(c.store.agent.harnessType,c.harnessAvailability)}r(Tp,"getHarnessType");function Ip(){return c.runtime}r(Ip,"getRuntime");function Rp(){return c.sessionTemplates}r(Rp,"getSessionTemplates");function Cp(n){c.pi=n}r(Cp,"setPiInstance");function Pp(n){c.sessionCtx=n}r(Pp,"setSessionCtx");function Sp(n){c.manager=n}r(Sp,"setManager");function Op(n){c.coordinator=n}r(Op,"setCoordinator");function _p(n){c.runtime=n}r(_p,"setRuntime");function Mp(n){c.sessionTemplates=n}r(Mp,"setSessionTemplates");var aa=new RegExp(`${gn}([A-Za-z0-9_-]+)`);function Lp(n=process.argv){for(let e of n){let t=aa.exec(e);if(t)return t[1]}}r(Lp,"detectSubagentSpawn");function jp(n){let e=n.theme.fg("success","\u2713"),t=n.theme.fg("error","\u2717");return{pending:r(o=>n.notify(`${o} \u2026`,"info"),"pending"),succeeded:r((o,i="info")=>n.notify(`${e} ${o}`,i),"succeeded"),failed:r((o,i)=>n.notify(`${t} ${o}: ${m(i)}`,"error"),"failed")}}r(jp,"actionReport");export{to as a,ot as b,L as c,ga as d,fa as e,ma as f,ya as g,ha as h,ba as i,va as j,fn as k,le as l,wa as m,de as n,Ha as o,Na as p,He as q,Da as r,ja as s,co as t,uo as u,Fa as v,go as w,$a as x,Ka as y,Wa as z,Ga as A,P as B,Va as C,Z as D,H as E,y as F,Rn as G,Ic as H,Sc as I,ze as J,_ as K,kr as L,Je as M,qe as N,As as O,vs as P,Ir as Q,Dd as R,jd as S,Fd as T,$d as U,Kd as V,xs as W,Xd as X,ks as Y,B as Z,Mr as _,Dr as $,ru as aa,ou as ba,Cu as ca,sa as da,rp as ea,op as fa,ip as ga,sp as ha,ap as ia,lp as ja,cp as ka,dp as la,up as ma,pp as na,gp as oa,fp as pa,mp as qa,yp as ra,hp as sa,bp as ta,Ep as ua,Ap as va,vp as wa,wp as xa,xp as ya,kp as za,Tp as Aa,Ip as Ba,Rp as Ca,Cp as Da,Pp as Ea,Sp as Fa,Op as Ga,_p as Ha,Mp as Ia,Lp as Ja,jp as Ka};
10
- //# sourceMappingURL=chunk-7W5EBKER.js.map
10
+ //# sourceMappingURL=chunk-CTBFJWEE.js.map
@@ -1,2 +1,2 @@
1
- import{h as l,n as h}from"./chunk-7KLHCZK2.js";import{a as r}from"./chunk-254PTGN5.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-2GTF3FFO.js.map
1
+ import{h as l,n as h}from"./chunk-WL3QYM2F.js";import{a as r}from"./chunk-254PTGN5.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-F526OOT6.js.map
@@ -1,4 +1,4 @@
1
- import{B as ue,C as D,J as le,S as pe,ma as fe,n as se,q as I,w as ce,y as de}from"./chunk-7W5EBKER.js";import{a as i,d as A,i as G,j as M}from"./chunk-254PTGN5.js";import*as v from"node:fs";import*as k from"node:path";var qe=`import ctypes, sys
1
+ import{B as ue,C as D,J as le,S as pe,ma as fe,n as se,q as I,w as ce,y as de}from"./chunk-CTBFJWEE.js";import{a as i,d as A,i as G,j as M}from"./chunk-254PTGN5.js";import*as v from"node:fs";import*as k from"node:path";var qe=`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:
@@ -12,4 +12,4 @@ ${n}`;return`merge of "${r}" into "${e}" ${o}
12
12
  The merge is still in progress in ${t}. No conflict was resolved automatically.`}i(Ae,"conflictMessage");var Z=class{constructor(e){this.runner=e}runner;static{i(this,"BranchCleaner")}async delete(e,t){let{branch:n,worktreePath:o,repoCwd:a}=e;if(!n.startsWith("cow-"))return{kind:"not-applicable"};try{if(!await q(this.runner,n,a))return{kind:"not-applicable"};let s=await this.runner.run(["merge-base","--is-ancestor","--",n,"HEAD"],a);if(s===void 0)throw new h(`git merge-base --is-ancestor -- ${n} HEAD could not run in ${a}`);return s.code!==0?{kind:"kept",reason:"unmerged"}:t&&await t(o)?{kind:"kept",reason:"checked-out"}:await V(this.runner,n,a)}catch(s){return{kind:"delete-failed",detail:s instanceof Error?s.message:String(s)}}}};async function tr(r,e){return new X(new y(r)).merge(e)}i(tr,"mergeBranchIntoTarget");async function Se(r,e,t){return new Z(new y(r)).delete(e,t)}i(Se,"deleteWorktreeBranch");function Ie(r,e){return new S(new y(r),e)}i(Ie,"worktree");async function Me(r,e){return Ie(r,e).isDirty()}i(Me,"isWorktreeDirty");async function ar(r,e){let t=await Ie(r,e).isDirty();return t===void 0?{kind:"unverifiable",detail:"git status probe failed"}:t?{kind:"dirty"}:null}i(ar,"worktreeRetentionReason");function De(r){switch(r.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${r.detail})`}}i(De,"formatRetentionClause");import*as P from"node:fs";import*as W from"node:path";function Q(r){return{kind:"recorded",phase:r.lifecycle.phase}}i(Q,"recordedSettlement");function Le(r){let e=r.pane?{paneId:r.pane.paneId,origin:r.paneCreated?"self-created":"adopted"}:null,t=r.worktree;return t!==null&&t.repoCwd!==void 0?{kind:"worktree",worktree:{workspaceId:t.workspaceId,worktreePath:t.path,repoCwd:t.repoCwd,branchName:r.branch},pane:e}:r.worktreeManaged?{kind:"worktree-unlocatable",branchName:r.branch,worktreePath:t?.path??null,pane:e}:{kind:"no-worktree",pane:e}}i(Le,"planRecovered");async function ee(r,e,t){if(e?.force!==void 0)return{kind:"removable"};let n=await r(t.worktreePath);return n===void 0?{kind:"kept",reason:{kind:"unverifiable",detail:"git status probe failed"}}:n?{kind:"kept",reason:{kind:"dirty"}}:{kind:"removable"}}i(ee,"assessRemovability");function ze(r){if(r===void 0)return{kind:"allow",basis:{kind:"pane-absent"}};switch(r.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:r.state}};default:return M(r.state)}}i(ze,"recoveryGate");function te(r){switch(r.kind){case"pane-working":return{kind:"recovered-refusal",basis:r};case"pane-unreadable":return{kind:"unverifiable",detail:`the pane state could not be read (${r.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(te,"recoveryRefusalReason");function B(r,e,t,n,o){let a=t.kind==="worktree"?{kind:"kept",path:t.worktree.worktreePath}:t.kind==="worktree-unlocatable"?{kind:"kept",path:t.worktreePath}:{kind:"none"};return{agentId:r,source:e,outcome:{kind:"refused",reason:o.reason,forceable:o.forceable},branchName:t.kind==="worktree"?t.worktree.branchName:t.kind==="worktree-unlocatable"?t.branchName:void 0,settlement:n,pane:t.pane?{kind:"open",paneId:t.pane.paneId}:{kind:"none"},worktree:a,branch:{kind:"not-applicable"}}}i(B,"keptReport");function Be(r,e,t,n){return{agentId:r,source:e,outcome:{kind:"refused",reason:{kind:"ambiguous-artifacts",candidates:n},forceable:!1},settlement:t,pane:{kind:"none"},worktree:{kind:"kept",path:null},branch:{kind:"not-applicable"}}}i(Be,"ambiguousReport");function re(r){return r?.force!==void 0?{forced:r.force}:{}}i(re,"forcedFields");function _e(r,e,t,n,o,a){return{agentId:r,source:e,outcome:{kind:"torn-down",...re(a)},branchName:t.kind==="worktree"?t.worktree.branchName:void 0,settlement:n,pane:o.pane,worktree:o.worktree,branch:o.branch}}i(_e,"assembleReport");function wr(r){return r.outcome.kind==="refused"&&r.outcome.forceable}i(wr,"isForceableRefusal");function ne(r){return r.worktree.kind==="removed"||r.worktree.kind==="absent"?!0:r.worktree.kind==="none"?r.pane.kind==="none"||r.pane.kind==="closed":!1}i(ne,"shouldDropSpawn");function _(r){return r.workspaceId!==void 0?"multiplexer":"git"}i(_,"removalMechanismOf");function Ne(r,e,t){if(r===null)return{kind:"none"};if(!t)return{kind:"leave-open"};switch(e){case"multiplexer":return{kind:"closed-with-workspace"};case"git":case null:switch(r.origin){case"self-created":return{kind:"close"};case"adopted":return{kind:"leave-open"};default:return M(r.origin)}default:return M(e)}}i(Ne,"paneDispositionFor");var Ct=le("cleanup");function Rt(r,e){let t=r.pane,n=t?.workspaceId??r.worktree?.workspaceId;if(!(t===null||n===void 0))return{multiplexer:e,name:r.branch,paneId:t.paneId,tabId:t.tabId,workspaceId:n,paneCreated:r.paneCreated}}i(Rt,"hostRefFor");async function xt(r,e,t){if(!t)throw new Error(`cleanup has a pane (${e.paneId}) with no host address`);return await r.closePane(t),{kind:"closed",paneId:e.paneId}}i(xt,"closeOwnedPane");async function Ge(r,e,t){let n=t!==void 0&&e.workspaceId!==void 0;return(n?await r.removeWorktree(t):await r.removeGitWorktree(e.worktreePath,e.repoCwd))?{kind:"removed",path:e.worktreePath}:{kind:"removal-failed",path:e.worktreePath,detail:n?"herdr did not confirm the worktree removal":"git did not confirm the worktree removal"}}i(Ge,"removeOwnedTree");async function N(r,e,t,n,o){if(e===null)return{kind:"none"};switch(Ne(e,t,n).kind){case"none":return{kind:"none"};case"closed-with-workspace":return{kind:"closed",paneId:e.paneId};case"close":return xt(r,e,o);case"leave-open":return{kind:"open",paneId:e.paneId}}}i(N,"paneOutcomeFor");async function Pt(r,e){if(e===null)return{kind:"none"};let t;try{t=await r.observe(e)}catch{return{kind:"unknown",paneId:e.paneId}}return t===void 0?{kind:"gone",paneId:e.paneId}:{kind:"open",paneId:e.paneId}}i(Pt,"paneOutcomeForAbsentTree");async function Et(r,e,t){if(e.kind==="no-worktree")return{pane:await N(r,e.pane,null,!0,t),worktree:{kind:"none"},branch:{kind:"not-applicable"}};let{worktree:n,pane:o}=e,a=await Ge(r,n,t);return a.kind==="removed"?{pane:await N(r,o,_(n),!0,t),worktree:a,branch:await r.deleteBranch({branch:n.branchName,worktreePath:n.worktreePath,repoCwd:n.repoCwd})}:{pane:await N(r,o,_(n),!1,t),worktree:a,branch:{kind:"not-applicable"}}}i(Et,"removeResources");function oe(r){return{async removeWorktree(e,t){let n=e.worktree,o=e.pane,a=e.kind==="detached"?void 0:e.ref;try{if(!await r.worktreeExists(n.worktreePath))return{kind:"absent",path:n.worktreePath};let s=await ee(r.isWorktreeDirty,t,n);if(s.kind==="kept")return{kind:"kept",path:n.worktreePath,reason:s.reason};let c=await Ge(r,n,a);if(c.kind==="removal-failed")return c;let u=_(n);await N(r,o,u,!0,a);let d=await r.deleteBranch({branch:n.branchName,worktreePath:n.worktreePath,repoCwd:n.repoCwd});return{kind:"removed",path:n.worktreePath,branchName:n.branchName,via:u,branch:d}}catch(s){return{kind:"removal-failed",path:n.worktreePath,detail:A(s)}}}}}i(oe,"createWorktreeTeardown");function Pr(r){let e=oe(r);function t(a,s){return{kind:"discovered",basis:s,deliverable:r.deliverable(a)}}i(t,"recovered");async function n(a,s,c,u){if(c!==void 0){let p=Q(c);return pe(c.lifecycle)?{kind:"torn-down",settlement:p}:{kind:"refused",settlement:p,reason:{kind:"agent-active",phase:c.lifecycle.phase},forceable:!1}}if(u?.force!==void 0)return{kind:"torn-down",settlement:t(a,{kind:"forced"})};let d;if(s.pane!==null)try{d=await r.observe(s.pane)}catch(p){let m={kind:"pane-unreadable",detail:A(p)};return{kind:"refused",settlement:t(a,m),reason:te(m),forceable:!0}}let l=ze(d);return l.kind==="allow"?{kind:"torn-down",settlement:t(a,l.basis)}:{kind:"refused",settlement:t(a,l.basis),reason:te(l.basis),forceable:!0}}i(n,"verdictFor");async function o(a,s,c){let u=s.getSpawn(a),d=await r.locate(a,u);if(d.kind==="not-found")throw new Error(`Agent ${a} not found.`);if(d.kind==="ambiguous")return Be(a,u===void 0?"recovered":"tracked",u===void 0?t(a,{kind:"artifacts-ambiguous"}):Q(u),d.candidates.map(x=>x.worktreePath));let l=Le(d),p=await n(a,d,u,c);if(p.kind==="refused")return B(a,d.source,l,p.settlement,{reason:p.reason,forceable:p.forceable});let m=u?.execution.harness;if(m!==void 0)try{await r.harnessTeardown(m,{paneId:d.pane?.paneId??null,cwd:d.worktree?.path??null,subagentId:a})}catch(x){Ct.warn("harness teardown failed during cleanup",{spawnId:a,harness:m,error:A(x)})}if(l.kind==="worktree-unlocatable"){if(l.worktreePath!==null&&!await r.worktreeExists(l.worktreePath)){let x={agentId:a,source:d.source,outcome:{kind:"torn-down",...re(c)},branchName:l.branchName,settlement:p.settlement,pane:await Pt(r,d.pane),worktree:{kind:"absent",path:l.worktreePath},branch:{kind:"not-applicable"}};return ne(x)&&u!==void 0&&s.dropSpawn(u),x}return B(a,d.source,l,p.settlement,{reason:{kind:"unverifiable",detail:"missing worktree path or repo cwd"},forceable:!1})}if(l.kind==="worktree"){let x=await ee(r.isWorktreeDirty,c,l.worktree);if(x.kind==="kept")return B(a,d.source,l,p.settlement,{reason:x.reason,forceable:!0})}let T=await Et(r,l,Rt(d,r.multiplexer)),ae=_e(a,d.source,l,p.settlement,T,c);return ne(ae)&&u!==void 0&&s.dropSpawn(u),ae}return i(o,"cleanupAgent"),{...e,cleanupAgent:o}}i(Pr,"createCleanup");import*as He from"node:path";async function Wt(r,e,t){let n=await U(r,["rev-parse","--verify","--quiet",`refs/heads/${t}`],e,R);return n===void 0?!0:n.code===0}i(Wt,"branchExisted");async function je(r,e){let t=e.branch.trim();if(t==="")throw new h("worktree checkout requires a branch name");let n=await z(r,e.repoCwd),o=He.resolve(e.path),a=e.materialization??se,s=e.dirtyCheckout??I,c=await Wt(r,n,t),u=await U(r,["worktree","add",...Ee(a),"-b",t,o,e.base??"HEAD"],n,R);if(u===void 0||u.code!==0)throw await E(r,n,o),c||await O(r,t,n),new h(u===void 0?`git worktree add for "${t}" could not run (worktree removed)`:`git worktree add for "${t}" failed (worktree removed): ${(u.stderr||u.stdout||`exit ${u.code}`).slice(0,300)}`);let d=await xe(r,["branch","--show-current"],o);if(d!==t)throw await E(r,n,o),await O(r,t,n),new h(d===void 0?`worktree created at ${o} but its branch could not be verified (worktree removed)`:`worktree created at ${o} is on branch "${d||"(detached)"}", not the requested "${t}" (worktree removed). The branch "${d}" still exists.`);let l;try{l=await We(r,o,a,s)}catch(p){await E(r,n,o),await O(r,t,n);let m=p instanceof Error?p.message:String(p);throw new h(`worktree created but ${a} materialization failed (worktree removed): ${m}`)}if(l.kind==="cow-fallback"){let p=s==="dirty"?" The parent's uncommitted work was not carried over.":"";e.notify?.(`[cowboy] ${l.reason}${p} Nothing is shared with the parent checkout.`,"warning")}return{path:o,branch:t,repoCwd:n,materialization:l}}i(je,"createWorktreeCheckout");function Tt(r){try{let e=P.statSync(r,{bigint:!0});return`${e.dev}:${e.ino}`}catch{return W.resolve(r)}}i(Tt,"canonicalRepoKey");var Fe=class r{static{i(this,"AgentSandbox")}branch;projectTrusted;host;placement;current={kind:"bound"};constructor(e,t,n,o){this.host=e,this.placement=t,this.branch=n,this.projectTrusted=o}static async allocate(e,t){let{naming:n,parentCwd:o,worktreeRoot:a,materialization:s,dirtyCheckout:c,notify:u,host:d}=t,l=n.kind==="generated"?ce(n.taskSlug,n.id):n.branch.trim();if(n.kind==="explicit"&&l==="")throw new Error("explicit worktree naming requires a branch name");let p;try{p=await z(e,o)}catch{return u?.("[cowboy] Parent is not inside a git repository \u2014 spawning in the parent cwd without a worktree","warning"),new r(d,{kind:"parent-cwd"},l,!0)}let m=await Ot(e,{repoCwd:p,path:W.join(de(a,p),l),branch:l,materialization:s,dirtyCheckout:c,notify:u,host:d});return new r(d,{kind:"worktree",checkout:{path:m.path,branch:m.branch,repoCwd:m.repoCwd},ref:m.ref},l,!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(e,t){let n=this.placement;if(n.kind==="parent-cwd")return this.current={kind:"destroyed"},{kind:"absent"};if(this.current.kind==="destroyed")return{kind:"absent",path:n.checkout.path};let o=await oe(St(e,this.host)).removeWorktree({kind:"adopted",worktree:{workspaceId:n.ref.workspaceId,worktreePath:n.checkout.path,repoCwd:n.checkout.repoCwd,branchName:n.checkout.branch},pane:{paneId:n.ref.paneId,origin:n.ref.paneCreated===!0?"self-created":"adopted"},ref:n.ref},t);return this.current=At(o),o}};function At(r){switch(r.kind){case"kept":return{kind:"preserved",reason:r.reason};case"removed":case"absent":return{kind:"destroyed"};case"removal-failed":return{kind:"teardown-failed",detail:r.detail}}}i(At,"stateAfterTeardown");async function Ot(r,e){let t=W.resolve(e.path);return P.mkdirSync(W.dirname(t),{recursive:!0}),fe().run(Tt(e.repoCwd),()=>$t(r,e.host,{...e,path:t}))}i(Ot,"createAdoptedWorktree");async function $t(r,e,t){let{repoCwd:n,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:u}=t,d;try{d=await je(r,{repoCwd:n,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:u})}catch(p){throw Ue(p,await Ke(r,n,o))}let l;try{l=await e.hostAt({unit:"pane",cwd:d.path,label:a,name:a,checkout:{path:d.path,repoCwd:n,branch:d.branch}})}catch(p){let m=await Ke(r,n,d.path),T=await O(r,d.branch,n);throw Ue(p,`${m}. ${ie(d.branch,T)}`)}return{path:d.path,branch:d.branch,repoCwd:n,materialization:d.materialization,ref:l}}i($t,"adoptWorktree");function St(r,e){return{isWorktreeDirty:i(t=>Me(r,t),"isWorktreeDirty"),worktreeExists:i(async t=>P.existsSync(t),"worktreeExists"),removeWorktree:i(t=>e.release(t,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(t,n)=>(await E(r,n,t),!P.existsSync(t)),"removeGitWorktree"),deleteBranch:i(t=>Se(r,t,n=>e.isAttached(n,{repoCwd:t.repoCwd})),"deleteBranch"),closePane:i(async t=>{await e.release(t,"placement")},"closePane"),harnessTeardown:i(async()=>{},"harnessTeardown")}}i(St,"cleanupDeps");async function Ke(r,e,t){return await E(r,e,t),P.existsSync(t)?`worktree ${t} NOT removed \u2014 inspect it manually`:`worktree ${t} removed`}i(Ke,"removeFailedCheckout");function Ue(r,e){return new Error(`could not create the herdr worktree: ${A(r)}
13
13
 
14
14
  Launch-failure cleanup: ${e}.`)}i(Ue,"createFailureMessage");function ie(r,e){switch(e.kind){case"deleted":return`branch ${r} deleted`;case"kept":return`branch ${r} kept (${e.reason})`;case"delete-failed":return`branch ${r} NOT deleted \u2014 ${e.detail}`;case"not-applicable":return`branch ${r} already gone`}}i(ie,"formatLaunchedBranchOutcome");function Br(r){switch(r.kind){case"removed":return r.via==="multiplexer"?`Launch-failure cleanup: worktree ${r.path} removed \u2014 its workspace, tab, and pane were closed with it. ${ie(r.branchName,r.branch)}.`:`Launch-failure cleanup: worktree ${r.path} removed. ${ie(r.branchName,r.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${r.path} KEPT \u2014 ${De(r.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 ${r.path}: ${r.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(Br,"formatLaunchCleanupNote");export{Mt as a,Ce as b,y as c,xe as d,$ as e,Bt as f,z as g,E as h,Ht as i,jt as j,Te as k,tr as l,Se as m,Me as n,ar as o,De as p,wr as q,Pr as r,Fe as s,Ot as t,Br as u};
15
- //# sourceMappingURL=chunk-HPB3IRXW.js.map
15
+ //# sourceMappingURL=chunk-KMXT7XW7.js.map
@@ -1,4 +1,4 @@
1
- import{b as Rt,c as It,e as Pt,g as Mt,k as Me,l as Nt,p as $t}from"./chunk-HPB3IRXW.js";import{$ as St,Ba as Pe,Ca as se,F as At,I as _e,K as xt,L as G,M as Se,N as P,O as Ee,P as Ct,R as te,S as _,T as M,V as _t,aa as ne,b as it,ea as C,fa as re,ga as b,h as st,i as at,ia as f,j as K,ja as N,k as lt,ka as Oe,l as xe,la as Re,m as ct,na as Et,o as dt,qa as Ie,r as ut,ra as oe,sa as x,ta as ie,v as pt,va as j,w as gt,x as mt,y as ht,ya as Ot}from"./chunk-7W5EBKER.js";import{a as r,d as ee,f as Ce,g as ft,j as yt,k as wt,l as kt,s as bt,t as vt,u as Tt}from"./chunk-254PTGN5.js";import{visibleWidth as De}from"@earendil-works/pi-tui";var Ne="\u{1F920}",Ft="\u{1F404}",rr="\u{1F4A9}",or=2,ir=1e3,ae=De(Ft),sr="76;175;80";function ar(e){return`\x1B[48;2;${sr}m${e}\x1B[49m`}r(ar,"greenBackground");function jt(e){return e===0?0:Math.max(or,Math.ceil(Math.sqrt(2*e)))}r(jt,"pastureEdge");function Ht(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Ht,"emptyPasture");function lr(e,t){let n=jt(e.cows+e.droppings),o=Ht(n),i=Array.from({length:n*n},(a,l)=>l),s=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let a=0;a<s.length;a+=1){let l=a+Math.floor(t()*(i.length-a)),d=i[l];i[l]=i[a],i[a]=d,o[Math.floor(d/n)][d%n]=s[a]}return o}r(lr,"grazedPasture");function le(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(le,"cellsOf");function cr(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(cr,"neighboursOf");function Bt(e,t){return cr(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Bt,"openNeighboursOf");function dr(e,t){let n=le(e,"cow").filter(l=>Bt(l,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Bt(o,e),s=i[Math.floor(t()*i.length)],a=e.map(l=>l.slice());return a[o.row][o.col]="empty",a[s.row][s.col]="cow",a}r(dr,"moveHerd");function Dt(e,t,n,o){for(let i=0;i<n;i+=1){let s=le(e,"empty"),a=s[Math.floor(o()*s.length)];e[a.row][a.col]=t}}r(Dt,"placeAtRandom");function ur(e,t,n,o){let i=le(e,"cow"),s=le(e,"dropping"),a=i.length-t,l=s.length-n;for(;a>0&&l<0;){let d=i.pop();e[d.row][d.col]="dropping",a-=1,l+=1}for(;a>0;){let d=i.pop();e[d.row][d.col]="empty",a-=1}for(;l>0;){let d=s.pop();e[d.row][d.col]="empty",l-=1}Dt(e,"cow",-a,o),Dt(e,"dropping",-l,o)}r(ur,"reconcileCounts");function pr(e,t,n){if(e===null)return lr(t,n);let o=jt(t.cows+t.droppings),i=Ht(o);for(let s=0;s<e.length&&s<o;s+=1)for(let a=0;a<e[s].length&&a<o;a+=1)i[s][a]=e[s][a];return ur(i,t.cows,t.droppings,n),i}r(pr,"reconcilePasture");var gr={anchor:"top-right",width:De(Ne),get offsetX(){return N()?.cowboyOffsetX??0},nonCapturing:!0},mr={anchor:"top-right",offsetY:1,get width(){return N()?.pastureWidth??0},nonCapturing:!0};function hr(e){return e==="cow"?Ft:e==="dropping"?rr:" ".repeat(ae)}r(hr,"cellText");function fr(e,t){return e.map(n=>t(n.map(hr).join("")))}r(fr,"drawnRows");function yr(){return Re().list(["spawned"]).length}r(yr,"liveAgentCount");function wr(){return Re().list(Ct).length}r(wr,"endedAgentCount");function kr(){return{live:yr(),ended:wr()}}r(kr,"agentCounts");function br(){return f().agent.grazingEnabled}r(br,"grazingEnabled");var $e=class{constructor(t,n,o,i,s){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=s}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return De(Ne)}get pastureWidth(){return this.drawnPasture().length*ae}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*ae-(t*ae-this.cowboyWidth)}render(){return this.frame(),[Ne]}pastureRows(){return this.frame(),fr(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(),ir))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,s=(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:dr(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let a=s&&this.drawnPasture().length===0;this.tui.requestRender(a)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:pr(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Be=class{static{r(this,"PastureView")}render(){return N()?.pastureRows()??[]}invalidate(){}};function Lt(e){Fe(),e.custom(t=>{let n=new $e(t,kr,br,ar,Math.random);return Oe(n),n},{overlay:!0,overlayOptions:gr,onHandle:r(t=>N()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Be,{overlay:!0,overlayOptions:mr,onHandle:r(t=>N()?.attachPasture(t),"onHandle")})}r(Lt,"showExtensionIndicator");function Fe(){let e=N();Oe(null),e?.dispose()}r(Fe,"hideExtensionIndicator");function ce(){return f().agent.extensionEnabled}r(ce,"isExtensionEnabled");function vr(){return ce()&&f().agent.showActiveIndicator}r(vr,"isActiveIndicatorShown");function de(e){vr()?Lt(e):Fe()}r(de,"syncExtensionIndicator");function ui(e,t){f().mutate.agent.setShowActiveIndicator(t),de(e)}r(ui,"setShowActiveIndicator");import{Type as D}from"typebox";import{Text as Bn}from"@earendil-works/pi-tui";import{Type as y}from"typebox";var Tr="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.",Ar=`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.`,xr=`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.`,Cr=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${wt.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.`,_r=y.Object({prompt:y.String({description:Tr}),task_name:y.String({description:Ar}),agent_type:y.Optional(y.Union([y.String(),y.Null()])),model:y.Optional(y.Union([y.String(),y.Null()],{description:xr})),harness_type:y.Optional(y.Union([y.String(),y.Null()],{description:Cr}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=y.Object({agents:y.Array(_r,{minItems:1}),run_in_background:y.Optional(y.Boolean())},{additionalProperties:!1,required:["agents"]});import{Type as je}from"typebox";var Sr="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Ut=je.Object({agent_ids:je.Array(je.String({minLength:1}),{minItems:1,description:Sr})},{additionalProperties:!1,required:["agent_ids"]});import{Type as He}from"typebox";var Er="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",Wt=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:Er})},{additionalProperties:!1,required:["agent_ids"]});import{Type as $}from"typebox";var Or="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",Rr="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",Ir="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",qt=$.Object({branches:$.Array($.String({minLength:1}),{minItems:1,description:Or}),target:$.Optional($.String({description:Rr})),repo:$.Optional($.String({description:Ir}))},{additionalProperties:!1,required:["branches"]});import{Type as ue}from"typebox";var Pr="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.",Mr="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.",Kt=ue.Object({agent_ids:ue.Array(ue.String({minLength:1}),{minItems:1,description:Pr}),message:ue.String({description:Mr})},{additionalProperties:!1,required:["agent_ids","message"]});import*as pe from"node:fs";import*as Gt from"node:path";import{parse as Nr,TomlError as $r}from"smol-toml";import{z as Br}from"zod";var Dr=".toml";function ge(e){return Nr(e.replace(/^\uFEFF/,""))}r(ge,"parseTemplateToml");function T(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0))}r(T,"compactDefined");function Fr(e){let t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}r(Fr,"describeZodIssue");function jr(e){if(e instanceof Br.ZodError)return e.issues.map(Fr).join("; ").replace(/\s+/g," ").trim();if(e instanceof $r){let[n]=e.message.split(`
1
+ import{b as Rt,c as It,e as Pt,g as Mt,k as Me,l as Nt,p as $t}from"./chunk-KMXT7XW7.js";import{$ as St,Ba as Pe,Ca as se,F as At,I as _e,K as xt,L as G,M as Se,N as P,O as Ee,P as Ct,R as te,S as _,T as M,V as _t,aa as ne,b as it,ea as C,fa as re,ga as b,h as st,i as at,ia as f,j as K,ja as N,k as lt,ka as Oe,l as xe,la as Re,m as ct,na as Et,o as dt,qa as Ie,r as ut,ra as oe,sa as x,ta as ie,v as pt,va as j,w as gt,x as mt,y as ht,ya as Ot}from"./chunk-CTBFJWEE.js";import{a as r,d as ee,f as Ce,g as ft,j as yt,k as wt,l as kt,s as bt,t as vt,u as Tt}from"./chunk-254PTGN5.js";import{visibleWidth as De}from"@earendil-works/pi-tui";var Ne="\u{1F920}",Ft="\u{1F404}",rr="\u{1F4A9}",or=2,ir=1e3,ae=De(Ft),sr="76;175;80";function ar(e){return`\x1B[48;2;${sr}m${e}\x1B[49m`}r(ar,"greenBackground");function jt(e){return e===0?0:Math.max(or,Math.ceil(Math.sqrt(2*e)))}r(jt,"pastureEdge");function Ht(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Ht,"emptyPasture");function lr(e,t){let n=jt(e.cows+e.droppings),o=Ht(n),i=Array.from({length:n*n},(a,l)=>l),s=[...Array.from({length:e.cows},()=>"cow"),...Array.from({length:e.droppings},()=>"dropping")];for(let a=0;a<s.length;a+=1){let l=a+Math.floor(t()*(i.length-a)),d=i[l];i[l]=i[a],i[a]=d,o[Math.floor(d/n)][d%n]=s[a]}return o}r(lr,"grazedPasture");function le(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(le,"cellsOf");function cr(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(cr,"neighboursOf");function Bt(e,t){return cr(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Bt,"openNeighboursOf");function dr(e,t){let n=le(e,"cow").filter(l=>Bt(l,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Bt(o,e),s=i[Math.floor(t()*i.length)],a=e.map(l=>l.slice());return a[o.row][o.col]="empty",a[s.row][s.col]="cow",a}r(dr,"moveHerd");function Dt(e,t,n,o){for(let i=0;i<n;i+=1){let s=le(e,"empty"),a=s[Math.floor(o()*s.length)];e[a.row][a.col]=t}}r(Dt,"placeAtRandom");function ur(e,t,n,o){let i=le(e,"cow"),s=le(e,"dropping"),a=i.length-t,l=s.length-n;for(;a>0&&l<0;){let d=i.pop();e[d.row][d.col]="dropping",a-=1,l+=1}for(;a>0;){let d=i.pop();e[d.row][d.col]="empty",a-=1}for(;l>0;){let d=s.pop();e[d.row][d.col]="empty",l-=1}Dt(e,"cow",-a,o),Dt(e,"dropping",-l,o)}r(ur,"reconcileCounts");function pr(e,t,n){if(e===null)return lr(t,n);let o=jt(t.cows+t.droppings),i=Ht(o);for(let s=0;s<e.length&&s<o;s+=1)for(let a=0;a<e[s].length&&a<o;a+=1)i[s][a]=e[s][a];return ur(i,t.cows,t.droppings,n),i}r(pr,"reconcilePasture");var gr={anchor:"top-right",width:De(Ne),get offsetX(){return N()?.cowboyOffsetX??0},nonCapturing:!0},mr={anchor:"top-right",offsetY:1,get width(){return N()?.pastureWidth??0},nonCapturing:!0};function hr(e){return e==="cow"?Ft:e==="dropping"?rr:" ".repeat(ae)}r(hr,"cellText");function fr(e,t){return e.map(n=>t(n.map(hr).join("")))}r(fr,"drawnRows");function yr(){return Re().list(["spawned"]).length}r(yr,"liveAgentCount");function wr(){return Re().list(Ct).length}r(wr,"endedAgentCount");function kr(){return{live:yr(),ended:wr()}}r(kr,"agentCounts");function br(){return f().agent.grazingEnabled}r(br,"grazingEnabled");var $e=class{constructor(t,n,o,i,s){this.tui=t;this.countAgents=n;this.isGrazing=o;this.grass=i;this.random=s}tui;countAgents;isGrazing;grass;random;static{r(this,"PresenceMarker")}herd=null;cowboyHandle=null;pastureHandle=null;poll=null;disposed=!1;grazing=null;get cowboyWidth(){return De(Ne)}get pastureWidth(){return this.drawnPasture().length*ae}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*ae-(t*ae-this.cowboyWidth)}render(){return this.frame(),[Ne]}pastureRows(){return this.frame(),fr(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(),ir))}recount(){let{live:t,ended:n}=this.countAgents(),o=this.isGrazing(),i=o!==this.grazing,s=(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:dr(this.herd.pasture,this.random)};else if(!i)return;if(this.grazing=o,this.pollWhile(o),o||i){let a=s&&this.drawnPasture().length===0;this.tui.requestRender(a)}}place({live:t,ended:n}){return{liveAgents:t,endedAgents:n,pasture:pr(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Be=class{static{r(this,"PastureView")}render(){return N()?.pastureRows()??[]}invalidate(){}};function Lt(e){Fe(),e.custom(t=>{let n=new $e(t,kr,br,ar,Math.random);return Oe(n),n},{overlay:!0,overlayOptions:gr,onHandle:r(t=>N()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Be,{overlay:!0,overlayOptions:mr,onHandle:r(t=>N()?.attachPasture(t),"onHandle")})}r(Lt,"showExtensionIndicator");function Fe(){let e=N();Oe(null),e?.dispose()}r(Fe,"hideExtensionIndicator");function ce(){return f().agent.extensionEnabled}r(ce,"isExtensionEnabled");function vr(){return ce()&&f().agent.showActiveIndicator}r(vr,"isActiveIndicatorShown");function de(e){vr()?Lt(e):Fe()}r(de,"syncExtensionIndicator");function ui(e,t){f().mutate.agent.setShowActiveIndicator(t),de(e)}r(ui,"setShowActiveIndicator");import{Type as D}from"typebox";import{Text as Bn}from"@earendil-works/pi-tui";import{Type as y}from"typebox";var Tr="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.",Ar=`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.`,xr=`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.`,Cr=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${wt.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.`,_r=y.Object({prompt:y.String({description:Tr}),task_name:y.String({description:Ar}),agent_type:y.Optional(y.Union([y.String(),y.Null()])),model:y.Optional(y.Union([y.String(),y.Null()],{description:xr})),harness_type:y.Optional(y.Union([y.String(),y.Null()],{description:Cr}))},{additionalProperties:!1,required:["prompt","task_name"]}),H=y.Object({agents:y.Array(_r,{minItems:1}),run_in_background:y.Optional(y.Boolean())},{additionalProperties:!1,required:["agents"]});import{Type as je}from"typebox";var Sr="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Ut=je.Object({agent_ids:je.Array(je.String({minLength:1}),{minItems:1,description:Sr})},{additionalProperties:!1,required:["agent_ids"]});import{Type as He}from"typebox";var Er="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",Wt=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:Er})},{additionalProperties:!1,required:["agent_ids"]});import{Type as $}from"typebox";var Or="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",Rr="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",Ir="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",qt=$.Object({branches:$.Array($.String({minLength:1}),{minItems:1,description:Or}),target:$.Optional($.String({description:Rr})),repo:$.Optional($.String({description:Ir}))},{additionalProperties:!1,required:["branches"]});import{Type as ue}from"typebox";var Pr="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.",Mr="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.",Kt=ue.Object({agent_ids:ue.Array(ue.String({minLength:1}),{minItems:1,description:Pr}),message:ue.String({description:Mr})},{additionalProperties:!1,required:["agent_ids","message"]});import*as pe from"node:fs";import*as Gt from"node:path";import{parse as Nr,TomlError as $r}from"smol-toml";import{z as Br}from"zod";var Dr=".toml";function ge(e){return Nr(e.replace(/^\uFEFF/,""))}r(ge,"parseTemplateToml");function T(e){return Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0))}r(T,"compactDefined");function Fr(e){let t=e.path.join(".");return t?`${t}: ${e.message}`:e.message}r(Fr,"describeZodIssue");function jr(e){if(e instanceof Br.ZodError)return e.issues.map(Fr).join("; ").replace(/\s+/g," ").trim();if(e instanceof $r){let[n]=e.message.split(`
2
2
 
3
3
  `);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}r(jr,"describeParseError");var Hr={label:"File",problem:"was skipped"};async function me(e,t,n,o,i=Hr,s){try{await pe.promises.access(e)}catch{return[]}let l=(await pe.promises.readdir(e,{withFileTypes:!0})).filter(c=>c.isFile()&&c.name.endsWith(Dr)),d=[];for(let c of l){let h=Gt.join(e,c.name),g;try{g=await pe.promises.readFile(h,"utf-8")}catch{continue}try{let p=t(g),m=s?.(p);if(m!==void 0)throw new Error(m);n(p)&&d.push(p)}catch(p){o?.(`[cowboy] ${i.label} file ${h} ${i.problem}: ${jr(p)}`,"warning")}}return d}r(me,"scanTemplateFilesInDir");import{z as u}from"zod";var Vt=u.union([u.boolean(),u.array(u.string())]),Lr={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 fe(e){return u.record(u.string(),u.unknown()).transform((t,n)=>St(t,{reserved:bt[e],report:r((o,i)=>n.addIssue({code:"custom",path:[o],message:Lr[i]}),"report")}))}r(fe,"envTable");var zt={model:u.string().optional(),thinking:G.optional(),extensions:Vt.optional(),skills:Vt.optional(),inlined_skills:u.array(u.string()).optional(),fork:u.boolean().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:fe("pi").optional()},Ur=u.strictObject(zt),Wr=u.strictObject({model:u.string().optional(),variant:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:fe("opencode").optional()}),qr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),env:fe("codex").optional()}),Kr=u.strictObject({model:u.string().optional(),thinking:u.string().optional(),tools:u.array(u.string()).optional(),exclude_tools:u.array(u.string()).optional(),env:fe("claude").optional()});function Le(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}r(Le,"toToolFilter");function he(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}r(he,"nonEmptyEnv");var Gr=u.strictObject({include_context_files:u.boolean().optional(),pi:Ur.optional(),opencode:Wr.optional(),codex:qr.optional(),claude:Kr.optional(),...zt}).transform(({pi:e,opencode:t,codex:n,claude:o,...i})=>{let{model:s,thinking:a,tools:l,exclude_tools:d,env:c,...h}=i,{model:g,thinking:p,tools:m,exclude_tools:w,env:k,...v}=T(e??{}),{model:F,variant:q,tools:Ae,exclude_tools:Kn,env:Gn,...Vn}=T(t??{}),{model:zn,thinking:Yn,env:Qn,...Xn}=T(n??{}),{model:Zn,thinking:Jn,tools:er,exclude_tools:tr,env:nr}=T(o??{}),tt=T({pi:g??s,opencode:F,codex:zn,claude:Zn}),nt=T({pi:Le(m??l,w??d),opencode:Le(Ae,Kn),claude:Le(er,tr)}),rt=T({pi:p??a,opencode:q,codex:Yn,claude:Jn}),ot=T({pi:he(ne(c,k)),opencode:he(Gn),codex:he(Qn),claude:he(nr)});return{...h,...v,...Vn,...Xn,...Object.keys(tt).length>0?{modelsByFamily:tt}:{},...Object.keys(nt).length>0?{toolsByFamily:nt}:{},...Object.keys(rt).length>0?{thinkingByFamily:rt}:{},...Object.keys(ot).length>0?{envByFamily:ot}:{}}}),Yt=u.strictObject({name:u.string().optional(),display_name:u.string().optional(),description:u.string().optional(),hidden:u.boolean().optional(),worktree_checkout_type:u.enum(ut).optional(),system_prompt:u.string().optional(),harness_type:u.string().min(1).optional(),harness:Gr.optional()});function Vr(e){return Yt.parse(ge(e))}r(Vr,"parseAgentFile");var zr={label:"Agent",problem:"is not a valid agent template and was skipped"};async function L(e,t,n){return me(e,Vr,o=>o.name,t,zr,n)}r(L,"scanAgentFilesInDir");function ye(e,t,n,o){let i=new Map;for(let[s,a]of e)i.set(s,{...a});return Ue(i,t),Ue(i,n),Ue(i,o),i}r(ye,"mergeAgents");function Ue(e,t){for(let n of t){if(!n.name)continue;let o=e.get(n.name);if(o){let i={displayName:n.display_name,description:n.description??""},s=Qt(n),a=Yr(o.modelsByFamily,s.modelsByFamily),l=Qr(o.toolsByFamily,s.toolsByFamily),d=Xr(o.thinkingByFamily,s.thinkingByFamily),c=Zr(o.envByFamily,s.envByFamily);e.set(n.name,{...o,...s,...a?{modelsByFamily:a}:{},...l?{toolsByFamily:l}:{},...d?{thinkingByFamily:d}:{},...c?{envByFamily:c}:{},...i})}else e.set(n.name,{...Jr,...Qt(n)})}}r(Ue,"mergeAgentOverrides");function Yr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Yr,"mergeModelsByFamily");function Qr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Qr,"mergeToolsByFamily");function Xr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}r(Xr,"mergeThinkingByFamily");function Zr(e,t){let n={...e};for(let[o,i]of Object.entries(t??{})){let s=o;n[s]=ne(n[s],i)}return Object.keys(n).length>0?n:void 0}r(Zr,"mergeEnvByFamily");function Qt(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 T(n)}r(Qt,"fromTemplate");var Jr={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var We=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return se().agents}r(S,"registry");function V(e){let t=e.harness_type;if(t===void 0)return;let n=x();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}r(V,"unregisteredHarness");function Vi(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[o,i]of We)n.set(o,i);for(let[o,i]of e)n.set(o,i);S().agents=n}r(Vi,"registerAgents");function zi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}r(zi,"setAgentScanDirs");async function eo(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,o=S().scanDirs,[i,s,a,l]=await Promise.all([t?Promise.resolve([]):L(st,n,V),L(o.user,n,V),L(o.shared,n,V),L(o.project,n,V)]),c=ye(t?new Map:We,i,[],[]);return ye(c,s,a,l)}r(eo,"scanAndMerge");async function to(e,t){let n=await eo(t),{agents:o}=S(),i=0;for(let[s,a]of n)o.has(s)||(o.set(s,a),i++);if(e){let s=await L(e,t?.notify,V),a=ye(new Map,[],[],s);for(let[l,d]of a)o.has(l)||(o.set(l,d),i++)}return i}r(to,"discoverNewAgents");function z(e){let{agents:t}=S();if(!e)return{kind:"not-found"};if(t.has(e))return{kind:"resolved",key:e};let n=e.toLowerCase(),o=[];for(let i of t.keys())i.toLowerCase()===n&&o.push(i);return o.length===1?{kind:"resolved",key:o[0]}:o.length>1?{kind:"ambiguous",candidates:o}:{kind:"not-found"}}r(z,"resolveType");async function Zt(e,t,n){let o=z(e);return o.kind==="not-found"&&(await to(t,{notify:n}),o=z(e)),o}r(Zt,"resolveTypeOrDiscover");function E(e){let t=z(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}r(E,"getAgentConfig");function Jt(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}r(Jt,"getAvailableTypes");function Yi(){return[...S().agents.keys()]}r(Yi,"getAllTypes");function Xt(e,t,n,o){return{skills:e??n,extensions:t??o}}r(Xt,"applyGlobalDefaults");function Qi(e,t=!0,n=!0){let o=E(e);if(o){let{skills:s,extensions:a,...l}=o,d=Xt(s,a,t,n);return{displayName:l.displayName??l.name,description:l.description,...d}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Xt(void 0,void 0,t,n)}}r(Qi,"getConfig");var qe="_configuredModel",Ke="_configuredThinking";function U(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(U,"readModelKey");function en(e){return U(e.thinking)??U(e[Ke])}r(en,"readThinkingRequest");function tn(e){let t=U(e.model);if(t)return{source:"call",key:t};let n=U(e[qe]);if(n)return{source:"configured",key:n}}r(tn,"readModelRequest");function Y(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(Y,"withoutModel");function nn(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(nn,"modelChoiceFor");function Q(e){return`${e.provider}/${e.id}`}r(Q,"modelKey");function no(e,t){if(t!==void 0&&!G.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${G.options.join(", ")}); launching "${Q(e)}" with "${t}".`}r(no,"undeclaredLevelWarning");function rn(e,t){let n=no(e,t);return{resolved:{kind:"resolved",model:e,modelKey:Q(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(rn,"resolvedModel");function ro(e){return`No API key found for "${e}"`}r(ro,"missingCredential");function on(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:ee(o)}}return!At(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:ro(t.provider)}}r(on,"probeCredentials");function Ge(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ge,"refusal");function Ve(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return Y(i);let l=on(n,o);if(l.verdict!=="unusable")return rn(o,i);throw new Error(Ge(`The parent session's model "${Q(o)}" did not resolve credentials in this session`,l.reason))}let s=e.source==="call"?Ce(e.key,n,void 0):Ce(e.key,n,o);if(!s){if(e.source==="call")throw new Error(`Model "${e.key}" is not available in this session. Nothing was spawned.`);return Y(i)}let a=on(n,s);if(a.verdict!=="unusable")return rn(s,i);throw e.source==="call"?new Error(Ge(`Model "${Q(s)}" cannot authenticate in this session`,a.reason)):new Error(Ge(`The subagent model "${Q(s)}" for this configured default cannot authenticate in this session`,a.reason))}r(Ve,"resolvePiModel");async function oo(e){try{return await e.listModels(e.harness)}catch{return[]}}r(oo,"harnessModels");function io(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(io,"undeclaredLevelWarning");async function sn(e,t){if(!e)return Y(t.thinking);let n=await oo(t),o=n.find(s=>s.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 s=io(t.harness,o,t.thinking);s!==void 0&&i.push(s)}return{resolved:{kind:"foreign",harness:t.harness,modelKey:e.key,modelName:o?.label??e.key,thinking:t.thinking??null},notices:i}}r(sn,"resolveForeignModel");async function an(e,t){let{harness:n}=t;if(kt(n))return Ve(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return sn(e,o)}r(an,"resolveSpawnModel");function we(e,t){return{content:[{type:"text",text:e}],details:t}}r(we,"successResult");var ze=`
4
4
 
@@ -20,5 +20,5 @@ ${Do(p)}`,details:v}}let m=d;if(p.lifecycle.phase==="queued"){let v=b().listAgen
20
20
  `)}r(Rn,"renderCleanupReport");function Pa(e){let t=e.pane.kind==="closed"?"pane closed":e.pane.kind==="open"?"pane left open":e.pane.kind==="gone"?"pane already gone":e.pane.kind==="unknown"?"pane state unknown":"no pane";return e.outcome.kind==="refused"?`${et(e)} ${t}`:`${et(e)} ${t}, worktree ${En(e.worktree)}, branch ${On(e)}`}r(Pa,"summarizeCleanupReport");function Ma(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Ma,"cleanupNeedsAttention");function Wo(e){switch(e.kind){case"cleaned":return Rn(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(Wo,"renderCleanupOutcome");async function In(e,t,n,o,i){let s=t.agent_ids;return O({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:s,render:Wo,handleItem:r(async a=>{let l=b();if(!l.getSpawn(a)&&(await l.locate(a)).kind==="not-found")return{kind:"unknown",agentId:a,activeAgents:B(l)};let d=await l.cleanup(a);return{kind:"cleaned",agentId:a,report:d}},"handleItem")})}r(In,"executeCleanupAgentTool");import*as Mn from"node:fs";import*as W from"node:path";function Pn(e){let t=W.normalize(e),{root:n}=W.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Pn,"normalizeRepoRoot");function qo(e,t){return Pn(e)===Pn(t)}r(qo,"isSameRepoRoot");function Ko(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(Ko,"formatOutsideRepoWarning");async function Go(e,t){let n=new It(e),o=await n.probe(["rev-parse","--show-toplevel"],t);if(o===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: ${t} is not inside a git repository (git rev-parse --show-toplevel failed). Refusing to merge without a repo-scope check \u2014 run the session from inside a git checkout or pass an explicit \`repo\` inside one.`);let i=await n.probe(["rev-parse","--git-common-dir"],o);if(i===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: could not resolve the git directory for ${t}. Refusing to merge without a repo-scope check.`);let{mainRoot:s}=Pt(i,o);if(!Mn.existsSync(W.join(s,".git")))throw new Error(`merge_cowboy_branch cannot verify the session repo: no main checkout found for ${t} (unsupported repo layout). Refusing to merge without a repo-scope check.`);return s}r(Go,"resolveSessionMainRoot");var Vo="has conflicts in:";function zo(e){return e.includes(Vo)}r(zo,"isConflictError");function Yo(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
21
21
  `).map(n=>n.trim()).filter(n=>n!==""):[]}r(Yo,"parseConflictFiles");function Qo(e,t){return e.includes(`branch "${t}" does not exist`)}r(Qo,"isUnknownBranchError");async function Nn(e,t,n,o,i){let s=t.target!==void 0&&t.target.trim()!==""?t.target.trim():"main",a=t.repo!==void 0&&t.repo.trim()!==""?t.repo.trim():void 0,l,d=r(()=>(l??=(async()=>{let c=re().cwd;if(typeof c!="string"||c.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 Go(C(),c),cwd:a??c}})(),l),"mergeScope");return O({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,prepare:r(async()=>{Me(s,"target");for(let c of t.branches)Me(c.trim(),"branch");await d()},"prepare"),halt:{on:r(c=>c.kind==="conflict","on"),skip:r((c,h)=>{let g=c.trim(),p=`not attempted \u2014 the merge of "${h.trim()}" conflicted and is still in progress`;return{outcome:{kind:"not-attempted",branch:g,reason:p},text:`"${g}" ${p}.`}},"skip")},handleItem:r(async c=>{let{sessionRoot:h,cwd:g}=await d(),p=c.trim();try{let m=await Nt(C(),{cwd:g,branch:p,target:s}),w=qo(m.mainRoot,h)?void 0:Ko(m.mainRoot,h);if(w!==void 0)try{i.ui.notify(w,"warning")}catch{}let k=w!==void 0?`${w}
22
22
  `:"";return m.alreadyMerged?{outcome:{kind:"already-merged",branch:p,target:s},text:`${k}"${p}" is already merged into "${m.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:p,target:m.target,output:m.output},text:`${k}Merged "${p}" into "${m.target}" in ${m.mainRoot}.`+(m.output?`
23
- ${m.output}`:"")}}catch(m){let w=m instanceof Error?m.message:String(m);return zo(w)?{outcome:{kind:"conflict",branch:p,target:s,files:Yo(w)},text:`"${p}": ${w}`}:Qo(w,p)?{outcome:{kind:"unknown",branch:p},text:`"${p}": ${w}`}:{outcome:{kind:"failed",branch:p,error:w},text:`"${p}": ${w}`}}},"handleItem")})}r(Nn,"executeMergeBranchTool");async function $n(e,t,n,o,i){let s=t.message.trim();return O({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,prepare:r(()=>{if(s==="")throw new Error("message is required")},"prepare"),handleItem:r(async a=>{let l=b().getSpawn(a);if(!l){let g=`not found. Active agents: ${B()}`;return{outcome:{kind:"refused",agentId:a,reason:g},text:`Agent ${a} was not steered: ${g}`}}let d=M(l.lifecycle),c;try{c=await b().steer(a,s)}catch(g){c={kind:"refused",reason:`steering failed: ${ee(g)}`}}if(c.kind==="refused")return{outcome:{kind:"refused",agentId:a,reason:c.reason},text:`Agent ${a} was not steered (${d}): ${c.reason}`};if(c.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:a,reason:c.reason},text:`Agent ${a} had settled (${d}) and the message reached its pane, but it was not revived: ${c.reason}`};let h=d!=="spawned"&&l.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:a},text:h?`Agent ${a} had settled (${d}) \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.`:d==="spawned"?`Message delivered to spawned agent ${a}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${a} was delivered to (${d}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r($n,"executeSteerAgentTool");var A={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Fn=Object.values(A),J={type:"json_schema",strict:"prefer"};function Xo(e){let t=D.Object({prompt:H.properties.agents.items.properties.prompt,task_name:H.properties.agents.items.properties.task_name,agent_type:D.Optional(D.Union([D.String(),D.Null()],{description:`Optional agent type. Omit it, or pass null, to use the configured default agent type \u2014 never pass a type the user did not ask for. An unknown or ambiguous name is rejected before any agent in the batch spawns.${e.length>0?` Available: ${e.join(",")}`:""}`})),model:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type},{additionalProperties:!1,required:["prompt","task_name"]});return D.Object({agents:D.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Xo,"cowboyAgentsSchemaWithTypes");function jn(e){let t=Xo(Jt()),n={name:A.agent,label:A.agent,description:"Delegate one or more tasks to agents. Each agent gets an isolated worktree and a fresh pi process \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. When an agent settles, the completion message names its `cow-` branch and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.",parameters:t,execute:xn,constrainedSampling:J};e.registerTool(n)}r(jn,"registerAgentTool");function Zo(e,t){f().mutate.agent.setExtensionEnabled(t),t?Jo(e):ei(e)}r(Zo,"setExtensionEnabled");function Jo(e){let t=C();jn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Fn])]),de(e)}r(Jo,"activateExtension");function ei(e){let t=C();t.setActiveTools(t.getActiveTools().filter(n=>!Fn.includes(n))),de(e)}r(ei,"deactivateExtension");function fl(e){jn(e);let t={name:A.stopAgent,label:A.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping interrupts the pi process (its pane is left in place) and settles the agent as stopped. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Ut,execute:Cn,constrainedSampling:J,renderResult:r((s,a,l,d)=>{let c=d.isError??!1,h=s.content.at(0),g=h?.type==="text"?h.text:"",p=c?l.fg("error","\u2717"):l.fg("success","\u2713");return new Bn(`${p} ${g}`,0,0)},"renderResult")};e.registerTool(t);let n={name:A.mergeBranch,label:A.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:qt,execute:Nn,constrainedSampling:J};e.registerTool(n);let o={name:A.steerAgent,label:A.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 \u2014 wait for its report. Every refusal states its reason and what to do about it.",parameters:Kt,execute:$n,constrainedSampling:J};e.registerTool(o);let i={name:A.cleanupAgent,label:A.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:Wt,execute:In,constrainedSampling:J};e.registerTool(i),e.registerMessageRenderer("subagent-result",(s,a,l)=>{let d=typeof s=="object"&&typeof s.content=="string"?s.content:"",c=/\b(error|stopped)\b/.test(d.slice(0,200)),h=l.fg(c?"error":"success",c?"\u2717":"\u2713");return new Bn(`${h} ${d}`,0,0)})}r(fl,"registerTools");async function Dn(e,t){let n=await x().listModelOptions({pi:e,modelCatalog:ie(t.modelRegistry)},j());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Dn,"harnessModelOptions");var Hn="cowboy",ti={wt:"worktree",sp:"spawn",st:"status"};function yl(e,t){e.registerCommand(Hn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(yl,"registerUnavailableCowboyCommand");function wl(e){e.registerCommand(Hn,{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-VQEDJJFS.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{Ot(n);let[o,...i]=t.trim().split(/\s+/),s=ti[o]??o,a=[s,...i].join(" ");if(a==="enable"||a==="disable"){let c=a==="enable";if(c&&Pe()===null){n.ui.notify(_e,"warning");return}if(ce()===c){n.ui.notify(`pi-cowboy is already ${c?"enabled":"disabled"}`,"info");return}Zo(n.ui,c),n.ui.notify(c?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(Pe()===null){n.ui.notify(_e,"warning");return}if(s==="worktree"){let{showWorktreeCommandMenu:c}=await import("./menu-worktree-command-NH52QLGX.js");await c(n,i.join(" "));return}if((s==="model"||a==="spawn"||a==="status")&&!ce()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(s==="model"){let{handleModelArg:c}=await import("./model-picker-VQEDJJFS.js");await c(i.join(" "),n);return}if(a==="spawn"||a==="status"){let{showAgentsActionMenu:c}=await import("./menus-Z5QGWG5V.js");await c(n,a,await Dn(e,n));return}if(a!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:d}=await import("./menus-Z5QGWG5V.js");await d(n,await Dn(e,n))},"handler")})}r(wl,"registerCowboyCommand");import*as Ln from"node:fs";import{tmpdir as ni}from"node:os";import*as Te from"node:path";async function Un(e,t){try{return await Rt(e).probe(t),K(dt)}catch{return K(["checkout"])}}r(Un,"detectCowAvailability");function Wn(e){let t=Te.resolve(e??it());for(;;){try{if(Ln.statSync(t).isDirectory())return t}catch{}let n=Te.dirname(t);if(n===t)return ni();t=n}}r(Wn,"probeTargetFor");function ri(e){return(t,n,o)=>e.exec(t,n,o)}r(ri,"execOf");function Il(e){return qn(e,Ie())}r(Il,"startCowSupportProbe");function Pl(e){let t=Ie();return oe(t,lt()),qn(e,t)}r(Pl,"refreshCowSupportProbe");function qn(e,t){let n=Wn(f().agent.worktreeRoot);return Un(ri(e),n).then(o=>{oe(t,o)},()=>{oe(t,K(["checkout"]))})}r(qn,"probe");export{We as a,Vi as b,zi as c,eo as d,E as e,Jt as f,Yi as g,Qi as h,R as i,qs as j,Ks as k,Gs as l,Vs as m,Mo as n,kn as o,na as p,ve as q,Ze as r,Bo as s,Do as t,Oa as u,Sn as v,Pa as w,Ma as x,Fe as y,ce as z,ui as A,Il as B,Pl as C,Zo as D,Jo as E,ei as F,fl as G,yl as H,wl as I};
24
- //# sourceMappingURL=chunk-EFERFQIQ.js.map
23
+ ${m.output}`:"")}}catch(m){let w=m instanceof Error?m.message:String(m);return zo(w)?{outcome:{kind:"conflict",branch:p,target:s,files:Yo(w)},text:`"${p}": ${w}`}:Qo(w,p)?{outcome:{kind:"unknown",branch:p},text:`"${p}": ${w}`}:{outcome:{kind:"failed",branch:p,error:w},text:`"${p}": ${w}`}}},"handleItem")})}r(Nn,"executeMergeBranchTool");async function $n(e,t,n,o,i){let s=t.message.trim();return O({toolName:"steer_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:t.agent_ids,prepare:r(()=>{if(s==="")throw new Error("message is required")},"prepare"),handleItem:r(async a=>{let l=b().getSpawn(a);if(!l){let g=`not found. Active agents: ${B()}`;return{outcome:{kind:"refused",agentId:a,reason:g},text:`Agent ${a} was not steered: ${g}`}}let d=M(l.lifecycle),c;try{c=await b().steer(a,s)}catch(g){c={kind:"refused",reason:`steering failed: ${ee(g)}`}}if(c.kind==="refused")return{outcome:{kind:"refused",agentId:a,reason:c.reason},text:`Agent ${a} was not steered (${d}): ${c.reason}`};if(c.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:a,reason:c.reason},text:`Agent ${a} had settled (${d}) and the message reached its pane, but it was not revived: ${c.reason}`};let h=d!=="spawned"&&l.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:a},text:h?`Agent ${a} had settled (${d}) \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.`:d==="spawned"?`Message delivered to spawned agent ${a}. Delivery is fire-and-forget \u2014 the agent picks it up on its next turn; its next completion message will report the result.`:`Agent ${a} was delivered to (${d}), but it was not revived \u2014 it has no process left to act on the message.`}},"handleItem")})}r($n,"executeSteerAgentTool");var A={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Fn=Object.values(A),J={type:"json_schema",strict:"prefer"};function Xo(e){let t=D.Object({prompt:H.properties.agents.items.properties.prompt,task_name:H.properties.agents.items.properties.task_name,agent_type:D.Optional(D.Union([D.String(),D.Null()],{description:`Optional agent type. Omit it, or pass null, to use the configured default agent type \u2014 never pass a type the user did not ask for. An unknown or ambiguous name is rejected before any agent in the batch spawns.${e.length>0?` Available: ${e.join(",")}`:""}`})),model:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type},{additionalProperties:!1,required:["prompt","task_name"]});return D.Object({agents:D.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Xo,"cowboyAgentsSchemaWithTypes");function jn(e){let t=Xo(Jt()),n={name:A.agent,label:A.agent,description:"Delegate one or more tasks to agents. Each agent gets an isolated worktree and a fresh pi process \u2014 pass a single-item `agents` array to delegate one task, or several to launch them in one call. Every item in `agents` requires its own short `task_name`; a name used twice in one call is rejected before anything spawns. Each agent is instructed to write its complete final response to a report file when it finishes \u2014 do not repeat reporting instructions in the `prompt`. Delegation is NON-BLOCKING by default: the call returns immediately with one agent id per item, and each result is delivered to you as a message when that agent settles \u2014 do not poll, do not re-delegate the task, do not duplicate the work. Pass `run_in_background: false` ONLY when `agents` has exactly one item AND you need that result inline in the same turn; a non-background call with multiple items is rejected before anything spawns. When an agent settles, the completion message names its `cow-` branch and says whether the worktree is kept and why. Merge the settled branch with merge_cowboy_branch when the work is good (or reject it), then call cleanup_cowboy_agent to remove it.",parameters:t,execute:xn,constrainedSampling:J};e.registerTool(n)}r(jn,"registerAgentTool");function Zo(e,t){f().mutate.agent.setExtensionEnabled(t),t?Jo(e):ei(e)}r(Zo,"setExtensionEnabled");function Jo(e){let t=C();jn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Fn])]),de(e)}r(Jo,"activateExtension");function ei(e){let t=C();t.setActiveTools(t.getActiveTools().filter(n=>!Fn.includes(n))),de(e)}r(ei,"deactivateExtension");function fl(e){jn(e);let t={name:A.stopAgent,label:A.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping interrupts the pi process (its pane is left in place) and settles the agent as stopped. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Ut,execute:Cn,constrainedSampling:J,renderResult:r((s,a,l,d)=>{let c=d.isError??!1,h=s.content.at(0),g=h?.type==="text"?h.text:"",p=c?l.fg("error","\u2717"):l.fg("success","\u2713");return new Bn(`${p} ${g}`,0,0)},"renderResult")};e.registerTool(t);let n={name:A.mergeBranch,label:A.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:qt,execute:Nn,constrainedSampling:J};e.registerTool(n);let o={name:A.steerAgent,label:A.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 \u2014 wait for its report. Every refusal states its reason and what to do about it.",parameters:Kt,execute:$n,constrainedSampling:J};e.registerTool(o);let i={name:A.cleanupAgent,label:A.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:Wt,execute:In,constrainedSampling:J};e.registerTool(i),e.registerMessageRenderer("subagent-result",(s,a,l)=>{let d=typeof s=="object"&&typeof s.content=="string"?s.content:"",c=/\b(error|stopped)\b/.test(d.slice(0,200)),h=l.fg(c?"error":"success",c?"\u2717":"\u2713");return new Bn(`${h} ${d}`,0,0)})}r(fl,"registerTools");async function Dn(e,t){let n=await x().listModelOptions({pi:e,modelCatalog:ie(t.modelRegistry)},j());for(let o of n.notices)t.ui.notify(o,"warning");return n.options}r(Dn,"harnessModelOptions");var Hn="cowboy",ti={wt:"worktree",sp:"spawn",st:"status"};function yl(e,t){e.registerCommand(Hn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(yl,"registerUnavailableCowboyCommand");function wl(e){e.registerCommand(Hn,{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-IIXU4GJP.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{Ot(n);let[o,...i]=t.trim().split(/\s+/),s=ti[o]??o,a=[s,...i].join(" ");if(a==="enable"||a==="disable"){let c=a==="enable";if(c&&Pe()===null){n.ui.notify(_e,"warning");return}if(ce()===c){n.ui.notify(`pi-cowboy is already ${c?"enabled":"disabled"}`,"info");return}Zo(n.ui,c),n.ui.notify(c?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(Pe()===null){n.ui.notify(_e,"warning");return}if(s==="worktree"){let{showWorktreeCommandMenu:c}=await import("./menu-worktree-command-SXLBWK4D.js");await c(n,i.join(" "));return}if((s==="model"||a==="spawn"||a==="status")&&!ce()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(s==="model"){let{handleModelArg:c}=await import("./model-picker-IIXU4GJP.js");await c(i.join(" "),n);return}if(a==="spawn"||a==="status"){let{showAgentsActionMenu:c}=await import("./menus-Q3TEDIPV.js");await c(n,a,await Dn(e,n));return}if(a!==""){n.ui.notify(`Unknown option "${o}". Usage: /cowboy [status | spawn | worktree [<name>] | model [<provider/model-id>|clear] | enable | disable]`,"warning");return}let{showAgentsMainMenu:d}=await import("./menus-Q3TEDIPV.js");await d(n,await Dn(e,n))},"handler")})}r(wl,"registerCowboyCommand");import*as Ln from"node:fs";import{tmpdir as ni}from"node:os";import*as Te from"node:path";async function Un(e,t){try{return await Rt(e).probe(t),K(dt)}catch{return K(["checkout"])}}r(Un,"detectCowAvailability");function Wn(e){let t=Te.resolve(e??it());for(;;){try{if(Ln.statSync(t).isDirectory())return t}catch{}let n=Te.dirname(t);if(n===t)return ni();t=n}}r(Wn,"probeTargetFor");function ri(e){return(t,n,o)=>e.exec(t,n,o)}r(ri,"execOf");function Il(e){return qn(e,Ie())}r(Il,"startCowSupportProbe");function Pl(e){let t=Ie();return oe(t,lt()),qn(e,t)}r(Pl,"refreshCowSupportProbe");function qn(e,t){let n=Wn(f().agent.worktreeRoot);return Un(ri(e),n).then(o=>{oe(t,o)},()=>{oe(t,K(["checkout"]))})}r(qn,"probe");export{We as a,Vi as b,zi as c,eo as d,E as e,Jt as f,Yi as g,Qi as h,R as i,qs as j,Ks as k,Gs as l,Vs as m,Mo as n,kn as o,na as p,ve as q,Ze as r,Bo as s,Do as t,Oa as u,Sn as v,Pa as w,Ma as x,Fe as y,ce as z,ui as A,Il as B,Pl as C,Zo as D,Jo as E,ei as F,fl as G,yl as H,wl as I};
24
+ //# sourceMappingURL=chunk-PDV4AFO7.js.map
@@ -1,2 +1,2 @@
1
- import{za as x}from"./chunk-7W5EBKER.js";import{a as s,e as f,l as C}from"./chunk-254PTGN5.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-7KLHCZK2.js.map
1
+ import{za as x}from"./chunk-CTBFJWEE.js";import{a as s,e as f,l as C}from"./chunk-254PTGN5.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-WL3QYM2F.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{B as Ft,E as Mt,F as ke,G as Dt,H as Ot,I as jt,a as mt,b as ft,c as ht,d as yt,e as wt,h as vt,j as St,k as kt,l as Pt,p as bt,q as At,r as Se,s as xt,t as Rt,u as It,y as Et,z as H}from"./chunk-EFERFQIQ.js";import{a as lt,f as dt,g as ve,h as ut,m as ct,n as pt,o as gt,r as Tt,s as Lt}from"./chunk-HPB3IRXW.js";import{A as We,Ba as U,D as Y,Da as it,E as N,Ea as st,Fa as ye,G as Ge,Ga as we,Ha as ee,I as me,Ia as ot,J as j,Ja as at,Ka as Ct,O as V,Q as Qe,R as Ke,S as q,T as X,U as ze,V as fe,_ as Ye,a as E,aa as Ve,ba as Xe,c as Me,ca as Je,d as I,da as Ze,e as De,ea as b,f as Oe,fa as J,g as je,ha as he,ia as P,j as He,la as T,oa as Z,sa as A,u as Q,ua as et,va as tt,w as K,wa as nt,xa as rt,y as $e,z}from"./chunk-7W5EBKER.js";import{a as s,b as _e,d as y,h as O,i as Ne,r as qe,s as Ue,v as Be}from"./chunk-254PTGN5.js";import*as L from"node:path";function ne(t,e){let r=t.at(0);if(r)return{kind:"spawn",spawn:r};let n=e.at(0);return n?{kind:"multiplexer",attempt:n}:{kind:"none"}}s(ne,"findTaskDedup");var F=class extends Error{static{s(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",i=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?X(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${i} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},te=class{constructor(e){this.deps=e}deps;static{s(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let i=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,i);try{return await i}finally{this.admissionBySlug.get(r)===i&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let c=this.deps.listAgents().filter(m=>m.display.taskSlug===e.taskSlug&&Ke(m.lifecycle.phase)),g=ne(c,await this.deps.findTaskAttempts(e.taskSlug));if(g.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:g.kind==="spawn"?g.spawn.id:g.attempt.name}}let{type:r,prompt:n,runInBackground:i,signal:o,...l}=e,a={...l,isBackground:i,signal:o},d=this.deps.spawn(r,n,a);return this.deps.getSpawn(d)?.lifecycle.phase==="queued"?{status:"queued",agentId:d,queuePosition:this.deps.queuePosition(d)}:{status:"admitted",agentId:d}}};import Ht from"node:fs";var re=class{constructor(e){this.resultFile=e}resultFile;static{s(this,"FileDeliverable")}async readDeliverable(){try{let e=Ht.statSync(this.resultFile).mtimeMs,r=Ht.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import $n from"node:fs";import*as $t from"node:path";function B(t){try{$n.rmSync($t.dirname(t),{recursive:!0,force:!0})}catch{}}s(B,"removeResultArtifacts");import*as $ from"node:fs";import*as ie from"node:path";async function Wt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}s(Wt,"probeList");function Wn(t,e,r){let n=r(e);return t?.find(i=>r(i.path)===n)}s(Wn,"matchWorktree");function Nt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}s(Nt,"paneOf");function _t(t,e,r){let n=r(e),i=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return i===void 0?void 0:Nt(i)}s(_t,"paneInWorktree");function _n(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:Nt(r)}s(_n,"paneInWorkspace");function Nn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}s(e,"root");async function r(a,d){let u=await e(),c=[],g=new Set,m=s(p=>{let h=t.canonicalizePath(p.path);g.has(h)||(g.add(h),c.push(p))},"push");for(let p of d??[]){let h=ie.basename(p.path);z(h,a)&&(u!==void 0&&!We(p.path,u)||m({path:p.path,branch:p.branch!==void 0&&z(p.branch,a)?p.branch:h,workspaceId:p.workspaceId}))}if(c.length>0||u===void 0)return c;for(let p of await t.listRootEntries(u))z(p,a)&&m({path:ie.join(u,p),branch:p});return c}s(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}s(n,"candidateSummary");async function i(a,d,u,c){let g=d.execution.host,m=d.display.worktree,p=m?.kind==="owned",h=g?{paneId:g.paneId,tabId:g.tabId,workspaceId:g.workspaceId}:null,f="tracked",S=m?.kind==="owned"?m.path:void 0,k=g?.workspaceId;if(S!==void 0){let x=Wn(u,S,t.canonicalizePath);x!==void 0&&(k=x.workspaceId)}let v=S===void 0?h:_t(c,S,t.canonicalizePath)??h,R=S===void 0?null:{path:S,workspaceId:k,repoCwd:await t.resolveRepoCwd(S)};return{kind:"located",source:f,id:a,branch:m?.branch??K(d.display.taskSlug??Q(d.display.type),d.id),worktreeManaged:p||R!==null,paneCreated:g?.paneCreated===!0,worktree:R,pane:v}}s(i,"locateTracked");async function o(a,d,u){let c=await r(a,d);if(c.length===0)return{kind:"not-found",id:a};if(c.length>1)return{kind:"ambiguous",id:a,candidates:c.map(n)};let g=c[0],m=_t(u,g.path,t.canonicalizePath)??_n(u,g.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:g.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:g.path,workspaceId:g.workspaceId,repoCwd:await t.resolveRepoCwd(g.path)},pane:m}}s(o,"locateDiscovered");async function l(a,d){let u=await Wt(t.listWorktrees),c=await Wt(t.listPlacements),g=u.ok?u.entries:void 0,m=c.ok?c.entries:void 0;return d===void 0?o(a,g,m):i(a,d,g,m)}return s(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:s(a=>t.readPane(a.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,harnessTeardown:t.harnessTeardown}}s(Nn,"createAgentAssets");function qt(t,e,r){return Nn({multiplexer:r.multiplexer,canonicalizePath:s(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:s(n=>{let i=I(n);return{path:i,present:$.existsSync(i)}},"deliverable"),listWorktrees:s(()=>r.listWorktrees(),"listWorktrees"),listPlacements:s(()=>r.listPlacements(),"listPlacements"),readPane:s(n=>r.observePane(n),"readPane"),worktreeRoot:s(async()=>{let n=J().cwd;if(!n)return;let i=await ve(t,n).catch(()=>{});return i===void 0?void 0:$e(P().agent.worktreeRoot,i)},"worktreeRoot"),listRootEntries:s(async n=>{try{return await $.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:s(async n=>{try{return await ve(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:s(n=>pt(t,n),"isWorktreeDirty"),worktreeExists:s(async n=>$.existsSync(n),"worktreeExists"),removeWorktree:s(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:s(async(n,i)=>(await ut(t,i,n),!$.existsSync(n)),"removeGitWorktree"),deleteBranch:s(n=>ct(t,n,i=>e.isAttached(i,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:s(async n=>{await e.release(n,"placement")},"closePane"),harnessTeardown:s(async(n,i)=>{await A().get(n)?.teardown({pi:t,...i})},"harnessTeardown")})}s(qt,"createMultiplexerAgentAssets");var C=j("supervisor"),qn=2e3;function Un(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}s(Un,"deferred");var se=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??qn,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp}host;deliverable;static{s(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;phase={kind:"idle"};outcome=null;settlement=Un();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,r){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:r};try{await this.host.start(r,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(n){throw this.isWatching()&&(this.phase={kind:"idle"}),n}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},C.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),C.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{C.error("poll loop failed",{errorMessage:y(r)})}),this.settlement.promise}async stop(e){let r=this.phase;if(r.kind!=="watching"||this.outcome!==null)return!1;let{ref:n}=r,i=await this.host.stop(n,{interruptGraceMs:e,confirmMs:0}).catch(o=>(C.debug("host stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:i,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),i}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let r=this.phase;r.kind==="watching"&&(C.debug(e,{paneId:r.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,C.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let r=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);r.unref(),this.wakeLoop=()=>{clearTimeout(r),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!Bn(this.held,e)){this.held=e,C.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return C.debug("readDeliverable failed",{errorMessage:y(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Bn(t,e){return t.content===e.content&&t.mtime===e.mtime}s(Bn,"sameReport");function oe(t){let e=t.transport.createDeliverable(t.resultFile);return new se(t.host,e,t.supervisorOptions)}s(oe,"createPaneSupervisor");import Ae from"node:fs";import D from"node:path";import{SettingsManager as ur}from"@earendil-works/pi-coding-agent";import tr from"node:fs";import{loadProjectContextFiles as nr}from"@earendil-works/pi-coding-agent";function Ut(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
1
+ import{B as Ft,E as Mt,F as ke,G as Dt,H as Ot,I as jt,a as mt,b as ft,c as ht,d as yt,e as wt,h as vt,j as St,k as kt,l as Pt,p as bt,q as At,r as Se,s as xt,t as Rt,u as It,y as Et,z as H}from"./chunk-PDV4AFO7.js";import{a as lt,f as dt,g as ve,h as ut,m as ct,n as pt,o as gt,r as Tt,s as Lt}from"./chunk-KMXT7XW7.js";import{A as We,Ba as U,D as Y,Da as it,E as N,Ea as st,Fa as ye,G as Ge,Ga as we,Ha as ee,I as me,Ia as ot,J as j,Ja as at,Ka as Ct,O as V,Q as Qe,R as Ke,S as q,T as X,U as ze,V as fe,_ as Ye,a as E,aa as Ve,ba as Xe,c as Me,ca as Je,d as I,da as Ze,e as De,ea as b,f as Oe,fa as J,g as je,ha as he,ia as P,j as He,la as T,oa as Z,sa as A,u as Q,ua as et,va as tt,w as K,wa as nt,xa as rt,y as $e,z}from"./chunk-CTBFJWEE.js";import{a as s,b as _e,d as y,h as O,i as Ne,r as qe,s as Ue,v as Be}from"./chunk-254PTGN5.js";import*as L from"node:path";function ne(t,e){let r=t.at(0);if(r)return{kind:"spawn",spawn:r};let n=e.at(0);return n?{kind:"multiplexer",attempt:n}:{kind:"none"}}s(ne,"findTaskDedup");var F=class extends Error{static{s(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,r){let n=e.kind==="spawn",i=n?`agent ${e.spawn.id}`:e.attempt.name,o=n?X(e.spawn.lifecycle):"live";super(`Task "${r}" is already in flight as ${i} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=r,this.dedup=e}},te=class{constructor(e){this.deps=e}deps;static{s(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let r=e.taskSlug;if(r===void 0)return this.admitOne(e);let i=(this.admissionBySlug.get(r)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(r,i);try{return await i}finally{this.admissionBySlug.get(r)===i&&this.admissionBySlug.delete(r)}}async admitOne(e){if(e.taskSlug){let c=this.deps.listAgents().filter(m=>m.display.taskSlug===e.taskSlug&&Ke(m.lifecycle.phase)),g=ne(c,await this.deps.findTaskAttempts(e.taskSlug));if(g.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:g.kind==="spawn"?g.spawn.id:g.attempt.name}}let{type:r,prompt:n,runInBackground:i,signal:o,...l}=e,a={...l,isBackground:i,signal:o},d=this.deps.spawn(r,n,a);return this.deps.getSpawn(d)?.lifecycle.phase==="queued"?{status:"queued",agentId:d,queuePosition:this.deps.queuePosition(d)}:{status:"admitted",agentId:d}}};import Ht from"node:fs";var re=class{constructor(e){this.resultFile=e}resultFile;static{s(this,"FileDeliverable")}async readDeliverable(){try{let e=Ht.statSync(this.resultFile).mtimeMs,r=Ht.readFileSync(this.resultFile,"utf-8").trim();return r?{content:r,mtime:e}:null}catch{return null}}};import $n from"node:fs";import*as $t from"node:path";function B(t){try{$n.rmSync($t.dirname(t),{recursive:!0,force:!0})}catch{}}s(B,"removeResultArtifacts");import*as $ from"node:fs";import*as ie from"node:path";async function Wt(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}s(Wt,"probeList");function Wn(t,e,r){let n=r(e);return t?.find(i=>r(i.path)===n)}s(Wn,"matchWorktree");function Nt(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}s(Nt,"paneOf");function _t(t,e,r){let n=r(e),i=t?.find(o=>o.cwd!==void 0&&r(o.cwd)===n);return i===void 0?void 0:Nt(i)}s(_t,"paneInWorktree");function _n(t,e){if(e===void 0)return;let r=t?.find(n=>n.workspaceId===e);return r===void 0?void 0:Nt(r)}s(_n,"paneInWorkspace");function Nn(t){async function e(){try{return await t.worktreeRoot()}catch{return}}s(e,"root");async function r(a,d){let u=await e(),c=[],g=new Set,m=s(p=>{let h=t.canonicalizePath(p.path);g.has(h)||(g.add(h),c.push(p))},"push");for(let p of d??[]){let h=ie.basename(p.path);z(h,a)&&(u!==void 0&&!We(p.path,u)||m({path:p.path,branch:p.branch!==void 0&&z(p.branch,a)?p.branch:h,workspaceId:p.workspaceId}))}if(c.length>0||u===void 0)return c;for(let p of await t.listRootEntries(u))z(p,a)&&m({path:ie.join(u,p),branch:p});return c}s(r,"discoverCandidates");function n(a){return{worktreePath:a.path,branch:a.branch,workspaceId:a.workspaceId}}s(n,"candidateSummary");async function i(a,d,u,c){let g=d.execution.host,m=d.display.worktree,p=m?.kind==="owned",h=g?{paneId:g.paneId,tabId:g.tabId,workspaceId:g.workspaceId}:null,f="tracked",S=m?.kind==="owned"?m.path:void 0,k=g?.workspaceId;if(S!==void 0){let x=Wn(u,S,t.canonicalizePath);x!==void 0&&(k=x.workspaceId)}let v=S===void 0?h:_t(c,S,t.canonicalizePath)??h,R=S===void 0?null:{path:S,workspaceId:k,repoCwd:await t.resolveRepoCwd(S)};return{kind:"located",source:f,id:a,branch:m?.branch??K(d.display.taskSlug??Q(d.display.type),d.id),worktreeManaged:p||R!==null,paneCreated:g?.paneCreated===!0,worktree:R,pane:v}}s(i,"locateTracked");async function o(a,d,u){let c=await r(a,d);if(c.length===0)return{kind:"not-found",id:a};if(c.length>1)return{kind:"ambiguous",id:a,candidates:c.map(n)};let g=c[0],m=_t(u,g.path,t.canonicalizePath)??_n(u,g.workspaceId)??null;return{kind:"located",source:"recovered",id:a,branch:g.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:g.path,workspaceId:g.workspaceId,repoCwd:await t.resolveRepoCwd(g.path)},pane:m}}s(o,"locateDiscovered");async function l(a,d){let u=await Wt(t.listWorktrees),c=await Wt(t.listPlacements),g=u.ok?u.entries:void 0,m=c.ok?c.entries:void 0;return d===void 0?o(a,g,m):i(a,d,g,m)}return s(l,"locate"),{multiplexer:t.multiplexer,locate:l,observe:s(a=>t.readPane(a.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,harnessTeardown:t.harnessTeardown}}s(Nn,"createAgentAssets");function qt(t,e,r){return Nn({multiplexer:r.multiplexer,canonicalizePath:s(n=>r.canonicalizePath(n),"canonicalizePath"),deliverable:s(n=>{let i=I(n);return{path:i,present:$.existsSync(i)}},"deliverable"),listWorktrees:s(()=>r.listWorktrees(),"listWorktrees"),listPlacements:s(()=>r.listPlacements(),"listPlacements"),readPane:s(n=>r.observePane(n),"readPane"),worktreeRoot:s(async()=>{let n=J().cwd;if(!n)return;let i=await ve(t,n).catch(()=>{});return i===void 0?void 0:$e(P().agent.worktreeRoot,i)},"worktreeRoot"),listRootEntries:s(async n=>{try{return await $.promises.readdir(n)}catch{return[]}},"listRootEntries"),resolveRepoCwd:s(async n=>{try{return await ve(t,n)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:s(n=>pt(t,n),"isWorktreeDirty"),worktreeExists:s(async n=>$.existsSync(n),"worktreeExists"),removeWorktree:s(n=>e.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:s(async(n,i)=>(await ut(t,i,n),!$.existsSync(n)),"removeGitWorktree"),deleteBranch:s(n=>ct(t,n,i=>e.isAttached(i,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:s(async n=>{await e.release(n,"placement")},"closePane"),harnessTeardown:s(async(n,i)=>{await A().get(n)?.teardown({pi:t,...i})},"harnessTeardown")})}s(qt,"createMultiplexerAgentAssets");var C=j("supervisor"),qn=2e3;function Un(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}s(Un,"deferred");var se=class{constructor(e,r,n={}){this.host=e;this.deliverable=r;this.pollMs=n.pollMs??qn,this.stopInitiator=n.stopInitiator??"user",this.onFollowUp=n.onFollowUp}host;deliverable;static{s(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;phase={kind:"idle"};outcome=null;settlement=Un();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,r){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:r};try{await this.host.start(r,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(n){throw this.isWatching()&&(this.phase={kind:"idle"}),n}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},C.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),C.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(r=>{C.error("poll loop failed",{errorMessage:y(r)})}),this.settlement.promise}async stop(e){let r=this.phase;if(r.kind!=="watching"||this.outcome!==null)return!1;let{ref:n}=r,i=await this.host.stop(n,{interruptGraceMs:e,confirmMs:0}).catch(o=>(C.debug("host stop failed",{errorMessage:y(o)}),!1));return C.debug("stop requested",{paneId:n.paneId,graceMs:e,stopped:i,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),i}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let r=this.phase;r.kind==="watching"&&(C.debug(e,{paneId:r.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,C.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let r=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);r.unref(),this.wakeLoop=()=>{clearTimeout(r),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!Bn(this.held,e)){this.held=e,C.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return C.debug("readDeliverable failed",{errorMessage:y(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Bn(t,e){return t.content===e.content&&t.mtime===e.mtime}s(Bn,"sameReport");function oe(t){let e=t.transport.createDeliverable(t.resultFile);return new se(t.host,e,t.supervisorOptions)}s(oe,"createPaneSupervisor");import Ae from"node:fs";import D from"node:path";import{SettingsManager as ur}from"@earendil-works/pi-coding-agent";import tr from"node:fs";import{loadProjectContextFiles as nr}from"@earendil-works/pi-coding-agent";function Ut(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
2
2
  `):""}s(Ut,"buildOrchestrationGuidance");import{formatSkillsForPrompt as Gn}from"@earendil-works/pi-coding-agent";function Qn(t){let e=t;return e=e.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g,`
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,`
@@ -1,3 +1,3 @@
1
- import{a as M,b as y}from"./chunk-2GTF3FFO.js";import{d as g,g as R,j as P,t as H}from"./chunk-HPB3IRXW.js";import{b as S,o as D}from"./chunk-7KLHCZK2.js";import{Ba as x,Ka as _,ea as I,ia as T,r as p,s as b,t as E,xa as v,y as A}from"./chunk-7W5EBKER.js";import{a as t,d as N}from"./chunk-254PTGN5.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=E,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
1
+ import{a as M,b as y}from"./chunk-F526OOT6.js";import{d as g,g as R,j as P,t as H}from"./chunk-KMXT7XW7.js";import{b as S,o as D}from"./chunk-WL3QYM2F.js";import{Ba as x,Ka as _,ea as I,ia as T,r as p,s as b,t as E,xa as v,y as A}from"./chunk-CTBFJWEE.js";import{a as t,d as N}from"./chunk-254PTGN5.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=E,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
2
2
  `)}t(Y,"describeCreatedWorktree");async function J(e,r,o,a){if($.existsSync(a))return`Cannot create the worktree: ${a} already exists. Pick another name.`;if(await g(e,["rev-parse","--verify","--quiet",`refs/heads/${o}`],r)!==void 0)return`Cannot create the worktree: the branch "${o}" already exists. Pick another name.`}t(J,"describeCollision");async function pe(e,r){let o=new S(e),a=t((n,i)=>e.ui.notify(n,i),"notify"),s=await o.open(({theme:n,close:i})=>new y(L({prefill:r,notify:a,onDone:t(m=>i(m),"onDone"),onCancel:t(()=>i(),"onCancel")}),{title:"Worktree Name",theme:n,passthroughKeys:!0}));if(s===void 0)return;let k=T(),c=I();if(!await P(c,e.cwd)){a("Cannot create a worktree: this session is not inside a git repository.","error");return}let d;try{d=await R(c,e.cwd)}catch(n){a(`Cannot create a worktree: ${N(n)}`,"error");return}let G=await g(c,["status","--porcelain"],d)==="",u=k.agent.worktreeCheckoutType;if(!G){let n=await o.open(({theme:i,close:m})=>{let h=new X(p.map(l=>({value:l,label:l,description:q[l]})),p.length,D(i));return h.setSelectedIndex(p.indexOf(k.agent.worktreeCheckoutType)),h.onSelect=l=>m(b(l.value)),h.onCancel=()=>m(),new y(h,{title:"Worktree Checkout",theme:i,onCancel:t(()=>m(),"onCancel")})});if(n===void 0)return;u=n}let C=z.join(A(k.agent.worktreeRoot,d),s),w=await J(c,d,s,C);if(w!==void 0){a(w,"error");return}let f=_(e.ui);f.pending(`Creating worktree ${s}`);let W;try{W=await H(c,{repoCwd:d,path:C,branch:s,materialization:v(),dirtyCheckout:u,notify:a,host:x().host})}catch(n){f.failed("Worktree creation failed",n);return}f.succeeded(Y(W,u))}t(pe,"showWorktreeCommandMenu");export{pe as showWorktreeCommandMenu};
3
- //# sourceMappingURL=menu-worktree-command-NH52QLGX.js.map
3
+ //# sourceMappingURL=menu-worktree-command-SXLBWK4D.js.map
@@ -1,4 +1,4 @@
1
- import{A as Bt,C as Zt,D as Jt,e as B,f as Pe,g as _t,i as Dt,m as Nt,n as Vt,o as Wt,p as Kt,q as ne,v as Re,w as Gt,x as Je}from"./chunk-EFERFQIQ.js";import{a as Xt,b as H}from"./chunk-2GTF3FFO.js";import{i as Ht,j as Ft,q as zt,s as qt,u as Yt}from"./chunk-HPB3IRXW.js";import{a as pe,b as V,c as re,d as oe,e as je,f as fe,g as U,h as He,i as Qe,j as Fe,k as we,l as _,m as Ut,n as X,o as Q,p as _e,q as Te}from"./chunk-7KLHCZK2.js";import{Aa as jt,Ba as Ee,G as Ye,H as Z,Ka as J,L as Tt,M as Ot,N as Mt,Q as Ae,R as Ce,S as Le,T as It,U as At,V as Lt,W as $t,X as xt,Y as Et,Z as $e,a as pt,b as ft,ca as Xe,ea as se,fa as me,ga as Pt,ha as ae,ia as $,l as qe,m as ke,na as Rt,o as gt,p as ht,pa as Ze,r as yt,s as vt,sa as Y,t as bt,va as le,xa as xe}from"./chunk-7W5EBKER.js";import{a as t,d as de,e as kt,f as Se,g as St,k as Ct,l as te,m as wt}from"./chunk-254PTGN5.js";import{SettingsList as Gn}from"@earendil-works/pi-tui";import{SettingsManager as Un}from"@earendil-works/pi-coding-agent";async function Qt(e,n){return Un.create(e,n??pt()).getDefaultThinkingLevel()}t(Qt,"getPiDefaultThinkingLevel");import{SettingsList as tr}from"@earendil-works/pi-tui";var zn={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 en(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=zn[e];return n.fg(o.color,o.icon)}t(en,"statusIcon");function et(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(et,"formatMs");function tn(e){let n=B(e);return n?.displayName??n?.name??"Agent"}t(tn,"getDisplayName");function ie(e){return`${e.fg("accent","\u2022")} `}t(ie,"agentBulletPrefix");function nn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(nn,"truncatePath");function De(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(De,"formatSlotLimit");function rn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:s,harnessDefaultFor:i,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:d}=e,c=new Map;for(let u of n){let g=o[u],{model:v,source:h}=$t({subagentType:u,harnessFamily:l(u),agentConfig:g,config:{agent:r},harnessDefault:i(u),parentModelId:d,sessionOverrides:s});if(!tt(s,r,u,e.sessionThinking))continue;let k=h==="session-per-type"||h==="session-default"?"[session]":a(u)?"[project]":"",{level:b,source:T}=nt({type:u,agentConfig:g,harnessFamily:l(u),config:r,harnessDefault:e.harnessDefaultThinkingFor(u),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),C=T==="session-per-type"?" [session]":T==="parent"?" [parent]":T==="config-per-type"&&e.hasProjectThinkingKey(u)?" [project]":"",L=c.get(v)??[];L.push({type:u,thinking:b,thinkingTag:C,tag:k}),c.set(v,L)}return[...c.entries()].sort((u,g)=>u[0]===g[0]?0:u[0]===null?-1:g[0]===null?1:u[0]<g[0]?-1:1).map(([u,g])=>({modelId:u,rows:g}))}t(rn,"buildModelGroups");function tt(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(tt,"hasExplicitPerTypeOverride");function nt(e){let n=Et({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"?xt:null,source:void 0}}t(nt,"displayedThinking");import{SettingsList as Xn}from"@earendil-works/pi-tui";import{matchesKey as Oe,SelectList as qn,truncateToWidth as Yn}from"@earendil-works/pi-tui";function on(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],s=X(new qn(r,5,Q(e.theme)));return s.onSelect=i=>{i.value==="Yes"?(e.onConfirm(),o("Yes")):o()},s.onCancel=()=>o(),s}}t(on,"createConfirmSubmenu");function sn(e){return oe({invalidate(){},render(o){let r=Math.max(0,o-4),s=t(l=>` ${Yn(l,r,"...",!0)}`,"line"),i=[s(e.theme.bold(e.message))];if(e.detail)for(let l of e.detail.split(`
1
+ import{A as Bt,C as Zt,D as Jt,e as B,f as Pe,g as _t,i as Dt,m as Nt,n as Vt,o as Wt,p as Kt,q as ne,v as Re,w as Gt,x as Je}from"./chunk-PDV4AFO7.js";import{a as Xt,b as H}from"./chunk-F526OOT6.js";import{i as Ht,j as Ft,q as zt,s as qt,u as Yt}from"./chunk-KMXT7XW7.js";import{a as pe,b as V,c as re,d as oe,e as je,f as fe,g as U,h as He,i as Qe,j as Fe,k as we,l as _,m as Ut,n as X,o as Q,p as _e,q as Te}from"./chunk-WL3QYM2F.js";import{Aa as jt,Ba as Ee,G as Ye,H as Z,Ka as J,L as Tt,M as Ot,N as Mt,Q as Ae,R as Ce,S as Le,T as It,U as At,V as Lt,W as $t,X as xt,Y as Et,Z as $e,a as pt,b as ft,ca as Xe,ea as se,fa as me,ga as Pt,ha as ae,ia as $,l as qe,m as ke,na as Rt,o as gt,p as ht,pa as Ze,r as yt,s as vt,sa as Y,t as bt,va as le,xa as xe}from"./chunk-CTBFJWEE.js";import{a as t,d as de,e as kt,f as Se,g as St,k as Ct,l as te,m as wt}from"./chunk-254PTGN5.js";import{SettingsList as Gn}from"@earendil-works/pi-tui";import{SettingsManager as Un}from"@earendil-works/pi-coding-agent";async function Qt(e,n){return Un.create(e,n??pt()).getDefaultThinkingLevel()}t(Qt,"getPiDefaultThinkingLevel");import{SettingsList as tr}from"@earendil-works/pi-tui";var zn={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 en(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=zn[e];return n.fg(o.color,o.icon)}t(en,"statusIcon");function et(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(et,"formatMs");function tn(e){let n=B(e);return n?.displayName??n?.name??"Agent"}t(tn,"getDisplayName");function ie(e){return`${e.fg("accent","\u2022")} `}t(ie,"agentBulletPrefix");function nn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(nn,"truncatePath");function De(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(De,"formatSlotLimit");function rn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:s,harnessDefaultFor:i,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:d}=e,c=new Map;for(let u of n){let g=o[u],{model:v,source:h}=$t({subagentType:u,harnessFamily:l(u),agentConfig:g,config:{agent:r},harnessDefault:i(u),parentModelId:d,sessionOverrides:s});if(!tt(s,r,u,e.sessionThinking))continue;let k=h==="session-per-type"||h==="session-default"?"[session]":a(u)?"[project]":"",{level:b,source:T}=nt({type:u,agentConfig:g,harnessFamily:l(u),config:r,harnessDefault:e.harnessDefaultThinkingFor(u),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),C=T==="session-per-type"?" [session]":T==="parent"?" [parent]":T==="config-per-type"&&e.hasProjectThinkingKey(u)?" [project]":"",L=c.get(v)??[];L.push({type:u,thinking:b,thinkingTag:C,tag:k}),c.set(v,L)}return[...c.entries()].sort((u,g)=>u[0]===g[0]?0:u[0]===null?-1:g[0]===null?1:u[0]<g[0]?-1:1).map(([u,g])=>({modelId:u,rows:g}))}t(rn,"buildModelGroups");function tt(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(tt,"hasExplicitPerTypeOverride");function nt(e){let n=Et({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"?xt:null,source:void 0}}t(nt,"displayedThinking");import{SettingsList as Xn}from"@earendil-works/pi-tui";import{matchesKey as Oe,SelectList as qn,truncateToWidth as Yn}from"@earendil-works/pi-tui";function on(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],s=X(new qn(r,5,Q(e.theme)));return s.onSelect=i=>{i.value==="Yes"?(e.onConfirm(),o("Yes")):o()},s.onCancel=()=>o(),s}}t(on,"createConfirmSubmenu");function sn(e){return oe({invalidate(){},render(o){let r=Math.max(0,o-4),s=t(l=>` ${Yn(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(Oe(o,"y")||Oe(o,"shift+y")){e.onYes();return}(Oe(o,"n")||Oe(o,"shift+n")||Oe(o,"escape"))&&e.onNo()}})}t(sn,"createKeyConfirm");var Zn={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 rt(e,n){let o=Zn[e];return{id:e,label:o.label,currentValue:"",description:n?o.clearDescription:o.setDescription}}t(rt,"levelItem");function ge(e){let n=[];return e.offered.session&&n.push(rt("session",e.clearMode===!0)),e.offered.global&&n.push(rt("global",e.clearMode===!0)),e.offered.project&&n.push(rt("project",e.clearMode===!0)),e.includeClear&&n.push({id:"clear",label:"Clear...",currentValue:""}),e.includeAll&&n.push({id:"all",label:"All levels",currentValue:""}),n}t(ge,"buildLevelItems");function ee(e){return(n,o)=>{let r=e.items.map(i=>({...i,submenu:t((l,a)=>{let d=e.onPick(i.id,a,()=>o());return d||(a(i.id),re)},"submenu")})),s=X(new Xn(r,r.length,_(e.theme),(i,l)=>o(l),()=>o()));return oe(s)}}t(ee,"createLevelPickerSubmenu");function Ne(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,d=ge({offered:{session:r,global:s,project:i},clearMode:o,includeClear:a!==void 0,includeAll:n?l>=2:e.includeAll===!0});return ee({theme:e.theme,items:d,onPick:t((c,u)=>c==="clear"?he({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,availableLevels:e.availableLevels,onClear:t(g=>a?.(g),"onClear")})("",u):e.onPick(c,u),"onPick")})}t(Ne,"createTargetSelectSubmenu");function he(e){return Ne({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,includeAll:!0,availableLevels:e.availableLevels,onPick:t(n=>e.onClear(n),"onPick")})}t(he,"createClearPickerSubmenu");function Ve(e){return(n,o)=>Ne({theme:e.theme,projectOffered:e.projectOffered,includeAll:!0,availableLevels:e.availableLevels,onPick:t((r,s)=>on({message:e.message(r),theme:e.theme,onConfirm:t(()=>e.onConfirm(r),"onConfirm")})(n,s),"onPick")})(n,o)}t(Ve,"createClearAllSubmenu");import{Input as an}from"@earendil-works/pi-tui";function ot(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 an;return a.setValue(i),a.onSubmit=d=>{let c=d.trim();if(!c||/^unlimited$/i.test(c))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 u=Ut(c,o);if(u===void 0){s(`Invalid value \u2014 must be a number ${r(o)}`);return}n.onValid?.(u),l(String(u))},a.onEscape=()=>l(),a}}t(ot,"createNumericSubmenu");function ye(e,n){return(o,r)=>{let s=new an;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(ye,"createInputSubmenu");var ln="__custom__",ve="__none__";function Jn(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:ln,label:"Custom token...",currentValue:"",description:"A level or variant this harness advertises beyond its own list."})}return o.push({id:ve,label:"None",currentValue:n===null?"(current)":"",description:"Use the template, configured default, or parent session's level."}),o}t(Jn,"valueItems");function cn(e){return ee({theme:e.theme,items:Jn(e.offering,e.current),onPick:t((n,o)=>{if(n===ln)return ye(e.ctx)(e.current??"",r=>{if(r===void 0){o();return}e.onPick(r),o(r)});e.onPick(n===ve?null:n)},"onPick")})}t(cn,"createThinkingValuePicker");function un(e){let n=e.currentModel??null,o=e.showClear===!0?e.onClear:void 0;return ee({theme:e.theme,items:ge({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:o!==void 0}),onPick:t((r,s,i)=>{if(r==="clear")return he({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(a=>o?.(a),"onClear")})("",s);let l=r;return new pe(Qe(e.modelOptions,n,e.mergedModels),n,{onSelect:t(a=>{e.onSet(l,a),a==null?i():s(a)},"onSelect"),onCancel:t(()=>s(),"onCancel")},e.theme)},"onPick")})}t(un,"createModelSelectSubmenu");function dn(e){let n=e.currentModel??null;return ee({theme:e.theme,items:ge({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:e.showClear}),onPick:t((o,r,s)=>{if(o==="clear")return he({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(d=>e.onClear(d),"onClear")})("",r);let i=o,l,a=new pe(Qe(e.modelOptions,n,e.mergedModels),n,{onSelect:t(d=>{if(d==null){e.onClear(i),s();return}let c=e.offeringFor(d);if(c.kind==="none"){e.onSet(i,d,null),r(d);return}l.activate(cn({theme:e.theme,ctx:e.ctx,offering:c,current:e.currentThinking,onPick:t(u=>e.onSet(i,d,u),"onPick")})("",r))},"onSelect"),onCancel:t(()=>r(),"onCancel")},e.theme);return l=new je(a),l},"onPick")})}t(dn,"createModelThinkingSubmenu");import{getSupportedThinkingLevels as Qn}from"@earendil-works/pi-ai";function We(e){let{harnessId:n,modelKey:o,entries:r,piModel:s}=e;if(te(n))return s===void 0?{kind:"advisory",levels:[]}:s.reasoning?{kind:"closed",levels:Qn(s)}:{kind:"none"};if(o==="")return er(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(We,"thinkingOfferingFor");function er(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(er,"unionThinkingOffering");function mn(e){return We({harnessId:e.harnessId,modelKey:e.modelKey??"",entries:e.entries.get(e.harnessId)??[],piModel:Se(e.modelKey??"",e.registry,e.parentModel)})}t(mn,"thinkingOfferingForModel");function Ke(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(Ke,"pairedRow");function Ge(e,n){return e?" [session]":n?" [project]":""}t(Ge,"layerTag");function it(e,n){return n===null?"":Ge(e.session,e.project)}t(it,"thinkingTagOf");function pn(e,n,o,r){if(o===null){e.mutate.agent.clearHarnessDefaultThinking(n,r);return}r!=="session"&&te(n)&&!Tt.safeParse(o).success||e.mutate.agent.setHarnessDefaultThinking(n,o,r)}t(pn,"writeHarnessDefaultThinking");function nr(e,n,o,r){o===null?e.mutate.agent.clearThinkingOverride(n,r):e.mutate.agent.setThinkingOverride(n,o,r)}t(nr,"writeTypeThinking");function rr(e){return Y().runnable(e).filter(n=>!te(n))}t(rr,"harnessDefaultRowIds");function or(e){let n=rr(le());return oe(ir(e,n))}t(or,"buildModelSettingsScreen");function ir(e,n){let{ctx:o,store:r,theme:s,harnessModelOptions:i,piDefaultThinking:l,close:a}=e,d,c=t(v=>{let h=[],k=r.isProjectWritable,b=t((f,E)=>o.ui.notify(f,E),"notify"),T=me(),C=T.model??o.model,L=C?`${C.provider}/${C.id}`:null,O=T.thinkingLevel??null,P=r.agentConfigSnapshot(),W=Fe(P),R=t(()=>{d?.(c(v))},"refresh"),j=t(f=>E=>mn({harnessId:f,modelKey:E,entries:i,registry:T.modelRegistry,parentModel:C}),"offeringFor"),D=t(f=>{let E={session:f.modelLevels.session||f.thinkingLevels.session,global:f.modelLevels.global||f.thinkingLevels.global,project:f.modelLevels.project||f.thinkingLevels.project};return dn({modelOptions:f.modelOptions,mergedModels:f.mergedModels,projectOffered:k,theme:v,ctx:o,currentModel:f.model,currentThinking:f.thinking,showClear:E.session||E.global||E.project,availableLevels:E,offeringFor:j(f.harnessId),onSet:t((M,G,N)=>{f.write(M,G,N),b(`${f.label} set to ${G} \xB7 ${N??"(none)"} (${M})`,"info")},"onSet"),onClear:t(M=>{f.clear(M),b(`${f.label} cleared (${M})`,"info"),R()},"onClear")})},"pairSubmenu"),K=P.default,p=r.modelOverrideLevels("default"),m=r.harnessDefaultThinkingLevels("pi"),y=r.defaultThinkingForHarness("pi"),S=r.sessionDefaultModel??K;h.push({id:"defaultModel",label:"Pi Default Model",currentValue:Ke({model:S,modelTag:Ge(p.session,r.hasProjectModelKey("default")),thinking:y,thinkingTag:it(m,y)}),description:"Default model and thinking level applied when no session, per-type, or template override is set.",submenu:D({label:"Pi Default Model",harnessId:"pi",modelOptions:Z(i,"pi"),mergedModels:we("pi",W),model:S,thinking:y,modelLevels:p,thinkingLevels:m,write:t((f,E,M)=>{r.mutate.agent.setModelOverride("default",E,f),pn(r,"pi",M,f)},"write"),clear:t(f=>{r.mutate.agent.clearModelOverride("default",f),r.mutate.agent.clearHarnessDefaultThinking("pi",f)},"clear")})});for(let f of n){let E=`${Y().displayName(f)} Default Model`,M=r.harnessDefaultModelLevels(f),G=r.harnessDefaultThinkingLevels(f),N=r.defaultThinkingForHarness(f);h.push({id:`harness:${f}`,label:E,currentValue:Ke({model:r.defaultModelForHarness(f),modelTag:Ge(M.session,M.project),thinking:N,thinkingTag:it(G,N)}),description:`Default model and thinking level applied to agents launched under ${f} when no session, per-type, or template override is set.`,submenu:D({label:E,harnessId:f,modelOptions:Z(i,f),mergedModels:[],model:r.defaultModelForHarness(f),thinking:N,modelLevels:M,thinkingLevels:G,write:t((q,ze,Bn)=>{r.mutate.agent.setHarnessDefaultModel(f,ze,q),pn(r,f,Bn,q)},"write"),clear:t(q=>{r.mutate.agent.clearHarnessDefaultModel(f,q),r.mutate.agent.clearHarnessDefaultThinking(f,q)},"clear")})})}let w=_t(),I={default:r.sessionDefaultModel},A={};for(let f of w)I[f]=r.sessionModelOverride(f),A[f]=B(f);let x={};for(let f of w)x[f]=r.sessionThinkingOverride(f);let F=rn({types:w,agentConfigs:A,config:P,sessionOverrides:I,sessionThinking:x,harnessDefaultFor:t(f=>r.defaultModelForHarness(ne(f)),"harnessDefaultFor"),harnessDefaultThinkingFor:t(f=>{let E=ne(f),M=r.defaultThinkingForHarness(E);return M!==null?M:te(E)&&O===null?l??null:null},"harnessDefaultThinkingFor"),harnessFamilyFor:t(f=>Ye(ne(f)),"harnessFamilyFor"),hasProjectModelKey:t(f=>r.hasProjectModelKey(f),"hasProjectModelKey"),hasProjectThinkingKey:t(f=>r.hasProjectThinkingKey(f),"hasProjectThinkingKey"),parentModelId:L,parentThinking:O}),z=t((f,E,M,G)=>D({label:f,harnessId:E,modelOptions:Z(i,E),mergedModels:we(E,W),model:M,thinking:G,modelLevels:r.modelOverrideLevels(f),thinkingLevels:r.thinkingOverrideLevels(f),write:t((N,q,ze)=>{r.mutate.agent.setModelOverride(f,q,N),nr(r,f,ze,N)},"write"),clear:t(N=>{r.mutate.agent.clearModelOverride(f,N),r.mutate.agent.clearThinkingOverride(f,N)},"clear")}),"typeSubmenu");for(let f of F){h.push({id:U,label:" ",currentValue:""}),h.push(fe(v,f.modelId??"(no model)"));let E=Math.max(...f.rows.map(M=>`${M.thinking??"(none)"}${M.thinkingTag}`.length));for(let M of f.rows){let G=ne(M.type),N=`${M.thinking??"(none)"}${M.thinkingTag}`,q=M.thinking!==null&&M.thinkingTag.trim()===M.tag.trim()?"":M.tag;h.push({id:`type:${M.type}`,label:`${ie(v)}${M.type}`,currentValue:`${N.padEnd(E)} ${q}`.trimEnd(),description:`Model and thinking level for the ${M.type} agent type.`,submenu:z(M.type,G,f.modelId,M.thinking)})}}h.push({id:U,label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",currentValue:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});let Me=w.filter(f=>!tt(I,P,f,x));Me.length>0&&h.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((f,E)=>_e(Me.map(M=>({value:M,label:`${ie(v)}${M}`})),{onSelect:t(M=>{if(M==null)return E();let G=ne(M),N=B(M),q=r.modelFor(M,L,N,G);return z(M,G,q,nt({type:M,agentConfig:N,harnessFamily:Ye(G),config:P,harnessDefault:r.defaultThinkingForHarness(G),parentThinking:O??void 0,sessionThinking:x}).level)("",E)},"onSelect"),onCancel:t(()=>E(),"onCancel")},v),"submenu")}),h.push({id:U,label:" ",currentValue:""});let mt=r.modelSettingsLevels(),Ie={...mt,project:mt.project&&k};return(Ie.session||Ie.global||Ie.project)&&h.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:Ve({theme:v,projectOffered:k,availableLevels:Ie,message:t(f=>`Clear all model and thinking overrides at the ${f} level?`,"message"),onConfirm:t(f=>{r.mutate.agent.clearAllModelOverrides(f),b(`Model and thinking overrides cleared (${f})`,"info")},"onConfirm")})}),h},"buildItems"),u=new tr(c(s),15,_(s),(v,h)=>d?.(c(s)),a),g=new H(u,{title:"Model Settings",theme:s,onCancel:a,onRebuild:t(v=>{d=v},"onRebuild")});return oe(g)}t(ir,"buildModelSettingsList");function fn(e){let{ctx:n,store:o,theme:r,harnessModelOptions:s,piDefaultThinking:i}=e,l=t(()=>{let a=o.modelOverrideLevels("default"),d=o.harnessDefaultThinkingLevels("pi"),c=o.defaultThinkingForHarness("pi");return Ke({model:o.sessionDefaultModel??o.agentConfigSnapshot().default,modelTag:Ge(a.session,o.hasProjectModelKey("default")),thinking:c,thinkingTag:it(d,c)})},"defaultDisplay");return{id:"modelOverrides",label:"Model overrides",currentValue:l(),description:"Pi's default model and thinking level, plus per-harness and per-type overrides; opens the model settings screen.",submenu:t((a,d)=>or({ctx:n,store:o,theme:r,harnessModelOptions:s,piDefaultThinking:i,close:t(()=>d(l()),"close")}),"submenu")}}t(fn,"buildModelOverridesRow");import{SettingsList as gn}from"@earendil-works/pi-tui";function hn(e,n){return e==="pi"?n:`${e}:${n}`}t(hn,"qualifiedKey");function Be(e){let n=new Map;for(let o of e){let r=$e(o)?.harness??"pi",s=n.get(r);s?s.push(o):n.set(r,[o])}return n}t(Be,"groupKeysByHarness");function ar(e,n){let o=[...e];for(let r of n.keys())o.includes(r)||o.push(r);return o}t(ar,"sectionHarnesses");async function yn(e,n){let o=[...n.keys()],r=t((i,l)=>{let a=[],d=i.isProjectWritable,c=t((p,m,y)=>m==="default"?p.default!==void 0:y===void 0?!1:m==="harnesses"?p.harnesses?.[y]!==void 0:p[m]?.[y]!==void 0,"layerHas"),u=t((p,m)=>({session:c(i.sessionConcurrency,p,m),global:c(i.globalConcurrency,p,m),project:c(i.projectConcurrency,p,m)}),"entryLevels"),g=t((p,m)=>c(i.sessionConcurrency,p,m)?" [session]":c(i.projectConcurrency,p,m)?" [project]":"","limitTag"),v=t((p,m)=>(y,S)=>Ne({theme:l,projectOffered:d,onPick:t((w,I)=>ot(e,{kind:"optional",min:1,onValid:t(A=>m(w,A),"onValid")})(p,I),"onPick")})(y,S),"targetThenValueSubmenu"),h=t((p,m,y,S)=>(w,I)=>{let A=ge({offered:{session:!0,global:!0,project:d},includeClear:S.session||S.global||S.project});return ee({theme:l,items:A,onPick:t((x,F)=>{if(x==="clear")return he({theme:l,projectOffered:d,availableLevels:S,onClear:y})("",F);let z=x;return ot(e,{kind:"optional",min:1,onValid:t(Me=>m(z,Me),"onValid")})(String(p),F)},"onPick")})(w,I)},"limitSubmenu"),k=t(p=>(m,y)=>{let S=t(()=>p(),"buildFresh"),w,I=X(new gn(S(),15,_(l),(A,x)=>{let F=w,z=S();F.items=z,F.filteredItems=z,F.submenuComponent=null,F.selectedIndex=0},()=>y("closed")));return w=I,He(w),oe(I)},"nestedListSubmenu"),b=t(p=>{let m=$(),y=m.concurrency.harnesses[p],S=Y().displayName(p),w=`Concurrent agents of every model launched under ${p}.`;if(y===void 0)return{id:`harness:${p}`,label:S,currentValue:"unset",description:w,submenu:v("",(A,x)=>{$().mutate.concurrency.setHarness(p,x,A),e.ui.notify(`${p} concurrency set to ${x} (${A})`,"info")})};let I=c(m.sessionConcurrency,"harnesses",p)?" [session]":c(m.projectConcurrency,"harnesses",p)?" [project]":"";return{id:`harness:${p}`,label:S,currentValue:De(y,I),description:w,submenu:h(y,(A,x)=>{$().mutate.concurrency.setHarness(p,x,A),e.ui.notify(`${S} concurrency set to ${x} (${A})`,"info")},A=>{$().mutate.concurrency.removeHarness(p,A),e.ui.notify(`Removed per-harness limit for ${p} (${A})`,"info")},{session:c(m.sessionConcurrency,"harnesses",p),global:c(m.globalConcurrency,"harnesses",p),project:c(m.projectConcurrency,"harnesses",p)})}},"harnessLimitRow"),T=t(()=>{let p=$(),m=[...o];for(let y of Object.keys(p.concurrency.harnesses))y.trim()!==""&&!m.includes(y)&&m.push(y);return m.map(y=>b(y))},"harnessListItems"),C=t(p=>{let m=Z(n,p);return[...new Set(m.map(y=>kt(y)?.provider).filter(y=>y!==void 0))].sort()},"providerOptionsFor"),L=t((p,m)=>{let y=$(),S=y.concurrency.providers[m],w=`Concurrent slots reserved for agents under ${p} using the ${$e(m)?.provider??m} provider.`;if(S===void 0)return{id:`provider:${m}`,label:m,currentValue:"unset",description:w,submenu:v("",(A,x)=>{$().mutate.concurrency.setProvider(m,x,A),e.ui.notify(`${m} concurrency set to ${x} (${A})`,"info")})};let I=c(y.sessionConcurrency,"providers",m)?" [session]":c(y.projectConcurrency,"providers",m)?" [project]":"";return{id:`provider:${m}`,label:m,currentValue:De(S,I),description:w,submenu:h(S,(A,x)=>{$().mutate.concurrency.setProvider(m,x,A),e.ui.notify(`${m} concurrency set to ${x} (${A})`,"info")},A=>{$().mutate.concurrency.removeProvider(m,A),e.ui.notify(`Removed per-provider limit for ${m} (${A})`,"info")},{session:c(y.sessionConcurrency,"providers",m),global:c(y.globalConcurrency,"providers",m),project:c(y.projectConcurrency,"providers",m)})}},"providerLimitRow"),O=t(p=>{let m=$(),y=Be(Object.keys(m.concurrency.providers)).get(p)??[],S=C(p).map(I=>hn(p,I));return[...new Set([...S,...y])].sort().map(I=>L(p,I))},"providerListItems"),P=t((p,m)=>{let y=$(),S=y.concurrency.models[m],w=$e(m),I=w?.kind==="model"?w.model:m,A=`Concurrent slots reserved for agents under ${p} using the ${I} model.`;if(S===void 0)return{id:`model:${m}`,label:m,currentValue:"unset",description:A,submenu:v("",(F,z)=>{$().mutate.concurrency.setModel(m,z,F),e.ui.notify(`${m} concurrency set to ${z} (${F})`,"info")})};let x=c(y.sessionConcurrency,"models",m)?" [session]":c(y.projectConcurrency,"models",m)?" [project]":"";return{id:`model:${m}`,label:m,currentValue:De(S,x),description:A,submenu:h(S,(F,z)=>{$().mutate.concurrency.setModel(m,z,F),e.ui.notify(`${m} concurrency set to ${z} (${F})`,"info")},F=>{$().mutate.concurrency.removeModel(m,F),e.ui.notify(`Removed per-model limit for ${m} (${F})`,"info")},{session:c(y.sessionConcurrency,"models",m),global:c(y.globalConcurrency,"models",m),project:c(y.projectConcurrency,"models",m)})}},"modelLimitRow"),W=t(p=>{let m=$(),y=Be(Object.keys(m.concurrency.models)).get(p)??[],S=Z(n,p).map(I=>hn(p,I));return[...new Set([...S,...y])].sort().map(I=>P(p,I))},"modelListItems"),R=t(p=>{let m=$(),y=Be(Object.keys(p==="providers"?m.concurrency.providers:m.concurrency.models));return ar(o,y).filter(S=>{let w=(y.get(S)??[]).length>0;return p==="providers"?w||C(S).length>0:w||Z(n,S).length>0}).map(S=>({id:`${p}-harness:${S}`,label:Y().displayName(S),currentValue:"",description:p==="providers"?`Provider limits under ${S}.`:`Model limits under ${S}.`,submenu:k(()=>p==="providers"?O(S):W(S))}))},"harnessPickerItems"),j=i.concurrency.default;a.push({id:"defaultConcurrency",label:"Default concurrency limit",currentValue:`${j}${g("default")}`,description:"Concurrent agents, whatever harness, provider, or model they use.",submenu:h(j,(p,m)=>{i.mutate.concurrency.setDefault(m,p),e.ui.notify(`Default concurrency set to ${m} (${p})`,"info")},p=>{i.mutate.concurrency.removeDefault(p),e.ui.notify(`Removed default concurrency limit (${p})`,"info")},u("default"))}),a.push({id:"harnessLimits",label:"Per-harness limits",currentValue:"",description:"Cap how many agents run at once under a single harness.",submenu:k(T)}),a.push({id:"providerLimits",label:"Per-provider limits",currentValue:"",description:"Cap how many agents run at once for a single provider.",submenu:k(()=>R("providers"))}),a.push({id:"modelLimits",label:"Per-model limits",currentValue:"",description:"Cap how many agents run at once for a single model.",submenu:k(()=>R("models"))});let D=i.concurrencySettingsLevels(),K={...D,project:D.project&&d};return(K.session||K.global||K.project)&&a.push({id:"resetAll",label:"Clear all concurrency limits...",currentValue:"",description:"Remove concurrency overrides at the chosen level (session, global, project, or all).",submenu:Ve({theme:l,projectOffered:d,availableLevels:K,message:t(p=>`Clear all concurrency limits at the ${p} level?`,"message"),onConfirm:t(p=>{i.mutate.concurrency.clearAll(p),e.ui.notify(`Concurrency limits cleared (${p})`,"info")},"onConfirm")})}),a},"buildItems"),s;await new V(e).open(({theme:i,close:l})=>{let a=t(()=>s?.(r($(),i)),"triggerRebuild"),d=$(),c=r(d,i),u=new gn(c,15,_(i),(g,v)=>a(),l);return new H(u,{title:"Concurrency Settings",theme:i,onCancel:l,onRebuild:t(g=>{s=g},"onRebuild")})})}t(yn,"showConcurrencySettingsMenu");import{matchesKey as ce,SelectList as at,truncateToWidth as Sn,visibleWidth as Ue}from"@earendil-works/pi-tui";import{SelectList as lr}from"@earendil-works/pi-tui";async function vn(e,n){let o=ae();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:de(i)})}return r}t(vn,"runCleanupPass");function st(e,n){let o=J(e.ui);for(let r of n)r.kind==="report"?o.succeeded(Gt(r.report),Je(r.report)?"warning":"info"):o.failed(`Failed to clean up agent ${r.id}`,r.error)}t(st,"reportCleanupOutcomes");function bn(e){return e.outcome.kind==="refused"?e.outcome.reason:void 0}t(bn,"refusalReason");function cr(e){return e.worktree.kind==="kept"?e.worktree.path??void 0:void 0}t(cr,"refusalWorktreePath");function ur(e){switch(e.kind){case"dirty":return"It has uncommitted changes";case"unverifiable":return`Its state could not be verified (${e.detail})`;case"recovered-refusal":return"Herdr still reports it at work";default:return Re(e)}}t(ur,"offerReason");function dr(e,n){return{invalidate(){},render:t(()=>[` ${e.fg("dim",n)}`],"render")}}t(dr,"progressBody");function mr(e,n,o,r){let s=[{value:"force",label:"Force",description:n},{value:"cancel",label:"Cancel",description:"Keep the worktree and its changes"}],i=X(new lr(s,6,Q(e)));return i.onSelect=l=>l.value==="force"?o():r(),i.onCancel=r,i}t(mr,"forceOfferList");function kn(e){let{ctx:n,theme:o,view:r,refresh:s,close:i,requestRender:l}=e,a=t(u=>{r.activate(u),l()},"show"),d=t((u,g,v,h)=>{let k=u.length===1;a(sn({theme:o,message:k?`Force cleanup of agent ${u[0]}?`:`Force cleanup of ${u.length} agents?`,detail:[...v,"",k?"This DELETES its worktree and anything uncommitted in it.":"This DELETES their worktrees and anything uncommitted in them."].join(`
3
3
  `),onNo:h,onYes:t(()=>{i(),J(n.ui).pending(`Forcing cleanup of ${Te(u)}`),(async()=>{let b=await vn(u,T=>{let C=g.get(T);return{force:C?{reason:C}:{}}});st(n,b)})()},"onYes")}))},"askForceConfirm"),c=t(u=>{let g=new Map;for(let{id:L,report:O}of u){let P=bn(O);P&&g.set(L,P)}let v=[...g.keys()],h=v.length===1,k=u.map(({id:L,report:O})=>{let P=bn(O),W=P?h?Re(P):`${L}: ${Re(P)}`:`${L}: kept`,R=cr(O);return R?`${W} (${R})`:W}),b=g.get(v[0]??""),T=h?`Clean up agent ${v[0]} anyway? ${b?ur(b):"kept"}.`:`Clean up ${v.length} agents anyway?`,C=t(()=>{st(n,u),s()},"backOut");a(mr(o,T,()=>d(v,g,k,C),C))},"offerForce");return u=>{a(dr(o,`Cleaning up ${Te(u)}\u2026`)),(async()=>{let g=await vn(u,()=>{}),v=g.filter(b=>b.kind==="report"&&zt(b.report)),h=new Set(v.map(b=>b.id));if(st(n,g.filter(b=>!h.has(b.id))),v.length>0){c(v);return}g.some(b=>b.kind==="error"||Je(b.report))?s():i()})()}}t(kn,"createStatusCleanup");async function pr(e,n){let o=n.execution.host;if(!o){e.ui.notify("Agent has no herdr pane yet (still queued)","info");return}let r=Ee();if(!r){e.ui.notify("Agent runtime is not initialized","warning");return}let s=J(e.ui);s.pending(`Focusing agent ${n.id}'s herdr pane`);try{await r.view.focus(o),s.succeeded(`Focused agent ${n.id}'s herdr pane`)}catch(i){s.failed(`Failed to focus agent ${n.id}'s herdr pane`,i)}}t(pr,"focusHerdrPane");async function Cn(e,n,o,r){let s=o==="result"?n.id:"Error",i=r.split(`
4
4
  `),l=tn(n.display.type),a=5,d=3,c=70,u=0,g=!0;await new V(e).openOverlay(({tui:v,theme:h,close:k})=>{let b=h.fg("border","\u2502"),T=t(()=>{let C=Math.floor(v.terminal.rows*c/100);return Math.max(d,C-a)},"viewportHeight");return{invalidate(){},render(C){let L=C-4,O=[h.fg("border",`\u256D${"\u2500".repeat(C-2)}\u256E`)],P=h.bold(h.fg("accent",`${l} \xB7 ${s}`)),W=Math.max(0,L-Ue(P));O.push(`${b} ${Sn(P+" ".repeat(W),L,"...",!0)} ${b}`),O.push(`${b} ${h.fg("dim","\u2500".repeat(L))} ${b}`);let R=T(),j=Math.max(0,i.length-R);g&&(u=j);let D=Math.min(u,j),K=i.slice(D,D+R);for(let w=0;w<R;w++){let I=K[w]??"",A=Sn(I,L,"...",!0),x=Math.max(0,L-Ue(A));O.push(`${b} ${A}${" ".repeat(x)} ${b}`)}let p=i.length<=R?"100%":`${Math.round((D+R)/i.length*100)}%`,m=h.fg("dim",`${i.length} lines \xB7 ${p}`),y=h.fg("dim","q/Esc close"),S=Math.max(1,L-Ue(m)-Ue(y));return O.push(`${b} ${m}${" ".repeat(S)}${y} ${b}`),O.push(h.fg("border",`\u2570${"\u2500".repeat(C-2)}\u256F`)),O},handleInput(C){if(ce(C,"q")||ce(C,"escape")){k();return}let L=T(),O=Math.max(0,i.length-L);ce(C,"up")?(u=Math.max(0,u-1),g=u>=O):ce(C,"down")?(u=Math.min(O,u+1),g=u>=O):ce(C,"pageUp")?(u=Math.max(0,u-L),g=!1):ce(C,"pageDown")?(u=Math.min(O,u+L),g=u>=O):ce(C,"home")||C==="g"?(u=0,g=!1):C==="G"&&(u=O,g=!0)}}})}t(Cn,"showTextViewer");function wn(e,n){let o=ae(),r=Te(n),s=J(e.ui);if(!o){s.failed(`Failed to stop ${r}`,"manager unavailable");return}(async()=>{let i=0,l=[];for(let d of n)try{await o.abort(d,"user")?i+=1:l.push({id:d,reason:"already settled"})}catch(c){l.push({id:d,reason:de(c)})}if(l.length===0){s.succeeded(n.length===1?`Stopped ${n[0]}`:`Stopped ${n.length} agent(s)`);return}let a=l.map(({id:d,reason:c})=>n.length===1?c:`${d} (${c})`).join(", ");i>0?s.succeeded(`Stopped ${i} of ${n.length} agent(s); ${a}`,"warning"):s.failed(`Failed to stop ${r}`,a)})()}t(wn,"stopAgentsOffMenu");function fr(e,n,o,r,s,i){let l=[],a=n.id,d=Ce(n.lifecycle.phase),c=!!n.execution.host,u=At(n.lifecycle),g=Le(n.lifecycle)&&n.lifecycle.status==="error"?n.lifecycle.error:"",v=u.length>0,h=g.length>0;if(c&&l.push({value:"focus-pane",label:"View shell",description:"Focus the subagent's herdr pane"}),v&&l.push({value:"view-result",label:"View result"}),h&&l.push({value:"view-error",label:"View error"}),d?l.push({value:"stop",label:"Stop"}):l.push({value:"cleanup",label:"Clean up",description:"Close its pane and remove its worktree and merged branch"}),l.length===0)return e.ui.notify(`Agent ${a} \u2014 no actions available`,"info"),r(),new at([],5,Q(o));let k=X(new at(l,10,Q(o)));return k.onSelect=async b=>{b.value==="focus-pane"?await pr(e,n):b.value==="view-result"?await Cn(e,n,"result",u):b.value==="view-error"?await Cn(e,n,"error",g):b.value==="stop"?(J(e.ui).pending(`Stopping agent ${a}`),r(),wn(e,[n.id])):b.value==="cleanup"&&i([n.id])},k.onCancel=()=>r(),k}t(fr,"buildAgentActionsList");async function Tn(e){if((ae()?.listAgents(Ae)??[]).length===0){e.ui.notify("No agents have been spawned this session","info");return}await new V(e).open(({tui:n,theme:o,close:r})=>{let s=ae()?.listAgents(Ae)??[],i=t(()=>s.filter(k=>Ce(k.lifecycle.phase)),"activeAgents"),l=t(()=>s.filter(k=>!Ce(k.lifecycle.phase)),"finishedAgents"),a=t(()=>s.filter(k=>Le(k.lifecycle)&&k.lifecycle.status==="completed"),"completedAgents"),d=t(()=>{let k=Date.now(),b=s.map(O=>{let P=It(O.lifecycle),W=Ce(O.lifecycle.phase),R=Le(O.lifecycle)?O.lifecycle.completedAt:k,j=et(R-Lt(O.lifecycle)),D=W?"":` ${et(k-R)} ago`,K=en(P,o),p=O.display.description?O.display.description:"",m=p?` \u2014 ${p}`:"",y=ie(o),S=O.display.worktree?` wt:${O.display.worktree.branch}`:"";return{value:O.id,label:`${K} ${O.id} ${y}${O.display.type} ${P} ${j}${S}${m}${D}`}}),T=i(),C=l(),L=a();return T.length>0&&(b.push({value:U,label:" "}),b.push({value:"__stop-all",label:`Stop ${T.length} active agent(s)`})),C.length>0&&(b.push({value:U,label:" "}),b.push({value:"__cleanup-finished",label:`Clean up ${C.length} settled agent(s)`}),L.length>0&&b.push({value:"__cleanup-completed",label:`Clean up ${L.length} completed agent(s)`})),b},"buildAgentItems"),c=X(new at(d(),15,Q(o)));He(c);let u=new je(c),g=t(()=>n.requestRender(),"requestRender"),v=t(k=>{s=ae()?.listAgents(Ae)??[];let b=c,T=d();b.items=T,b.filteredItems=T;let C=k?T.findIndex(L=>L.value===k):-1;c.setSelectedIndex(C>=0?C:0),u.activate(c),g()},"refresh"),h=kn({ctx:e,theme:o,view:u,refresh:v,close:r,requestRender:g});return c.onSelect=async k=>{if(k.value==="__stop-all"){let T=i();J(e.ui).pending(`Stopping ${T.length} agent(s)`),r(),wn(e,T.map(C=>C.id));return}if(k.value==="__cleanup-finished"){h(l().map(T=>T.id));return}if(k.value==="__cleanup-completed"){h(a().map(T=>T.id));return}let b=s.find(T=>T.id===k.value);b&&u.activate(fr(e,b,o,()=>v(b.id),()=>r(),h))},c.onCancel=()=>r(),new H(u,{title:"Status",theme:o,passthroughKeys:!0})})}t(Tn,"showAgentStatusMenu");import{SettingsList as gr,Input as hr}from"@earendil-works/pi-tui";function yr(e){let n="Harness that launches agents whose template omits harness_type. pi = the real pi binary; pig and pi-bolt = pi-compatible binaries launched through a shell function in the agent's own pane; opencode and codex = binaries of their own launched as their interactive UIs in the agent's own pane.",o=Ct.filter(l=>l!=="pi"&&!qe(l,e)),r=o.length===0?n:`${n} Not on PATH: ${o.join(", ")}.`,s=Y(),i=On().filter(l=>wt(l)===void 0);return i.length===0?r:`${r} Plugin harnesses: ${i.map(l=>s.displayName(l)).join(", ")}.`}t(yr,"harnessDescription");function On(){return[...ke(Y().ids(),le())]}t(On,"offerableHarnesses");async function Mn(e){let n=$(),o=t(i=>[fe(i,"Spawn defaults"),{id:U,label:" ",currentValue:""},{id:"harnessType",label:"Default harness",currentValue:jt(),values:On(),description:yr(le())},{id:U,label:" ",currentValue:""},fe(i,"Worktrees"),{id:"worktreeRoot",label:"Worktree root",currentValue:n.agent.worktreeRoot??"(default)",submenu:t((l,a)=>{let d=new hr;return d.setValue(l==="(default)"?"":l),d.onSubmit=c=>{let u=c.trim();n.mutate.agent.setWorktreeRoot(u||void 0),Zt(se()),e.ui.notify(u?`Worktree root set to ${u}`:"Worktree root cleared (default)","info"),a(u||"(default)")},d.onEscape=()=>a(),d},"submenu"),description:`Where worktrees are created. Blank = ${ft()}.`},{id:"worktreeMaterialization",label:"Worktree materialization",currentValue:xe(),values:[...ke(gt,Ze())],description:qe("copy-on-write",Ze())?"Copy-on-write = clone of the parent working tree (shares node_modules, .env). checkout = git's classic checkout, nothing shared.":"This volume cannot clone, so copy-on-write is unavailable and new worktrees use git's classic checkout."},{id:"worktreeCheckoutType",label:"Worktree checkout",currentValue:n.agent.worktreeCheckoutType,values:[...yt],description:"Where a new worktree's checkout starts when the parent has uncommitted work. clean = the worktree starts at HEAD: under copy-on-write, only ignored files like node_modules and .env are copied in; under checkout, it is git's plain checkout. dirty = the parent's work rides along: copy-on-write clones its edits and untracked files too, while checkout applies only its tracked changes, leaving untracked files behind. A clean parent starts at HEAD either way."},{id:U,label:" ",currentValue:""},fe(i,"Tools"),{id:"disableDefaultAgents",label:"Disable default agents",currentValue:n.agent.disableDefaultAgents?"ON":"OFF",values:["ON","OFF"],description:"Skip auto-loading built-in agent types next session; only .pi/agents types load."}],"buildItems"),r=t((i,l)=>{switch(i){case"worktreeRoot":break;case"worktreeMaterialization":{let a=ht(l);a!==void 0&&(n.mutate.agent.setWorktreeMaterialization(a),e.ui.notify(`Worktree materialization set to ${a}`,"info"));break}case"worktreeCheckoutType":{let a=vt(l);a!==void 0&&(n.mutate.agent.setWorktreeCheckoutType(a),e.ui.notify(`Worktree checkout set to ${a}`,"info"));break}case"harnessType":{n.mutate.agent.setHarnessType(l),e.ui.notify(`Default harness set to ${l}`,"info");break}case"disableDefaultAgents":n.mutate.agent.setDisableDefaultAgents(l==="ON"),e.ui.notify(`Disable default agents ${l} (takes effect on next session)`,"info");break}},"onChange"),s;await new V(e).open(({theme:i,close:l})=>{let a=o(i),d=t(()=>s?.(o(i)),"triggerRebuild"),c=new gr(a,10,_(i),(u,g)=>{r(u,g),a.some(v=>v.id===u&&v.submenu)&&d()},l);return new H(c,{title:"Agent settings",theme:i,onCancel:l,onRebuild:t(u=>{s=u},"onRebuild")})})}t(Mn,"showSpawnOptionsMenu");function vr(e,n,o){return(r,s)=>{let i=Pe();i.length===0&&n("No agent types available","error");let l=i.map(a=>({value:a,label:a,provider:B(a)?.description??""}));return new pe(l,e.agent.defaultAgentType,{onSelect:t(a=>{a!=null&&(e.mutate.agent.setDefaultAgentType(a),n(`Agent set to ${a}`,"info")),s(a??void 0)},"onSelect"),onCancel:t(()=>s(),"onCancel")},o)}}t(vr,"createAgentTypeSubmenu");function br(e,n,o){return(r,s)=>{let i=Nt(),a=(i.length>0?i:Object.keys(Dt)).map(d=>({value:d,label:d}));return new pe(a,e.agent.defaultOrchestrator,{onSelect:t(d=>{d!=null&&(e.mutate.agent.setDefaultOrchestrator(d),n(`Default orchestrator set to ${d}`,"info")),s(d??void 0)},"onSelect"),onCancel:t(()=>s(),"onCancel")},o)}}t(br,"createOrchestratorSubmenu");function In(e){return{id:"defaultAgentType",label:"Agent",currentValue:e.store.agent.defaultAgentType,submenu:vr(e.store,e.notify,e.theme),description:`Agent type used when cowboy_agent omits \`agent_type\`. Default: ${Ot}.`}}t(In,"buildDefaultAgentTypeRow");function An(e){return{id:"defaultOrchestrator",label:"Default orchestrator",currentValue:e.store.agent.defaultOrchestrator,submenu:br(e.store,e.notify,e.theme),description:`Orchestration template used for every cowboy_agent spawn; the tool accepts no per-call orchestrator input. Default: ${Mt}.`}}t(An,"buildDefaultOrchestratorRow");import lt from"node:fs";import kr from"node:path";import{SettingsList as Sr}from"@earendil-works/pi-tui";async function Ln(e){let n=$(),o=t(()=>{let l=Xe(),a=[{id:"systemPromptMode",label:"System prompt mode",currentValue:n.agent.systemPromptMode,values:["replace","inherit","custom"],description:"How the subagent system prompt is built: replace, inherit, or custom."}];return n.agent.systemPromptMode==="custom"&&!lt.existsSync(l)&&a.push({id:"createPromptFile",label:"Create prompt file",currentValue:l,values:["Create"],description:`Create ${l} with a starter template for custom mode.`}),a.push({id:"includeContextFiles",label:"Include context files",currentValue:n.agent.includeContextFiles?"ON":"OFF",values:["ON","OFF"],description:"Load project and ~/.pi/agent AGENTS.md as shared <project_context>."},{id:"loadSkillsImplicitly",label:"Load skills implicitly",currentValue:n.agent.loadSkillsImplicitly?"ON":"OFF",values:["ON","OFF"],description:"Give new agents all skills when an agent template omits the field."},{id:"loadExtensionsImplicitly",label:"Load extensions implicitly",currentValue:n.agent.loadExtensionsImplicitly?"ON":"OFF",values:["ON","OFF"],description:"Give new agents all extensions when an agent template omits the field."}),a},"buildItems"),r=o(),s=null,i=t((l,a)=>{switch(l){case"systemPromptMode":n.mutate.agent.setSystemPromptMode(a),e.ui.notify(`System prompt mode set to ${a}`,"info"),r=o(),s?.(r);break;case"createPromptFile":try{let d=Xe();lt.mkdirSync(kr.dirname(d),{recursive:!0}),lt.writeFileSync(d,`You are a Pi, an expert coding sub-agent.
@@ -6,4 +6,4 @@ You have been invoked to handle a specific task autonomously`,"utf-8"),e.ui.noti
6
6
  `,1)[0]??"").slice(0,$r),P=Rt(),W=Wt();try{await P.spawn(o,{spawnId:b,type:g.type,requestedHarness:g.harness,prompt:h,description:O,orchestration:W,modelChoice:g.modelChoice,worktree:L,hostRef:T?.hostRef,projectTrusted:T?.projectTrusted,invocation:{...xn(g.modelChoice),runInBackground:g.runInBackground,fork:g.fork},runInBackground:g.runInBackground,fork:g.fork})}catch(R){let j=`Spawn failed: ${R instanceof Error?R.message:String(R)}`;if(!T){e.ui.notify(j,"error");return}let D=await T.teardown(k);e.ui.notify(`${j}
7
7
 
8
8
  ${Yt(D)}`,"error")}},"launch"),a=await Wn(e,n);if(a===void 0)return;let d=new V(e),c;if(a.worktreeChoice.kind==="new"){let g=await Nn(d,(v,h)=>e.ui.notify(v,h));if(g===void 0)return;c={kind:"new",branch:g}}else c=a.worktreeChoice;let u=await d.open(({tui:g,theme:v,keybindings:h,close:k})=>new H(Vn({prefill:"",onDone:t(b=>k(b),"onDone"),onCancel:t(()=>k(),"onCancel"),tui:g,theme:v,keybindings:h}),{title:"Agent Prompt (optional)",theme:v,passthroughKeys:!0}));u!==void 0&&await l(a,c,u)}t(Kn,"showSpawnAgentMenu");async function xr(e){return await new V(e).open(({theme:n,close:o})=>{let r=t(c=>o(c),"handOff"),s=$(),i=s.agent.showActiveIndicator,l=s.agent.grazingEnabled,a=[be("concurrency","Concurrency Settings","Set per-model slot limits",r),be("spawnoptions","Agent behavior","spawn defaults, results delivery, output, tools, worktrees",r),be("systemprompt","System prompt","Prompt mode, AGENTS.md, skills, extensions",r),{id:"showActiveIndicator",label:"Show cowboy \u{1F920}",currentValue:i?"ON":"OFF",values:["ON","OFF"]},{id:"grazingEnabled",label:"Grazing \u{1F404}",currentValue:l?"ON":"OFF",values:["ON","OFF"]}],d=new Gn(a,10,_(n),(c,u)=>{c==="showActiveIndicator"?Bt(e.ui,u==="ON"):c==="grazingEnabled"&&s.mutate.agent.setGrazingEnabled(u==="ON")},o);return new H(d,{title:"Settings",theme:n,onCancel:o})})}t(xr,"showSettingsList");async function Er(e,n){for(;;){let o=await xr(e);if(o===void 0)return;switch(o){case"concurrency":await yn(e,n);break;case"spawnoptions":await Mn(e);break;case"systemprompt":await Ln(e);break}}}t(Er,"showSettingsMenu");async function Pr(e,n,o){switch(n){case"status":await Tn(e);break;case"spawn":await Kn(e,o);break;case"settings":await Er(e,o);break}}t(Pr,"showAgentsActionMenu");function be(e,n,o,r){return{id:e,label:n,description:o,currentValue:"",submenu:t(()=>(r(e),re),"submenu")}}t(be,"handOffRow");async function Rr(e,n){let o=await Qt(e.cwd),r;return await new V(e).open(({theme:s,close:i})=>{let l=t(c=>i(c),"handOff"),a=t(()=>{let c=$(),u=t((h,k)=>e.ui.notify(h,k),"notify"),g=c.agent.extensionEnabled,v={id:"extensionEnabled",label:"Enabled",currentValue:g?"ON":"OFF",values:["ON","OFF"],description:g?"Unload the cowboy tools and stop subagent-result notifications. Persisted; active agents keep working.":"cowboy tools are unloaded and the rest of this menu is hidden. Active agents keep working."};return g?[fn({ctx:e,store:c,theme:s,harnessModelOptions:n,piDefaultThinking:o}),An({store:c,theme:s,notify:u}),In({store:c,theme:s,notify:u}),be("status","Status","List spawned, queued and settled agents",l),be("spawn","Spawn agent","Manually spawn a new agent",l),be("settings","Settings","Concurrency, agent behavior, and system prompt settings",l),v]:[v]},"buildItems"),d=new Gn(a(),10,_(s),(c,u)=>{let g=c==="extensionEnabled";if(g){let v=u==="ON";Jt(e.ui,v),e.ui.notify(v?"pi-cowboy enabled":"pi-cowboy disabled","info")}r?.(a(),g?"extensionEnabled":void 0)},i);return new H(d,{title:"Agents",theme:s,onCancel:i,onRebuild:t(c=>{r=c},"onRebuild")})})}t(Rr,"showAgentsMainList");async function ma(e,n){for(;;){let o=await Rr(e,n);if(o===void 0)return;await Pr(e,o,n)}}t(ma,"showAgentsMainMenu");export{Pr as showAgentsActionMenu,ma as showAgentsMainMenu,Er as showSettingsMenu,Kn as showSpawnAgentMenu};
9
- //# sourceMappingURL=menus-Z5QGWG5V.js.map
9
+ //# sourceMappingURL=menus-Q3TEDIPV.js.map
@@ -1,2 +1,2 @@
1
- import{a as E,b as R,i as A}from"./chunk-7KLHCZK2.js";import{ea as v,fa as u,ia as c,sa as S,ta as k}from"./chunk-7W5EBKER.js";import{a as s,e as w,f as m,t as h,u as C}from"./chunk-254PTGN5.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
- //# sourceMappingURL=model-picker-VQEDJJFS.js.map
1
+ import{a as E,b as R,i as A}from"./chunk-WL3QYM2F.js";import{ea as v,fa as u,ia as c,sa as S,ta as k}from"./chunk-CTBFJWEE.js";import{a as s,e as w,f as m,t as h,u as C}from"./chunk-254PTGN5.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
2
+ //# sourceMappingURL=model-picker-IIXU4GJP.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-cowboy",
3
- "version": "0.22.1",
3
+ "version": "0.22.2",
4
4
  "type": "module",
5
5
  "packageManager": "pnpm@12.9.1",
6
6
  "description": "Agent orchestrator for pi: can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",
@@ -94,12 +94,13 @@
94
94
  "@types/estree": "^1.0.9",
95
95
  "@types/mustache": "^4.2.6",
96
96
  "@types/node": "^26.6.4",
97
+ "@vitest/coverage-v8": "5.0.3",
97
98
  "@vitest/ui": "^5.0.3",
98
99
  "esbuild": "^0.28.2",
99
100
  "eslint": "^10.12.0",
100
101
  "eslint-plugin-import-x": "^4.17.1",
101
102
  "husky": "^9.1.7",
102
- "oxlint": "1.88.0",
103
+ "oxlint": "1.89.0",
103
104
  "oxlint-tsgolint": "7.0.2004",
104
105
  "prettier": "^3.9.9",
105
106
  "semantic-release": "^25.0.9",