pi-cowboy 0.36.3 → 0.36.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/result-renderer.d.ts +2 -0
- package/dist/{chunk-UG3ZH2M5.js → chunk-3FQQMEHD.js} +2 -2
- package/dist/{chunk-353K3BOB.js → chunk-EWHWPOTC.js} +12 -10
- package/dist/{chunk-M5B2YQME.js → chunk-UEMXTMQN.js} +2 -2
- package/dist/{chunk-6YJCZNKG.js → chunk-WP65L6WI.js} +2 -2
- package/dist/{chunk-UKOJ2RLH.js → chunk-YTDE2OUW.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{menu-worktree-command-T5ALHG5N.js → menu-worktree-command-JXTKYYEV.js} +2 -2
- package/dist/{menus-FBA2LRNT.js → menus-EETUYB5S.js} +2 -2
- package/dist/{model-picker-NHSPKBCV.js → model-picker-KTV7DIQR.js} +2 -2
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as et,Aa as Z,D as nt,E as Y,K as rt,Ka as J,M as ot,N as ke,O as F,T as it,b as pe,ea as at,fa as X,i as qe,j as Ke,m as fe,n as Qe,na as j,o as Ye,r as Q,ra as st,s as Xe,u as Ze,w as Je,xa as M,y as me}from"./chunk-
|
|
1
|
+
import{A as et,Aa as Z,D as nt,E as Y,K as rt,Ka as J,M as ot,N as ke,O as F,T as it,b as pe,ea as at,fa as X,i as qe,j as Ke,m as fe,n as Qe,na as j,o as Ye,r as Q,ra as st,s as Xe,u as Ze,w as Je,xa as M,y as me}from"./chunk-UEMXTMQN.js";import{F as tt,a as i,p as W,u as ge,v as he}from"./chunk-AOUEQXPY.js";import*as x from"node:fs";import*as k from"node:path";var hn=`import ctypes, sys
|
|
2
2
|
libc = ctypes.CDLL(None, use_errno=True)
|
|
3
3
|
# CLONE_NOFOLLOW = 0x01; clonefile clones whole directory trees on APFS.
|
|
4
4
|
if libc.clonefile(sys.argv[1].encode(), sys.argv[2].encode(), 0x01) != 0:
|
|
@@ -23,4 +23,4 @@ Error: {{error}}{{/error}}{{#has_worktree}}
|
|
|
23
23
|
`);return`${n} (line ${e.line}, column ${e.column})`}return(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim()}i(Jn,"describeParseError");var er={label:"File",problem:"was skipped"};async function oe(e,t,n,r,o=er,a){try{await ne.promises.access(e)}catch{return[]}let c=(await ne.promises.readdir(e,{withFileTypes:!0})).filter(l=>l.isFile()&&l.name.endsWith(Xn)),d=[];for(let l of c){let u=_t.join(e,l.name),p;try{p=await ne.promises.readFile(u,"utf-8")}catch{continue}try{let m=t(p),v=a?.(m);if(v!==void 0)throw new Error(v);n(m)&&d.push(m)}catch(m){r?.(`[cowboy] ${o.label} file ${u} ${o.problem}: ${Jn(m)}`,"warning")}}return d}i(oe,"scanTemplateFilesInDir");import{z as P}from"zod";import $t from"mustache";function Wt(e){return{has_worktree:!0,worktree_path:e.path,worktree_branch:e.branch}}i(Wt,"worktreeVariables");function tr(e){switch(e.kind){case"completed":return e.result!==""?{result:e.result}:{};case"failed":return{error:e.error};case"stopped":return{}}}i(tr,"outcomeVariables");function nr(e){return e?{...Wt(e),...e.retention!==void 0?{retention:e.retention}:{},...e.processAlive?{process_alive:!0}:{}}:{}}i(nr,"settledWorktreeVariables");function rr(e){return e.worktree?{agent_id:e.agentId,...Wt(e.worktree)}:{agent_id:e.agentId}}i(rr,"spawnCueContext");function jo(e){return{...rr(e),queue_running:e.queueRunning,queue_running_label:e.queueRunning===1?"agent":"agents"}}i(jo,"queuedCueContext");function Lo(e){let{outcome:t,statusNote:n,worktree:r,multiplexerId:o}=e;return{...tr(t),...n?{status_note:n}:{},...nr(r),...o!=null?{multiplexer_id:o}:{}}}i(Lo,"settledCueContext");var or={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0},ir={agent_id:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,queue_running:!0,queue_running_label:!0},ar={result:!0,error:!0,status_note:!0,has_worktree:!0,worktree_path:!0,worktree_branch:!0,retention:!0,process_alive:!0,multiplexer_id:!0},sr=Object.keys(or),cr=Object.keys(ir),dr=Object.keys(ar);function Ft(e){switch(e){case"spawned":return sr;case"queued":return cr;case"settled":return dr;default:return}}i(Ft,"cueVariables");var lr={ok:!0},ur="&",pr=new Set(["name",ur,"#","^"]);function Vo(e,t,n){return $t.render(e[t],n,void 0,{escape:i(r=>r==null?"":String(r),"escape")})}i(Vo,"renderCue");function fr(e){let t=e[4];return Array.isArray(t)?t:void 0}i(fr,"spanChildren");function It(e,t,n){for(let r of e){let[o,a]=r;if(o===">")return`partials are not supported: "{{>${a}}}"`;if(o==="=")return`delimiter changes are not supported: "{{=${a}=}}"`;if(pr.has(o)&&!t.includes(a))return`unknown variable "{{${a}}}" \u2014 allowed variables for the ${n} cue: ${t.join(", ")}`;let s=fr(r);if(s){let c=It(s,t,n);if(c)return c}}}i(It,"findTemplateProblem");function Dt(e,t){let n=Ft(e);if(!n)return{ok:!1,reason:`unknown cue event "${e}"`};let r;try{r=$t.parse(t)}catch(a){return{ok:!1,reason:`unparsable template: ${(a instanceof Error?a.message:String(a)).replace(/\s+/g," ").trim()}`}}let o=It(r,n,e);return o?{ok:!1,reason:o}:lr}i(Dt,"validateCueTemplate");var mr=["spawned","queued","settled"],gr=P.strictObject({spawned:P.string().optional(),queued:P.string().optional(),settled:P.string().optional()}).superRefine((e,t)=>{for(let n of mr){let r=e[n];if(r===void 0)continue;let o=Dt(n,r);o.ok||t.addIssue({code:"custom",message:o.reason,path:[n]})}}),Mt=P.strictObject({name:P.string().optional(),display_name:P.string().optional(),guidance:P.string().optional(),cues:gr.optional()});var hr={label:"Orchestrator",problem:"is not a valid orchestrator template and was skipped"};function kr(e){return Mt.parse(re(e))}i(kr,"parseOrchestratorFile");async function z(e,t){return oe(e,kr,n=>n.name,t,hr)}i(z,"scanOrchestratorFilesInDir");function Pe(e,t,n,r){let o=new Map(e instanceof Map?e:Object.entries(e)),a=o.get("default")??O.default;for(let s of[t,n,r])for(let c of s)c.name&&o.set(c.name,wr(o.get(c.name)??yr(c.name,a),c));return o}i(Pe,"mergeOrchestrators");function yr(e,t){return{...t,name:e,displayName:e}}i(yr,"namedBase");function wr(e,t){return{...e,name:t.name??e.name,displayName:t.display_name??e.displayName,cues:{...e.cues,...t.cues},guidance:t.guidance??e.guidance}}i(wr,"applyOverride");function G(){return J().orchestrators}i(G,"registry");function si(e,t){let n=new Map;if(!t?.disableDefaultOrchestrators)for(let[r,o]of Object.entries(O))n.set(r,o);for(let[r,o]of e)n.set(r,o);G().orchestrators=n}i(si,"registerOrchestrators");function ci(e,t,n){G().scanDirs={user:e,project:t,shared:n??""}}i(ci,"setOrchestratorScanDirs");async function di(e){let t=e?.disableDefaultOrchestrators===!0,n=e?.notify,r=G().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):z(Ke,n),z(r.user,n),z(r.shared,n),z(r.project,n)]),l=Pe(t?new Map:O,o,[],[]);return Pe(l,a,s,c)}i(di,"scanAndMergeOrchestrators");function Se(e){let{orchestrators:t}=G();if(!e)return;let n=t.get(e);if(n)return n;let r=e.toLowerCase(),o=[];for(let[a,s]of t)a.toLowerCase()===r&&o.push(s);return o.length===1?o[0]:void 0}i(Se,"resolveOrchestrator");function li(){return[...G().orchestrators.values()].map(e=>e.name)}i(li,"getAvailableOrchestrators");import{z as f}from"zod";var Nt=f.union([f.boolean(),f.array(f.string())]),br={name:"is not a valid environment variable name",reserved:"is a reserved environment variable and cannot be overridden","not-string":"must be a string",control:"contains a control character"};function ae(e){return f.record(f.string(),f.unknown()).transform((t,n)=>at(t,{reserved:tt[e],report:i((r,o)=>n.addIssue({code:"custom",path:[r],message:br[o]}),"report")}))}i(ae,"envTable");var Bt={model:f.string().optional(),thinking:ot.optional(),extensions:Nt.optional(),skills:Nt.optional(),inlined_skills:f.array(f.string()).optional(),fork:f.boolean().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("pi").optional()},Cr=f.strictObject(Bt),vr=f.strictObject({model:f.string().optional(),variant:f.string().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("opencode").optional()}),xr=f.strictObject({model:f.string().optional(),thinking:f.string().optional(),env:ae("codex").optional()}),Rr=f.strictObject({model:f.string().optional(),thinking:f.string().optional(),tools:f.array(f.string()).optional(),exclude_tools:f.array(f.string()).optional(),env:ae("claude").optional()});function _e(e,t){if(e!==void 0)return{tools:e};if(t!==void 0)return{excludeTools:t}}i(_e,"toToolFilter");function ie(e){return e!==void 0&&Object.keys(e).length>0?e:void 0}i(ie,"nonEmptyEnv");var Tr=f.strictObject({include_context_files:f.boolean().optional(),pi:Cr.optional(),opencode:vr.optional(),codex:xr.optional(),claude:Rr.optional(),...Bt}).transform(({pi:e,opencode:t,codex:n,claude:r,...o})=>{let{model:a,thinking:s,tools:c,exclude_tools:d,env:l,...u}=o,{model:p,thinking:m,tools:v,exclude_tools:D,env:ue,...K}=A(e??{}),{model:R,variant:tn,tools:nn,exclude_tools:rn,env:on,...an}=A(t??{}),{model:sn,thinking:cn,env:dn,...ln}=A(n??{}),{model:un,thinking:pn,tools:fn,exclude_tools:mn,env:gn}=A(r??{}),ze=A({pi:p??a,opencode:R,codex:sn,claude:un}),Ge=A({pi:_e(v??c,D??d),opencode:_e(nn,rn),claude:_e(fn,mn)}),Ue=A({pi:m??s,opencode:tn,codex:cn,claude:pn}),Ve=A({pi:ie(X(l,ue)),opencode:ie(on),codex:ie(dn),claude:ie(gn)});return{...u,...K,...an,...ln,...Object.keys(ze).length>0?{modelsByFamily:ze}:{},...Object.keys(Ge).length>0?{toolsByFamily:Ge}:{},...Object.keys(Ue).length>0?{thinkingByFamily:Ue}:{},...Object.keys(Ve).length>0?{envByFamily:Ve}:{}}}),jt=f.strictObject({name:f.string().optional(),display_name:f.string().optional(),description:f.string().optional(),hidden:f.boolean().optional(),worktree_checkout_type:f.enum(Xe).optional(),system_prompt:f.string().optional(),harness_type:f.string().min(1).optional(),harness:Tr.optional()});function Er(e){return jt.parse(re(e))}i(Er,"parseAgentFile");var Ar={label:"Agent",problem:"is not a valid agent template and was skipped"};async function B(e,t,n){return oe(e,Er,r=>r.name,t,Ar,n)}i(B,"scanAgentFilesInDir");function se(e,t,n,r){let o=new Map;for(let[a,s]of e)o.set(a,{...s});return We(o,t),We(o,n),We(o,r),o}i(se,"mergeAgents");function We(e,t){for(let n of t){if(!n.name)continue;let r=e.get(n.name);if(r){let o={displayName:n.display_name,description:n.description??""},a=Lt(n),s=Or(r.modelsByFamily,a.modelsByFamily),c=Pr(r.toolsByFamily,a.toolsByFamily),d=Sr(r.thinkingByFamily,a.thinkingByFamily),l=_r(r.envByFamily,a.envByFamily);e.set(n.name,{...r,...a,...s?{modelsByFamily:s}:{},...c?{toolsByFamily:c}:{},...d?{thinkingByFamily:d}:{},...l?{envByFamily:l}:{},...o})}else e.set(n.name,{...Wr,...Lt(n)})}}i(We,"mergeAgentOverrides");function Or(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Or,"mergeModelsByFamily");function Pr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Pr,"mergeToolsByFamily");function Sr(e,t){let n={...e,...t};return Object.keys(n).length>0?n:void 0}i(Sr,"mergeThinkingByFamily");function _r(e,t){let n={...e};for(let[r,o]of Object.entries(t??{})){let a=r;n[a]=X(n[a],o)}return Object.keys(n).length>0?n:void 0}i(_r,"mergeEnvByFamily");function Lt(e){let{harness:t}=e,n={name:e.name,displayName:e.display_name,description:e.description,harnessType:e.harness_type,toolsByFamily:t?.toolsByFamily,extensions:t?.extensions,skills:t?.skills,inlinedSkills:t?.inlined_skills,modelsByFamily:t?.modelsByFamily,thinkingByFamily:t?.thinkingByFamily,envByFamily:t?.envByFamily,hidden:e.hidden,fork:t?.fork,includeContextFiles:t?.include_context_files,worktreeCheckoutType:e.worktree_checkout_type,systemPrompt:e.system_prompt};return A(n)}i(Lt,"fromTemplate");var Wr={name:"unknown",description:"",inlinedSkills:[],systemPrompt:""};var Fe=new Map([["general-purpose",{name:"general-purpose",displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",inlinedSkills:[],systemPrompt:""}]]);function S(){return J().agents}i(S,"registry");function U(e){let t=e.harness_type;if(t===void 0)return;let n=M();if(n.get(t)===void 0)return`harness_type "${t}" names no harness this session registered (registered: ${n.ids().join(", ")})`}i(U,"unregisteredHarness");function _i(e,t){let n=new Map;if(!t?.disableDefaultAgents)for(let[r,o]of Fe)n.set(r,o);for(let[r,o]of e)n.set(r,o);S().agents=n}i(_i,"registerAgents");function Wi(e,t,n){S().scanDirs={user:e,project:t,shared:n??""}}i(Wi,"setAgentScanDirs");async function Fr(e){let t=e?.disableDefaultAgents===!0,n=e?.notify,r=S().scanDirs,[o,a,s,c]=await Promise.all([t?Promise.resolve([]):B(qe,n,U),B(r.user,n,U),B(r.shared,n,U),B(r.project,n,U)]),l=se(t?new Map:Fe,o,[],[]);return se(l,a,s,c)}i(Fr,"scanAndMerge");async function $r(e,t){let n=await Fr(t),{agents:r}=S(),o=0;for(let[a,s]of n)r.has(a)||(r.set(a,s),o++);if(e){let a=await B(e,t?.notify,U),s=se(new Map,[],[],a);for(let[c,d]of s)r.has(c)||(r.set(c,d),o++)}return o}i($r,"discoverNewAgents");function V(e){let{agents:t}=S();if(!e)return{kind:"not-found"};if(t.has(e))return{kind:"resolved",key:e};let n=e.toLowerCase(),r=[];for(let o of t.keys())o.toLowerCase()===n&&r.push(o);return r.length===1?{kind:"resolved",key:r[0]}:r.length>1?{kind:"ambiguous",candidates:r}:{kind:"not-found"}}i(V,"resolveType");async function Fi(e,t,n){let r=V(e);return r.kind==="not-found"&&(await $r(t,{notify:n}),r=V(e)),r}i(Fi,"resolveTypeOrDiscover");function ce(e){let t=V(e);return t.kind==="resolved"?S().agents.get(t.key):void 0}i(ce,"getAgentConfig");function $i(){return[...S().agents.entries()].filter(([e,t])=>t.hidden!==!0).map(([e])=>e)}i($i,"getAvailableTypes");function Ii(){return[...S().agents.keys()]}i(Ii,"getAllTypes");function Ht(e,t,n,r){return{skills:e??n,extensions:t??r}}i(Ht,"applyGlobalDefaults");function Di(e,t=!0,n=!0){let r=ce(e);if(r){let{skills:a,extensions:s,...c}=r,d=Ht(a,s,t,n);return{displayName:c.displayName??c.name,description:c.description,...d}}return{displayName:"Agent",description:"General-purpose agent for complex, multi-step tasks",...Ht(void 0,void 0,t,n)}}i(Di,"getConfig");function zt(e){return typeof e=="string"&&e!==""?e:void 0}i(zt,"configuredString");function Ir(){let e=zt(j().agent.defaultAgentType);if(e===void 0)return ke;let t=V(e);return t.kind==="resolved"?t.key:ke}i(Ir,"resolveDefaultAgentType");function Dr(){let e=zt(j().agent.defaultOrchestrator);return e===void 0?F:e===F||Se(e)?e:F}i(Dr,"resolveDefaultOrchestratorName");function Ui(e){return typeof e=="string"&&e!==""?e:Ir()}i(Ui,"resolveAgentTypeParam");function Vi(){let e=Dr();return Se(e)??(e===F?O[F]:void 0)??O[F]}i(Vi,"resolveDefaultOrchestrator");function Gt(e){return ce(e)?.worktreeCheckoutType??j().agent.worktreeCheckoutType}i(Gt,"resolveWorktreeCheckoutType");function Ut(e){return typeof e=="string"&&e.trim()!==""?e:void 0}i(Ut,"harnessParam");function qi(e){let t=Ut(e);if(t!==void 0&&M().get(t)!==void 0)return fe(t,Z())?t:void 0}i(qi,"requestedHarnessId");function Ki(e){let t=Ut(e);if(t===void 0)return;let n=M();if(n.get(t)===void 0)throw new Error(`Unknown harness_type "${t}": valid harnesses are ${n.ids().join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);let r=Z();if(!fe(t,r))throw new Error(`Harness "${t}" cannot be launched on this machine \u2014 this machine can launch ${Qe(n.ids(),r).join(", ")}. Nothing was spawned. Omit \`harness_type\` to use the agent template's harness, then the configured default.`);return t}i(Ki,"resolveRequestedHarness");function Qi(e,t){if(t!==void 0)return t;let n=ce(e)?.harnessType??j().agent.harnessType;return M().resolve(n,Z())}i(Qi,"resolveHarnessType");function $e(e){return{kind:"recorded",phase:e.lifecycle.phase}}i($e,"recordedSettlement");function Vt(e,t){let n=e.worktree;return n!==null&&n.repoCwd!==void 0?{kind:"worktree",worktree:{workspaceId:n.workspaceId,worktreePath:n.path,repoCwd:n.repoCwd,branchName:e.branch},panes:t}:e.worktreeManaged?{kind:"worktree-unlocatable",branchName:e.branch,worktreePath:n?.path??null,panes:t}:{kind:"no-worktree",panes:t}}i(Vt,"planRecovered");async function Ie(e,t,n){if(t?.force!==void 0)return{kind:"removable"};let r=await e(n.worktreePath);return r===void 0?{kind:"kept",reason:{kind:"unverifiable",detail:"git status probe failed"}}:r?{kind:"kept",reason:{kind:"dirty"}}:{kind:"removable"}}i(Ie,"assessRemovability");function qt(e){if(e===void 0)return{kind:"allow",basis:{kind:"pane-absent"}};switch(e.state){case"working":return{kind:"refuse",basis:{kind:"pane-working"}};case"idle":case"blocked":case"done":case"unknown":return{kind:"allow",basis:{kind:"pane-not-working",state:e.state}};default:return he(e.state)}}i(qt,"recoveryGate");function De(e){switch(e.kind){case"pane-working":return{kind:"recovered-refusal",basis:e};case"pane-unreadable":return{kind:"unverifiable",detail:`the pane state could not be read (${e.detail})`};case"pane-absent":case"pane-not-working":case"forced":case"artifacts-ambiguous":return{kind:"unverifiable",detail:"the run's end could not be established"}}}i(De,"recoveryRefusalReason");function q(e,t,n,r,o){let a=n.kind==="worktree"?{kind:"kept",path:n.worktree.worktreePath}:n.kind==="worktree-unlocatable"?{kind:"kept",path:n.worktreePath}:{kind:"none"};return{agentId:e,source:t,outcome:{kind:"refused",reason:o.reason,forceable:o.forceable},branchName:n.kind==="worktree"?n.worktree.branchName:n.kind==="worktree-unlocatable"?n.branchName:void 0,settlement:r,panes:n.panes.map(s=>({kind:"open",paneId:s.paneId})),worktree:a,branch:{kind:"not-applicable"}}}i(q,"keptReport");function Kt(e,t,n,r){return{agentId:e,source:t,outcome:{kind:"refused",reason:{kind:"ambiguous-artifacts",candidates:r},forceable:!1},settlement:n,panes:[],worktree:{kind:"kept",path:null},branch:{kind:"not-applicable"}}}i(Kt,"ambiguousReport");function Me(e){return e?.force!==void 0?{forced:e.force}:{}}i(Me,"forcedFields");function Qt(e,t,n,r,o,a){return{agentId:e,source:t,outcome:{kind:"torn-down",...Me(a)},branchName:n.kind==="worktree"?n.worktree.branchName:void 0,settlement:r,panes:o.panes,worktree:o.worktree,branch:o.branch}}i(Qt,"assembleReport");function Ji(e){return e.outcome.kind==="refused"&&e.outcome.forceable}i(Ji,"isForceableRefusal");function Ne(e){return e.worktree.kind==="removed"||e.worktree.kind==="absent"?!0:e.worktree.kind==="none"?e.panes.every(t=>t.kind==="closed"):!1}i(Ne,"shouldDropSpawn");function de(e){return e.workspaceId!==void 0?"multiplexer":"git"}i(de,"removalMechanismOf");function Yt(e,t){if(t.kind==="retained")return{kind:"leave-open"};let n=t.workspaceId===void 0||e.workspaceId===t.workspaceId;if(t.mechanism==="multiplexer"&&n)return{kind:"closed-with-workspace"};switch(t.mechanism){case"multiplexer":case"git":case null:return e.paneCreated?{kind:"close"}:{kind:"leave-open"};default:return he(t.mechanism)}}i(Yt,"paneDispositionFor");var Mr=rt("cleanup");function Nr(e,t){let n=e.pane,r=n?.workspaceId??e.worktree?.workspaceId;if(!(n===null||r===void 0))return{multiplexer:t,name:e.branch,paneId:n.paneId,tabId:n.tabId,workspaceId:r,paneCreated:e.paneCreated}}i(Nr,"hostRefFor");async function Xt(e,t,n){let r=n!==void 0&&t.workspaceId!==void 0;return(r?await e.removeWorktree(n):await e.removeGitWorktree(t.worktreePath,t.repoCwd))?{kind:"removed",path:t.worktreePath}:{kind:"removal-failed",path:t.worktreePath,detail:r?"herdr did not confirm the worktree removal":"git did not confirm the worktree removal"}}i(Xt,"removeOwnedTree");async function le(e,t,n){let r=[];for(let o of t)switch(Yt(o,n).kind){case"closed-with-workspace":r.push({kind:"closed",paneId:o.paneId});break;case"close":await e.closePane(o),r.push({kind:"closed",paneId:o.paneId});break;case"leave-open":r.push({kind:"open",paneId:o.paneId});break}return r}i(le,"paneOutcomes");async function Br(e,t){let n=[];for(let r of t){let o;try{o=await e.observe(r)}catch{n.push({kind:"unknown",paneId:r.paneId});continue}n.push(o===void 0?{kind:"gone",paneId:r.paneId}:{kind:"open",paneId:r.paneId})}return n}i(Br,"paneOutcomesForAbsentTree");async function jr(e,t,n){if(t.kind==="no-worktree")return{panes:await le(e,t.panes,{kind:"removed",mechanism:null,workspaceId:void 0}),worktree:{kind:"none"},branch:{kind:"not-applicable"}};let{worktree:r,panes:o}=t,a=await Xt(e,r,n);return a.kind==="removed"?{panes:await le(e,o,{kind:"removed",mechanism:de(r),workspaceId:r.workspaceId}),worktree:a,branch:await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd})}:{panes:await le(e,o,{kind:"retained"}),worktree:a,branch:{kind:"not-applicable"}}}i(jr,"removeResources");function Be(e){return{async removeWorktree(t,n){let{worktree:r,panes:o,address:a}=t;try{if(!await e.worktreeExists(r.worktreePath))return{kind:"absent",path:r.worktreePath};let s=await Ie(e.isWorktreeDirty,n,r);if(s.kind==="kept")return{kind:"kept",path:r.worktreePath,reason:s.reason};let c=await Xt(e,r,a);if(c.kind==="removal-failed")return c;let d=de(r);await le(e,o,{kind:"removed",mechanism:d,workspaceId:r.workspaceId});let l=await e.deleteBranch({branch:r.branchName,worktreePath:r.worktreePath,repoCwd:r.repoCwd});return{kind:"removed",path:r.worktreePath,branchName:r.branchName,via:d,branch:l}}catch(s){return{kind:"removal-failed",path:r.worktreePath,detail:W(s)}}}}}i(Be,"createWorktreeTeardown");async function Lr(e,t,n){if(t.kind!=="worktree"||n===void 0||de(t.worktree)!=="multiplexer")return{kind:"exclusive"};try{let r=await e.otherTenants({workspaceId:n.workspaceId,checkoutPath:t.worktree.worktreePath},n.paneId);return r.length===0?{kind:"exclusive"}:{kind:"shared",tenants:r}}catch(r){return{kind:"unreadable",detail:W(r)}}}i(Lr,"spaceTenancy");function Hr(e,t){let n=e===void 0?[]:[e];for(let r of t===void 0?[]:t.execution.history)n.some(o=>o.paneId===r.host.paneId)||n.push(r.host);return n}i(Hr,"environmentPanes");function zr(e,t){if(e===void 0)return[];let n=e.execution.history.map(o=>({harness:o.harness,paneId:o.host.paneId,cwd:o.cwd})),r=e.execution.harness===void 0?[]:[{harness:e.execution.harness,paneId:t.pane?.paneId??null,cwd:t.worktree?.path??null}];return[...n,...r]}i(zr,"teardownRuns");function aa(e){let t=Be(e);function n(a,s){return{kind:"discovered",basis:s,deliverable:e.deliverable(a)}}i(n,"recovered");async function r(a,s,c,d){if(c!==void 0){let p=$e(c);return it(c.lifecycle)?{kind:"torn-down",settlement:p}:{kind:"refused",settlement:p,reason:{kind:"agent-active",phase:c.lifecycle.phase},forceable:!1}}if(d?.force!==void 0)return{kind:"torn-down",settlement:n(a,{kind:"forced"})};let l;if(s.pane!==null)try{l=await e.observe(s.pane)}catch(p){let m={kind:"pane-unreadable",detail:W(p)};return{kind:"refused",settlement:n(a,m),reason:De(m),forceable:!0}}let u=qt(l);return u.kind==="allow"?{kind:"torn-down",settlement:n(a,u.basis)}:{kind:"refused",settlement:n(a,u.basis),reason:De(u.basis),forceable:!0}}i(r,"verdictFor");async function o(a,s,c){let d=s.getSpawn(a),l=await e.locate(a,d);if(l.kind==="not-found")throw new Error(`Agent ${a} not found.`);if(l.kind==="ambiguous")return Kt(a,d===void 0?"recovered":"tracked",d===void 0?n(a,{kind:"artifacts-ambiguous"}):$e(d),l.candidates.map(R=>R.worktreePath));let u=Nr(l,e.multiplexer),p=Vt(l,Hr(u,d)),m=await r(a,l,d,c);if(m.kind==="refused")return q(a,l.source,p,m.settlement,{reason:m.reason,forceable:m.forceable});let v=await Lr(e,p,u);if(v.kind!=="exclusive")return q(a,l.source,p,m.settlement,{reason:v.kind==="shared"?{kind:"space-in-use",tenants:v.tenants}:{kind:"unverifiable",detail:`could not check the workspace for other agents (${v.detail})`},forceable:!1});let D=zr(d,l);if(D.length>0)try{await e.teardownEnvironment({subagentId:a,runs:D})}catch(R){Mr.warn("environment teardown failed during cleanup",{spawnId:a,error:W(R)})}if(p.kind==="worktree-unlocatable"){if(p.worktreePath!==null&&!await e.worktreeExists(p.worktreePath)){let R={agentId:a,source:l.source,outcome:{kind:"torn-down",...Me(c)},branchName:p.branchName,settlement:m.settlement,panes:await Br(e,p.panes),worktree:{kind:"absent",path:p.worktreePath},branch:{kind:"not-applicable"}};return Ne(R)&&d!==void 0&&s.dropSpawn(d),R}return q(a,l.source,p,m.settlement,{reason:{kind:"unverifiable",detail:"missing worktree path or repo cwd"},forceable:!1})}if(p.kind==="worktree"){let R=await Ie(e.isWorktreeDirty,c,p.worktree);if(R.kind==="kept")return q(a,l.source,p,m.settlement,{reason:R.reason,forceable:!0})}let ue=await jr(e,p,u),K=Qt(a,l.source,p,m.settlement,ue,c);return Ne(K)&&d!==void 0&&s.dropSpawn(d),K}return i(o,"cleanupAgent"),{...t,cleanupAgent:o}}i(aa,"createCleanup");import*as Zt from"node:path";async function Gr(e,t,n){let r=await ve(e,["rev-parse","--verify","--quiet",`refs/heads/${n}`],t,E);return r===void 0?!0:r.code===0}i(Gr,"branchExisted");async function Jt(e,t){let n=t.branch.trim();if(n==="")throw new h("worktree checkout requires a branch name");let r=await te(e,t.repoCwd),o=Zt.resolve(t.path),a=t.materialization??Ye,s=t.dirtyCheckout??Q,c=await Gr(e,r,n),d=await ve(e,["worktree","add",...Ct(a),"-b",n,o,t.base??"HEAD"],r,E);if(d===void 0||d.code!==0)throw await $(e,r,o),c||await N(e,n,r),new h(d===void 0?`git worktree add for "${n}" could not run (worktree removed)`:`git worktree add for "${n}" failed (worktree removed): ${(d.stderr||d.stdout||`exit ${d.code}`).slice(0,300)}`);let l=await yt(e,["branch","--show-current"],o);if(l!==n)throw await $(e,r,o),await N(e,n,r),new h(l===void 0?`worktree created at ${o} but its branch could not be verified (worktree removed)`:`worktree created at ${o} is on branch "${l||"(detached)"}", not the requested "${n}" (worktree removed). The branch "${l}" still exists.`);let u;try{u=await vt(e,o,a,s)}catch(p){await $(e,r,o),await N(e,n,r);let m=p instanceof Error?p.message:String(p);throw new h(`worktree created but ${a} materialization failed (worktree removed): ${m}`)}if(u.kind==="cow-fallback"){let p=s==="dirty"?" The parent's uncommitted work was not carried over.":"";t.notify?.(`[cowboy] ${u.reason}${p} Nothing is shared with the parent checkout.`,"warning")}return{path:o,branch:n,repoCwd:r,materialization:u}}i(Jt,"createWorktreeCheckout");function Ca(e){return e.kind==="checkout"?e.branch:me(e.taskSlug??Je(e.type),e.id)}i(Ca,"spawnAgentName");function Ur(e){try{let t=_.statSync(e,{bigint:!0});return`${t.dev}:${t.ino}`}catch{return I.resolve(e)}}i(Ur,"canonicalRepoKey");async function va(e){let t=await Le.allocate(e.pi,{naming:{kind:"generated",taskSlug:e.taskSlug??e.agentType,id:e.spawnId},parentCwd:e.parentCwd,worktreeRoot:e.worktreeRoot,materialization:e.materialization,dirtyCheckout:Gt(e.agentType),notify:e.notify,host:e.host}),n=t.worktree,r=t.hostRef;return n===void 0||r===void 0?{kind:"parent-cwd"}:{kind:"owned",hostRef:r,worktree:n}}i(va,"provisionOwnedCheckout");var Le=class e{static{i(this,"AgentSandbox")}branch;projectTrusted;host;placement;current={kind:"bound"};constructor(t,n,r,o){this.host=t,this.placement=n,this.branch=r,this.projectTrusted=o}static async allocate(t,n){let{naming:r,parentCwd:o,worktreeRoot:a,materialization:s,dirtyCheckout:c,notify:d,host:l}=n,u=r.kind==="generated"?me(r.taskSlug,r.id):r.branch.trim();if(r.kind==="explicit"&&u==="")throw new Error("explicit worktree naming requires a branch name");let p;try{p=await te(t,o)}catch{return d?.("[cowboy] Parent is not inside a git repository \u2014 spawning in the parent cwd without a worktree","warning"),new e(l,{kind:"parent-cwd"},u,!0)}let m=await qr(t,{repoCwd:p,path:I.join(et(a,p),u),branch:u,materialization:s,dirtyCheckout:c,notify:d,host:l});return new e(l,{kind:"worktree",checkout:{path:m.path,branch:m.branch,repoCwd:m.repoCwd},ref:m.ref},u,!0)}get state(){return this.current}get worktree(){return this.placement.kind==="worktree"?{path:this.placement.checkout.path,branch:this.placement.checkout.branch}:void 0}get hostRef(){return this.placement.kind==="worktree"?this.placement.ref:void 0}async teardown(t,n){let r=this.placement;if(r.kind==="parent-cwd")return this.current={kind:"destroyed"},{kind:"absent"};if(this.current.kind==="destroyed")return{kind:"absent",path:r.checkout.path};let o=await Be(Yr(t,this.host)).removeWorktree({worktree:{workspaceId:r.ref.workspaceId,worktreePath:r.checkout.path,repoCwd:r.checkout.repoCwd,branchName:r.checkout.branch},address:r.ref,panes:[r.ref]},n);return this.current=Vr(o),o}};function Vr(e){switch(e.kind){case"kept":return{kind:"preserved",reason:e.reason};case"removed":case"absent":return{kind:"destroyed"};case"removal-failed":return{kind:"teardown-failed",detail:e.detail}}}i(Vr,"stateAfterTeardown");async function qr(e,t){let n=I.resolve(t.path);return _.mkdirSync(I.dirname(n),{recursive:!0}),st().run(Ur(t.repoCwd),()=>Qr(e,t.host,{...t,path:n}))}i(qr,"createAdoptedWorktree");async function Kr(e,t,n){let r=await bt(e,t),o=pe(n),a=o===void 0?void 0:r?.find(s=>pe(s.path)===o);if(a!==void 0)return{path:a.path,branch:Ze(a),repoCwd:t,materialization:{kind:"reused"}}}i(Kr,"existingCheckout");async function Qr(e,t,n){let{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:d}=n,l=await Kr(e,r,o),u;if(l!==void 0)u=l;else try{u=await Jt(e,{repoCwd:r,path:o,branch:a,materialization:s,dirtyCheckout:c,notify:d})}catch(m){throw je(m,await en(e,r,o))}let p;try{p=await t.hostAt({unit:"pane",cwd:u.path,label:a,name:a,checkout:{path:u.path,repoCwd:r,branch:u.branch}})}catch(m){if(l!==void 0)throw je(m,"existing worktree kept");let v=await en(e,r,u.path),D=await N(e,u.branch,r);throw je(m,`${v}. ${He(u.branch,D)}`)}return{path:u.path,branch:u.branch,repoCwd:r,materialization:u.materialization,ref:p}}i(Qr,"adoptWorktree");function Yr(e,t){return{isWorktreeDirty:i(n=>Pt(e,n),"isWorktreeDirty"),worktreeExists:i(async n=>_.existsSync(n),"worktreeExists"),removeWorktree:i(n=>t.release(n,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(n,r)=>(await $(e,r,n),!_.existsSync(n)),"removeGitWorktree"),deleteBranch:i(n=>At(e,n,r=>t.isAttached(r,{repoCwd:n.repoCwd})),"deleteBranch"),closePane:i(async n=>{await t.release(n,"placement")},"closePane"),teardownEnvironment:i(async()=>{},"teardownEnvironment")}}i(Yr,"cleanupDeps");async function en(e,t,n){return await $(e,t,n),_.existsSync(n)?`worktree ${n} NOT removed \u2014 inspect it manually`:`worktree ${n} removed`}i(en,"removeFailedCheckout");function je(e,t){return new Error(`could not create the herdr worktree: ${W(e)}
|
|
24
24
|
|
|
25
25
|
Launch-failure cleanup: ${t}.`)}i(je,"createFailureMessage");function He(e,t){switch(t.kind){case"deleted":return`branch ${e} deleted`;case"kept":return`branch ${e} kept (${t.reason})`;case"delete-failed":return`branch ${e} NOT deleted \u2014 ${t.detail}`;case"not-applicable":return`branch ${e} already gone`}}i(He,"formatLaunchedBranchOutcome");function xa(e){switch(e.kind){case"removed":return e.via==="multiplexer"?`Launch-failure cleanup: worktree ${e.path} removed \u2014 its workspace, tab, and pane were closed with it. ${He(e.branchName,e.branch)}.`:`Launch-failure cleanup: worktree ${e.path} removed. ${He(e.branchName,e.branch)}.`;case"kept":return`Launch-failure cleanup: worktree ${e.path} KEPT \u2014 ${St(e.reason)}. No agent spawn exists for it, so extension cleanup cannot see it \u2014 inspect and remove it manually.`;case"removal-failed":return`Launch-failure cleanup FAILED for worktree ${e.path}: ${e.detail} \u2014 it may still exist, and no agent spawn exists for it, so inspect it manually.`;case"absent":return"Launch-failure cleanup: no worktree residue was left behind."}}i(xa,"formatLaunchCleanupNote");export{Zr as a,ht as b,b as c,yt as d,L as e,no as f,te as g,$ as h,bt as i,ao as j,xt as k,wo as l,At as m,Pt as n,Ro as o,St as p,Fe as q,_i as r,Wi as s,Fr as t,Fi as u,ce as v,$i as w,Ii as x,Di as y,O as z,rr as A,jo as B,Lo as C,Vo as D,si as E,ci as F,di as G,li as H,Ir as I,Ui as J,Vi as K,Gt as L,qi as M,Ki as N,Qi as O,Ji as P,aa as Q,Ca as R,va as S,Le as T,qr as U,xa as V};
|
|
26
|
-
//# sourceMappingURL=chunk-
|
|
26
|
+
//# sourceMappingURL=chunk-3FQQMEHD.js.map
|
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
import{A as bt,B as xt,C as At,D as V,I as St,J as Q,K as Tt,M as Ae,N as Rt,O as X,b as pt,c as ht,e as gt,g as mt,i as ft,k as xe,l as yt,p as wt,u as vt,v as z,w as kt}from"./chunk-UG3ZH2M5.js";import{$ as at,A as Xe,Aa as ct,Ca as j,Ga as ut,J as me,Ja as be,L as rt,M as fe,P as ye,Q as ot,S as K,T,U as I,W as st,_ as it,b as pe,c as We,ja as b,k as L,ka as G,l as Ue,la as y,m as qe,n as he,na as w,oa as O,p as Ke,pa as we,qa as ve,sa as dt,u as Ge,v as Ye,va as ke,wa as Y,x as ze,xa as _,y as Ve,ya as lt,z as Qe}from"./chunk-M5B2YQME.js";import{J as tt,K as nt,a as r,l as Fe,p as N,r as ge,s as Ze,v as Je,w as F,y as et}from"./chunk-AOUEQXPY.js";import{visibleWidth as Ee}from"@earendil-works/pi-tui";var Se="\u{1F920}",Ot="\u{1F404}",yn="\u{1F4A9}",wn=2,vn=1e3,Z=Ee(Ot),kn="76;175;80";function bn(e){return`\x1B[48;2;${kn}m${e}\x1B[49m`}r(bn,"greenBackground");function _t(e){return e===0?0:Math.max(wn,Math.ceil(Math.sqrt(2*e)))}r(_t,"pastureEdge");function Ct(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Ct,"emptyPasture");function xn(e,t){let n=_t(e.cows+e.droppings),o=Ct(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(xn,"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 An(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(An,"neighboursOf");function Et(e,t){return An(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Et,"openNeighboursOf");function Sn(e,t){let n=J(e,"cow").filter(d=>Et(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Et(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(Sn,"moveHerd");function It(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(It,"placeAtRandom");function Tn(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}It(e,"cow",-s,o),It(e,"dropping",-d,o)}r(Tn,"reconcileCounts");function Rn(e,t,n){if(e===null)return xn(t,n);let o=_t(t.cows+t.droppings),i=Ct(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 Tn(i,t.cows,t.droppings,n),i}r(Rn,"reconcilePasture");var En={anchor:"top-right",width:Ee(Se),get offsetX(){return O()?.cowboyOffsetX??0},nonCapturing:!0},In={anchor:"top-right",offsetY:1,get width(){return O()?.pastureWidth??0},nonCapturing:!0};function On(e){return e==="cow"?Ot:e==="dropping"?yn:" ".repeat(Z)}r(On,"cellText");function _n(e,t){return e.map(n=>t(n.map(On).join("")))}r(_n,"drawnRows");function Cn(){return ve().list(["spawned"]).length}r(Cn,"liveAgentCount");function Pn(){return ve().list(ot).length}r(Pn,"endedAgentCount");function Mn(){return{live:Cn(),ended:Pn()}}r(Mn,"agentCounts");function $n(){return w().agent.grazingEnabled}r($n,"grazingEnabled");var Te=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 Ee(Se)}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(),[Se]}pastureRows(){return this.frame(),_n(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(),vn))}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:Sn(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:Rn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Re=class{static{r(this,"PastureView")}render(){return O()?.pastureRows()??[]}invalidate(){}};function Pt(e){Ie(),e.custom(t=>{let n=new Te(t,Mn,$n,bn,Math.random);return we(n),n},{overlay:!0,overlayOptions:En,onHandle:r(t=>O()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Re,{overlay:!0,overlayOptions:In,onHandle:r(t=>O()?.attachPasture(t),"onHandle")})}r(Pt,"showExtensionIndicator");function Ie(){let e=O();we(null),e?.dispose()}r(Ie,"hideExtensionIndicator");function ee(){return w().agent.extensionEnabled}r(ee,"isExtensionEnabled");function Nn(){return ee()&&w().agent.showActiveIndicator}r(Nn,"isActiveIndicatorShown");function te(e){Nn()?Pt(e):Ie()}r(te,"syncExtensionIndicator");function go(e,t){w().mutate.agent.setShowActiveIndicator(t),te(e)}r(go,"setShowActiveIndicator");import{Type as E}from"typebox";import{Text as Gr}from"@earendil-works/pi-tui";import{Type as p}from"typebox";var Hn="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.",Dn=`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.`,Bn=`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.`,Ln=`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.`,jn='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.',Oe=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:jn}),Wn=p.Object({prompt:p.String({description:Hn}),task_name:p.String({description:Dn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:Bn})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:Ln})),worktree:p.Optional(Oe)},{additionalProperties:!1,required:["prompt","task_name"]}),H=p.Object({agents:p.Array(Wn,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var h={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},_e=Object.values(h),v={type:"json_schema",strict:"prefer"};var Ce="_configuredModel",Pe="_configuredThinking";function C(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(C,"readModelKey");function ne(e){return C(e.thinking)??C(e[Pe])}r(ne,"readThinkingRequest");function re(e){let t=C(e.model);if(t)return{source:"call",key:t};let n=C(e[Ce]);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 Un(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(Un,"undeclaredLevelWarning");function Mt(e,t){let n=Un(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Mt,"resolvedModel");function qn(e){return`No API key found for "${e}"`}r(qn,"missingCredential");function $t(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:N(o)}}return!Fe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:qn(t.provider)}}r($t,"probeCredentials");function Me(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Me,"refusal");function $e(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return W(i);let d=$t(n,o);if(d.verdict!=="unusable")return Mt(o,i);throw new Error(Me(`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=$t(n,a);if(s.verdict!=="unusable")return Mt(a,i);throw e.source==="call"?new Error(Me(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Me(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r($e,"resolvePiModel");async function Fn(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Fn,"harnessModels");function Kn(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(Kn,"undeclaredLevelWarning");async function Nt(e,t){if(!e)return W(t.thinking);let n=await Fn(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=Kn(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(Nt,"resolveForeignModel");async function se(e,t){let{harness:n}=t;if(et(n))return $e(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Nt(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 Ne=`
|
|
1
|
+
import{A as bt,B as xt,C as At,D as V,I as St,J as Q,K as Tt,M as Ae,N as Rt,O as X,b as pt,c as ht,e as gt,g as mt,i as ft,k as xe,l as yt,p as wt,u as vt,v as z,w as kt}from"./chunk-3FQQMEHD.js";import{$ as at,A as Xe,Aa as ct,Ca as j,Ga as ut,J as me,Ja as be,L as rt,M as fe,P as ye,Q as ot,S as K,T,U as I,W as st,_ as it,b as pe,c as We,ja as b,k as L,ka as G,l as Ue,la as w,m as qe,n as he,na as v,oa as O,p as Ke,pa as we,qa as ve,sa as dt,u as Ge,v as Ye,va as ke,wa as Y,x as ze,xa as _,y as Ve,ya as lt,z as Qe}from"./chunk-UEMXTMQN.js";import{J as tt,K as nt,a as r,l as Fe,p as N,r as ge,s as Ze,v as Je,w as F,y as et}from"./chunk-AOUEQXPY.js";import{visibleWidth as Ee}from"@earendil-works/pi-tui";var Se="\u{1F920}",Ot="\u{1F404}",vn="\u{1F4A9}",kn=2,bn=1e3,Z=Ee(Ot),xn="76;175;80";function An(e){return`\x1B[48;2;${xn}m${e}\x1B[49m`}r(An,"greenBackground");function _t(e){return e===0?0:Math.max(kn,Math.ceil(Math.sqrt(2*e)))}r(_t,"pastureEdge");function Ct(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Ct,"emptyPasture");function Sn(e,t){let n=_t(e.cows+e.droppings),o=Ct(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(Sn,"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 Tn(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(Tn,"neighboursOf");function Et(e,t){return Tn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(Et,"openNeighboursOf");function Rn(e,t){let n=J(e,"cow").filter(d=>Et(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=Et(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(Rn,"moveHerd");function It(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(It,"placeAtRandom");function En(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}It(e,"cow",-s,o),It(e,"dropping",-d,o)}r(En,"reconcileCounts");function In(e,t,n){if(e===null)return Sn(t,n);let o=_t(t.cows+t.droppings),i=Ct(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 En(i,t.cows,t.droppings,n),i}r(In,"reconcilePasture");var On={anchor:"top-right",width:Ee(Se),get offsetX(){return O()?.cowboyOffsetX??0},nonCapturing:!0},_n={anchor:"top-right",offsetY:1,get width(){return O()?.pastureWidth??0},nonCapturing:!0};function Cn(e){return e==="cow"?Ot:e==="dropping"?vn:" ".repeat(Z)}r(Cn,"cellText");function Pn(e,t){return e.map(n=>t(n.map(Cn).join("")))}r(Pn,"drawnRows");function Mn(){return ve().list(["spawned"]).length}r(Mn,"liveAgentCount");function $n(){return ve().list(ot).length}r($n,"endedAgentCount");function Nn(){return{live:Mn(),ended:$n()}}r(Nn,"agentCounts");function Hn(){return v().agent.grazingEnabled}r(Hn,"grazingEnabled");var Te=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 Ee(Se)}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(),[Se]}pastureRows(){return this.frame(),Pn(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(),bn))}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:Rn(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:In(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Re=class{static{r(this,"PastureView")}render(){return O()?.pastureRows()??[]}invalidate(){}};function Pt(e){Ie(),e.custom(t=>{let n=new Te(t,Nn,Hn,An,Math.random);return we(n),n},{overlay:!0,overlayOptions:On,onHandle:r(t=>O()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Re,{overlay:!0,overlayOptions:_n,onHandle:r(t=>O()?.attachPasture(t),"onHandle")})}r(Pt,"showExtensionIndicator");function Ie(){let e=O();we(null),e?.dispose()}r(Ie,"hideExtensionIndicator");function ee(){return v().agent.extensionEnabled}r(ee,"isExtensionEnabled");function Dn(){return ee()&&v().agent.showActiveIndicator}r(Dn,"isActiveIndicatorShown");function te(e){Dn()?Pt(e):Ie()}r(te,"syncExtensionIndicator");function ko(e,t){v().mutate.agent.setShowActiveIndicator(t),te(e)}r(ko,"setShowActiveIndicator");import{Type as E}from"typebox";import{getMarkdownTheme as Bn,keyHint as Ln}from"@earendil-works/pi-coding-agent";import{Container as jn,Markdown as Wn,Spacer as Un,Text as Mt}from"@earendil-works/pi-tui";var $t=r((e,t,n)=>{let o=typeof e=="object"&&typeof e.content=="string"?e.content:"",i=o.indexOf(`
|
|
2
|
+
|
|
3
|
+
`),a=(i<0?o:o.slice(0,i)).trim(),s=i<0?"":o.slice(i+2).trim(),d=/\b(error|stopped)\b/i.test(a),l=`${n.fg(d?"error":"success",d?"\u2717":"\u2713")} ${n.fg("toolTitle",n.bold(a||"Cowboy agent report"))}`;if(!t.expanded||!s){let g=s?n.fg("muted",` (${"keyHint"in t&&typeof t.keyHint=="function"?t.keyHint("app.tools.expand","to expand"):Ln("app.tools.expand","to expand")})`):"";return new Mt(`${l}${g}`,t.outputPad,0)}let f=new jn;return f.addChild(new Mt(l,t.outputPad,0)),f.addChild(new Un(1)),f.addChild(new Wn(s,t.outputPad,0,Bn())),f},"renderSubagentResult");import{Type as p}from"typebox";var qn="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.",Fn=`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.`,Kn=`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.`,Gn=`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.`,Yn='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.',Oe=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:Yn}),zn=p.Object({prompt:p.String({description:qn}),task_name:p.String({description:Fn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:Kn})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:Gn})),worktree:p.Optional(Oe)},{additionalProperties:!1,required:["prompt","task_name"]}),H=p.Object({agents:p.Array(zn,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var h={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},_e=Object.values(h),k={type:"json_schema",strict:"prefer"};var Ce="_configuredModel",Pe="_configuredThinking";function C(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(C,"readModelKey");function ne(e){return C(e.thinking)??C(e[Pe])}r(ne,"readThinkingRequest");function re(e){let t=C(e.model);if(t)return{source:"call",key:t};let n=C(e[Ce]);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 Vn(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(Vn,"undeclaredLevelWarning");function Nt(e,t){let n=Vn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Nt,"resolvedModel");function Qn(e){return`No API key found for "${e}"`}r(Qn,"missingCredential");function Ht(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:N(o)}}return!Fe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Qn(t.provider)}}r(Ht,"probeCredentials");function Me(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Me,"refusal");function $e(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return W(i);let d=Ht(n,o);if(d.verdict!=="unusable")return Nt(o,i);throw new Error(Me(`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=Ht(n,a);if(s.verdict!=="unusable")return Nt(a,i);throw e.source==="call"?new Error(Me(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Me(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r($e,"resolvePiModel");async function Xn(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Xn,"harnessModels");function Zn(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(Zn,"undeclaredLevelWarning");async function Dt(e,t){if(!e)return W(t.thinking);let n=await Xn(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=Zn(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(Dt,"resolveForeignModel");async function se(e,t){let{harness:n}=t;if(et(n))return $e(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Dt(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 Ne=`
|
|
2
4
|
|
|
3
5
|
---
|
|
4
6
|
|
|
5
|
-
`,
|
|
6
|
-
`)[0].slice(0,80)||a.slice(0,80),agentType:i,resolvedType:l.key,orchestrator:c,fork:z(i)?.fork??!1,modelChoice:oe(
|
|
7
|
+
`,Jn={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function R(e){let{items:t}=e;tr(t,e),await e.prepare?.();let n=er(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(Ne),{[e.detailsKey]:o})}r(R,"runBatch");function er(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(er,"batchSteps");function tr(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=Jn[n];throw new Error(`${t} received duplicate ${a.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(tr,"rejectRepeatedKeys");var Bt={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"},nr={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 rr(e){if(!T(e)||e.status!=="stopped")return Bt.agent;let{stop:t}=e;return e.phase==="never-started"?nr[t.initiator]:Bt[t.initiator]}r(rr,"stopNote");function Lt(e){return!T(e)||e.status!=="stopped"?"":` (${rr(e)})`}r(Lt,"getStatusNote");async function or(e,t){let n=j();return n!==null?await n.list(e):await _().require(e).listModels({pi:b(),modelCatalog:lt(t.modelRegistry)})}r(or,"readHarnessModelList");function ae(e){return async t=>{let n=await or(t,e),o=nt(n);return o!==void 0&&e.hasUI&&e.ui.notify(o,"warning"),tt(n)}}r(ae,"harnessModelReader");function P(e=w()){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(P,"formatActiveAgents");function He(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-st(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(He,"buildAgentDetails");function sr(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 Je(e)}}r(sr,"settledOutcome");function ir(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${I(e.lifecycle)}]`}r(ir,"settledHeadline");function ar(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",At({outcome:sr(t),statusNote:Lt(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?wt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:v().multiplexer||rt}))}r(ar,"formatResultContent");async function dr(e,t){let n=Ye(e);if(n.kind!=="picked")return n;let o=pe(n.path),a=(o===void 0?null:await ft(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:Ge(a)}}r(dr,"resolveWorktreeRequest");var De=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=ze(s),c=Tt(),l=await vt(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=Rt(t.harness_type),g=X(l.key,f),u=ne(t),m=await se(re(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:u,listModels:ae(n)});for(let S of m.notices)n.ui.notify(S,"warning");let y=await dr(t.worktree,n),A=t.run_in_background!==!1;return new e({ctx:n,toolCallId:o,taskSlug:d,prompt:a,description:a.split(`
|
|
8
|
+
`)[0].slice(0,80)||a.slice(0,80),agentType:i,resolvedType:l.key,orchestrator:c,fork:z(i)?.fork??!1,modelChoice:oe(m.resolved),requestedHarness:f,worktree:y,isBackground:A})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:a}=this.intent,s=b(),d=w().mintSpawnId(),c=await this.resolveWorktree(s,d),l=this.intent.modelChoice?.thinking??void 0,f=Ze(this.intent.modelChoice),{agentId:g,spawn:u}=await dt().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=He(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:`${ir(u)}
|
|
7
9
|
|
|
8
|
-
${
|
|
9
|
-
`)}r(
|
|
10
|
-
`).map(n=>n.trim()).filter(n=>n!==""):[]}r(
|
|
11
|
-
`:"";return
|
|
12
|
-
${g.output}`:"")}}catch(g){let f=g instanceof Error?g.message:String(g);return Er(f)?{outcome:{kind:"conflict",branch:u,target:a,files:Ir(f)},text:`"${u}": ${f}`}:Or(f,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${f}`}:{outcome:{kind:"failed",branch:u,error:f},text:`"${u}": ${f}`}}},"handleItem")})}r(_r,"executeMergeBranchTool");import{Type as de}from"typebox";var Cr="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.",Pr="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.",en=de.Object({agent_ids:de.Array(de.String({minLength:1}),{minItems:1,description:Cr}),message:de.String({description:Pr})},{additionalProperties:!1,required:["agent_ids","message"]});var tn={name:h.steerAgent,label:h.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:en,execute:$r,constrainedSampling:v};function Mr(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(Mr,"steerSeverity");async function $r(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:Mr,prepare:r(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:r(async s=>{let d=y().getSpawn(s);if(!d){let m=`not found. Active agents: ${P()}`;return{outcome:{kind:"refused",agentId:s,reason:m},text:`Agent ${s} was not steered: ${m}`}}let c=I(d.lifecycle),l;try{l=await y().steer(s,a)}catch(m){l={kind:"refused",reason:`steering failed: ${N(m)}`}}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 k=c!=="spawned"&&d.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:s},text:k?`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($r,"executeSteerAgentTool");function hi(e,t,n){return he(e.ids(),t).filter(o=>o!==n)}r(hi,"handoverTargets");function nn(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.`}}:qe(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(nn,"resolveHandoverTarget");import{Type as x}from"typebox";var Nr="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.",Hr=`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.`,Dr=`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.`,Br="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",rn=x.Object({agent_id:x.String({minLength:1,description:Nr}),harness_type:x.String({description:Hr}),model:x.Optional(x.Union([x.String(),x.Null()],{description:Dr})),thinking:x.Optional(x.Union([x.String(),x.Null()],{description:Br}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Lr(e,t){let n=nn(e.harness_type,_(),ct());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:N(i)}}}}r(Lr,"resolveIntent");function jr(e,t){return`Agent ${e} ${Wr(t)}`}r(jr,"renderHandoverOutcome");function Wr(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":it(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(Wr,"handoverReport");async function Ur(e,t,n,o,i){let a=t.agent_id.trim(),s=await Lr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await y().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return D(at(d),jr(a,d),{agentId:a,outcome:d})}r(Ur,"executeHandoverAgentTool");var on={name:h.handoverAgent,label:h.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:rn,execute:Ur,constrainedSampling:v};import{Text as qr}from"@earendil-works/pi-tui";var Fr={success:"\u2713",warning:"!",error:"\u2717"};function Kr(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
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
${ar(u)}`,details:S}}let m=c;if(u.lifecycle.phase==="queued"){let S=w().listAgents(ye).filter(wn=>wn.lifecycle.phase==="spawned").length,ce=V(this.intent.orchestrator.cues,"queued",xt({agentId:g,worktree:m,queueRunning:S})),ue=He(u);return ue.agentId=g,ue.status="queued",{message:`[Agent queued] ${ce}`,details:ue}}let y=V(this.intent.orchestrator.cues,"spawned",bt({agentId:g,worktree:m})),A=He(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 mt(t,G().cwd).catch(()=>{});if(o===void 0)return;let i=Xe(v().agent.worktreeRoot,o);return{kind:"owned",path:Qe(i,this.intent.taskSlug,n),branch:Ve(this.intent.taskSlug,n)}}};async function jt(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=>De.parse(l,t,n)));lr(a);let s=await Promise.all(a.map(l=>l.run(o))),d=s.map(l=>l.message).join(Ne),c={agents:s.map(l=>l.details)};return{message:d,details:c}}r(jt,"runDelegationBatch");function lr(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(lr,"rejectRepeatedTaskSlugs");var q=globalThis.__PI_COWBOY_DEV_MODE__===!0;import{Type as Be}from"typebox";var cr="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).",Wt=Be.Object({agent_ids:Be.Array(Be.String({minLength:1}),{minItems:1,description:cr})},{additionalProperties:!1,required:["agent_ids"]});function ur(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(ur,"delegationSeverity");function pr(e){return{...e,agents:e.agents.map(t=>{let n={...t};return delete n.worktree,n})}}r(pr,"withoutWorktreeTarget");async function qt(e,t,n,o,i){let{message:a,details:s}=await jt(q?t:pr(t),i,e,n);return D(ur(s),a,s)}r(qt,"executeAgentTool");var Ft={name:h.stopAgent,label:h.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:Wt,execute:mr,constrainedSampling:k};function hr(e){switch(e.kind){case"stopped":return"success";case"failed":return"error";case"already-settled":case"unknown":case"refused":return"warning"}}r(hr,"stopSeverity");function gr(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(gr,"renderStopOutcome");async function mr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:gr,severity:hr,handleItem:r(async s=>{let d=w().getSpawn(s);if(!d)return{kind:"unknown",agentId:s,activeAgents:P()};if(w().isHandingOver(s))return{kind:"refused",agentId:s,reason:"it is being handed over to another harness \u2014 wait for the handover to finish, then stop the new run if you still want it stopped."};if(!K(d.lifecycle.phase))return{kind:"already-settled",agentId:s,status:I(d.lifecycle),activeAgents:P()};try{return await w().abort(s,"agent")?{kind:"stopped",agentId:s}:{kind:"failed",agentId:s,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:s,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}r(mr,"executeStopAgentTool");function Ut(e,t,n,o){let i=z(n),a=t.model?`${t.model.provider}/${t.model.id}`:null,s=C(e.model),d=s??v().modelFor(n,a,i,o,_().family(o));if(d&&!s&&(e[Ce]=d),e.thinking===void 0){let c=v().thinkingFor(n,i,o,_().family(o),t.thinkingLevel);c!==void 0&&(e[Pe]=c)}}r(Ut,"injectConfiguredDefaults");async function Bs(e,t){let n=e.input;if(e.toolName===h.handoverAgent){let i=Ae(n.harness_type);if(i===void 0)return;let a=C(n.agent_id)??"",s=w().getSpawn(a)?.display.type??St();Ut(n,t,s,i);return}if(e.toolName!==h.agent)return;let o=n.agents??[];for(let i of o){let a=Q(i.agent_type),s=Ae(i.harness_type),d=X(a,s);Ut(i,t,a,d)}}r(Bs,"toolCallListener");import{Type as Le}from"typebox";var fr="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).",Kt=Le.Object({agent_ids:Le.Array(Le.String({minLength:1}),{minItems:1,description:fr})},{additionalProperties:!1,required:["agent_ids"]});function Gt(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(Gt,"formatBasis");function yr(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${Gt(e.basis)})`}r(yr,"formatSettlement");function Yt(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 (${Gt(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(Yt,"formatKeptReason");function wr(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(wr,"paneText");function vr(e){return e.length===0?"none (the agent never had a pane)":e.map(t=>`${t.paneId} ${wr(t)}`).join(", ")}r(vr,"panesText");function kr(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(kr,"paneSummary");function br(e){if(e.length===0)return"no pane";if(e.length===1)return kr(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(br,"panesSummary");function zt(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(zt,"worktreeText");function Vt(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(Vt,"branchText");function xr(e){return e?` forced${e.reason?` \u2014 ${Yt(e.reason)}`:""}`:""}r(xr,"forcedClause");function je(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Yt(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${xr(e.outcome.forced)}:`}r(je,"headline");function Qt(e){let t=[je(e),` agent status: ${yr(e.settlement)}`,` panes: ${vr(e.panes)}`,` worktree: ${zt(e.worktree)}`,` branch: ${Vt(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(`
|
|
11
|
+
`)}r(Qt,"renderCleanupReport");function qs(e){let t=br(e.panes);return e.outcome.kind==="refused"?`${je(e)} ${t}`:`${je(e)} ${t}, worktree ${zt(e.worktree)}, branch ${Vt(e)}`}r(qs,"summarizeCleanupReport");function Fs(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Fs,"cleanupNeedsAttention");var Xt={name:h.cleanupAgent,label:h.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:Kt,execute:Tr,constrainedSampling:k};function Ar(e){return e.kind==="unknown"?"warning":e.report.outcome.kind==="torn-down"?"success":"warning"}r(Ar,"cleanupSeverity");function Sr(e){switch(e.kind){case"cleaned":return Qt(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(Sr,"renderCleanupOutcome");async function Tr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:Sr,severity:Ar,handleItem:r(async s=>{let d=w();if(!d.getSpawn(s)&&(await d.locate(s)).kind==="not-found")return{kind:"unknown",agentId:s,activeAgents:P(d)};let c=await d.cleanup(s);return{kind:"cleaned",agentId:s,report:c}},"handleItem")})}r(Tr,"executeCleanupAgentTool");import*as en from"node:fs";import*as B from"node:path";import{Type as M}from"typebox";var Rr="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.",Er="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.",Zt=M.Object({branches:M.Array(M.String({minLength:1}),{minItems:1,description:Rr}),target:M.Optional(M.String({description:Er})),repo:M.Optional(M.String({description:Ir}))},{additionalProperties:!1,required:["branches"]});function Jt(e){let t=B.normalize(e),{root:n}=B.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Jt,"normalizeRepoRoot");function Or(e,t){return Jt(e)===Jt(t)}r(Or,"isSameRepoRoot");function _r(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(_r,"formatOutsideRepoWarning");async function Cr(e,t){let n=new ht(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}=gt(i,o);if(!en.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(Cr,"resolveSessionMainRoot");var tn={name:h.mergeBranch,label:h.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:Dr,constrainedSampling:k};function Pr(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(Pr,"mergeSeverity");var Mr="has conflicts in:";function $r(e){return e.includes(Mr)}r($r,"isConflictError");function Nr(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
|
|
12
|
+
`).map(n=>n.trim()).filter(n=>n!==""):[]}r(Nr,"parseConflictFiles");function Hr(e,t){return e.includes(`branch "${t}" does not exist`)}r(Hr,"isUnknownBranchError");async function Dr(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 Cr(b(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:Pr,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 m=await yt(b(),{cwd:g,branch:u,target:a}),y=Or(m.mainRoot,f)?void 0:_r(m.mainRoot,f);if(y!==void 0)try{i.ui.notify(y,"warning")}catch{}let A=y!==void 0?`${y}
|
|
13
|
+
`:"";return m.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${A}"${u}" is already merged into "${m.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:m.target,output:m.output},text:`${A}Merged "${u}" into "${m.target}" in ${m.mainRoot}.`+(m.output?`
|
|
14
|
+
${m.output}`:"")}}catch(m){let y=m instanceof Error?m.message:String(m);return $r(y)?{outcome:{kind:"conflict",branch:u,target:a,files:Nr(y)},text:`"${u}": ${y}`}:Hr(y,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${y}`}:{outcome:{kind:"failed",branch:u,error:y},text:`"${u}": ${y}`}}},"handleItem")})}r(Dr,"executeMergeBranchTool");import{Type as de}from"typebox";var Br="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.",Lr="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.",nn=de.Object({agent_ids:de.Array(de.String({minLength:1}),{minItems:1,description:Br}),message:de.String({description:Lr})},{additionalProperties:!1,required:["agent_ids","message"]});var rn={name:h.steerAgent,label:h.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:nn,execute:Wr,constrainedSampling:k};function jr(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(jr,"steerSeverity");async function Wr(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:jr,prepare:r(()=>{if(a==="")throw new Error("message is required")},"prepare"),handleItem:r(async s=>{let d=w().getSpawn(s);if(!d){let g=`not found. Active agents: ${P()}`;return{outcome:{kind:"refused",agentId:s,reason:g},text:`Agent ${s} was not steered: ${g}`}}let c=I(d.lifecycle),l;try{l=await w().steer(s,a)}catch(g){l={kind:"refused",reason:`steering failed: ${N(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(Wr,"executeSteerAgentTool");function Ai(e,t,n){return he(e.ids(),t).filter(o=>o!==n)}r(Ai,"handoverTargets");function on(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.`}}:qe(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(on,"resolveHandoverTarget");import{Type as x}from"typebox";var Ur="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.",qr=`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.`,Fr=`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.`,Kr="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",sn=x.Object({agent_id:x.String({minLength:1,description:Ur}),harness_type:x.String({description:qr}),model:x.Optional(x.Union([x.String(),x.Null()],{description:Fr})),thinking:x.Optional(x.Union([x.String(),x.Null()],{description:Kr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Gr(e,t){let n=on(e.harness_type,_(),ct());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:N(i)}}}}r(Gr,"resolveIntent");function Yr(e,t){return`Agent ${e} ${zr(t)}`}r(Yr,"renderHandoverOutcome");function zr(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":it(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(zr,"handoverReport");async function Vr(e,t,n,o,i){let a=t.agent_id.trim(),s=await Gr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await w().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return D(at(d),Yr(a,d),{agentId:a,outcome:d})}r(Vr,"executeHandoverAgentTool");var an={name:h.handoverAgent,label:h.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:sn,execute:Vr,constrainedSampling:k};import{Text as Qr}from"@earendil-works/pi-tui";var Xr={success:"\u2713",warning:"!",error:"\u2717"};function Zr(e,t,n,o){let i=e.content.map(d=>d.text??"").join(`
|
|
15
|
+
`),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Qr(`${n.fg(a,Xr[a])} ${s}`,0,0)}r(Zr,"renderCowboyToolResult");function $(e){return{...e,renderResult:Zr}}r($,"withCowboyRenderer");var Jr=_e;function eo(e){return q?{...e,worktree:E.Optional(Oe)}:e}r(eo,"offeredItemProperties");function to(e){let t=E.Object(eo({prompt:H.properties.agents.items.properties.prompt,task_name:H.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:H.properties.agents.items.properties.model,harness_type:H.properties.agents.items.properties.harness_type}),{additionalProperties:!1,required:["prompt","task_name"]});return E.Object({agents:E.Array(t,{minItems:1}),run_in_background:H.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(to,"cowboyAgentsSchemaWithTypes");var no=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 dn(e){let t=to(kt()),n={name:h.agent,label:h.agent,description:no,parameters:t,execute:qt,constrainedSampling:k};e.registerTool($(n))}r(dn,"registerAgentTool");function ro(e,t){v().mutate.agent.setExtensionEnabled(t),t?oo(e):so(e)}r(ro,"setExtensionEnabled");function oo(e){let t=b();dn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Jr])]),te(e)}r(oo,"activateExtension");function so(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!_e.includes(n))),te(e)}r(so,"deactivateExtension");function oa(e){dn(e),e.registerTool($(Ft)),e.registerTool($(tn)),e.registerTool($(rn)),e.registerTool($(an)),e.registerTool($(Xt)),e.registerMessageRenderer("subagent-result",$t)}r(oa,"registerTools");var ln="cowboy",io={wt:"worktree",sp:"spawn",st:"status"};function sa(e,t){e.registerCommand(ln,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(sa,"registerUnavailableCowboyCommand");function ia(e){e.registerCommand(ln,{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-KTV7DIQR.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{ut(n);let[o,...i]=t.trim().split(/\s+/),a=io[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}ro(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-JXTKYYEV.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-KTV7DIQR.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-EETUYB5S.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-EETUYB5S.js");await c(n,j()?.options??new Map)},"handler")})}r(ia,"registerCowboyCommand");import*as cn from"node:fs";import{tmpdir as ao}from"node:os";import*as le from"node:path";async function un(e,t){try{return await pt(e).probe(t),L(Ke)}catch{return L(["checkout"])}}r(un,"detectCowAvailability");function pn(e){let t=le.resolve(e??We());for(;;){try{if(cn.statSync(t).isDirectory())return t}catch{}let n=le.dirname(t);if(n===t)return ao();t=n}}r(pn,"probeTargetFor");function lo(e){return(t,n,o)=>e.exec(t,n,o)}r(lo,"execOf");function va(e){return hn(e,ke())}r(va,"startCowSupportProbe");function ka(e){let t=ke();return Y(t,Ue()),hn(e,t)}r(ka,"refreshCowSupportProbe");function hn(e,t){let n=pn(v().agent.worktreeRoot);return un(lo(e),n).then(o=>{Y(t,o)},()=>{Y(t,L(["checkout"]))})}r(hn,"probe");import gn from"node:fs";var co="/tmp";function uo(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(uo,"handoverNameField");function mn(e){return`${[e.worktree,e.harness,e.sessionId].map(uo).join("-")}.md`}r(mn,"handoverFileName");function fn(e){return`${co}/${e}`}r(fn,"handoverFilePath");function po(e){return gn.existsSync(e)}r(po,"handoverFileExists");function Sa(e,t){let n=po(e);return gn.writeFileSync(e,t,"utf8"),{replaced:n}}r(Sa,"writeHandoverFile");import*as yn from"node:path";function Ia(e,t){return e===void 0?`main-${t}`:yn.basename(e.path)}r(Ia,"exportWorktreeName");function Oa(e){return{kind:"prepared",defaultPath:fn(mn({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(Oa,"handoverExportArtifact");function _a(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(_a,"handoverExportFaultReason");function Ca(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(Ca,"handoverExportSeverity");export{He as a,ir as b,ar as c,Bs as d,Yt as e,qs as f,Fs as g,Ai as h,Yr as i,Ie as j,ee as k,ko as l,po as m,Sa as n,Ia as o,Oa as p,_a as q,Ca as r,va as s,ka as t,ro as u,oo as v,so as w,oa as x,sa as y,ia as z};
|
|
16
|
+
//# sourceMappingURL=chunk-EWHWPOTC.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as Jt,B as Xt,D as qt,G as x,H as Qt,I as m,J as Oe,K as Zt,L as er,M as O,N as C,O as nr,P as F,a as r,c as Wt,d as Kt,e as Ut,f as Ce,g as Kn,h as Bt,i as Vt,j as zt,k as Un,l as y,m as A,o as Yt,p as h,v as Xe,w as qe,x as X,y as $,z as Bn}from"./chunk-AOUEQXPY.js";import*as Q from"node:path";import*as rr from"node:fs";import{homedir as Vn,tmpdir as ks}from"node:os";import*as P from"node:path";import{fileURLToPath as or}from"node:url";var tr={name:"pi-cowboy",version:"0.36.
|
|
1
|
+
import{A as Jt,B as Xt,D as qt,G as x,H as Qt,I as m,J as Oe,K as Zt,L as er,M as O,N as C,O as nr,P as F,a as r,c as Wt,d as Kt,e as Ut,f as Ce,g as Kn,h as Bt,i as Vt,j as zt,k as Un,l as y,m as A,o as Yt,p as h,v as Xe,w as qe,x as X,y as $,z as Bn}from"./chunk-AOUEQXPY.js";import*as Q from"node:path";import*as rr from"node:fs";import{homedir as Vn,tmpdir as ks}from"node:os";import*as P from"node:path";import{fileURLToPath as or}from"node:url";var tr={name:"pi-cowboy",version:"0.36.4",type:"module",packageManager:"pnpm@12.9.1",description:"\u{1F920} Agent orchestrator for pi. It can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents and handover sessions in between them. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",keywords:["pi-package","pi","pi-agent","pi-coding-agent","pi-extension","subagents","herdr","ai","agents"],license:"MIT",author:"electric-dragon-80000v",homepage:"https://github.com/electric-dragon-80000v/pi-cowboy#readme",repository:{type:"git",url:"git+https://github.com/electric-dragon-80000v/pi-cowboy.git"},bugs:{url:"https://github.com/electric-dragon-80000v/pi-cowboy/issues"},engines:{node:">=24.20.0",pnpm:">=12"},main:"./dist/index.js",types:"./dist/index.d.ts",files:["dist/","!dist/**/*.js.map","!dist/**/.*","agents/","orchestrators/","!orchestrators/with-code-review.toml","README.md","LICENSE"],exports:{".":"./dist/index.js","./plugin":"./dist/plugin/index.js","./package.json":"./package.json"},scripts:{format:"prettier --write src/ test/ scripts/ lint/ docs/","format:check":"prettier --check src/ test/ scripts/ lint/ docs/",typecheck:"tsc6 --noEmit","find-unused":"node --disable-warning=ExperimentalWarning scripts/find-unused.ts",build:"node scripts/build.ts && tsc6 -p tsconfig.build.json",prepack:"pnpm run build",test:"pnpm run build && vitest run","test:unit":"vitest run --project unit","test:integration":"pnpm run build && vitest run --project integration-no-cow --project integration-cow","test:integration-no-cow":"pnpm run build && vitest run --project integration-no-cow","test:integration-cow":"pnpm run build && vitest run --project integration-cow","dev:install":"pi remove . 2>/dev/null; pi install ./dev",lint:"oxlint","lint:fix":"oxlint --fix",commitlint:"commitlint",release:"semantic-release","release:stage":"npm stage publish","release:approve":"scripts/publish.sh",prepare:"husky"},pi:{image:"https://raw.githubusercontent.com/electric-dragon-80000v/pi-cowboy/main/docs/assets/logo-pi-package-landscape.png",video:"https://github.com/electric-dragon-80000v/pi-cowboy/raw/refs/heads/main/docs/assets/pi-cowboy.mp4",extensions:["./dist/index.js"]},peerDependencies:{"@earendil-works/pi-ai":"*","@earendil-works/pi-coding-agent":"*","@earendil-works/pi-tui":"*",typebox:"*"},devDependencies:{"@commitlint/cli":"^21.2.3","@commitlint/config-conventional":"^21.2.3","@commitlint/types":"^21.2.3","@semantic-release/changelog":"^7.0.0","@semantic-release/commit-analyzer":"^13.0.1","@semantic-release/exec":"^7.1.0","@semantic-release/git":"^11.0.1","@semantic-release/github":"^12.0.10","@semantic-release/npm":"^13.2.0","@semantic-release/release-notes-generator":"^14.1.1","@types/estree":"^1.0.9","@types/mustache":"^4.2.6","@types/node":"^26.6.4","@vitest/coverage-v8":"5.0.3","@vitest/ui":"^5.0.3",esbuild:"^0.28.2",eslint:"^10.12.0","eslint-plugin-import-x":"^4.17.1",husky:"^9.1.7",oxlint:"1.93.0","oxlint-tsgolint":"7.0.2006",prettier:"^3.9.9","semantic-release":"^25.0.9",typescript:"npm:@typescript/typescript6@^6.0.2",vitest:"^5.0.3"},dependencies:{"jsonc-parser":"^3.3.1",mustache:"^4.2.0","smol-toml":"^1.9.0",yaml:"^2.9.1",zod:"^4.6.5"}};var zn=tr.name,As="PI_CODING_AGENT_DIR";function Ss(){let e=process.env[As];return e?v(e):P.join(Vn(),".pi","agent")}r(Ss,"agentDir");function v(e){return e==="~"?Vn():e.startsWith("~/")?P.join(Vn(),e.slice(2)):e}r(v,"expandTilde");function M(e){try{return rr.realpathSync.native(e)}catch{return}}r(M,"canonicalPath");function Qe(){return P.join(Ss(),zn)}r(Qe,"defaultExtensionDir");function sr(){return P.join(Qe(),"worktrees")}r(sr,"defaultWorktreeRoot");function Rs(){return P.join(ks(),"pi-cowboy")}r(Rs,"subagentResultDir");function q(e){return P.join(Rs(),e)}r(q,"subagentResultDirFor");function Qc(e){return P.join(q(e),"result.md")}r(Qc,"subagentResultFileFor");var Is="system.md",Ts="prompt.md";function Zc(e){return P.join(q(e),Is)}r(Zc,"subagentSystemFileFor");var _s="env.sh";function ir(e){return P.join(q(e),_s)}r(ir,"subagentEnvFileFor");function eu(e){return P.join(q(e),Ts)}r(eu,"subagentTaskFileFor");var Yn="cowboy-subagent-";function ye(e){return`${Yn}${e}`}r(ye,"subagentTokenFor");var nu=or(new URL("../agents/",import.meta.url)),tu=or(new URL("../orchestrators/",import.meta.url));function su(e){return{status:"known",available:new Set(e)}}r(su,"probed");function Jn(){return{status:"unknown"}}r(Jn,"unprobed");function Pe(e,n){return n.status==="unknown"||n.available.has(e)}r(Pe,"isAvailable");function iu(e,n){return e.filter(t=>Pe(t,n))}r(iu,"selectable");function ar(e,n){return n.status==="known"&&n.available.has(e)}r(ar,"isProven");var Ze="cow-",Me="copy-on-write",gu=["copy-on-write","checkout"];function fu(e){if(e==="copy-on-write"||e==="checkout")return e}r(fu,"parseWorktreeMaterialization");function ur(e,n){return Pe("copy-on-write",n)?e??Me:"checkout"}r(ur,"resolveWorktreeMaterialization");var en="clean",mu=["dirty","clean"];function yu(e){if(e==="dirty"||e==="clean")return e}r(yu,"parseWorktreeCheckoutType");function hu(e){return e.branch??Q.basename(e.path)}r(hu,"worktreeBranchOf");function Eu(e){if(e==null)return{kind:"new"};if(e==="new"||e==="inherit")return{kind:e};if(typeof e=="object"&&!Array.isArray(e)&&typeof e.path=="string"){let n=e.path.trim();if(n!=="")return{kind:"picked",path:n}}throw new Error('Invalid `worktree`: pass "new", "inherit", or { "path": "/absolute/checkout" }. Nothing was spawned.')}r(Eu,"parseWorktreeRequest");var dr=3,lr=Ce-Ze.length-1-Wt-Bt;function Cs(e){return e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}r(Cs,"slugifyWorktreeType");function Os(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(n=>n.length>0)}r(Os,"taskNameWords");function bu(e){let n=Os(e);if(n.length===0)throw new Error("Task name is empty \u2014 provide a short 2-3 word name.");if(n.length>dr)throw new Error(`Task name "${e}" gives the branch name "${n.join("-")}" with ${n.length} words. The limit is ${dr} words.`);let t=n.join("-");if(t.length>lr)throw new Error(`Task name "${e}" gives the branch name "${t}" with ${t.length} characters. The limit is ${lr} characters, because herdr limits agent names to 32 characters.`);return t}r(bu,"buildTaskSlug");function Ps(e,n){return`${Ze}${Cs(e)}-${n}`}r(Ps,"buildWorktreeBranch");function xu(e,n,t){return Q.join(e,Ps(n,t))}r(xu,"buildWorktreePath");function wu(e,n){return e&&e.trim()!==""?Q.isAbsolute(e)?e:Q.resolve(n,e):sr()}r(wu,"resolveWorktreeRoot");function cr(e){return(M(e)??e.replace(/\\/g,"/")).replace(/\/+$/,"")}r(cr,"normalizeRoot");function vu(e,n){return n!==""&&e.startsWith(Ze)&&e.length>n.length&&e.endsWith(`-${n}`)}r(vu,"isSpawnArtifactName");function ku(e,n){let t=cr(e),o=cr(n);return t!==o&&!t.startsWith(`${o}/`)?!1:(t.split("/").filter(Boolean).pop()??"").startsWith(Ze)}r(ku,"isExtensionWorktree");import{getSupportedThinkingLevels as Wc}from"@earendil-works/pi-ai";var nn=class{static{r(this,"RepoLock")}tails=new Map;async run(n,t){let o=(this.tails.get(n)??Promise.resolve()).then(t),s=o.then(()=>{},()=>{});this.tails.set(n,s);try{return await o}finally{this.tails.get(n)===s&&this.tails.delete(n)}}};import*as he from"node:fs";import*as tn from"node:path";function V(e){for(let n of(process.env.PATH??"").split(tn.delimiter)){if(n==="")continue;let t=tn.join(n,e);try{if(!he.statSync(t).isFile())continue;return he.accessSync(t,he.constants.X_OK),t}catch{}}}r(V,"commandPath");function Tu(e){return V(e)??e}r(Tu,"resolveCommand");import{readFile as Xn,readdir as Ms}from"node:fs/promises";import*as He from"node:path";import{z as Ee}from"zod";var pr=3,Hs="sessionDir",fr=Ee.object({type:Ee.string(),text:Ee.string().optional(),thinking:Ee.string().optional()}),Ls=Ee.array(Ee.unknown());function rn(e){return`--${(M(e)??He.resolve(e)).replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}r(rn,"sessionBucketName");async function be(e){let n;try{n=await Xn(He.join(e,"settings.json"),"utf8")}catch{return}let t;try{t=JSON.parse(n)}catch{return}if(y(t))return A(t[Hs])}r(be,"readSessionDirSetting");async function Ns(e,n,t){let o;try{o=await Ms(e,{withFileTypes:!0})}catch{throw new m("session-not-found",`no session record under ${e} for ${t} (subagent ${n})`)}let s=[];for(let i of o){if(!i.isFile()||!i.name.endsWith(".jsonl"))continue;let a=He.join(e,i.name);await Ds(a)===n&&s.push(a)}if(s.length===0)throw new m("session-not-found",`no session record under ${e} for ${t} (subagent ${n})`);if(s.length>1)throw new m("ambiguous-session",`more than one session record under ${e} names subagent ${n}: ${s.join(", ")}`);return s[0]}r(Ns,"findSessionFile");async function Ds(e){let n;try{n=await Xn(e,"utf8")}catch{return}let t;for(let o of n.split(`
|
|
2
2
|
`)){if(o.trim()==="")continue;let s;try{s=JSON.parse(o)}catch{continue}!y(s)||s.type!=="session_info"||(t=A(s.name))}return t}r(Ds,"readLatestSessionName");async function js(e){let n=await Gs(e),t=!n.endsWith(`
|
|
3
3
|
`),o=n.split(`
|
|
4
4
|
`);t||o.pop();let s=$s(o,t,e);return{sessionId:s.header.id,records:Fs(o,s.index,t)}}r(js,"readSessionFile");function $s(e,n,t){for(let o=0;o<e.length;o++){let s=e[o];if(s.trim()==="")continue;let i;try{i=JSON.parse(s)}catch{if(n&&o===e.length-1)break;throw new m("malformed-record",`malformed session record in ${t} at line ${o+1}`)}if(!y(i))throw new m("malformed-record",`malformed session record in ${t} at line ${o+1}`);return{index:o,header:Ws(i,t)}}throw new m("malformed-record",`session record ${t} has no session header`)}r($s,"findSessionHeader");function*Fs(e,n,t){for(let o=0;o<e.length;o++){let s=e[o];if(s.trim()==="")continue;if(o===n){yield x("session",s);continue}let i;try{i=JSON.parse(s)}catch{if(t&&o===e.length-1)break;yield{kind:"unparseable",content:s};continue}if(!y(i)){yield{kind:"unparseable",content:s};continue}yield Ks(i,s)}}r(Fs,"sessionRecords");async function Gs(e){try{return await Xn(e,"utf8")}catch(n){throw new m("unreadable-record",`cannot read session record ${e}: ${h(n)}`)}}r(Gs,"readSessionFileContent");function Ws(e,n){if(e.type!=="session")throw new m("malformed-record",`session record ${n} does not start with a session header`);let t=e.version;if(typeof t!="number"||!Number.isInteger(t))throw new m("malformed-record",`session record ${n} has no numeric version`);if(t!==pr)throw new m("unsupported-version",`session record ${n} uses version ${t}; this export reads version ${pr}`);let o=A(e.id);if(o===void 0)throw new m("missing-session-id",`session record ${n} names no session id`);return{id:o}}r(Ws,"readHeader");function Ks(e,n){if(e.type==="compaction")return Us(e,n);if(e.type!=="message")return x(e.type,n);if(!y(e.message))return{kind:"unparseable",content:n};let t=e.message.role;if(t!=="user"&&t!=="assistant"&&t!=="toolResult")return x(t,n);let o=Ls.safeParse(e.message.content);if(!o.success)return{kind:"unparseable",content:n};if(t==="toolResult")return{kind:"tool-call",content:JSON.stringify(o.data)};let s=gr(o.data,"text");if(s!=="")return{kind:t,content:s};let i=gr(o.data,"thinking");if(i!=="")return{kind:"thinking",content:i};let a=Bs(o.data,"toolCall");return a.length>0?{kind:"tool-call",content:JSON.stringify(a)}:x(t,n)}r(Ks,"readTurn");function Us(e,n){return typeof e.summary!="string"?{kind:"unparseable",content:n}:{kind:"compaction",content:mr(e.summary)}}r(Us,"readCompaction");function gr(e,n){let t=[];for(let o of e){let s=fr.safeParse(o);if(!s.success||s.data.type!==n)continue;let i=n==="thinking"?s.data.thinking??s.data.text:s.data.text;if(i===void 0)continue;let a=mr(i);a!==""&&t.push(a)}return t.join(`
|
|
@@ -51,4 +51,4 @@ ${rs(i.content)}`;break}case"thinking":case"tool-call":case"other":break;case"un
|
|
|
51
51
|
`).map(t=>{let o=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(t);if(o!==null){let a=o[1];return n===void 0?n=a:a[0]===n[0]&&a.length>=n.length&&o[2].trim()===""&&(n=void 0),t}if(n!==void 0)return t;let s=/^( {0,3})#{1,6}(?=\s|$)/.exec(t);if(s===null)return t;let i=s[1];return`${i}\\${t.slice(i.length)}`}).join(`
|
|
52
52
|
`)}r(rs,"escapeContentHeadings");async function ay(e,n,t,o){let s=e.get(n);if(s===void 0||!er(s))return{kind:"faulted",fault:{kind:"harness-cannot-export-session",harness:n}};let i;try{i=await s.readHandoverRecords(t)}catch(u){return{kind:"faulted",fault:{kind:"session-export-failed",harness:n,detail:u instanceof Error?u.message:String(u),...u instanceof m?{exportFault:u.fault}:{}}}}if(i.sessionId.trim()==="")return{kind:"faulted",fault:{kind:"session-export-failed",harness:n,detail:"the harness named no session id for the run it exported"}};let a=ec(i),d=a.loss;return d!==void 0&&d.total>0&&d.excluded/d.total>o.maxExcludedRatio?{kind:"faulted",fault:{kind:"session-export-failed",harness:n,detail:Zl(d,o)}}:a.session.trim()===""?{kind:"faulted",fault:{kind:"session-empty",harness:n}}:{kind:"exported",sessionId:a.sessionId,session:a.session,...d===void 0?{}:{loss:d}}}r(ay,"exportRunSession");var nc="<<pi-cowboy-handover",tc=">>";function rc(e){let n=e.map(({harness:t,sessionId:o})=>({harness:t,sessionId:o}));return`${nc} ${JSON.stringify(n)}${tc}`}r(rc,"renderHandoverMarker");function dy(e){return[e.taskSlug===void 0?"You are continuing this task in this workspace.":`You are continuing work on task "${e.taskSlug}" in this workspace.`,`This task was previously handled by another agent harness (${e.sourceName}).`,`The previous run's session id is "${e.current.sessionId}".`,rc([...e.previous,e.current]),"","The session of the previous run is quoted below. Review it together with the current state of the files in this repository, then proceed with the task.","","---","",e.session,""].join(`
|
|
53
53
|
`)}r(dy,"renderHandoverTask");var os=4;function ge(e){let n=e.indexOf("/"),t=e.indexOf(":"),o=t>0&&(n<0||t<n),s=X,i=e;if(o){if(s=e.slice(0,t),s.trim()==="")return;i=e.slice(t+1)}let a=i.indexOf("/");if(a<0)return i===""?void 0:{kind:"provider",harness:s,provider:i};let d=i.slice(0,a),u=i.slice(a+1);if(!(d===""||u===""))return{kind:"model",harness:s,provider:d,model:u}}r(ge,"parsePoolKey");function is(e,n,t){return`${e}:${n}/${t}`}r(is,"qualifiedModelKey");function as(e,n){return`${e}:${n}`}r(as,"qualifiedProviderKey");function oc(e){let n=ge(e);return n?.kind==="model"?is(n.harness,n.provider,n.model):void 0}r(oc,"modelPoolKeyOf");function sc(e){let n=ge(e);return n?.kind==="provider"?as(n.harness,n.provider):void 0}r(sc,"providerPoolKeyOf");function Pt(e){return Math.max(1,e)}r(Pt,"clampLimit");var ss=class{static{r(this,"ConcurrencyPools")}modelPools=new Map;providerPools=new Map;harnessPools=new Map;globalPool={limit:os,spawned:0};queue=[];reservations=new Map;constructor(n){this.setLimits(n??{default:os,harnesses:{},providers:{},models:{}})}setConcurrency(n){this.setLimits(n),this.drainQueue()}admitSpawn(n,t){let o=this.applicablePools(n);return this.hasRoom(o)?{kind:"start",reservation:o}:(this.queue.push({id:t.id,identity:n,start:t.start}),{kind:"queue"})}reserve(n,t){for(let o of t)o.spawned++;this.reservations.set(n,t)}reacquire(n,t){this.reservations.has(n)||this.reserve(n,this.applicablePools(t))}release(n){let t=this.reservations.get(n);if(t){for(let o of t)o.spawned=Math.max(0,o.spawned-1);this.reservations.delete(n)}this.cancelQueued(n),this.drainQueue()}cancelQueued(n){this.queue=this.queue.filter(t=>t.id!==n)}clearQueue(){this.queue=[]}queuePosition(n){return this.queue.findIndex(t=>t.id===n)+1}setLimits(n){this.globalPool.limit=Pt(n.default),this.syncHarnessPools(n.harnesses),this.syncPools(this.providerPools,n.providers,sc),this.syncPools(this.modelPools,n.models,oc)}syncHarnessPools(n){let t=new Map;for(let[o,s]of Object.entries(n))o.trim()!==""&&typeof s=="number"&&t.set(o,Pt(s));for(let[o,s]of t){let i=this.harnessPools.get(o);i?i.limit=s:this.harnessPools.set(o,{limit:s,spawned:0})}for(let o of this.harnessPools.keys())t.has(o)||this.harnessPools.delete(o)}syncPools(n,t,o){let s=new Map;for(let[i,a]of Object.entries(t)){let d=o(i);d!==void 0&&a!==void 0&&s.set(d,Pt(a))}for(let[i,a]of s){let d=n.get(i);d?d.limit=a:n.set(i,{limit:a,spawned:0})}for(let i of n.keys())s.has(i)||n.delete(i)}applicablePools(n){let t=[];if(n.modelKey){let s=ge(n.modelKey);if(s?.kind==="model"){let i=this.modelPools.get(is(n.harness,s.provider,s.model));i&&t.push(i);let a=this.providerPools.get(as(n.harness,s.provider));a&&t.push(a)}}let o=this.harnessPools.get(n.harness);return o&&t.push(o),t.push(this.globalPool),t}hasRoom(n){return n.every(t=>t.spawned<t.limit)}drainQueue(){let n=[];for(let t of this.queue){let o=this.applicablePools(t.identity);if(!this.hasRoom(o)){n.push(t);continue}t.start(o)}this.queue=n}};var We="defaultModelByHarness",fe="defaultThinkingByHarness",Ie="thinking",Hn=["default","defaultAgentType","defaultOrchestrator","systemPromptMode","includeContextFiles","defaultThinking",fe,Ie,"loadSkillsImplicitly","loadExtensionsImplicitly","disableDefaultAgents","extensionEnabled","showActiveIndicator","grazingEnabled","worktreeRoot","worktreeMaterialization","worktreeCheckoutType","handoverMaxExcludedRatio","harnessType"];import*as N from"node:fs";import*as _e from"node:path";import{z as B}from"zod";function ds(e,n,t){return Jt(e)?qt(e,t)?"reserved":typeof n!="string"?"not-string":Xt(n)?"control":null:"name"}r(ds,"envProblem");function ls(e,n){let t={};for(let[o,s]of Object.entries(e)){if(s===void 0)continue;let i=ds(o,s,n.reserved);if(i!==null){n.report(o,i,s);continue}t[o]=s}return t}r(ls,"sanitizeEnv");function yy(e,n){return e===void 0?n:n===void 0?e:{...e,...n}}r(yy,"mergeEnv");function hy(e){for(let[n,t]of Object.entries(e)){let o=ds(n,t,[]);if(o!==null)throw new Error(`Invalid environment variable ${n}: ${o}`)}return e}r(hy,"trustedEnv");import{z as ic}from"zod";var Mt=ic.number().int().min(1),Te="positive integer";function Ln(e){return Mt.safeParse(e).success}r(Ln,"isConcurrencyLimit");var ac="Set it again in the /cowboy menu, or edit or delete the file to fix it.",Ue="Edit or delete the key in that file to fix it.",dc={schema:B.number().min(0).max(1),expected:"a number from 0 to 1",fix:Ue},Ht={schema:B.union([B.string(),B.null()]),expected:"string or null"},me={schema:B.boolean(),expected:"boolean"},lc={schema:B.enum(["replace","inherit","custom"]),expected:'"replace" | "inherit" | "custom"'},cc={schema:B.enum(["off","minimal","low","medium","high","xhigh","max"]),expected:'"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"'},uc={schema:B.enum(["copy-on-write","checkout"]),expected:'"copy-on-write" | "checkout"'},pc={schema:B.enum(["dirty","clean"]),expected:'"dirty" | "clean"'},us=B.string().min(1).refine(e=>/\S/.test(e)),Ke={schema:us,expected:"non-empty string"},ps=qe.map(e=>`"${e}"`).join(" | "),gc=`an object keyed by a harness id (${ps} or a plugin's), with string or null values`,fc=`an object keyed by a harness id (${ps} or a plugin's), with a non-empty thinking token or null per entry`,mc="an object keyed by an agent type, with a non-empty thinking token or null per entry",yc="non-empty string or null",hc=r(e=>typeof e=="string"||e===null,"isModelKeyOrNull"),Ec=r(e=>e===null||typeof e=="string"&&/\S/.test(e),"isThinkingTokenOrNull"),bc={default:Ht,defaultAgentType:Ke,defaultOrchestrator:Ke,systemPromptMode:lc,includeContextFiles:me,defaultThinking:cc,loadSkillsImplicitly:me,loadExtensionsImplicitly:me,disableDefaultAgents:me,extensionEnabled:me,showActiveIndicator:me,grazingEnabled:me,worktreeRoot:Ke,worktreeMaterialization:uc,worktreeCheckoutType:pc,handoverMaxExcludedRatio:dc,harnessType:Ke};function xc(e){return Array.isArray(e)?"array":e===null?"null":typeof e=="object"?"object":typeof e}r(xc,"describeValue");function Be(e,n,t,o,s){return`[subagents] Incompatible value in ${e}: "${n}" is ${xc(t)}, expected ${o}. ${s}`}r(Be,"incompatibleWarning");function S(e,n,t,o,s=ac){console.warn(Be(e,n,t,o,s))}r(S,"warnIncompatible");var se="object";function Lt(e,n){let t={};if(!y(e))return S(n,"(config)",e,se),t;if(e.agent!==void 0)if(!y(e.agent))S(n,"agent",e.agent,se);else{let o=Sc(e.agent,n);Object.keys(o).length>0&&(t.agent=o)}if(e.concurrency!==void 0){let o=Rc(e.concurrency,n);Object.keys(o).length>0&&(t.concurrency=o)}if(e.harness!==void 0){let o=wc(e.harness,n);o!==void 0&&(t.harness=o)}if(e.multiplexer!==void 0){let o=us.safeParse(e.multiplexer);o.success?t.multiplexer=o.data:S(n,"multiplexer",e.multiplexer,Ke.expected)}return t}r(Lt,"validateRawLayer");function wc(e,n){if(!y(e)){console.warn(Be(n,"harness",e,se,Ue));return}let t={};for(let[o,s]of Object.entries(e))if(s!==void 0){if(!y(s)){console.warn(Be(n,`harness.${o}`,s,se,Ue));continue}t[o]=vc(s,o,n)}return Object.keys(t).length>0?t:void 0}r(wc,"cleanHarnessSections");function vc(e,n,t){if(e.env===void 0)return e;let o=Ac(e.env,n,t),s={...e};return delete s.env,o===void 0?s:{...s,env:o}}r(vc,"cleanHarnessSlice");var kc={name:"a valid environment variable name",reserved:"a variable that is not reserved","not-string":"string",control:"a value without control characters"};function Ac(e,n,t){if(!y(e)){S(t,`harness.${n}.env`,e,se);return}let o=ls(e,{reserved:[],report:r((s,i,a)=>{let d=i==="name"||i==="reserved";S(t,`harness.${n}.env.${s}`,d?s:a,kc[i])},"report")});return Object.keys(o).length>0?o:void 0}r(Ac,"cleanHarnessEnv");function Sc(e,n){let t={};for(let[o,s]of Object.entries(e)){if(s===void 0)continue;if(o===We){let d=cs(s,n,{keyPath:`agent.${o}`,expected:gc,valueExpected:Ht.expected,accepts:hc});d!==void 0&&(t[o]=d);continue}if(o===fe||o===Ie){let d=cs(s,n,{keyPath:`agent.${o}`,expected:o===fe?fc:mc,valueExpected:yc,accepts:Ec});d!==void 0&&(t[o]=d);continue}let i=bc[o]??Ht,a=i.schema.safeParse(s);a.success?t[o]=a.data:S(n,`agent.${o}`,s,i.expected,i.fix)}return t}r(Sc,"cleanAgentEntries");function cs(e,n,{keyPath:t,expected:o,valueExpected:s,accepts:i}){if(!y(e)){S(n,t,e,o);return}let a={};for(let[d,u]of Object.entries(e))if(u!==void 0){if(!/\S/.test(d)){S(n,`${t}.${d}`,d,"non-empty key");continue}i(u)?a[d]=u:S(n,`${t}.${d}`,u,s)}return Object.keys(a).length>0?a:void 0}r(cs,"cleanEntryMap");function Rc(e,n){let t={};if(!y(e))return S(n,"concurrency",e,se),t;e.default!==void 0&&(Ln(e.default)?t.default=e.default:S(n,"concurrency.default",e.default,Te));let o=e.harnesses;if(o!==void 0)if(!y(o))S(n,"concurrency.harnesses",o,se);else{let i={};for(let[a,d]of Object.entries(o)){if(!/\S/.test(a)){S(n,`concurrency.harnesses.${a}`,a,"non-empty harness id");continue}Ln(d)?i[a]=d:S(n,`concurrency.harnesses.${a}`,d,Te)}Object.keys(i).length>0&&(t.harnesses=i)}let s={providers:{level:"provider",expected:'a provider key "provider" or "<harness>:<provider>"'},models:{level:"model",expected:'a model key "provider/model" or "<harness>:<provider>/<model>"'}};for(let i of["providers","models"]){let a=e[i];if(a===void 0)continue;if(!y(a)){S(n,`concurrency.${i}`,a,se);continue}let{level:d,expected:u}=s[i],l={};for(let[c,f]of Object.entries(a)){if(ge(c)?.kind!==d){S(n,`concurrency.${i}.${c}`,c,u);continue}Ln(f)?l[c]=f:S(n,`concurrency.${i}.${c}`,f,Te)}Object.keys(l).length>0&&(t[i]=l)}return t}r(Rc,"cleanConcurrencySection");var ms="config.json";function Ve(){return _e.join(Qe(),ms)}r(Ve,"configPath");function Wy(){return _e.join(Qe(),"prompt.md")}r(Wy,"customPromptPath");var Ic={default:4},Tc={default:null,defaultAgentType:_n,defaultOrchestrator:Cn,systemPromptMode:"replace",includeContextFiles:!0,disableDefaultAgents:!1,extensionEnabled:!0,showActiveIndicator:!0,grazingEnabled:!0,worktreeMaterialization:Me,worktreeCheckoutType:en,handoverMaxExcludedRatio:Mn,harnessType:X},Nt=new Set(["default","defaultThinking",We,fe,Ie]),_c=new Set([We,fe,Ie]);function Dt(e){return Nt.has(e)||!Hn.includes(e)}r(Dt,"isProjectAllowedAgentKey");function ze(e){let n=e?_e.join(e,zn,ms):null,t=e?"absent":"untrusted",o=null,s=!1;return{load:r(()=>{let i=Oc(),a=i.raw;if(s=i.malformed,n){let d=Pc(n);d===null?(o=null,t="absent"):d==="malformed"?(o=null,t="malformed"):(o=d.raw,t="loaded")}else o=null,t="untrusted";return{global:a,project:o,projectStatus:t}},"load"),isGlobalWritable:r(()=>!s,"isGlobalWritable"),paths:r(()=>({global:Ve(),project:n??void 0}),"paths"),saveGlobal:r(i=>{if(s){console.warn("[subagents] Refusing to write global config (malformed); change not saved");return}fs(Ve(),i)},"saveGlobal"),saveProject:r(i=>{if(!n||t==="malformed"||t==="untrusted"){console.warn(`[subagents] Refusing to write project config (${t}); change not saved`);return}fs(n,i)},"saveProject")}}r(ze,"createConfigIO");function ys(e,n){let t={...e.agent};if(n?.agent){for(let[o,s]of Object.entries(n.agent))if(Dt(o)){if(_c.has(o)&&y(t[o])&&y(s)){t[o]={...t[o],...s};continue}t[o]=s}}return{agent:t,concurrency:Cc(e.concurrency,n?.concurrency),multiplexer:e.multiplexer}}r(ys,"mergeLayers");function Cc(...e){let n={},t={},o={},s={};for(let i of e)i&&(i.default!==void 0&&(n.default=i.default),Object.assign(t,i.harnesses??{}),Object.assign(o,i.providers??{}),Object.assign(s,i.models??{}));return Object.keys(t).length>0&&(n.harnesses=t),Object.keys(o).length>0&&(n.providers=o),Object.keys(s).length>0&&(n.models=s),n}r(Cc,"mergeRawConcurrency");function jt(e){return{agent:{...Tc,...e.agent},concurrency:{...Ic,...e.concurrency},multiplexer:e.multiplexer??_t()}}r(jt,"mergeDefaults");function Oc(){let e;try{e=N.readFileSync(Ve(),"utf-8")}catch(t){return t?.code==="ENOENT"?{raw:{},malformed:!1}:gs(t)}let n;try{n=JSON.parse(e)}catch(t){return gs(t)}return{raw:Lt(n,Ve()),malformed:!1}}r(Oc,"readGlobalRaw");function gs(e){return console.warn(`[subagents] Ignoring malformed global config ${Ve()}: ${h(e)}`),{raw:{},malformed:!0}}r(gs,"warnMalformedGlobal");function Pc(e){if(!N.existsSync(e))return null;let n;try{n=N.readFileSync(e,"utf-8")}catch(t){return console.warn(`[subagents] Ignoring malformed project config ${e}: ${h(t)}`),"malformed"}return Mc(n,e)}r(Pc,"readProjectRaw");function Mc(e,n){let t;try{t=JSON.parse(e)}catch(s){return console.warn(`[subagents] Ignoring malformed project config ${n}: ${h(s)}`),"malformed"}if(!y(t))return console.warn(`[subagents] Ignoring malformed project config ${n}: not a JSON object`),"malformed";let o=t;return o.agent!==void 0&&!y(o.agent)?Nn(n,"agent"):o.concurrency!==void 0&&!y(o.concurrency)?Nn(n,"concurrency"):o.concurrency?.providers!==void 0&&!y(o.concurrency.providers)?Nn(n,"concurrency.providers"):o.concurrency?.models!==void 0&&!y(o.concurrency.models)?Nn(n,"concurrency.models"):{raw:Lt(o,n)}}r(Mc,"parseProjectContents");function Nn(e,n){return console.warn(`[subagents] Ignoring malformed project config ${e}: "${n}" is not a JSON object`),"malformed"}r(Nn,"malformedSection");function fs(e,n){let t=e+".tmp";try{N.mkdirSync(_e.dirname(e),{recursive:!0}),N.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),N.renameSync(t,e)}catch(o){console.error(`[subagents] Failed to save config: ${h(o)}`)}}r(fs,"writeJsonAtomic");var Hc=ze();function Lc(e){return e.project?{kind:"present",raw:e.project}:e.projectStatus==="untrusted"||e.projectStatus==="malformed"?{kind:"refused",status:e.projectStatus}:{kind:"creatable"}}r(Lc,"projectLayerFrom");function $t(e){return e.kind==="present"?e.raw:null}r($t,"projectRawOf");var Nc="[subagents] Refusing to write config before the first load; change not saved",Dn=class{static{r(this,"LayeredConfig")}io;files=null;constructor(n=Hc){this.io=n}get paths(){return this.io.paths()}get effective(){let n=this.files;return n===null?jt({}):jt(ys(n.globalRaw,$t(n.projectLayer)))}get global(){return this.files?.globalRaw??{}}get project(){let n=this.files;return n===null?null:$t(n.projectLayer)}get isProjectWritable(){let n=this.files;return n!==null&&n.projectLayer.kind!=="refused"}get isGlobalWritable(){return this.files!==null&&this.io.isGlobalWritable()}setProjectDir(n){this.io=ze(n)}reload(){let n=this.io.load();this.files={globalRaw:n.global,projectLayer:Lc(n)}}mutate(n,t){let o=this.loadedOrWarn();if(o===null)return!1;if(n==="global")return this.globalWritableOrWarn()?(t(o.globalRaw),this.io.saveGlobal(o.globalRaw),!0):!1;let s=Dc(o);return s===null?!1:(t(s),this.io.saveProject(s),!0)}clear(n,t,o){if((n==="session"||n==="all")&&o(),n==="session")return;let s=this.loadedOrWarn();if(s===null)return;(n==="global"||n==="all")&&this.globalWritableOrWarn()&&(t(s.globalRaw),this.io.saveGlobal(s.globalRaw));let i=$t(s.projectLayer);i&&(n==="project"||n==="all")&&(t(i),this.io.saveProject(i))}loadedOrWarn(){return this.files!==null?this.files:(console.warn(Nc),null)}globalWritableOrWarn(){return this.isGlobalWritable?!0:(console.warn("[subagents] Refusing to write global config (malformed); change not saved"),!1)}};function Dc(e){let n=e.projectLayer;if(n.kind==="present")return n.raw;if(n.kind==="refused")return console.warn(`[subagents] Project config target unavailable (${n.status}); change ignored`),null;let t={};return e.projectLayer={kind:"present",raw:t},t}r(Dc,"projectLayerToWrite");var jc=ze();function hs(e){let n=e?.agent;return n?Object.keys(n).some(t=>Dt(t)&&n[t]!==void 0):!1}r(hs,"agentLayerHasModelSettings");function jn(e,n){return e?.agent!=null&&e.agent[n]!==void 0}r(jn,"layerHasAgentKey");function Ye(e,n){return e!=null&&Object.hasOwn(e,n)}r(Ye,"layerCarriesEntry");function $c(e){let n=Yo.safeParse(e);if(!n.success)throw new RangeError(`Invalid pi thinking level ${JSON.stringify(e)}`);return n.data}r($c,"piThinkingLevel");function $n(e){return $(e)?"pi":e}r($n,"thinkingSlot");function Fc(e){return Object.values(e).some(n=>n!=null)}r(Fc,"sessionOverridesHasModelSettings");function Ft(e){return e.default!==void 0||e.harnesses!=null&&Object.keys(e.harnesses).length>0||e.providers!=null&&Object.keys(e.providers).length>0||e.models!=null&&Object.keys(e.models).length>0}r(Ft,"concurrencyLayerHasSettings");var Gc=new Set(Hn.filter(e=>!Nt.has(e)));function Je(e){return typeof e=="string"&&/\S/.test(e)?e:void 0}r(Je,"nonBlankString");function Fn(e){if(!Mt.safeParse(e).success)throw new RangeError(`Invalid concurrency limit ${JSON.stringify(e)}: expected ${Te}.`)}r(Fn,"assertConcurrencyLimit");function Gt(e){return e.defaultModelByHarness??{}}r(Gt,"rawHarnessDefaults");function Es(e){return e.defaultThinkingByHarness??{}}r(Es,"rawThinkingByHarness");function bs(e){return e.thinking??{}}r(bs,"rawThinkingByType");var Gn=class{static{r(this,"ConfigStore")}layers;sessionOverrides={default:null};sessionThinking={};sessionHarnessDefaults={};sessionThinkingDefaults={};sessionConcurrencyLayer={};manager;constructor(n=jc){this.layers=new Dn(n)}setProjectDir(n){this.layers.setProjectDir(n)}get isProjectWritable(){return this.layers.isProjectWritable}get agent(){let n=this.layers.effective.agent;return{defaultModel:n.default,defaultAgentType:n.defaultAgentType??_n,defaultOrchestrator:n.defaultOrchestrator??Cn,systemPromptMode:n.systemPromptMode??"replace",includeContextFiles:n.includeContextFiles??!0,defaultThinking:n.defaultThinking,loadSkillsImplicitly:n.loadSkillsImplicitly??!0,loadExtensionsImplicitly:n.loadExtensionsImplicitly??!0,disableDefaultAgents:n.disableDefaultAgents??!1,extensionEnabled:n.extensionEnabled??!0,showActiveIndicator:n.showActiveIndicator??!0,grazingEnabled:n.grazingEnabled===!0,worktreeRoot:n.worktreeRoot,worktreeMaterialization:n.worktreeMaterialization??Me,worktreeCheckoutType:n.worktreeCheckoutType??en,handoverMaxExcludedRatio:n.handoverMaxExcludedRatio??Mn,harnessType:n.harnessType??X}}get multiplexer(){return this.layers.effective.multiplexer}harnessConfigLayers(){return{global:this.layers.global.harness??{},project:this.layers.project?.harness??{}}}harnessEnv(n){let t=this.layers.global.harness?.[n]?.env;return y(t)?t:void 0}reportHarnessConfigIssue(n,t){let o=this.layers.paths,s=t.layer==="project"?o.project??o.global:o.global;console.warn(Be(s,`harness.${n}${t.keyPath===""?"":`.${t.keyPath}`}`,t.got,t.expected,Ue))}get concurrency(){let n=this.layers.effective.concurrency,t=this.sessionConcurrencyLayer;return{default:t.default??n.default,harnesses:{...n.harnesses,...t.harnesses},providers:{...n.providers,...t.providers},models:{...n.models,...t.models}}}get sessionDefaultModel(){return this.sessionOverrides.default??null}sessionModelOverride(n){return this.sessionOverrides[n]??null}defaultModelForHarness(n){return Je(this.sessionHarnessDefaults[n])??qo(this.layers.effective.agent,n)}sessionThinkingOverride(n){return this.sessionThinking[n]??null}defaultThinkingForHarness(n){return Je(this.sessionThinkingDefaults[$n(n)])??es(this.layers.effective.agent,n)}thinkingFor(n,t,o,s,i){return ns({subagentType:n,agentConfig:t,harnessFamily:s,config:this.layers.effective,harnessDefault:this.defaultThinkingForHarness(o),parentThinking:i,sessionThinking:this.sessionThinking})}configuredHarnessIds(){let n=new Set([this.agent.harnessType]);for(let o of Object.keys(Gt(this.layers.effective.agent)))n.add(o);for(let o of Object.keys(this.concurrency.harnesses))n.add(o);let t=this.harnessConfigLayers();for(let o of Object.keys(t.global))n.add(o);for(let o of Object.keys(t.project))n.add(o);for(let o of[...Object.keys(this.concurrency.providers),...Object.keys(this.concurrency.models)]){let s=ge(o);s!==void 0&&n.add(s.harness)}return[...n]}modelOverrideLevels(n){return{session:this.sessionModelOverride(n)!==null,global:jn(this.layers.global,n),project:jn(this.layers.project,n)}}harnessDefaultModelLevels(n){return{session:Je(this.sessionHarnessDefaults[n])!==void 0,global:Ye(this.layers.global.agent?.defaultModelByHarness,n),project:Ye(this.layers.project?.agent?.defaultModelByHarness,n)}}harnessDefaultThinkingLevels(n){return{session:Je(this.sessionThinkingDefaults[$n(n)])!==void 0,global:this.harnessThinkingAt(this.layers.global,n),project:this.harnessThinkingAt(this.layers.project,n)}}harnessThinkingAt(n,t){return $(t)?jn(n,"defaultThinking"):Ye(n?.agent?.defaultThinkingByHarness,t)}thinkingOverrideLevels(n){return{session:this.sessionThinking[n]!=null,global:Ye(this.layers.global.agent?.thinking,n),project:Ye(this.layers.project?.agent?.thinking,n)}}hasProjectModelKey(n){return jn(this.layers.project,n)}hasProjectThinkingKey(n){return Ge(this.layers.project?.agent?.thinking?.[n])}modelSettingsLevels(){return{session:Fc(this.sessionOverrides)||Object.keys(this.sessionHarnessDefaults).length>0||Object.values(this.sessionThinking).some(n=>n!=null)||Object.values(this.sessionThinkingDefaults).some(n=>Je(n)!==void 0),global:hs(this.layers.global),project:hs(this.layers.project)}}get projectConcurrency(){return{...this.layers.project?.concurrency}}get globalConcurrency(){return{...this.layers.global.concurrency}}get sessionConcurrency(){return{...this.sessionConcurrencyLayer}}concurrencySettingsLevels(){return{session:Ft(this.sessionConcurrencyLayer),global:Ft(this.layers.global.concurrency??{}),project:Ft(this.layers.project?.concurrency??{})}}agentConfigSnapshot(){return this.layers.effective.agent}modelFor(n,t,o,s,i){return Zo({subagentType:n,agentConfig:o,harnessFamily:i,config:this.layers.effective,harnessDefault:this.defaultModelForHarness(s),parentModelId:t,sessionOverrides:this.sessionOverrides})}mutate={agent:{setDefaultModel:r((n,t="global")=>{this.setAgentModelKey("default",n,t)},"setDefaultModel"),setModelOverride:r((n,t,o="global")=>{this.setAgentModelKey(n,t,o)},"setModelOverride"),clearModelOverride:r((n,t="global")=>{this.layers.clear(t,o=>{o.agent&&delete o.agent[n]},()=>{delete this.sessionOverrides[n]})},"clearModelOverride"),clearAllModelOverrides:r((n="global")=>{this.layers.clear(n,t=>this.clearAgentModelKeys(t),()=>{this.sessionOverrides={default:null},this.sessionThinking={},this.sessionHarnessDefaults={},this.sessionThinkingDefaults={}})},"clearAllModelOverrides"),setDefaultAgentType:r(n=>this.setAgentLayerEntry("defaultAgentType",n,"global"),"setDefaultAgentType"),setDefaultOrchestrator:r(n=>this.setAgentLayerEntry("defaultOrchestrator",n,"global"),"setDefaultOrchestrator"),setSystemPromptMode:r(n=>this.setAgentLayerEntry("systemPromptMode",n,"global"),"setSystemPromptMode"),setIncludeContextFiles:r(n=>this.setAgentLayerEntry("includeContextFiles",n,"global"),"setIncludeContextFiles"),setDefaultThinking:r((n,t="global")=>{this.setAgentLayerEntry("defaultThinking",n,t)},"setDefaultThinking"),setLoadSkillsImplicitly:r(n=>this.setAgentLayerEntry("loadSkillsImplicitly",n,"global"),"setLoadSkillsImplicitly"),setLoadExtensionsImplicitly:r(n=>this.setAgentLayerEntry("loadExtensionsImplicitly",n,"global"),"setLoadExtensionsImplicitly"),setDisableDefaultAgents:r(n=>this.setAgentLayerEntry("disableDefaultAgents",n,"global"),"setDisableDefaultAgents"),setExtensionEnabled:r(n=>this.setAgentLayerEntry("extensionEnabled",n,"global"),"setExtensionEnabled"),setShowActiveIndicator:r(n=>this.setAgentLayerEntry("showActiveIndicator",n,"global"),"setShowActiveIndicator"),setGrazingEnabled:r(n=>this.setAgentLayerEntry("grazingEnabled",n,"global"),"setGrazingEnabled"),setWorktreeRoot:r(n=>this.setAgentLayerEntry("worktreeRoot",n,"global"),"setWorktreeRoot"),setWorktreeMaterialization:r(n=>this.setAgentLayerEntry("worktreeMaterialization",n,"global"),"setWorktreeMaterialization"),setWorktreeCheckoutType:r(n=>this.setAgentLayerEntry("worktreeCheckoutType",n,"global"),"setWorktreeCheckoutType"),setHarnessType:r(n=>this.setAgentLayerEntry("harnessType",n,"global"),"setHarnessType"),setHarnessDefaultModel:r((n,t,o="global")=>{if(o==="session"){this.sessionHarnessDefaults[n]=t;return}this.layers.mutate(o,s=>{s.agent??={},s.agent.defaultModelByHarness={...Gt(s.agent),[n]:t}})},"setHarnessDefaultModel"),clearHarnessDefaultModel:r((n,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;let s=Gt(o.agent);delete s[n],Object.keys(s).length===0?delete o.agent.defaultModelByHarness:o.agent.defaultModelByHarness=s},()=>{delete this.sessionHarnessDefaults[n]})},"clearHarnessDefaultModel"),setThinkingOverride:r((n,t,o="global")=>{if(o==="session"){this.sessionThinking[n]=t;return}this.layers.mutate(o,s=>{s.agent??={},s.agent.thinking={...bs(s.agent),[n]:t}})},"setThinkingOverride"),clearThinkingOverride:r((n,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;let s=bs(o.agent);delete s[n],Object.keys(s).length===0?delete o.agent.thinking:o.agent.thinking=s},()=>{delete this.sessionThinking[n]})},"clearThinkingOverride"),setHarnessDefaultThinking:r((n,t,o="global")=>{if(o==="session"){this.sessionThinkingDefaults[$n(n)]=t;return}if($(n)){let s=t===null?void 0:$c(t);this.setAgentLayerEntry("defaultThinking",s,o);return}this.layers.mutate(o,s=>{s.agent??={},s.agent.defaultThinkingByHarness={...Es(s.agent),[n]:t}})},"setHarnessDefaultThinking"),clearHarnessDefaultThinking:r((n,t="global")=>{this.layers.clear(t,o=>{if(!o.agent)return;if($(n)){delete o.agent.defaultThinking;return}let s=Es(o.agent);delete s[n],Object.keys(s).length===0?delete o.agent.defaultThinkingByHarness:o.agent.defaultThinkingByHarness=s},()=>{delete this.sessionThinkingDefaults[$n(n)]})},"clearHarnessDefaultThinking")},concurrency:{setDefault:r((n,t="global")=>{Fn(n),this.applyConcurrencyWrite(t,o=>{o.default=n})},"setDefault"),setHarness:r((n,t,o="global")=>{Fn(t),this.applyConcurrencyWrite(o,s=>{s.harnesses={...s.harnesses,[n]:t}})},"setHarness"),setProvider:r((n,t,o="global")=>{Fn(t),this.applyConcurrencyWrite(o,s=>{s.providers={...s.providers,[n]:t}})},"setProvider"),setModel:r((n,t,o="global")=>{Fn(t),this.applyConcurrencyWrite(o,s=>{s.models={...s.models,[n]:t}})},"setModel"),removeHarness:r((n,t="global")=>{this.removeConcurrencyEntry("harnesses",n,t)},"removeHarness"),removeProvider:r((n,t="global")=>{this.removeConcurrencyEntry("providers",n,t)},"removeProvider"),removeDefault:r((n="global")=>{this.removeConcurrencyEntry("default",void 0,n)},"removeDefault"),removeModel:r((n,t="global")=>{this.removeConcurrencyEntry("models",n,t)},"removeModel"),clearAll:r((n="global")=>{this.layers.clear(n,t=>{delete t.concurrency},()=>{this.sessionConcurrencyLayer={}}),this.applyConcurrency()},"clearAll")},session:{setOverride:r((n,t)=>{this.sessionOverrides[n]=t},"setOverride"),clearOverride:r(n=>{delete this.sessionOverrides[n]},"clearOverride"),clearAll:r(()=>{this.sessionOverrides={default:null}},"clearAll")}};reload(){this.layers.reload(),this.sessionOverrides={default:null},this.sessionThinking={},this.sessionHarnessDefaults={},this.sessionThinkingDefaults={},this.sessionConcurrencyLayer={},this.applyConcurrency()}setDeps(n){n.manager!==void 0&&(this.manager=n.manager),this.applyConcurrency()}dispose(){this.manager=void 0}setAgentLayerEntry(n,t,o){this.layers.mutate(o,s=>{s.agent??={},t===void 0?delete s.agent[n]:s.agent[n]=t})}setAgentModelKey(n,t,o){if(o==="session"){this.sessionOverrides[n]=t;return}this.setAgentLayerEntry(n,t,o)}applyConcurrencyWrite(n,t){if(n==="session")t(this.sessionConcurrencyLayer);else if(!this.layers.mutate(n,o=>{o.concurrency??={},t(o.concurrency)}))return;this.applyConcurrency()}clearAgentModelKeys(n){if(n.agent)for(let t of Object.keys(n.agent))Gc.has(t)||delete n.agent[t]}removeConcurrencyEntry(n,t,o){let s=r(i=>{if(!i)return;if(n==="default"){delete i.default;return}if(t===void 0)return;if(n==="harnesses"){i.harnesses&&delete i.harnesses[t];return}let a=i[n];a&&delete a[t]},"removeFrom");this.layers.clear(o,i=>s(i.concurrency),()=>s(this.sessionConcurrencyLayer)),this.applyConcurrency()}applyConcurrency(){this.manager?.setConcurrency(this.concurrency)}};var xs={user:"",project:"",shared:""};function Kc(){return{agents:{agents:new Map,scanDirs:xs},orchestrators:{orchestrators:new Map,scanDirs:xs}}}r(Kc,"createSessionTemplates");var p={pi:null,sessionCtx:null,manager:null,store:new Gn,coordinator:null,runtime:null,agentSpawns:new On,repoLock:new nn,sessionTemplates:Kc(),indicatorMarker:null,harnesses:Et(),multiplexers:Ct(),cowAvailability:Jn(),cowAvailabilityClaim:0,harnessAvailability:Jn(),harnessModelCatalog:null,uiFlowClaim:0,uiFlows:new WeakMap};function Uc(){if(p.pi===null)throw new Error("pi instance read before the extension factory bound it");return p.pi}r(Uc,"getPiInstance");function Bc(){if(p.sessionCtx===null)throw new Error("session context read before session_start fired");return p.sessionCtx}r(Bc,"getSessionCtx");function Eh(){if(p.manager===null)throw new Error("agent manager read outside a live session");return p.manager}r(Eh,"getManager");function bh(){return p.manager}r(bh,"getManagerOrNull");function xh(){return p.store}r(xh,"getStore");function wh(){return p.indicatorMarker}r(wh,"getIndicatorMarker");function vh(e){p.indicatorMarker=e}r(vh,"setIndicatorMarker");function kh(){return p.agentSpawns}r(kh,"getAgentSpawns");function Ah(){return p.repoLock}r(Ah,"getRepoLock");function Sh(){if(p.coordinator===null)throw new Error("spawn coordinator read outside a live session");return p.coordinator}r(Sh,"getCoordinator");function Rh(){return p.coordinator}r(Rh,"getCoordinatorOrNull");function Ih(){return p.cowAvailability}r(Ih,"getCowAvailability");function Th(){return p.cowAvailabilityClaim+=1,p.cowAvailabilityClaim}r(Th,"beginCowAvailabilityProbe");function _h(e,n){return e!==p.cowAvailabilityClaim?!1:(p.cowAvailability=n,!0)}r(_h,"setCowAvailability");function Ch(){return p.harnesses}r(Ch,"getHarnessRegistry");function Vc(e){return{getAvailable:r(()=>e.getAvailable().map(n=>({provider:n.provider,id:n.id,thinkingLevels:Wc(n)})),"getAvailable")}}r(Vc,"piModelCatalog");function Oh(){let e=Et(),n=Ct();return p.harnesses=e,p.multiplexers=n,p.harnessModelCatalog=null,{harnesses:e,multiplexers:n}}r(Oh,"installSessionRegistries");function Ph(){return p.harnessAvailability}r(Ph,"getHarnessAvailability");function Mh(e){p.harnessAvailability=e}r(Mh,"setHarnessAvailability");function Hh(){return p.harnessModelCatalog}r(Hh,"getHarnessModelCatalogOrNull");function Lh(){return p.harnessModelCatalog??=wo({registry:p.harnesses,availability:p.harnessAvailability,request:{pi:Uc(),modelCatalog:Vc(Bc().modelRegistry)}}),p.harnessModelCatalog}r(Lh,"getHarnessModelCatalog");function Nh(e){p.harnessModelCatalog=e}r(Nh,"setHarnessModelCatalog");function Dh(){return ur(p.store.agent.worktreeMaterialization,p.cowAvailability)}r(Dh,"getWorktreeMaterialization");function jh(e){p.uiFlowClaim+=1,p.uiFlows.set(e,p.uiFlowClaim)}r(jh,"beginUiFlow");function $h(e){let n=p.uiFlows.get(e);return n===void 0||n===p.uiFlowClaim}r($h,"ownsUiFlow");function Fh(){return p.harnesses.resolve(p.store.agent.harnessType,p.harnessAvailability)}r(Fh,"getHarnessType");function Gh(){return p.runtime}r(Gh,"getRuntime");function Wh(){return p.sessionTemplates}r(Wh,"getSessionTemplates");function Kh(e){p.pi=e}r(Kh,"setPiInstance");function Uh(e){p.sessionCtx=e}r(Uh,"setSessionCtx");function Bh(e){p.manager=e}r(Bh,"setManager");function Vh(e){p.coordinator=e}r(Vh,"setCoordinator");function zh(e){p.runtime=e}r(zh,"setRuntime");function Yh(e){p.sessionTemplates=e}r(Yh,"setSessionTemplates");var zc=new RegExp(`${Yn}([A-Za-z0-9_-]+)`);function Jh(e=process.argv){for(let n of e){let t=zc.exec(n);if(t)return t[1]}}r(Jh,"detectSubagentSpawn");function Zh(e){let n=e.theme.fg("success","\u2713"),t=e.theme.fg("error","\u2717");return{pending:r(o=>e.notify(`${o} \u2026`,"info"),"pending"),succeeded:r((o,s="info")=>e.notify(`${n} ${o}`,s),"succeeded"),failed:r((o,s)=>e.notify(`${t} ${o}: ${h(s)}`,"error"),"failed"),outcome:r((o,s)=>o==="error"?e.notify(`${t} ${s}`,"error"):e.notify(`${n} ${s}`,o==="warning"?"warning":"info"),"outcome")}}r(Zh,"actionReport");export{Ss as a,M as b,sr as c,q as d,Qc as e,Zc as f,ir as g,eu as h,nu as i,tu as j,su as k,Jn as l,Pe as m,iu as n,Me as o,gu as p,fu as q,en as r,mu as s,yu as t,hu as u,Eu as v,Cs as w,bu as x,Ps as y,xu as z,wu as A,vu as B,ku as C,V as D,Tu as E,Z as F,H as G,Sf as H,wo as I,Hf as J,An as K,J as L,Yo as M,_n as N,Cn as O,Yl as P,Jl as Q,Xo as R,Gm as S,Wm as T,Km as U,Um as V,Bm as W,ql as X,Zm as Y,Ql as Z,sy as _,iy as $,ay as aa,dy as ba,ge as ca,ss as da,ls as ea,yy as fa,hy as ga,Wy as ha,Kc as ia,Uc as ja,Bc as ka,Eh as la,bh as ma,xh as na,wh as oa,vh as pa,kh as qa,Ah as ra,Sh as sa,Rh as ta,Ih as ua,Th as va,_h as wa,Ch as xa,Vc as ya,Oh as za,Ph as Aa,Mh as Ba,Hh as Ca,Lh as Da,Nh as Ea,Dh as Fa,jh as Ga,$h as Ha,Fh as Ia,Gh as Ja,Wh as Ka,Kh as La,Uh as Ma,Bh as Na,Vh as Oa,zh as Pa,Yh as Qa,Jh as Ra,Zh as Sa};
|
|
54
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
//# sourceMappingURL=chunk-UEMXTMQN.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ha as x}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{Ha as x}from"./chunk-UEMXTMQN.js";import{a as s,q as f,y as C}from"./chunk-AOUEQXPY.js";import{Container as y,fuzzyFilter as M,getKeybindings as N,Input as k,Spacer as v,Text as b}from"@earendil-works/pi-tui";import{DynamicBorder as w}from"@earendil-works/pi-coding-agent";var h=10,g=class extends y{static{s(this,"SearchableSelectDialog")}searchInput;listContainer;items;filteredItems;selectedIndex;currentValue;callbacks;theme;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,this.searchInput.focused=e}constructor(e,n,r,l){super(),this.items=e,this.currentValue=n,this.callbacks=r,this.theme=l,this.filteredItems=[...e];let a=e.findIndex(o=>o.value===n);this.selectedIndex=a>=0?a:0,this.addChild(new w),this.addChild(new v(1)),this.searchInput=new k,this.searchInput.onSubmit=()=>{this.filteredItems[this.selectedIndex]&&this.callbacks.onSelect(this.filteredItems[this.selectedIndex].value)},this.addChild(this.searchInput),this.addChild(new v(1)),this.listContainer=new y,this.addChild(this.listContainer),this.addChild(new v(1)),this.addChild(new w),this.updateList()}handleInput(e){let n=N();if(!(this.filteredItems.length===0&&(n.matches(e,"tui.select.up")||n.matches(e,"tui.select.down")||n.matches(e,"tui.select.pageUp")||n.matches(e,"tui.select.pageDown")))){if(n.matches(e,"tui.select.up")){this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.updateList();return}if(n.matches(e,"tui.select.down")){this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.updateList();return}if(n.matches(e,"tui.select.pageUp")){this.selectedIndex=Math.max(0,this.selectedIndex-h),this.updateList();return}if(n.matches(e,"tui.select.pageDown")){this.selectedIndex=Math.min(this.filteredItems.length-1,this.selectedIndex+h),this.updateList();return}if(n.matches(e,"tui.select.confirm")){let r=this.filteredItems.at(this.selectedIndex);r&&this.callbacks.onSelect(r.value);return}if(n.matches(e,"tui.select.cancel")){this.callbacks.onCancel();return}this.searchInput.handleInput(e),this.filterItems()}}invalidate(){}filterItems(){let e=this.searchInput.getValue();e?this.filteredItems=M(this.items,e,n=>`${n.label} ${n.provider} ${n.value??""}`):this.filteredItems=[...this.items],this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredItems.length-1)),this.updateList()}updateList(){this.listContainer.clear();let{filteredItems:e}=this;if(e.length===0){this.listContainer.addChild(new b(this.theme.fg("muted"," No matching items"),0,0));return}let n=Math.max(0,Math.min(this.selectedIndex-Math.floor(h/2),e.length-h)),r=Math.min(n+h,e.length);for(let l=n;l<r;l++){let a=e.at(l);if(!a)continue;let o=l===this.selectedIndex,d=a.value===this.currentValue,c=o?this.theme.fg("accent","\u2192 ")+this.theme.fg("accent",a.label):` ${a.label}`,i=a.provider?this.theme.fg("muted",`[${a.provider}]`):"",u=d?this.theme.fg("success"," \u2713"):"",m=`${c} ${i}${u}`;this.listContainer.addChild(new b(m,0,0))}if(n>0||r<e.length){let l=this.theme.fg("muted",` (${this.selectedIndex+1}/${e.length})`);this.listContainer.addChild(new b(l,0,0))}}};import{isFocusable as L}from"@earendil-works/pi-tui";var O=class{constructor(e){this.ctx=e}ctx;static{s(this,"ScreenHost")}async open(e){return await this.show(e,!1)}async openOverlay(e){return await this.show(e,!0)}async show(e,n){if(x(this.ctx))return await new Promise(r=>{this.ctx.ui.custom((l,a,o,d)=>e({tui:l,theme:a,keybindings:o,close:s(c=>{x(this.ctx)&&d(c),r(c)},"close")}),n?{overlay:!0}:void 0).then(r)})}},j=void 0;function K(t){return Object.assign(t,{focused:!0})}s(K,"asSubmenuComponent");var I=class{static{s(this,"SwappableView")}active;constructor(e){this.active=e}activate(e){this.active=e}invalidate(){this.active.invalidate()}render(e){return this.active.render(e)}handleInput(e){this.active.handleInput?.(e)}get focused(){return L(this.active)?this.active.focused:!1}set focused(e){L(this.active)&&(this.active.focused=e)}};var F="group-header";function q(t,e){return{id:T,kind:F,label:t.bold(t.fg("accent",e)),currentValue:""}}s(q,"headerItem");var T="__sep__",p=new WeakMap;function X(t){if(!Array.isArray(t.items))return;let e=s(o=>o?.value===T||o?.id===T,"isSep"),n=s((o,d,c)=>{let i=d+c;for(;i>=0&&i<o.length&&e(o[i]);)i+=c;return i},"firstNonSepFrom"),r=s((o,d)=>d>=0&&d<o.length,"inBounds"),l=s((o,d)=>{let c=Math.max(0,Math.min(d,o.length-1));for(let i=c;i<o.length;i+=1)if(!e(o[i]))return i;for(let i=c-1;i>=0;i-=1)if(!e(o[i]))return i;return 0},"seedIndex"),a=t.selectedIndex??0;Object.defineProperty(t,"selectedIndex",{get(){return p.get(t)},set(o){let d=t.items,c=p.get(t)??0,i=Math.max(0,Math.min(o,d.length-1));if(!e(d[i])){p.set(t,i);return}let u=o>c?1:-1,m=n(d,i,u),S=n(d,i,-u);r(d,m)?p.set(t,m):r(d,S)?p.set(t,S):p.set(t,i)},configurable:!0}),p.set(t,l(t.items,a))}s(X,"installSeparatorSkip");function J(t,e,n){let r=[{value:null,label:"(none)",provider:""}],l=[];for(let i of t){let u=f(i);u&&l.push({value:i,label:u.modelId,provider:u.provider})}if(e===null&&n.length===0)return r.push(...l),r;let a=[],o=[],d=[],c=new Set;if(e){let i=f(e);i&&(a.push({value:e,label:i.modelId,provider:i.provider}),c.add(e))}for(let i of n){if(c.has(i))continue;let u=f(i);u&&(o.push({value:i,label:u.modelId,provider:u.provider}),c.add(i))}for(let i of l)i.value!=null&&!c.has(i.value)&&d.push(i);return r.push(...a,...o,...d),r}s(J,"buildModelOptions");function Q(t){let e=[];t.default&&typeof t.default=="string"&&e.push(t.default);for(let[n,r]of Object.entries(t))n!=="default"&&typeof r=="string"&&r.includes("/")&&e.push(r);return[...new Set(e)]}s(Q,"extractConfiguredModels");function Y(t,e){return C(t)?e:[]}s(Y,"mergedModelsForHarness");function Z(t){return{label:s((e,n)=>n?t.fg("accent",e):e,"label"),value:s((e,n)=>n?t.fg("accent",e):t.fg("muted",e),"value"),description:s(e=>t.fg("dim",e),"description"),cursor:t.fg("accent","\u2192 "),hint:s(e=>t.fg("dim",e),"hint")}}s(Z,"buildSettingsListTheme");function ee(t,e){let n=t.trim();if(!/^\d*\.?\d+$/.test(n))return;let r=parseFloat(n);if(!(r<e))return r}s(ee,"validateNumeric");var _=new Map([["k","\x1B[A"],["j","\x1B[B"]]);function te(t){let e=t,n=e.handleInput?.bind(e);return n&&(e.handleInput=r=>{let l=e.submenuComponent?void 0:_.get(r);n(l??r)}),t}s(te,"withVimKeys");function ne(t){return{selectedPrefix:s(()=>t.fg("accent","\u2192 "),"selectedPrefix"),selectedText:s(e=>t.fg("accent",e),"selectedText"),description:s(e=>t.fg("muted",e),"description"),scrollInfo:s(e=>t.fg("dim",e),"scrollInfo"),noMatch:s(e=>t.fg("dim",e),"noMatch")}}s(ne,"buildSelectListTheme");function ie(t,e,n){let r,l=new g(t,null,{onSelect:s(a=>{let o=e.onSelect(a);o&&r.activate(o)},"onSelect"),onCancel:e.onCancel},n);return r=new I(l),r}s(ie,"createSearchableSelect");function se(t){return t.length===1?`agent ${t[0]}`:`${t.length} agent(s)`}s(se,"agentSubject");export{g as a,O as b,j as c,K as d,I as e,q as f,T as g,X as h,J as i,Q as j,Y as k,Z as l,ee as m,te as n,ne as o,ie as p,se as q};
|
|
2
|
+
//# sourceMappingURL=chunk-WP65L6WI.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as l,n as h}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{h as l,n as h}from"./chunk-WP65L6WI.js";import{a as r}from"./chunk-AOUEQXPY.js";import{isFocusable as c}from"@earendil-works/pi-tui";var g=new Map([["\x1B[C","\r"],["\x1BOC","\r"],["\x1B[D","\x1B"],["\x1BOD","\x1B"]]),p=class{static{r(this,"SettingsListWrapper")}settingsList;title;theme;separatorChar;passthroughKeys;constructor(t,e){this.settingsList=e.passthroughKeys?t:h(t),this.title=e.title,this.theme=e.theme,this.separatorChar=e.separatorChar??"\u2500",this.passthroughKeys=e.passthroughKeys??!1;let n=this.settingsList;if(e.onCancel&&!n.onCancel){let s=e.onCancel;n.onCancel=()=>s()}if(e.onCancel&&l(n),e.onRebuild){let s=r((o,m)=>{n.items=o,n.filteredItems=o,n.submenuComponent=null;let a=o.findIndex(u=>u.id===m);n.selectedIndex=a>0?a:0},"rebuild");e.onRebuild(s)}}invalidate(){this.settingsList.invalidate()}get submenuComponent(){return this.settingsList.submenuComponent??null}get hasSubmenu(){return c(this.submenuComponent)}handleInput(t){if(this.passthroughKeys||this.hasSubmenu){this.settingsList.handleInput?.(t);return}let e=g.get(t);if(e!==void 0){this.settingsList.handleInput?.(e);return}this.settingsList.handleInput?.(t)}render(t){let e=[];e.push(this.separatorChar.repeat(t)),e.push("");let n=this.theme.bold(this.theme.fg("accent",this.title));e.push(" "+n),e.push("");let s=this.settingsList.render(t),o=/Enter\/Space|Esc to cancel/;return s.length>=2&&o.test(s[s.length-1]??"")?e.push(...s.slice(0,-2)):e.push(...s),e.push(""),e.push(this.separatorChar.repeat(t)),e}};import{Input as d}from"@earendil-works/pi-tui";function f(i){let t=i.codePointAt(0)??0;return t<32||t===127||t>=128&&t<=159}r(f,"isControlCharacter");function S(i){let t=new d;t.focused=!0;for(let e of i.prefill)f(e)||t.handleInput(e);return t.onSubmit=e=>{let n=e.trim(),s=i.validate(n);if(s){i.notify(i.describeProblem(s),"error");return}i.onDone(n)},t.onEscape=()=>i.onCancel(),t}r(S,"createNameField");export{S as a,p as b};
|
|
2
|
+
//# sourceMappingURL=chunk-YTDE2OUW.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Te,b as Ut,c as Bt,d as Gt,j as Jt,k as U,o as Yt,p as Xt,s as Zt,v as en,w as Le,x as tn,y as nn,z as rn}from"./chunk-353K3BOB.js";import{E as qt,F as Nt,G as _t,O as Wt,Q as Vt,R as zt,S as Qt,a as It,f as Et,g as Q,h as Ct,m as Tt,n as Lt,o as Ft,q as Ot,r as jt,s as Ht,t as Mt,v as Dt,y as $t}from"./chunk-UG3ZH2M5.js";import{A as et,B as ie,Ba as St,C as tt,Ea as kt,F as oe,Fa as bt,G as K,I as at,J as xe,Ja as z,K as T,La as At,Ma as Pt,Na as Ee,Oa as Ce,P as W,Pa as ue,Qa as Rt,R as dt,Ra as xt,S as lt,Sa as Kt,T as V,U as H,V as ut,W as Ie,a as F,aa as ct,ba as pt,d as Ke,da as gt,e as C,ea as ht,f as re,fa as ae,g as Ve,ga as ft,h as se,ha as mt,ia as yt,ja as E,k as ze,ka as $,ma as de,na as A,qa as I,ta as le,w as Xe,xa as P,y as Ze,ya as wt,za as vt}from"./chunk-M5B2YQME.js";import{E as st,F as it,M as ot,a as i,b as Qe,c as Ye,n as nt,p as w,t as D,u as rt}from"./chunk-AOUEQXPY.js";import*as M from"node:path";function pe(t,e){let n=t.at(0);if(n)return{kind:"spawn",spawn:n};let r=e.at(0);return r?{kind:"multiplexer",attempt:r}:{kind:"none"}}i(pe,"findTaskDedup");var q=class extends Error{static{i(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,n){let r=e.kind==="spawn",s=r?`agent ${e.spawn.id}`:e.attempt.name,o=r?H(e.spawn.lifecycle):"live";super(`Task "${n}" is already in flight as ${s} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=n,this.dedup=e}},ce=class{constructor(e){this.deps=e}deps;static{i(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let n=e.taskSlug;if(n===void 0)return this.admitOne(e);let s=(this.admissionBySlug.get(n)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(n,s);try{return await s}finally{this.admissionBySlug.get(n)===s&&this.admissionBySlug.delete(n)}}async admitOne(e){if(e.taskSlug){let g=this.deps.listAgents().filter(p=>p.display.taskSlug===e.taskSlug&<(p.lifecycle.phase)),m=pe(g,await this.deps.findTaskAttempts(e.taskSlug));if(m.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:m.kind==="spawn"?m.spawn.id:m.attempt.name}}let{type:n,prompt:r,runInBackground:s,signal:o,...a}=e,d={...a,isBackground:s,signal:o},l=this.deps.spawn(n,r,d);return this.deps.getSpawn(l)?.lifecycle.phase==="queued"?{status:"queued",agentId:l,queuePosition:this.deps.queuePosition(l)}:{status:"admitted",agentId:l}}};import sn from"node:fs";var ge=class{constructor(e){this.resultFile=e}resultFile;static{i(this,"FileDeliverable")}async readDeliverable(){try{let e=sn.statSync(this.resultFile).mtimeMs,n=sn.readFileSync(this.resultFile,"utf-8").trim();return n?{content:n,mtime:e}:null}catch{return null}}};import on from"node:fs";import*as an from"node:path";function Y(t){try{on.rmSync(an.dirname(t),{recursive:!0,force:!0})}catch{}}i(Y,"removeResultArtifacts");function dn(t){try{on.rmSync(t,{force:!0})}catch{}}i(dn,"removeResultFile");import*as B from"node:fs";import*as he from"node:path";var br=T("assets");async function ln(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}i(ln,"probeList");function Ar(t,e,n){let r=n(e);return t?.find(s=>n(s.path)===r)}i(Ar,"matchWorktree");function un(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}i(un,"paneOf");function Pr(t,e,n,r){if(n===void 0)return e??void 0;let s=(t??[]).filter(o=>o.cwd!==void 0&&r(o.cwd)===r(n));return s.length===1?un(s[0]):e??void 0}i(Pr,"livePaneFor");function Fe(t,e){let n=t?.filter(e)??[];return n.length===1?un(n[0]):void 0}i(Fe,"solePaneAmong");function Rr(t){async function e(){try{return await t.worktreeRoot()}catch{return}}i(e,"root");async function n(l,c){let g=await e(),m=[],p=new Set,f=i(y=>{let h=t.canonicalizePath(y.path);p.has(h)||(p.add(h),m.push(y))},"push");for(let y of c??[]){let h=he.basename(y.path);ie(h,l)&&(g!==void 0&&!tt(y.path,g)||f({path:y.path,branch:y.branch!==void 0&&ie(y.branch,l)?y.branch:h,workspaceId:y.workspaceId}))}if(m.length>0||g===void 0)return m;for(let y of await t.listRootEntries(g))ie(y,l)&&f({path:he.join(g,y),branch:y});return m}i(n,"discoverCandidates");function r(l){return{worktreePath:l.path,branch:l.branch,workspaceId:l.workspaceId}}i(r,"candidateSummary");async function s(l,c,g,m){let p=c.execution.host,f=c.display.worktree,y=f?.kind==="owned",h=p?{paneId:p.paneId,tabId:p.tabId,workspaceId:p.workspaceId}:null,R="tracked",v=f?.kind==="owned"?f.path:void 0,b=p?.workspaceId;if(v!==void 0){let x=Ar(g,v,t.canonicalizePath);x!==void 0&&(b=x.workspaceId)}let L=h!==null?Pr(m,h,v,t.canonicalizePath)??h:v===void 0?null:Fe(m,x=>x.cwd!==void 0&&t.canonicalizePath(x.cwd)===t.canonicalizePath(v))??null,S=v===void 0?null:{path:v,workspaceId:b,repoCwd:await t.resolveRepoCwd(v)};return{kind:"located",source:R,id:l,branch:f?.branch??Ze(c.display.taskSlug??Xe(c.display.type),c.id),worktreeManaged:y||S!==null,paneCreated:p?.paneCreated===!0,worktree:S,pane:L}}i(s,"locateTracked");async function o(l,c,g){let m=await n(l,c);if(m.length===0)return{kind:"not-found",id:l};if(m.length>1)return{kind:"ambiguous",id:l,candidates:m.map(r)};let p=m[0],f=Fe(g,y=>y.cwd!==void 0&&t.canonicalizePath(y.cwd)===t.canonicalizePath(p.path))??Fe(g,y=>y.workspaceId===p.workspaceId)??null;return{kind:"located",source:"recovered",id:l,branch:p.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:p.path,workspaceId:p.workspaceId,repoCwd:await t.resolveRepoCwd(p.path)},pane:f}}i(o,"locateDiscovered");async function a(l,c){let g=await ln(t.listWorktrees),m=await ln(t.listPlacements),p=g.ok?g.entries:void 0,f=m.ok?m.entries:void 0;return c===void 0?o(l,p,f):s(l,c,p,f)}i(a,"locate");async function d(l,c){let g=await t.listPlacements(),m=l.checkoutPath===void 0?void 0:t.canonicalizePath(l.checkoutPath);return g.filter(p=>p.paneId===c?!1:p.workspaceId===l.workspaceId?!0:m!==void 0&&p.cwd!==void 0&&t.canonicalizePath(p.cwd)===m).map(p=>p.name??p.paneId)}return i(d,"otherTenants"),{multiplexer:t.multiplexer,locate:a,otherTenants:d,observe:i(l=>t.readPane(l.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}i(Rr,"createAgentAssets");function fe(t,e,n){return Rr({multiplexer:n.multiplexer,canonicalizePath:i(r=>n.canonicalizePath(r),"canonicalizePath"),deliverable:i(r=>{let s=C(r);return{path:s,present:B.existsSync(s)}},"deliverable"),listWorktrees:i(()=>n.listWorktrees(),"listWorktrees"),listPlacements:i(()=>n.listPlacements(),"listPlacements"),readPane:i(r=>n.observePane(r),"readPane"),worktreeRoot:i(async()=>{let r=$().cwd;if(!r)return;let s=await Q(t,r).catch(()=>{});return s===void 0?void 0:et(A().agent.worktreeRoot,s)},"worktreeRoot"),listRootEntries:i(async r=>{try{return await B.promises.readdir(r)}catch{return[]}},"listRootEntries"),resolveRepoCwd:i(async r=>{try{return await Q(t,r)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:i(r=>Lt(t,r),"isWorktreeDirty"),worktreeExists:i(async r=>B.existsSync(r),"worktreeExists"),removeWorktree:i(r=>e.release(r,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(r,s)=>(await Ct(t,s,r),!B.existsSync(r)),"removeGitWorktree"),deleteBranch:i(r=>Tt(t,r,s=>e.isAttached(s,{repoCwd:r.repoCwd})),"deleteBranch"),closePane:i(async r=>{await e.release(r,"placement")},"closePane"),teardownEnvironment:i(async({subagentId:r,runs:s})=>{let o=P();for(let a of s)try{await o.get(a.harness)?.teardown({pi:t,paneId:a.paneId,cwd:a.cwd,subagentId:r})}catch(d){br.warn("harness teardown failed during environment teardown",{subagentId:r,harness:a.harness,error:w(d)})}},"teardownEnvironment")})}i(fe,"createMultiplexerAgentAssets");var j=T("supervisor"),xr=2e3;function Ir(){let t;return{promise:new Promise(n=>{t=n}),resolve:t}}i(Ir,"deferred");var me=class{constructor(e,n,r={}){this.host=e;this.deliverable=n;this.pollMs=r.pollMs??xr,this.stopInitiator=r.stopInitiator??"user",this.onFollowUp=r.onFollowUp,this.stopProcess=r.stopProcess??((s,o)=>e.waitUntilGone(s,{timeoutMs:o}))}host;deliverable;static{i(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=Ir();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,n){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:n};try{await this.host.start(n,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(r){throw this.isWatching()&&(this.phase={kind:"idle"}),r}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},j.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),j.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(n=>{j.error("poll loop failed",{errorMessage:w(n)})}),this.settlement.promise}async stop(e){let n=this.phase;if(n.kind!=="watching"||this.outcome!==null)return!1;let{ref:r}=n,s=await this.stopProcess(r,e).catch(o=>(j.debug("stop failed",{errorMessage:w(o)}),!1));return j.debug("stop requested",{paneId:r.paneId,graceMs:e,stopped:s,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),s}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let n=this.phase;n.kind==="watching"&&(j.debug(e,{paneId:n.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,j.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let n=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);n.unref(),this.wakeLoop=()=>{clearTimeout(n),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!Er(this.held,e)){this.held=e,j.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return j.debug("readDeliverable failed",{errorMessage:w(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Er(t,e){return t.content===e.content&&t.mtime===e.mtime}i(Er,"sameReport");function X(t){let e=t.transport.createDeliverable(t.resultFile);return new me(t.host,e,t.supervisorOptions)}i(X,"createPaneSupervisor");function cn(t,e){t.host=e}i(cn,"placeExecution");function pn(t,e){t.harness=e}i(pn,"engageExecution");function gn(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}i(gn,"endExecutionRun");import He from"node:fs";import _ from"node:path";import{SettingsManager as Vr}from"@earendil-works/pi-coding-agent";import qr from"node:fs";import{loadProjectContextFiles as Nr}from"@earendil-works/pi-coding-agent";function hn(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
|
|
1
|
+
import{a as Te,b as Ut,c as Bt,d as Gt,j as Jt,k as U,o as Yt,p as Xt,s as Zt,v as en,w as Le,x as tn,y as nn,z as rn}from"./chunk-EWHWPOTC.js";import{E as qt,F as Nt,G as _t,O as Wt,Q as Vt,R as zt,S as Qt,a as It,f as Et,g as Q,h as Ct,m as Tt,n as Lt,o as Ft,q as Ot,r as jt,s as Ht,t as Mt,v as Dt,y as $t}from"./chunk-3FQQMEHD.js";import{A as et,B as ie,Ba as St,C as tt,Ea as kt,F as oe,Fa as bt,G as K,I as at,J as xe,Ja as z,K as T,La as At,Ma as Pt,Na as Ee,Oa as Ce,P as W,Pa as ue,Qa as Rt,R as dt,Ra as xt,S as lt,Sa as Kt,T as V,U as H,V as ut,W as Ie,a as F,aa as ct,ba as pt,d as Ke,da as gt,e as C,ea as ht,f as re,fa as ae,g as Ve,ga as ft,h as se,ha as mt,ia as yt,ja as E,k as ze,ka as $,ma as de,na as A,qa as I,ta as le,w as Xe,xa as P,y as Ze,ya as wt,za as vt}from"./chunk-UEMXTMQN.js";import{E as st,F as it,M as ot,a as i,b as Qe,c as Ye,n as nt,p as w,t as D,u as rt}from"./chunk-AOUEQXPY.js";import*as M from"node:path";function pe(t,e){let n=t.at(0);if(n)return{kind:"spawn",spawn:n};let r=e.at(0);return r?{kind:"multiplexer",attempt:r}:{kind:"none"}}i(pe,"findTaskDedup");var q=class extends Error{static{i(this,"TaskAlreadyInFlightError")}taskSlug;dedup;constructor(e,n){let r=e.kind==="spawn",s=r?`agent ${e.spawn.id}`:e.attempt.name,o=r?H(e.spawn.lifecycle):"live";super(`Task "${n}" is already in flight as ${s} (state: ${o}). No second agent was spawned.`),this.name="TaskAlreadyInFlightError",this.taskSlug=n,this.dedup=e}},ce=class{constructor(e){this.deps=e}deps;static{i(this,"HerdrTaskRegistry")}admissionBySlug=new Map;async admit(e){let n=e.taskSlug;if(n===void 0)return this.admitOne(e);let s=(this.admissionBySlug.get(n)??Promise.resolve()).catch(()=>{}).then(()=>this.admitOne(e));this.admissionBySlug.set(n,s);try{return await s}finally{this.admissionBySlug.get(n)===s&&this.admissionBySlug.delete(n)}}async admitOne(e){if(e.taskSlug){let g=this.deps.listAgents().filter(p=>p.display.taskSlug===e.taskSlug&<(p.lifecycle.phase)),m=pe(g,await this.deps.findTaskAttempts(e.taskSlug));if(m.kind!=="none")return{status:"rejected",reason:"already_in_flight",conflictingId:m.kind==="spawn"?m.spawn.id:m.attempt.name}}let{type:n,prompt:r,runInBackground:s,signal:o,...a}=e,d={...a,isBackground:s,signal:o},l=this.deps.spawn(n,r,d);return this.deps.getSpawn(l)?.lifecycle.phase==="queued"?{status:"queued",agentId:l,queuePosition:this.deps.queuePosition(l)}:{status:"admitted",agentId:l}}};import sn from"node:fs";var ge=class{constructor(e){this.resultFile=e}resultFile;static{i(this,"FileDeliverable")}async readDeliverable(){try{let e=sn.statSync(this.resultFile).mtimeMs,n=sn.readFileSync(this.resultFile,"utf-8").trim();return n?{content:n,mtime:e}:null}catch{return null}}};import on from"node:fs";import*as an from"node:path";function Y(t){try{on.rmSync(an.dirname(t),{recursive:!0,force:!0})}catch{}}i(Y,"removeResultArtifacts");function dn(t){try{on.rmSync(t,{force:!0})}catch{}}i(dn,"removeResultFile");import*as B from"node:fs";import*as he from"node:path";var br=T("assets");async function ln(t){try{return{ok:!0,entries:await t()}}catch{return{ok:!1}}}i(ln,"probeList");function Ar(t,e,n){let r=n(e);return t?.find(s=>n(s.path)===r)}i(Ar,"matchWorktree");function un(t){return{paneId:t.paneId,tabId:t.tabId,workspaceId:t.workspaceId}}i(un,"paneOf");function Pr(t,e,n,r){if(n===void 0)return e??void 0;let s=(t??[]).filter(o=>o.cwd!==void 0&&r(o.cwd)===r(n));return s.length===1?un(s[0]):e??void 0}i(Pr,"livePaneFor");function Fe(t,e){let n=t?.filter(e)??[];return n.length===1?un(n[0]):void 0}i(Fe,"solePaneAmong");function Rr(t){async function e(){try{return await t.worktreeRoot()}catch{return}}i(e,"root");async function n(l,c){let g=await e(),m=[],p=new Set,f=i(y=>{let h=t.canonicalizePath(y.path);p.has(h)||(p.add(h),m.push(y))},"push");for(let y of c??[]){let h=he.basename(y.path);ie(h,l)&&(g!==void 0&&!tt(y.path,g)||f({path:y.path,branch:y.branch!==void 0&&ie(y.branch,l)?y.branch:h,workspaceId:y.workspaceId}))}if(m.length>0||g===void 0)return m;for(let y of await t.listRootEntries(g))ie(y,l)&&f({path:he.join(g,y),branch:y});return m}i(n,"discoverCandidates");function r(l){return{worktreePath:l.path,branch:l.branch,workspaceId:l.workspaceId}}i(r,"candidateSummary");async function s(l,c,g,m){let p=c.execution.host,f=c.display.worktree,y=f?.kind==="owned",h=p?{paneId:p.paneId,tabId:p.tabId,workspaceId:p.workspaceId}:null,R="tracked",v=f?.kind==="owned"?f.path:void 0,b=p?.workspaceId;if(v!==void 0){let x=Ar(g,v,t.canonicalizePath);x!==void 0&&(b=x.workspaceId)}let L=h!==null?Pr(m,h,v,t.canonicalizePath)??h:v===void 0?null:Fe(m,x=>x.cwd!==void 0&&t.canonicalizePath(x.cwd)===t.canonicalizePath(v))??null,S=v===void 0?null:{path:v,workspaceId:b,repoCwd:await t.resolveRepoCwd(v)};return{kind:"located",source:R,id:l,branch:f?.branch??Ze(c.display.taskSlug??Xe(c.display.type),c.id),worktreeManaged:y||S!==null,paneCreated:p?.paneCreated===!0,worktree:S,pane:L}}i(s,"locateTracked");async function o(l,c,g){let m=await n(l,c);if(m.length===0)return{kind:"not-found",id:l};if(m.length>1)return{kind:"ambiguous",id:l,candidates:m.map(r)};let p=m[0],f=Fe(g,y=>y.cwd!==void 0&&t.canonicalizePath(y.cwd)===t.canonicalizePath(p.path))??Fe(g,y=>y.workspaceId===p.workspaceId)??null;return{kind:"located",source:"recovered",id:l,branch:p.branch,worktreeManaged:!0,paneCreated:!1,worktree:{path:p.path,workspaceId:p.workspaceId,repoCwd:await t.resolveRepoCwd(p.path)},pane:f}}i(o,"locateDiscovered");async function a(l,c){let g=await ln(t.listWorktrees),m=await ln(t.listPlacements),p=g.ok?g.entries:void 0,f=m.ok?m.entries:void 0;return c===void 0?o(l,p,f):s(l,c,p,f)}i(a,"locate");async function d(l,c){let g=await t.listPlacements(),m=l.checkoutPath===void 0?void 0:t.canonicalizePath(l.checkoutPath);return g.filter(p=>p.paneId===c?!1:p.workspaceId===l.workspaceId?!0:m!==void 0&&p.cwd!==void 0&&t.canonicalizePath(p.cwd)===m).map(p=>p.name??p.paneId)}return i(d,"otherTenants"),{multiplexer:t.multiplexer,locate:a,otherTenants:d,observe:i(l=>t.readPane(l.paneId),"observe"),deliverable:t.deliverable,isWorktreeDirty:t.isWorktreeDirty,worktreeExists:t.worktreeExists,removeWorktree:t.removeWorktree,removeGitWorktree:t.removeGitWorktree,deleteBranch:t.deleteBranch,closePane:t.closePane,teardownEnvironment:t.teardownEnvironment}}i(Rr,"createAgentAssets");function fe(t,e,n){return Rr({multiplexer:n.multiplexer,canonicalizePath:i(r=>n.canonicalizePath(r),"canonicalizePath"),deliverable:i(r=>{let s=C(r);return{path:s,present:B.existsSync(s)}},"deliverable"),listWorktrees:i(()=>n.listWorktrees(),"listWorktrees"),listPlacements:i(()=>n.listPlacements(),"listPlacements"),readPane:i(r=>n.observePane(r),"readPane"),worktreeRoot:i(async()=>{let r=$().cwd;if(!r)return;let s=await Q(t,r).catch(()=>{});return s===void 0?void 0:et(A().agent.worktreeRoot,s)},"worktreeRoot"),listRootEntries:i(async r=>{try{return await B.promises.readdir(r)}catch{return[]}},"listRootEntries"),resolveRepoCwd:i(async r=>{try{return await Q(t,r)}catch{return}},"resolveRepoCwd"),isWorktreeDirty:i(r=>Lt(t,r),"isWorktreeDirty"),worktreeExists:i(async r=>B.existsSync(r),"worktreeExists"),removeWorktree:i(r=>e.release(r,"worktree-association"),"removeWorktree"),removeGitWorktree:i(async(r,s)=>(await Ct(t,s,r),!B.existsSync(r)),"removeGitWorktree"),deleteBranch:i(r=>Tt(t,r,s=>e.isAttached(s,{repoCwd:r.repoCwd})),"deleteBranch"),closePane:i(async r=>{await e.release(r,"placement")},"closePane"),teardownEnvironment:i(async({subagentId:r,runs:s})=>{let o=P();for(let a of s)try{await o.get(a.harness)?.teardown({pi:t,paneId:a.paneId,cwd:a.cwd,subagentId:r})}catch(d){br.warn("harness teardown failed during environment teardown",{subagentId:r,harness:a.harness,error:w(d)})}},"teardownEnvironment")})}i(fe,"createMultiplexerAgentAssets");var j=T("supervisor"),xr=2e3;function Ir(){let t;return{promise:new Promise(n=>{t=n}),resolve:t}}i(Ir,"deferred");var me=class{constructor(e,n,r={}){this.host=e;this.deliverable=n;this.pollMs=r.pollMs??xr,this.stopInitiator=r.stopInitiator??"user",this.onFollowUp=r.onFollowUp,this.stopProcess=r.stopProcess??((s,o)=>e.waitUntilGone(s,{timeoutMs:o}))}host;deliverable;static{i(this,"ProcessSupervisorEngine")}pollMs;stopInitiator;onFollowUp;stopProcess;phase={kind:"idle"};outcome=null;settlement=Ir();watchIssued=!1;wakeLoop=null;delivered=null;held=null;watchStartedAt=0;async start(e,n){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.start() may launch once per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:n};try{await this.host.start(n,{name:e.name??"subagent",piArgs:e.piArgs,agentMultiplexerKind:e.agentMultiplexerKind})}catch(r){throw this.isWatching()&&(this.phase={kind:"idle"}),r}}adopt(e){if(this.phase.kind!=="idle")throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor \u2014 create a fresh instance per attempt");this.phase={kind:"watching",ref:e},j.debug("adopted",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator})}watch(){if(this.outcome!==null)return Promise.resolve(this.outcome);switch(this.phase.kind){case"idle":return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));case"ended":return this.settlement.promise;case"watching":break}if(this.watchIssued)return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));let{ref:e}=this.phase;return this.watchIssued=!0,this.watchStartedAt=performance.now(),j.debug("started",{paneId:e.paneId,pollMs:this.pollMs,stopInitiator:this.stopInitiator}),this.runLoop().catch(n=>{j.error("poll loop failed",{errorMessage:w(n)})}),this.settlement.promise}async stop(e){let n=this.phase;if(n.kind!=="watching"||this.outcome!==null)return!1;let{ref:r}=n,s=await this.stopProcess(r,e).catch(o=>(j.debug("stop failed",{errorMessage:w(o)}),!1));return j.debug("stop requested",{paneId:r.paneId,graceMs:e,stopped:s,initiator:this.stopInitiator}),this.settle({kind:"stopped",initiator:this.stopInitiator}),this.stopPolling("stopped"),s}abandon(){this.stopPolling("abandoned")}detach(){this.stopPolling("detached")}stopPolling(e){let n=this.phase;n.kind==="watching"&&(j.debug(e,{paneId:n.ref.paneId,pollMs:this.pollMs,outcome:this.outcome?.kind??null}),this.phase={kind:"ended"},this.endWait())}settle(e){this.phase.kind!=="watching"||this.outcome!==null||(this.outcome=e,j.debug("settlement decision",{...e,paneId:this.phase.ref.paneId,runDurationMs:this.watchStartedAt?performance.now()-this.watchStartedAt:0}),this.settlement.resolve(e))}async runLoop(){for(;;){if(!await this.pauseUntilNextPoll())return;await this.pollOnce()}}pauseUntilNextPoll(){return this.isWatching()?new Promise(e=>{let n=setTimeout(()=>{this.wakeLoop=null,e(!0)},this.pollMs);n.unref(),this.wakeLoop=()=>{clearTimeout(n),e(!1)}}):Promise.resolve(!1)}endWait(){this.wakeLoop?.(),this.wakeLoop=null}async pollOnce(){let e=await this.readDeliverable();if(e===null||e.content.trim().length===0){this.held=null;return}if(this.delivered!==null&&this.delivered.content===e.content){this.held=null;return}if(this.held===null||!Er(this.held,e)){this.held=e,j.debug("deliverable held for confirmation");return}if(this.held=null,this.delivered=e,this.outcome===null){this.settle({kind:"completed",deliverable:e.content});return}this.isWatching()&&this.onFollowUp?.(e.content)}async readDeliverable(){try{return await this.deliverable.readDeliverable()}catch(e){return j.debug("readDeliverable failed",{errorMessage:w(e)}),null}}isWatching(){return this.phase.kind==="watching"}};function Er(t,e){return t.content===e.content&&t.mtime===e.mtime}i(Er,"sameReport");function X(t){let e=t.transport.createDeliverable(t.resultFile);return new me(t.host,e,t.supervisorOptions)}i(X,"createPaneSupervisor");function cn(t,e){t.host=e}i(cn,"placeExecution");function pn(t,e){t.harness=e}i(pn,"engageExecution");function gn(t,e){t.history.push(e),t.host=void 0,t.harness=void 0}i(gn,"endExecutionRun");import He from"node:fs";import _ from"node:path";import{SettingsManager as Vr}from"@earendil-works/pi-coding-agent";import qr from"node:fs";import{loadProjectContextFiles as Nr}from"@earendil-works/pi-coding-agent";function hn(t){return t?.trim()?["## Orchestrator Guidance","",t].join(`
|
|
2
2
|
`):""}i(hn,"buildOrchestrationGuidance");import{formatSkillsForPrompt as Cr}from"@earendil-works/pi-coding-agent";function Tr(t){let e=t;return e=e.replace(/\n?<\s*project_context\s*>[\s\S]*?<\/\s*project_context\s*>\n?/g,`
|
|
3
3
|
`),e=e.replace(/\n?(?:The following skills provide[\s\S]*?)?<\s*available_skills\s*>[\s\S]*?<\/\s*available_skills\s*>\n?/g,`
|
|
4
4
|
`),e=e.replace(/\n?Current date:.*\n?/g,`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as M,b as y}from"./chunk-
|
|
1
|
+
import{a as M,b as y}from"./chunk-YTDE2OUW.js";import{U as H,d as g,g as R,j as P}from"./chunk-3FQQMEHD.js";import{b as S,o as D}from"./chunk-WP65L6WI.js";import{A,Fa as T,Ja as v,Sa as _,ja as x,na as I,s as u,t as E}from"./chunk-UEMXTMQN.js";import{a as t,f as b,p as N}from"./chunk-AOUEQXPY.js";import*as $ from"node:fs";import*as z from"node:path";import{SelectList as X}from"@earendil-works/pi-tui";var O=b,K=/[ ~^:?*[\\]/;function j(e){for(let r of e){let o=r.codePointAt(0)??0;if(o<32||o===127||K.test(r))return!0}return!1}t(j,"hasIllegalCharacter");function B(e){return e===""?{kind:"empty-name"}:e.length>O?{kind:"too-long"}:j(e)?{kind:"invalid-characters"}:e.startsWith("-")||e.startsWith(".")||e.startsWith("/")||e.endsWith(".")||e.endsWith("/")||e.endsWith(".lock")||e.includes("..")||e.includes("//")||e.includes("@{")||e==="@"?{kind:"invalid-shape"}:null}t(B,"validateWorktreeCommandName");function U(e){switch(e.kind){case"empty-name":return"Enter a name: it becomes the worktree's directory and its git branch.";case"too-long":return`Name is too long: the pane adoption carries it as a herdr agent name, which caps at ${O} characters.`;case"invalid-characters":return"Invalid name: it must be a git branch name, so letters, digits, and - _ . / only \u2014 no spaces, and none of ~ ^ : ? * [ \\.";case"invalid-shape":return"Invalid name: a git branch name cannot contain .. or @{, cannot start with - . or /, and cannot end with . / or .lock."}}t(U,"describeWorktreeCommandNameProblem");function L(e){return M({prefill:e.prefill,notify:e.notify,validate:B,describeProblem:U,onDone:e.onDone,onCancel:e.onCancel})}t(L,"createWorktreeCommandNameInput");var q={dirty:"Start from the parent's uncommitted work: copy-on-write clones its edits and untracked files, checkout applies only its tracked changes.",clean:"Start at HEAD: the parent's uncommitted work stays out of the worktree."};function F(e){switch(e.kind){case"cow":return"copy-on-write";case"cow-fallback":return"checkout (the volume cannot clone, so copy-on-write was unavailable)";case"checkout":return"checkout";case"reused":return"reused (the checkout already existed)"}}t(F,"materializationLabel");function V(e,r){switch(e.kind){case"cow":return e.clone.mode==="seeded"?"nothing the parent had uncommitted: tracked files came from HEAD and only ignored state was seeded":e.clone.reason!==void 0?"the parent's uncommitted work: its tracked edits and its untracked files":"nothing uncommitted \u2014 the parent was clean, so the worktree is a clone at HEAD";case"cow-fallback":return"nothing: the fallback checkout starts at HEAD, whatever the checkout policy says";case"checkout":return r==="dirty"?"the parent's tracked changes, applied on top of git's checkout of HEAD (a clean parent carries none)":"nothing: git checked out HEAD, and the parent's uncommitted work stays out";case"reused":return"nothing: the existing checkout was reused exactly as it was"}}t(V,"inheritedLabel");function Y(e,r){return[`Worktree ready: ${e.path}`,`branch: ${e.branch}`,`materialization: ${F(e.materialization)}`,`inherited: ${V(e.materialization,r)}`].join(`
|
|
2
2
|
`)}t(Y,"describeCreatedWorktree");async function J(e,r,o,a){if($.existsSync(a))return`Cannot create the worktree: ${a} already exists. Pick another name.`;if(await g(e,["rev-parse","--verify","--quiet",`refs/heads/${o}`],r)!==void 0)return`Cannot create the worktree: the branch "${o}" already exists. Pick another name.`}t(J,"describeCollision");async function ue(e,r){let o=new S(e),a=t((n,i)=>e.ui.notify(n,i),"notify"),s=await o.open(({theme:n,close:i})=>new y(L({prefill:r,notify:a,onDone:t(m=>i(m),"onDone"),onCancel:t(()=>i(),"onCancel")}),{title:"Worktree Name",theme:n,passthroughKeys:!0}));if(s===void 0)return;let p=I(),c=x();if(!await P(c,e.cwd)){a("Cannot create a worktree: this session is not inside a git repository.","error");return}let d;try{d=await R(c,e.cwd)}catch(n){a(`Cannot create a worktree: ${N(n)}`,"error");return}let G=await g(c,["status","--porcelain"],d)==="",k=p.agent.worktreeCheckoutType;if(!G){let n=await o.open(({theme:i,close:m})=>{let h=new X(u.map(l=>({value:l,label:l,description:q[l]})),u.length,D(i));return h.setSelectedIndex(u.indexOf(p.agent.worktreeCheckoutType)),h.onSelect=l=>m(E(l.value)),h.onCancel=()=>m(),new y(h,{title:"Worktree Checkout",theme:i,onCancel:t(()=>m(),"onCancel")})});if(n===void 0)return;k=n}let w=z.join(A(p.agent.worktreeRoot,d),s),C=await J(c,d,s,w);if(C!==void 0){a(C,"error");return}let f=_(e.ui);f.pending(`Creating worktree ${s}`);let W;try{W=await H(c,{repoCwd:d,path:w,branch:s,materialization:T(),dirtyCheckout:k,notify:a,host:v().host})}catch(n){f.failed("Worktree creation failed",n);return}f.succeeded(Y(W,k))}t(ue,"showWorktreeCommandMenu");export{ue as showWorktreeCommandMenu};
|
|
3
|
-
//# sourceMappingURL=menu-worktree-command-
|
|
3
|
+
//# sourceMappingURL=menu-worktree-command-JXTKYYEV.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as _e,f as rn,g as ot,h as on,i as sn,l as an,m as mn,n as pn,q as Ae,r as Ke,t as fn,u as gn}from"./chunk-
|
|
1
|
+
import{e as _e,f as rn,g as ot,h as on,i as sn,l as an,m as mn,n as pn,q as Ae,r as Ke,t as fn,u as gn}from"./chunk-EWHWPOTC.js";import{a as We,b as N}from"./chunk-YTDE2OUW.js";import{H as Qt,I as en,K as tn,L as nn,O as oe,P as dn,T as cn,V as un,i as Yt,j as Xt,v as z,w as Fe,x as Zt,z as Jt}from"./chunk-3FQQMEHD.js";import{a as fe,b as K,c as ie,d as se,e as ge,f as he,g as X,h as Ne,i as it,j as De,k as Oe,l as D,m as ln,n as B,o as Z,p as Ve,q as Me}from"./chunk-WP65L6WI.js";import{$ as Gt,Aa as re,Da as Ut,Fa as He,H as ee,Ia as zt,Ja as je,M as Pt,N as Ht,O as jt,R as Ee,S as ae,Sa as Y,T as Re,U as Ft,V as _t,W as Nt,X as Dt,Y as Vt,Z as Wt,_ as Kt,a as St,c as kt,ca as Pe,ha as nt,ja as de,ka as pe,la as qt,m as tt,ma as J,n as we,na as E,p as wt,q as Tt,s as Ot,sa as Bt,t as Mt,u as At,ua as rt,xa as _}from"./chunk-UEMXTMQN.js";import{J as Et,K as Rt,L as Le,a as t,f as Ct,p as me,q as It,r as Te,s as xt,w as $t,y as ne,z as Lt}from"./chunk-AOUEQXPY.js";import{SettingsList as sr}from"@earendil-works/pi-tui";import{SettingsManager as lr}from"@earendil-works/pi-coding-agent";async function hn(e,n){return lr.create(e,n??St()).getDefaultThinkingLevel()}t(hn,"getPiDefaultThinkingLevel");import{SettingsList as yr}from"@earendil-works/pi-tui";var dr={queued:{icon:"\u25C6",color:"accent"},spawned:{icon:"\u25C8",color:"accent"},completed:{icon:"\u2713",color:"success"},error:{icon:"\u2717",color:"error"},stopped:{icon:"\u25A0",color:"dim"}};function yn(e,n){if(e===void 0)return n.fg("muted","\u25B8");let o=dr[e];return n.fg(o.color,o.icon)}t(yn,"statusIcon");function st(e){if(!Number.isFinite(e)||e<1e3)return"<1s";let n=Math.floor(e/1e3),o=Math.floor(n/3600),r=Math.floor(n%3600/60),s=n%60,i=[];return o>0&&i.push(`${o}h`),r>0&&i.push(`${r}m`),(s>0||i.length===0)&&i.push(`${s}s`),i.join(" ")}t(st,"formatMs");function vn(e){let n=z(e);return n?.displayName??n?.name??"Agent"}t(vn,"getDisplayName");function le(e){return`${e.fg("accent","\u2022")} `}t(le,"agentBulletPrefix");function bn(e,n){return e.length<=n?e:"..."+e.slice(e.length-n+3)}t(bn,"truncatePath");function Ge(e,n=""){return`${e} slot${e===1?"":"s"}${n}`}t(Ge,"formatSlotLimit");function Sn(e){let{types:n,agentConfigs:o,config:r,sessionOverrides:s,harnessDefaultFor:i,harnessFamilyFor:l,hasProjectModelKey:a,parentModelId:c}=e,u=new Map;for(let d of n){let h=o[d],{model:C,source:m}=Dt({subagentType:d,harnessFamily:l(d),agentConfig:h,config:{agent:r},harnessDefault:i(d),parentModelId:c,sessionOverrides:s});if(!at(s,r,d,e.sessionThinking))continue;let k=m==="session-per-type"||m==="session-default"?"[session]":a(d)?"[project]":"",{level:f,source:w}=lt({type:d,agentConfig:h,harnessFamily:l(d),config:r,harnessDefault:e.harnessDefaultThinkingFor(d),parentThinking:e.parentThinking??void 0,sessionThinking:e.sessionThinking}),g=w==="session-per-type"?" [session]":w==="parent"?" [parent]":w==="config-per-type"&&e.hasProjectThinkingKey(d)?" [project]":"",b=u.get(C)??[];b.push({type:d,thinking:f,thinkingTag:g,tag:k}),u.set(C,b)}return[...u.entries()].sort((d,h)=>d[0]===h[0]?0:d[0]===null?-1:h[0]===null?1:d[0]<h[0]?-1:1).map(([d,h])=>({modelId:d,rows:h}))}t(Sn,"buildModelGroups");function at(e,n,o,r){return e[o]!=null||typeof n[o]=="string"||r[o]!=null||typeof n.thinking?.[o]=="string"}t(at,"hasExplicitPerTypeOverride");function lt(e){let n=Wt({subagentType:e.type,harnessFamily:e.harnessFamily,agentConfig:e.agentConfig,config:{agent:e.config},harnessDefault:e.harnessDefault,parentThinking:e.parentThinking,sessionThinking:e.sessionThinking});return n!==void 0?{level:n.value,source:n.source}:{level:e.harnessFamily==="pi"?Vt:null,source:void 0}}t(lt,"displayedThinking");import{SettingsList as mr}from"@earendil-works/pi-tui";import{matchesKey as Ie,SelectList as cr,truncateToWidth as ur}from"@earendil-works/pi-tui";function kn(e){return(n,o)=>{let r=[{value:"Yes",label:"Yes",description:e.message},{value:"No",label:"No",description:e.message}],s=B(new cr(r,5,Z(e.theme)));return s.onSelect=i=>{i.value==="Yes"?(e.onConfirm(),o("Yes")):o()},s.onCancel=()=>o(),s}}t(kn,"createConfirmSubmenu");function ye(e){return se({invalidate(){},render(o){let r=Math.max(0,o-4),s=t(l=>` ${ur(l,r,"...",!0)}`,"line"),i=[s(e.theme.bold(e.message))];if(e.detail)for(let l of e.detail.split(`
|
|
2
2
|
`))i.push(s(l));return i.push(s(e.theme.fg("dim","Y yes \xB7 N no"))),i},handleInput(o){if(Ie(o,"y")||Ie(o,"shift+y")){e.onYes();return}(Ie(o,"n")||Ie(o,"shift+n")||Ie(o,"escape"))&&e.onNo()}})}t(ye,"createKeyConfirm");var pr={session:{label:"Session",setDescription:"Not saved",clearDescription:"Removes from the session"},global:{label:"Global",setDescription:"Saves to the global config file",clearDescription:"Removes from the global config file"},project:{label:"Project",setDescription:"Saves to the project config file",clearDescription:"Removes from the project config file"}};function dt(e,n){let o=pr[e];return{id:e,label:o.label,currentValue:"",description:n?o.clearDescription:o.setDescription}}t(dt,"levelItem");function ve(e){let n=[];return e.offered.session&&n.push(dt("session",e.clearMode===!0)),e.offered.global&&n.push(dt("global",e.clearMode===!0)),e.offered.project&&n.push(dt("project",e.clearMode===!0)),e.includeClear&&n.push({id:"clear",label:"Clear...",currentValue:""}),e.includeAll&&n.push({id:"all",label:"All levels",currentValue:""}),n}t(ve,"buildLevelItems");function te(e){return(n,o)=>{let r=e.items.map(i=>({...i,submenu:t((l,a)=>{let c=e.onPick(i.id,a,()=>o());return c||(a(i.id),ie)},"submenu")})),s=B(new mr(r,r.length,D(e.theme),(i,l)=>o(l),()=>o()));return se(s)}}t(te,"createLevelPickerSubmenu");function qe(e){let n=e.availableLevels,o=e.includeAll===!0,r=(e.includeSession??!0)&&(!n||n.session),s=!n||n.global,i=e.projectOffered&&(!n||n.project),l=[r,s,i].filter(Boolean).length,a=e.showClear===!0?e.onClear:void 0,c=ve({offered:{session:r,global:s,project:i},clearMode:o,includeClear:a!==void 0,includeAll:n?l>=2:e.includeAll===!0});return te({theme:e.theme,items:c,onPick:t((u,d)=>u==="clear"?be({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,availableLevels:e.availableLevels,onClear:t(h=>a?.(h),"onClear")})("",d):e.onPick(u,d),"onPick")})}t(qe,"createTargetSelectSubmenu");function be(e){return qe({theme:e.theme,projectOffered:e.projectOffered,includeSession:e.includeSession??!0,includeAll:!0,availableLevels:e.availableLevels,onPick:t(n=>e.onClear(n),"onPick")})}t(be,"createClearPickerSubmenu");function Be(e){return(n,o)=>qe({theme:e.theme,projectOffered:e.projectOffered,includeAll:!0,availableLevels:e.availableLevels,onPick:t((r,s)=>kn({message:e.message(r),theme:e.theme,onConfirm:t(()=>e.onConfirm(r),"onConfirm")})(n,s),"onPick")})(n,o)}t(Be,"createClearAllSubmenu");import{Input as Cn}from"@earendil-works/pi-tui";function ct(e,n){let o=n.min??1,r=t(i=>i===0?"\u2265 0":`\u2265 ${i}`,"fmtLabel"),s=t(i=>e.ui.notify(i,"error"),"onError");return(i,l)=>{let a=new Cn;return a.setValue(i),a.onSubmit=c=>{let u=c.trim();if(!u||/^unlimited$/i.test(u))switch(n.kind){case"required":s(`Invalid value \u2014 must be a number ${r(o)}`);return;case"defaulted":n.onValid?.(n.default),l(String(n.default));return;case"optional":n.onEmpty?.(),l("");return}let d=ln(u,o);if(d===void 0){s(`Invalid value \u2014 must be a number ${r(o)}`);return}n.onValid?.(d),l(String(d))},a.onEscape=()=>l(),a}}t(ct,"createNumericSubmenu");function Se(e,n){return(o,r)=>{let s=new Cn;return s.setValue(o),s.onSubmit=i=>{let l=i.trim();if(!l){if(n?.required){e.ui.notify("Cannot be empty","error");return}r();return}r(l)},s.onEscape=()=>r(),s}}t(Se,"createInputSubmenu");var wn="__custom__",ke="__none__";function fr(e,n){let o=[];if(e.kind!=="none"){for(let r of e.levels)o.push({id:r,label:r==="off"?"Off":r.charAt(0).toUpperCase()+r.slice(1),currentValue:n===r?"(current)":""});e.kind==="advisory"&&o.push({id:wn,label:"Custom token...",currentValue:"",description:"A level or variant this harness advertises beyond its own list."})}return o.push({id:ke,label:"None",currentValue:n===null?"(current)":"",description:"Use the template, configured default, or parent session's level."}),o}t(fr,"valueItems");function Tn(e){return te({theme:e.theme,items:fr(e.offering,e.current),onPick:t((n,o)=>{if(n===wn)return Se(e.ctx)(e.current??"",r=>{if(r===void 0){o();return}e.onPick(r),o(r)});e.onPick(n===ke?null:n)},"onPick")})}t(Tn,"createThinkingValuePicker");function ze(e,n,o,r){return n.length>0?{}:{loadModelOptions:t(async()=>{let s=await Ut().list(e),i=Rt(s);return i!==void 0&&r?.(i,"warning"),Et(s).map(l=>l.key)},"loadModelOptions"),requestRender:o}}t(ze,"deferredModelList");var Ue=class{constructor(n){this.cancel=n}cancel;static{t(this,"LoadingModels")}focused=!0;render(){return["Loading models\u2026"]}invalidate(){}handleInput(n){(n==="\x1B"||n==="")&&this.cancel()}};function On(e){let n=e.currentModel??null,o=e.showClear===!0?e.onClear:void 0;return te({theme:e.theme,items:ve({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:o!==void 0}),onPick:t((r,s,i)=>{if(r==="clear")return be({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(u=>o?.(u),"onClear")})("",s);let l=r,a=t(u=>new fe(it(u,n,e.mergedModels),n,{onSelect:t(d=>{e.onSet(l,d),d==null?i():s(d)},"onSelect"),onCancel:t(()=>s(),"onCancel")},e.theme),"select");if(e.loadModelOptions===void 0)return a(e.modelOptions);let c=new ge(new Ue(s));return e.loadModelOptions().then(u=>{c.activate(a(u)),e.requestRender?.()}),c},"onPick")})}t(On,"createModelSelectSubmenu");function Mn(e){let n=e.currentModel??null;return te({theme:e.theme,items:ve({offered:{session:!0,global:!0,project:e.projectOffered},includeClear:e.showClear}),onPick:t((o,r,s)=>{if(o==="clear")return be({theme:e.theme,projectOffered:e.projectOffered,availableLevels:e.availableLevels,onClear:t(c=>e.onClear(c),"onClear")})("",r);let i=o,l,a=t(c=>new fe(it(c,n,e.mergedModels),n,{onSelect:t(u=>{if(u==null){e.onClear(i),s();return}let d=e.offeringFor(u);if(d.kind==="none"){e.onSet(i,u,null),r(u);return}l.activate(Tn({theme:e.theme,ctx:e.ctx,offering:d,current:e.currentThinking,onPick:t(h=>e.onSet(i,u,h),"onPick")})("",r))},"onSelect"),onCancel:t(()=>r(),"onCancel")},e.theme),"dialog");return e.loadModelOptions===void 0?(l=new ge(a(e.modelOptions)),l):(l=new ge(new Ue(r)),e.loadModelOptions().then(c=>{l.activate(a(c)),e.requestRender?.()}),l)},"onPick")})}t(Mn,"createModelThinkingSubmenu");import{getSupportedThinkingLevels as gr}from"@earendil-works/pi-ai";function Ye(e){let{harnessId:n,modelKey:o,entries:r,piModel:s}=e;if(ne(n))return s===void 0?{kind:"advisory",levels:[]}:s.reasoning?{kind:"closed",levels:gr(s)}:{kind:"none"};if(o==="")return hr(r);let i=r.find(l=>l.key===o);return i===void 0?{kind:"advisory",levels:[]}:i.thinkingLevels.kind==="advisory"?{kind:"advisory",levels:i.thinkingLevels.levels}:i.thinkingLevels.levels.length===0?{kind:"none"}:{kind:"closed",levels:i.thinkingLevels.levels}}t(Ye,"thinkingOfferingFor");function hr(e){let n=[...new Set(e.flatMap(r=>r.thinkingLevels.levels))],o=e.length===0||e.some(r=>r.thinkingLevels.kind==="advisory");return n.length===0&&!o?{kind:"none"}:o?{kind:"advisory",levels:n}:{kind:"closed",levels:n}}t(hr,"unionThinkingOffering");function An(e){return Ye({harnessId:e.harnessId,modelKey:e.modelKey??"",entries:e.entries.get(e.harnessId)??[],piModel:Te(e.modelKey??"",e.registry,e.parentModel)})}t(An,"thinkingOfferingForModel");function Xe(e){let n=e.model??"(none)",o=e.thinking??"(none)",r=e.model?e.modelTag:"",s=e.thinking?e.thinkingTag:"";return r!==""&&r===s?`${n} \xB7 ${o}${s}`:`${n}${r} \xB7 ${o}${s}`}t(Xe,"pairedRow");function Ze(e,n){return e?" [session]":n?" [project]":""}t(Ze,"layerTag");function ut(e,n){return n===null?"":Ze(e.session,e.project)}t(ut,"thinkingTagOf");function In(e,n,o,r){if(o===null){e.mutate.agent.clearHarnessDefaultThinking(n,r);return}r!=="session"&&ne(n)&&!Pt.safeParse(o).success||e.mutate.agent.setHarnessDefaultThinking(n,o,r)}t(In,"writeHarnessDefaultThinking");function vr(e,n,o,r){o===null?e.mutate.agent.clearThinkingOverride(n,r):e.mutate.agent.setThinkingOverride(n,o,r)}t(vr,"writeTypeThinking");function br(e){return _().runnable(e).filter(n=>!ne(n))}t(br,"harnessDefaultRowIds");function Sr(e){let n=br(re());return se(kr(e,n))}t(Sr,"buildModelSettingsScreen");function kr(e,n){let{ctx:o,store:r,theme:s,harnessModelOptions:i,requestRender:l,piDefaultThinking:a,close:c}=e,u,d=t(m=>{let k=[],f=r.isProjectWritable,w=t((y,P)=>o.ui.notify(y,P),"notify"),g=pe(),b=g.model??o.model,O=b?`${b.provider}/${b.id}`:null,R=g.thinkingLevel??null,F=r.agentConfigSnapshot(),$=De(F),H=t(()=>{u?.(d(m))},"refresh"),G=t(y=>P=>An({harnessId:y,modelKey:P,entries:i,registry:g.modelRegistry,parentModel:b}),"offeringFor"),W=t(y=>{let P={session:y.modelLevels.session||y.thinkingLevels.session,global:y.modelLevels.global||y.thinkingLevels.global,project:y.modelLevels.project||y.thinkingLevels.project};return Mn({modelOptions:y.modelOptions,...ze(y.harnessId,y.modelOptions,l,w),mergedModels:y.mergedModels,projectOffered:f,theme:m,ctx:o,currentModel:y.model,currentThinking:y.thinking,showClear:P.session||P.global||P.project,availableLevels:P,offeringFor:G(y.harnessId),onSet:t((I,q,V)=>{y.write(I,q,V),w(`${y.label} set to ${q} \xB7 ${V??"(none)"} (${I})`,"info")},"onSet"),onClear:t(I=>{y.clear(I),w(`${y.label} cleared (${I})`,"info"),H()},"onClear")})},"pairSubmenu"),v=F.default,p=r.modelOverrideLevels("default"),S=r.harnessDefaultThinkingLevels("pi"),T=r.defaultThinkingForHarness("pi"),M=r.sessionDefaultModel??v;k.push({id:"defaultModel",label:"Pi Default Model",currentValue:Xe({model:M,modelTag:Ze(p.session,r.hasProjectModelKey("default")),thinking:T,thinkingTag:ut(S,T)}),description:"Default model and thinking level applied when no session, per-type, or template override is set.",submenu:W({label:"Pi Default Model",harnessId:"pi",modelOptions:ee(i,"pi"),mergedModels:Oe("pi",$),model:M,thinking:T,modelLevels:p,thinkingLevels:S,write:t((y,P,I)=>{r.mutate.agent.setModelOverride("default",P,y),In(r,"pi",I,y)},"write"),clear:t(y=>{r.mutate.agent.clearModelOverride("default",y),r.mutate.agent.clearHarnessDefaultThinking("pi",y)},"clear")})});for(let y of n){let P=`${_().displayName(y)} Default Model`,I=r.harnessDefaultModelLevels(y),q=r.harnessDefaultThinkingLevels(y),V=r.defaultThinkingForHarness(y);k.push({id:`harness:${y}`,label:P,currentValue:Xe({model:r.defaultModelForHarness(y),modelTag:Ze(I.session,I.project),thinking:V,thinkingTag:ut(q,V)}),description:`Default model and thinking level applied to agents launched under ${y} when no session, per-type, or template override is set.`,submenu:W({label:P,harnessId:y,modelOptions:ee(i,y),mergedModels:[],model:r.defaultModelForHarness(y),thinking:V,modelLevels:I,thinkingLevels:q,write:t((Q,et,ar)=>{r.mutate.agent.setHarnessDefaultModel(y,et,Q),In(r,y,ar,Q)},"write"),clear:t(Q=>{r.mutate.agent.clearHarnessDefaultModel(y,Q),r.mutate.agent.clearHarnessDefaultThinking(y,Q)},"clear")})})}let A=Zt(),x={default:r.sessionDefaultModel},L={};for(let y of A)x[y]=r.sessionModelOverride(y),L[y]=z(y);let j={};for(let y of A)j[y]=r.sessionThinkingOverride(y);let U=Sn({types:A,agentConfigs:L,config:F,sessionOverrides:x,sessionThinking:j,harnessDefaultFor:t(y=>r.defaultModelForHarness(oe(y)),"harnessDefaultFor"),harnessDefaultThinkingFor:t(y=>{let P=oe(y),I=r.defaultThinkingForHarness(P);return I!==null?I:ne(P)&&R===null?a??null:null},"harnessDefaultThinkingFor"),harnessFamilyFor:t(y=>_().family(oe(y)),"harnessFamilyFor"),hasProjectModelKey:t(y=>r.hasProjectModelKey(y),"hasProjectModelKey"),hasProjectThinkingKey:t(y=>r.hasProjectThinkingKey(y),"hasProjectThinkingKey"),parentModelId:O,parentThinking:R}),xe=t((y,P,I,q)=>W({label:y,harnessId:P,modelOptions:ee(i,P),mergedModels:Oe(P,$),model:I,thinking:q,modelLevels:r.modelOverrideLevels(y),thinkingLevels:r.thinkingOverrideLevels(y),write:t((V,Q,et)=>{r.mutate.agent.setModelOverride(y,Q,V),vr(r,y,et,V)},"write"),clear:t(V=>{r.mutate.agent.clearModelOverride(y,V),r.mutate.agent.clearThinkingOverride(y,V)},"clear")}),"typeSubmenu");for(let y of U){k.push({id:X,label:" ",currentValue:""}),k.push(he(m,y.modelId??"(no model)"));let P=Math.max(...y.rows.map(I=>`${I.thinking??"(none)"}${I.thinkingTag}`.length));for(let I of y.rows){let q=oe(I.type),V=`${I.thinking??"(none)"}${I.thinkingTag}`,Q=I.thinking!==null&&I.thinkingTag.trim()===I.tag.trim()?"":I.tag;k.push({id:`type:${I.type}`,label:`${le(m)}${I.type}`,currentValue:`${V.padEnd(P)} ${Q}`.trimEnd(),description:`Model and thinking level for the ${I.type} agent type.`,submenu:xe(I.type,q,y.modelId,I.thinking)})}}k.push({id:X,label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",currentValue:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});let vt=A.filter(y=>!at(x,F,y,j));vt.length>0&&k.push({id:"overrideType",label:"Override another type...",currentValue:"",description:"Configure model and thinking level overrides for an agent type currently using inherited defaults.",submenu:t((y,P)=>Ve(vt.map(I=>({value:I,label:`${le(m)}${I}`})),{onSelect:t(I=>{if(I==null)return P();let q=oe(I),V=z(I),Q=r.modelFor(I,O,V,q,_().family(q));return xe(I,q,Q,lt({type:I,agentConfig:V,harnessFamily:_().family(q),config:F,harnessDefault:r.defaultThinkingForHarness(q),parentThinking:R??void 0,sessionThinking:j}).level)("",P)},"onSelect"),onCancel:t(()=>P(),"onCancel")},m),"submenu")}),k.push({id:X,label:" ",currentValue:""});let bt=r.modelSettingsLevels(),$e={...bt,project:bt.project&&f};return($e.session||$e.global||$e.project)&&k.push({id:"clearAll",label:"Clear all model and thinking overrides...",currentValue:"",description:"Remove model and thinking level overrides across a selected configuration layer (session, global, project, or all).",submenu:Be({theme:m,projectOffered:f,availableLevels:$e,message:t(y=>`Clear all model and thinking overrides at the ${y} level?`,"message"),onConfirm:t(y=>{r.mutate.agent.clearAllModelOverrides(y),w(`Model and thinking overrides cleared (${y})`,"info")},"onConfirm")})}),k},"buildItems"),h=new yr(d(s),15,D(s),(m,k)=>u?.(d(s)),c),C=new N(h,{title:"Model Settings",theme:s,onCancel:c,onRebuild:t(m=>{u=m},"onRebuild")});return se(C)}t(kr,"buildModelSettingsList");function xn(e){let{ctx:n,store:o,theme:r,harnessModelOptions:s,requestRender:i,piDefaultThinking:l}=e,a=t(()=>{let c=o.modelOverrideLevels("default"),u=o.harnessDefaultThinkingLevels("pi"),d=o.defaultThinkingForHarness("pi");return Xe({model:o.sessionDefaultModel??o.agentConfigSnapshot().default,modelTag:Ze(c.session,o.hasProjectModelKey("default")),thinking:d,thinkingTag:ut(u,d)})},"defaultDisplay");return{id:"modelOverrides",label:"Model overrides",currentValue:a(),description:"Pi's default model and thinking level, plus per-harness and per-type overrides; opens the model settings screen.",submenu:t((c,u)=>Sr({ctx:n,store:o,theme:r,harnessModelOptions:s,requestRender:i,piDefaultThinking:l,close:t(()=>u(a()),"close")}),"submenu")}}t(xn,"buildModelOverridesRow");import{SettingsList as $n}from"@earendil-works/pi-tui";function Ln(e,n){return e==="pi"?n:`${e}:${n}`}t(Ln,"qualifiedKey");function Je(e){let n=new Map;for(let o of e){let r=Pe(o)?.harness??"pi",s=n.get(r);s?s.push(o):n.set(r,[o])}return n}t(Je,"groupKeysByHarness");function wr(e,n){let o=[...e];for(let r of n.keys())o.includes(r)||o.push(r);return o}t(wr,"sectionHarnesses");async function En(e,n){let o=[...n.keys()],r=t((i,l)=>{let a=[],c=i.isProjectWritable,u=t((v,p,S)=>p==="default"?v.default!==void 0:S===void 0?!1:p==="harnesses"?v.harnesses?.[S]!==void 0:v[p]?.[S]!==void 0,"layerHas"),d=t((v,p)=>({session:u(i.sessionConcurrency,v,p),global:u(i.globalConcurrency,v,p),project:u(i.projectConcurrency,v,p)}),"entryLevels"),h=t((v,p)=>u(i.sessionConcurrency,v,p)?" [session]":u(i.projectConcurrency,v,p)?" [project]":"","limitTag"),C=t((v,p)=>(S,T)=>qe({theme:l,projectOffered:c,onPick:t((M,A)=>ct(e,{kind:"optional",min:1,onValid:t(x=>p(M,x),"onValid")})(v,A),"onPick")})(S,T),"targetThenValueSubmenu"),m=t((v,p,S,T)=>(M,A)=>{let x=ve({offered:{session:!0,global:!0,project:c},includeClear:T.session||T.global||T.project});return te({theme:l,items:x,onPick:t((L,j)=>{if(L==="clear")return be({theme:l,projectOffered:c,availableLevels:T,onClear:S})("",j);let U=L;return ct(e,{kind:"optional",min:1,onValid:t(xe=>p(U,xe),"onValid")})(String(v),j)},"onPick")})(M,A)},"limitSubmenu"),k=t(v=>(p,S)=>{let T=t(()=>v(),"buildFresh"),M,A=B(new $n(T(),15,D(l),(x,L)=>{let j=M,U=T();j.items=U,j.filteredItems=U,j.submenuComponent=null,j.selectedIndex=0},()=>S("closed")));return M=A,Ne(M),se(A)},"nestedListSubmenu"),f=t(v=>{let p=E(),S=p.concurrency.harnesses[v],T=_().displayName(v),M=`Concurrent agents of every model launched under ${v}.`;if(S===void 0)return{id:`harness:${v}`,label:T,currentValue:"unset",description:M,submenu:C("",(x,L)=>{E().mutate.concurrency.setHarness(v,L,x),e.ui.notify(`${v} concurrency set to ${L} (${x})`,"info")})};let A=u(p.sessionConcurrency,"harnesses",v)?" [session]":u(p.projectConcurrency,"harnesses",v)?" [project]":"";return{id:`harness:${v}`,label:T,currentValue:Ge(S,A),description:M,submenu:m(S,(x,L)=>{E().mutate.concurrency.setHarness(v,L,x),e.ui.notify(`${T} concurrency set to ${L} (${x})`,"info")},x=>{E().mutate.concurrency.removeHarness(v,x),e.ui.notify(`Removed per-harness limit for ${v} (${x})`,"info")},{session:u(p.sessionConcurrency,"harnesses",v),global:u(p.globalConcurrency,"harnesses",v),project:u(p.projectConcurrency,"harnesses",v)})}},"harnessLimitRow"),w=t(()=>{let v=E(),p=[...o];for(let S of Object.keys(v.concurrency.harnesses))S.trim()!==""&&!p.includes(S)&&p.push(S);return p.map(S=>f(S))},"harnessListItems"),g=t(v=>{let p=ee(n,v);return[...new Set(p.map(S=>It(S)?.provider).filter(S=>S!==void 0))].sort()},"providerOptionsFor"),b=t((v,p)=>{let S=E(),T=S.concurrency.providers[p],M=`Concurrent slots reserved for agents under ${v} using the ${Pe(p)?.provider??p} provider.`;if(T===void 0)return{id:`provider:${p}`,label:p,currentValue:"unset",description:M,submenu:C("",(x,L)=>{E().mutate.concurrency.setProvider(p,L,x),e.ui.notify(`${p} concurrency set to ${L} (${x})`,"info")})};let A=u(S.sessionConcurrency,"providers",p)?" [session]":u(S.projectConcurrency,"providers",p)?" [project]":"";return{id:`provider:${p}`,label:p,currentValue:Ge(T,A),description:M,submenu:m(T,(x,L)=>{E().mutate.concurrency.setProvider(p,L,x),e.ui.notify(`${p} concurrency set to ${L} (${x})`,"info")},x=>{E().mutate.concurrency.removeProvider(p,x),e.ui.notify(`Removed per-provider limit for ${p} (${x})`,"info")},{session:u(S.sessionConcurrency,"providers",p),global:u(S.globalConcurrency,"providers",p),project:u(S.projectConcurrency,"providers",p)})}},"providerLimitRow"),O=t(v=>{let p=E(),S=Je(Object.keys(p.concurrency.providers)).get(v)??[],T=g(v).map(A=>Ln(v,A));return[...new Set([...T,...S])].sort().map(A=>b(v,A))},"providerListItems"),R=t((v,p)=>{let S=E(),T=S.concurrency.models[p],M=Pe(p),A=M?.kind==="model"?M.model:p,x=`Concurrent slots reserved for agents under ${v} using the ${A} model.`;if(T===void 0)return{id:`model:${p}`,label:p,currentValue:"unset",description:x,submenu:C("",(j,U)=>{E().mutate.concurrency.setModel(p,U,j),e.ui.notify(`${p} concurrency set to ${U} (${j})`,"info")})};let L=u(S.sessionConcurrency,"models",p)?" [session]":u(S.projectConcurrency,"models",p)?" [project]":"";return{id:`model:${p}`,label:p,currentValue:Ge(T,L),description:x,submenu:m(T,(j,U)=>{E().mutate.concurrency.setModel(p,U,j),e.ui.notify(`${p} concurrency set to ${U} (${j})`,"info")},j=>{E().mutate.concurrency.removeModel(p,j),e.ui.notify(`Removed per-model limit for ${p} (${j})`,"info")},{session:u(S.sessionConcurrency,"models",p),global:u(S.globalConcurrency,"models",p),project:u(S.projectConcurrency,"models",p)})}},"modelLimitRow"),F=t(v=>{let p=E(),S=Je(Object.keys(p.concurrency.models)).get(v)??[],T=ee(n,v).map(A=>Ln(v,A));return[...new Set([...T,...S])].sort().map(A=>R(v,A))},"modelListItems"),$=t(v=>{let p=E(),S=Je(Object.keys(v==="providers"?p.concurrency.providers:p.concurrency.models));return wr(o,S).filter(T=>{let M=(S.get(T)??[]).length>0;return v==="providers"?M||g(T).length>0:M||ee(n,T).length>0}).map(T=>({id:`${v}-harness:${T}`,label:_().displayName(T),currentValue:"",description:v==="providers"?`Provider limits under ${T}.`:`Model limits under ${T}.`,submenu:k(()=>v==="providers"?O(T):F(T))}))},"harnessPickerItems"),H=i.concurrency.default;a.push({id:"defaultConcurrency",label:"Default concurrency limit",currentValue:`${H}${h("default")}`,description:"Concurrent agents, whatever harness, provider, or model they use.",submenu:m(H,(v,p)=>{i.mutate.concurrency.setDefault(p,v),e.ui.notify(`Default concurrency set to ${p} (${v})`,"info")},v=>{i.mutate.concurrency.removeDefault(v),e.ui.notify(`Removed default concurrency limit (${v})`,"info")},d("default"))}),a.push({id:"harnessLimits",label:"Per-harness limits",currentValue:"",description:"Cap how many agents run at once under a single harness.",submenu:k(w)}),a.push({id:"providerLimits",label:"Per-provider limits",currentValue:"",description:"Cap how many agents run at once for a single provider.",submenu:k(()=>$("providers"))}),a.push({id:"modelLimits",label:"Per-model limits",currentValue:"",description:"Cap how many agents run at once for a single model.",submenu:k(()=>$("models"))});let G=i.concurrencySettingsLevels(),W={...G,project:G.project&&c};return(W.session||W.global||W.project)&&a.push({id:"resetAll",label:"Clear all concurrency limits...",currentValue:"",description:"Remove concurrency overrides at the chosen level (session, global, project, or all).",submenu:Be({theme:l,projectOffered:c,availableLevels:W,message:t(v=>`Clear all concurrency limits at the ${v} level?`,"message"),onConfirm:t(v=>{i.mutate.concurrency.clearAll(v),e.ui.notify(`Concurrency limits cleared (${v})`,"info")},"onConfirm")})}),a},"buildItems"),s;await new K(e).open(({theme:i,close:l})=>{let a=t(()=>s?.(r(E(),i)),"triggerRebuild"),c=E(),u=r(c,i),d=new $n(u,15,D(i),(h,C)=>a(),l);return new N(d,{title:"Concurrency Settings",theme:i,onCancel:l,onRebuild:t(h=>{s=h},"onRebuild")})})}t(En,"showConcurrencySettingsMenu");import{matchesKey as ce,SelectList as pt,truncateToWidth as _n,visibleWidth as Qe}from"@earendil-works/pi-tui";import{SelectList as Tr}from"@earendil-works/pi-tui";async function Rn(e,n){let o=J();if(!o)return e.map(s=>({id:s,kind:"error",error:"manager unavailable"}));let r=[];for(let s of e)try{r.push({id:s,kind:"report",report:await o.cleanup(s,n(s))})}catch(i){r.push({id:s,kind:"error",error:me(i)})}return r}t(Rn,"runCleanupPass");function mt(e,n){let o=Y(e.ui);for(let r of n)r.kind==="report"?o.succeeded(rn(r.report),ot(r.report)?"warning":"info"):o.failed(`Failed to clean up agent ${r.id}`,r.error)}t(mt,"reportCleanupOutcomes");function Pn(e){return e.outcome.kind==="refused"?e.outcome.reason:void 0}t(Pn,"refusalReason");function Or(e){return e.worktree.kind==="kept"?e.worktree.path??void 0:void 0}t(Or,"refusalWorktreePath");function Mr(e){switch(e.kind){case"dirty":return"It has uncommitted changes";case"unverifiable":return`Its state could not be verified (${e.detail})`;case"recovered-refusal":return"Herdr still reports it at work";default:return _e(e)}}t(Mr,"offerReason");function Ar(e,n){return{invalidate(){},render:t(()=>[` ${e.fg("dim",n)}`],"render")}}t(Ar,"progressBody");function Ir(e,n,o,r){let s=[{value:"force",label:"Force",description:n},{value:"cancel",label:"Cancel",description:"Keep the worktree and its changes"}],i=B(new Tr(s,6,Z(e)));return i.onSelect=l=>l.value==="force"?o():r(),i.onCancel=r,i}t(Ir,"forceOfferList");function Hn(e){let{ctx:n,theme:o,view:r,refresh:s,close:i,requestRender:l}=e,a=t(d=>{r.activate(d),l()},"show"),c=t((d,h,C,m)=>{let k=d.length===1;a(ye({theme:o,message:k?`Force cleanup of agent ${d[0]}?`:`Force cleanup of ${d.length} agents?`,detail:[...C,"",k?"This DELETES its worktree and anything uncommitted in it.":"This DELETES their worktrees and anything uncommitted in them."].join(`
|
|
3
3
|
`),onNo:m,onYes:t(()=>{i(),Y(n.ui).pending(`Forcing cleanup of ${Me(d)}`),(async()=>{let f=await Rn(d,w=>{let g=h.get(w);return{force:g?{reason:g}:{}}});mt(n,f)})()},"onYes")}))},"askForceConfirm"),u=t(d=>{let h=new Map;for(let{id:b,report:O}of d){let R=Pn(O);R&&h.set(b,R)}let C=[...h.keys()],m=C.length===1,k=d.map(({id:b,report:O})=>{let R=Pn(O),F=R?m?_e(R):`${b}: ${_e(R)}`:`${b}: kept`,$=Or(O);return $?`${F} (${$})`:F}),f=h.get(C[0]??""),w=m?`Clean up agent ${C[0]} anyway? ${f?Mr(f):"kept"}.`:`Clean up ${C.length} agents anyway?`,g=t(()=>{mt(n,d),s()},"backOut");a(Ir(o,w,()=>c(C,h,k,g),g))},"offerForce");return d=>{a(Ar(o,`Cleaning up ${Me(d)}\u2026`)),(async()=>{let h=await Rn(d,()=>{}),C=h.filter(f=>f.kind==="report"&&dn(f.report)),m=new Set(C.map(f=>f.id));if(mt(n,h.filter(f=>!m.has(f.id))),C.length>0){u(C);return}h.some(f=>f.kind==="error"||ot(f.report))?s():i()})()}}t(Hn,"createStatusCleanup");import{copyToClipboard as xr}from"@earendil-works/pi-coding-agent";import{SelectList as $r}from"@earendil-works/pi-tui";function jn(e){let{ctx:n,theme:o,view:r,close:s,requestRender:i}=e,l=Y(n.ui),a=t(f=>{r.activate(f),i()},"show"),c=t(f=>f.loss===void 0?"":Kt(f.loss),"lossClause"),u=t((f,w,g)=>{try{pn(g,w.text)}catch(b){l.failed(`Failed to export agent ${f.id} to ${g}`,b),h(f,w,g);return}l.outcome(Ke(w),`Exported handover for agent ${f.id} to ${g}.${c(w)}`),s()},"writeTo"),d=t((f,w,g)=>{if(!mn(g)){u(f,w,g);return}a(ye({theme:o,message:`Overwrite ${g}?`,detail:"A file already exists there. Y replaces it with the current export; Esc keeps the existing file.",onYes:t(()=>u(f,w,g),"onYes"),onNo:t(()=>h(f,w,g),"onNo")}))},"confirmOverwrite"),h=t((f,w,g)=>{a(We({prefill:g,notify:t((b,O)=>n.ui.notify(b,O),"notify"),validate:t(b=>b===""?"empty":null,"validate"),describeProblem:t(()=>"The export needs a file path.","describeProblem"),onDone:t(b=>d(f,w,b),"onDone"),onCancel:t(()=>k(f),"onCancel")}))},"showPathField"),C=t((f,w)=>{(async()=>{try{await xr(w.text)}catch(g){l.failed(`Failed to export agent ${f.id} to the clipboard`,g);return}l.outcome(Ke(w),`Exported handover for agent ${f.id} to the clipboard.${c(w)}`),s()})()},"copyToClipboardAndReport"),m=t((f,w)=>{let g=J();if(!g){l.failed(`Failed to export agent ${f.id}`,"manager unavailable");return}l.pending(`Reading the handover for agent ${f.id}`),(async()=>{let b=await g.exportHandover(f.id);if(b.kind==="faulted"){l.outcome(Ke(b),`Agent ${f.id} ${Ae(b.fault)}`);return}w(b)})()},"readExport"),k=t(f=>{let w=[{value:"clipboard",label:"Export to clipboard",description:"Copy this run's handover text to the clipboard"},{value:"file",label:"Export to file",description:"Write the handover text to a file you choose"}],g=B(new $r(w,10,Z(o)));g.onSelect=b=>{if(b.value==="clipboard"){m(f,O=>C(f,O));return}m(f,O=>h(f,O,O.defaultPath))},g.onCancel=()=>s(),a(g)},"showChoice");return k}t(jn,"createStatusExport");import{SelectList as Lr}from"@earendil-works/pi-tui";function Fn(e){let{ctx:n,theme:o,view:r,close:s,requestRender:i,backToActions:l}=e,a=Y(n.ui),c=t(m=>{r.activate(m),i()},"show"),u=t((m,k)=>{s(),a.outcome("warning",`Agent ${m.id} ${k}`)},"refuse"),d=t((m,k)=>{let f=J();if(s(),!f){a.failed(`Failed to hand agent ${m.id} over to ${k}`,"manager unavailable");return}a.pending(`Handing agent ${m.id} over to ${k}`),(async()=>{let w=await f.handover(m.id,{harness:k});a.outcome(Gt(w),sn(m.id,w))})()},"runHandover"),h=t((m,k)=>{let f=_(),w=on(f,re(),k).map(b=>({value:`harness:${b}`,label:`Hand over to ${f.displayName(b)}`,description:`Launch the next run of this agent under ${f.displayName(b)}`}));if(w.length===0){u(m,"was not handed over: no other harness can take it over.");return}let g=B(new Lr(w,10,Z(o)));g.onSelect=b=>{d(m,b.value.slice(8))},g.onCancel=()=>s(),c(g)},"openSubmenu"),C=t((m,k)=>{c(ye({theme:o,message:`Agent ${m.id} is still running.`,detail:`pi-cowboy will need to stop it before it can be handed over. Proceed?
|
|
4
4
|
|
|
@@ -8,4 +8,4 @@ You have been invoked to handle a specific task autonomously`,"utf-8"),e.ui.noti
|
|
|
8
8
|
`,1)[0]??"").slice(0,zr),R=Bt(),F=tn();try{await R.spawn(o,{spawnId:f,type:h.type,requestedHarness:h.harness,prompt:m,description:O,orchestration:F,modelChoice:h.modelChoice,worktree:b,hostRef:w?.hostRef,projectTrusted:w?.projectTrusted,invocation:{...zn(h.modelChoice),runInBackground:h.runInBackground,fork:h.fork},runInBackground:h.runInBackground,fork:h.fork})}catch($){let H=`Spawn failed: ${$ instanceof Error?$.message:String($)}`;if(!w){e.ui.notify(H,"error");return}let G=await w.teardown(k);e.ui.notify(`${H}
|
|
9
9
|
|
|
10
10
|
${un(G)}`,"error")}},"launch"),a=await or(e,n);if(a===void 0)return;let c=new K(e),u;if(a.worktreeChoice.kind==="new"){let h=await nr(c,(C,m)=>e.ui.notify(C,m));if(h===void 0)return;u={kind:"new",branch:h}}else u=a.worktreeChoice;let d=await c.open(({tui:h,theme:C,keybindings:m,close:k})=>new N(rr({prefill:"",onDone:t(f=>k(f),"onDone"),onCancel:t(()=>k(),"onCancel"),tui:h,theme:C,keybindings:m}),{title:"Agent Prompt (optional)",theme:C,passthroughKeys:!0}));d!==void 0&&await l(a,u,d)}t(ir,"showSpawnAgentMenu");async function Yr(e){return await new K(e).open(({theme:n,close:o})=>{let r=t(u=>o(u),"handOff"),s=E(),i=s.agent.showActiveIndicator,l=s.agent.grazingEnabled,a=[Ce("concurrency","Concurrency Settings","Set per-model slot limits",r),Ce("spawnoptions","Agent behavior","spawn defaults, results delivery, output, tools, worktrees",r),Ce("systemprompt","System prompt","Prompt mode, AGENTS.md, skills, extensions",r),{id:"showActiveIndicator",label:"Show cowboy \u{1F920}",currentValue:i?"ON":"OFF",values:["ON","OFF"]},{id:"grazingEnabled",label:"Grazing \u{1F404}",currentValue:l?"ON":"OFF",values:["ON","OFF"]}],c=new sr(a,10,D(n),(u,d)=>{u==="showActiveIndicator"?an(e.ui,d==="ON"):u==="grazingEnabled"&&s.mutate.agent.setGrazingEnabled(d==="ON")},o);return new N(c,{title:"Settings",theme:n,onCancel:o})})}t(Yr,"showSettingsList");async function Xr(e,n){for(;;){let o=await Yr(e);if(o===void 0)return;switch(o){case"concurrency":await En(e,n);break;case"spawnoptions":await Kn(e);break;case"systemprompt":await Bn(e);break}}}t(Xr,"showSettingsMenu");async function Zr(e,n,o){switch(n){case"status":await Vn(e);break;case"spawn":await ir(e,o);break;case"settings":await Xr(e,o);break}}t(Zr,"showAgentsActionMenu");function Ce(e,n,o,r){return{id:e,label:n,description:o,currentValue:"",submenu:t(()=>(r(e),ie),"submenu")}}t(Ce,"handOffRow");async function Jr(e,n){let o=await hn(e.cwd),r;return await new K(e).open(({tui:s,theme:i,close:l})=>{let a=t(d=>l(d),"handOff"),c=t(()=>{let d=E(),h=t((k,f)=>e.ui.notify(k,f),"notify"),C=d.agent.extensionEnabled,m={id:"extensionEnabled",label:"Enabled",currentValue:C?"ON":"OFF",values:["ON","OFF"],description:C?"Unload the cowboy tools and stop subagent-result notifications. Persisted; active agents keep working.":"cowboy tools are unloaded and the rest of this menu is hidden. Active agents keep working."};return C?[xn({ctx:e,store:d,theme:i,harnessModelOptions:n,requestRender:t(()=>s.requestRender(),"requestRender"),piDefaultThinking:o}),qn({store:d,theme:i,notify:h}),Gn({store:d,theme:i,notify:h}),Ce("status","Status","List spawned, queued and settled agents",a),Ce("spawn","Spawn agent","Manually spawn a new agent",a),Ce("settings","Settings","Concurrency, agent behavior, and system prompt settings",a),m]:[m]},"buildItems"),u=new sr(c(),10,D(i),(d,h)=>{let C=d==="extensionEnabled";if(C){let m=h==="ON";gn(e.ui,m),e.ui.notify(m?"pi-cowboy enabled":"pi-cowboy disabled","info")}r?.(c(),C?"extensionEnabled":void 0)},l);return new N(u,{title:"Agents",theme:i,onCancel:l,onRebuild:t(d=>{r=d},"onRebuild")})})}t(Jr,"showAgentsMainList");async function il(e,n){for(;;){let o=await Jr(e,n);if(o===void 0)return;await Zr(e,o,n)}}t(il,"showAgentsMainMenu");export{Zr as showAgentsActionMenu,il as showAgentsMainMenu,Xr as showSettingsMenu,ir as showSpawnAgentMenu};
|
|
11
|
-
//# sourceMappingURL=menus-
|
|
11
|
+
//# sourceMappingURL=menus-EETUYB5S.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as E,b as R,i as A}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=model-picker-
|
|
1
|
+
import{a as E,b as R,i as A}from"./chunk-WP65L6WI.js";import{ja as v,ka as u,na as c,xa as S,ya as k}from"./chunk-UEMXTMQN.js";import{J as h,K as C,a as s,q as w,r as m}from"./chunk-AOUEQXPY.js";import{ModelSelectorComponent as L}from"@earendil-works/pi-coding-agent";import{fuzzyFilter as $}from"@earendil-works/pi-tui";function b(e,t,n){let o=`${n.provider}/${n.id}`;e.mutate.session.setOverride("default",o),t.ui.notify(`Subagent model set to ${o} (session)`,"info")}s(b,"applySessionDefault");function D(e){let t=c(),o=u().model??e.model,d=o?`${o.provider}/${o.id}`:null,r=t.sessionDefaultModel??t.agentConfigSnapshot().default??d;return r?m(r,e.modelRegistry,e.model):void 0}s(D,"currentSubagentModel");function O(e){let t=e.modelRegistry.runtime;return t&&typeof t.getAvailableSnapshot=="function"?t:void 0}s(O,"sessionModelRuntime");async function z(e,t){let n=c(),o=O(e),d=e.scopedModels,r=o?[]:await x(e);await new R(e).open(({tui:p,theme:f,close:l})=>{let i=D(e);if(!o){let y=u().modelRegistry,I=r.map(a=>a.key),P=A(I,i?.id??null,[]).filter(a=>a.value!=null);return new E(P,i?`${i.provider}/${i.id}`:null,{onSelect:s(a=>{let M=m(a,y,void 0);M&&b(n,e,M),l()},"onSelect"),onCancel:s(()=>l(),"onCancel")},f)}return new L(p,i,o,d,y=>{b(n,e,y),l()},()=>l(),t?.initialSearch)})}s(z,"openSubagentModelPicker");async function G(e){let n=e.trim();if(n==="model"||n.startsWith("model ")){let r=n.slice(5).trim(),p=await H(),f=[{value:"model clear",label:"clear",description:"Clear the session model override (the configured chain decides)"},...p.map(i=>{let g=w(i.key);return{value:`model ${i.key}`,label:g?.modelId??i.key,description:g?.provider??""}})],l=$(f,r,i=>`${i.label} ${i.description??""} ${i.value}`);return l.length>0?l:null}let d=$([{value:"status",label:"status",description:"List spawned, queued and settled agents"},{value:"spawn",label:"spawn",description:"Open the spawn wizard"},{value:"worktree",label:"worktree",description:"Create a git worktree with no agent attached"},{value:"model",label:"model",description:"Set the model sub-agents use (opens pi's model picker)"},{value:"enable",label:"enable",description:"Enable pi-cowboy"},{value:"disable",label:"disable",description:"Disable pi-cowboy"}],n,r=>r.label);return d.length>0?d:null}s(G,"cowboyCompletions");async function x(e){try{let t=await S().require("pi").listModels({pi:v(),modelCatalog:k(e.modelRegistry)}),n=C(t);return n!==void 0&&e.hasUI&&e.ui.notify(n,"warning"),h(t)}catch{return[]}}s(x,"piHarnessModels");async function H(){return await x(u())}s(H,"availableModelsForCompletion");async function J(e,t){let n=c();if(e==="clear"){n.mutate.session.clearOverride("default"),t.ui.notify("Subagent model override cleared (session) \u2014 the configured chain decides","info");return}if(e!==""){let o=m(e,t.modelRegistry,void 0);if(o){b(n,t,o);return}}await z(t,e!==""?{initialSearch:e}:void 0)}s(J,"handleModelArg");export{G as cowboyCompletions,J as handleModelArg,z as openSubagentModelPicker};
|
|
2
|
+
//# sourceMappingURL=model-picker-KTV7DIQR.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-cowboy",
|
|
3
|
-
"version": "0.36.
|
|
3
|
+
"version": "0.36.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"packageManager": "pnpm@12.9.1",
|
|
6
6
|
"description": "🤠 Agent orchestrator for pi. It can manage Codex, Claude Code, OpenCode, pi, pig and pi-bolt as subagents and handover sessions in between them. Runs subagents in background Herdr panes, isolated in copy-on-write Git worktrees.",
|