pi-cowboy 0.35.0 → 0.36.0

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