pi-cowboy 0.32.1 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,6 +25,8 @@ export declare class AgentManager {
25
25
  private readonly registry;
26
26
  constructor(pools: ConcurrencyPools, transport: SupervisorTransport);
27
27
  getRegistry(): HerdrTaskRegistry;
28
+ attachLiveSpawns(): void;
29
+ private attachSpawn;
28
30
  setConcurrency(config: ConcurrencyConfig): void;
29
31
  setOnComplete(cb: OnAgentComplete): void;
30
32
  setOnFollowUp(cb: OnAgentFollowUp): void;
@@ -1,4 +1,4 @@
1
- import type { ProcessSupervisor, ProcessSupervisorOptions, SubagentExitOutcome } from "../subagent/supervisor.js";
1
+ import type { ProcessSupervisor, ProcessSupervisorOptions } from "../subagent/supervisor.js";
2
2
  import { type SupervisorTransport } from "../subagent/pane-supervisor.js";
3
3
  import type { AgentLaunchState, AgentSpawn } from "../types.js";
4
4
  import type { AgentHostRef } from "./agent-host.js";
@@ -9,7 +9,6 @@ interface AgentReviveRequest {
9
9
  supervisorOptions: ProcessSupervisorOptions;
10
10
  attachSupervisor(supervisor: ProcessSupervisor, launch: AgentLaunchState): void;
11
11
  rebindParentSignal(): void;
12
- reportOutcome(supervisor: ProcessSupervisor, outcome: SubagentExitOutcome): void;
13
12
  }
14
13
  export declare function reviveSettledRun(request: AgentReviveRequest): void;
15
14
  export {};
@@ -1,11 +1,16 @@
1
1
  import type { AgentPhase, AgentSpawn } from "../types.js";
2
+ import type { AgentSpawnObserver } from "./spawn-journal.js";
2
3
  export declare class SpawnIdCollisionError extends Error {
3
4
  readonly spawnId: string;
4
5
  constructor(spawnId: string);
5
6
  }
6
7
  export declare class AgentSpawnStore {
7
8
  private spawns;
9
+ private observer;
10
+ setObserver(observer: AgentSpawnObserver | null): void;
11
+ clearObserver(observer: AgentSpawnObserver): void;
8
12
  add(spawn: AgentSpawn): void;
13
+ save(spawn: AgentSpawn): void;
9
14
  mint(mint?: () => string): string;
10
15
  get(id: string): AgentSpawn | undefined;
11
16
  drop(id: string): void;
@@ -70,6 +70,7 @@ export declare function enterSettling(state: RunState, terminal: RunTerminal, co
70
70
  export declare function finishSettling(state: RunState): RunState;
71
71
  export declare function handoverRun(state: RunState, startedAt: number): RunState;
72
72
  export declare function reviveRun(state: RunState, startedAt: number): RunState;
73
+ export declare function activeRun(queuedAt: number, startedAt: number): RunState;
73
74
  export declare function disposeQueuedRun(state: RunState, completedAt: number): RunState;
74
75
  export declare function disposeLiveRun(state: RunState): RunState;
75
76
  export declare function dropRun(state: RunState, artifacts: RunArtifacts): RunState;
@@ -0,0 +1,13 @@
1
+ import type { AgentSpawnStore } from "./agent-spawn-store.js";
2
+ import type { SpawnJournal } from "./spawn-journal.js";
3
+ import { type SpawnRecord } from "./spawn-record.js";
4
+ import type { Verdict } from "./spawn-verification.js";
5
+ export declare const RELOAD_QUEUED_MESSAGE = "The session was reloaded before the queued agent could start.";
6
+ export type VerdictSource = (record: SpawnRecord) => Promise<Verdict>;
7
+ export interface AdoptSpawnRecordsRequest {
8
+ readonly journal: SpawnJournal;
9
+ readonly store: AgentSpawnStore;
10
+ readonly verdictOf: VerdictSource;
11
+ notify?(message: string, kind: "warning"): void;
12
+ }
13
+ export declare function adoptSpawnRecords(request: AdoptSpawnRecordsRequest): Promise<void>;
@@ -0,0 +1,22 @@
1
+ import type { AgentSpawn } from "../types.js";
2
+ import { type SpawnJournalEntry, type SpawnRecord } from "./spawn-record.js";
3
+ export declare const SPAWN_JOURNAL_CUSTOM_TYPE = "pi-cowboy.spawn-journal";
4
+ export interface AgentSpawnObserver {
5
+ record(spawn: AgentSpawn): void;
6
+ forget(spawnId: string): void;
7
+ }
8
+ export interface SpawnReplay {
9
+ readonly records: readonly SpawnRecord[];
10
+ readonly unreadable: number;
11
+ }
12
+ export interface SpawnJournal extends AgentSpawnObserver {
13
+ replay(): SpawnReplay;
14
+ detach(): void;
15
+ }
16
+ export interface SpawnJournalDeps {
17
+ append(entry: SpawnJournalEntry): void;
18
+ readBranch(): readonly unknown[];
19
+ notify?(message: string, kind: "warning"): void;
20
+ now?(): number;
21
+ }
22
+ export declare function createSpawnJournal(deps: SpawnJournalDeps): SpawnJournal;
@@ -0,0 +1,55 @@
1
+ import type { OrchestratorConfig } from "../orchestrators/types.js";
2
+ import type { AgentLifecycleState, AgentSpawn, AgentWorktree } from "../types.js";
3
+ import type { AgentInvocation } from "./types.js";
4
+ export interface SpawnRecord {
5
+ readonly v: 1;
6
+ readonly id: string;
7
+ readonly lifecycle: AgentLifecycleState;
8
+ readonly display: SpawnRecordDisplay;
9
+ readonly execution: SpawnRecordExecution;
10
+ }
11
+ export interface SpawnRecordDisplay {
12
+ readonly type: string;
13
+ readonly description: string;
14
+ readonly taskSlug?: string;
15
+ readonly orchestration: OrchestratorConfig;
16
+ readonly invocation?: AgentInvocation;
17
+ readonly worktree?: AgentWorktree;
18
+ }
19
+ export interface SpawnRecordHostRef {
20
+ readonly multiplexer: string;
21
+ readonly name: string;
22
+ readonly paneId: string;
23
+ readonly tabId?: string;
24
+ readonly workspaceId: string;
25
+ readonly paneCreated: boolean;
26
+ }
27
+ export interface SpawnRecordEndedRun {
28
+ readonly harness: string;
29
+ readonly host: SpawnRecordHostRef;
30
+ readonly cwd: string | null;
31
+ readonly sessionId: string;
32
+ readonly startedAt: number;
33
+ readonly endedAt: number;
34
+ }
35
+ export interface SpawnRecordExecution {
36
+ readonly host?: SpawnRecordHostRef;
37
+ readonly harness?: string;
38
+ readonly modelKey?: string;
39
+ readonly history: readonly SpawnRecordEndedRun[];
40
+ }
41
+ export type SpawnJournalEntry = {
42
+ readonly v: 1;
43
+ readonly kind: "spawn";
44
+ readonly at: number;
45
+ readonly record: SpawnRecord;
46
+ } | {
47
+ readonly v: 1;
48
+ readonly kind: "forgotten";
49
+ readonly spawnId: string;
50
+ readonly at: number;
51
+ };
52
+ export declare function encodeSpawnRecord(spawn: AgentSpawn): SpawnRecord;
53
+ export declare function encodeForget(spawnId: string, at: number): SpawnJournalEntry;
54
+ export declare function spawnFromRecord(record: SpawnRecord): AgentSpawn;
55
+ export declare function decodeJournalEntry(data: unknown): SpawnJournalEntry | null;
@@ -0,0 +1,22 @@
1
+ import type { AgentSpawn } from "../types.js";
2
+ import type { HostObservation } from "./agent-host.js";
3
+ import type { LocateResult, PaneRef } from "./agent-assets.js";
4
+ import { type SpawnRecord } from "./spawn-record.js";
5
+ export type Verdict = {
6
+ readonly kind: "adopt-live";
7
+ } | {
8
+ readonly kind: "settle";
9
+ readonly reason: string;
10
+ } | {
11
+ readonly kind: "forget";
12
+ };
13
+ export interface SpawnVerificationDeps {
14
+ locate(id: string, hint: AgentSpawn): Promise<LocateResult>;
15
+ observe(pane: PaneRef): Promise<HostObservation | undefined>;
16
+ notify?(message: string, kind: "warning"): void;
17
+ }
18
+ export interface SpawnVerification {
19
+ verdict(record: SpawnRecord): Promise<Verdict>;
20
+ }
21
+ export declare const PROCESS_GONE_ARTIFACTS_REMAIN = "the process is gone, but its worktree and branch remain";
22
+ export declare function createSpawnVerification(deps: SpawnVerificationDeps): SpawnVerification;
@@ -41,6 +41,7 @@ interface SubagentSessionOptions {
41
41
  id: string;
42
42
  args: SpawnArgs;
43
43
  deps: SubagentSessionDeps;
44
+ existing?: AgentSpawn;
44
45
  }
45
46
  export interface SessionHandoverRequest {
46
47
  readonly harness: AnyHarnessId;
@@ -57,7 +58,12 @@ export declare class SubagentSession {
57
58
  private retention?;
58
59
  private supervisor?;
59
60
  private parentBinding?;
60
- constructor({ id, args, deps }: SubagentSessionOptions);
61
+ constructor({ id, args, deps, existing }: SubagentSessionOptions);
62
+ static attach(options: {
63
+ spawn: AgentSpawn;
64
+ harness: AnyHarnessId;
65
+ deps: SubagentSessionDeps;
66
+ }): SubagentSession;
61
67
  get spawn(): AgentSpawn;
62
68
  get promise(): Promise<string>;
63
69
  isQueued(): boolean;
@@ -65,12 +71,14 @@ export declare class SubagentSession {
65
71
  isActive(): boolean;
66
72
  isSettled(): boolean;
67
73
  private commit;
74
+ private harnessId;
68
75
  private get artifacts();
69
76
  start(reservation?: PoolReservation): void;
70
77
  rollbackStart(): void;
71
78
  settleStartFailure(err: unknown): void;
72
79
  steer(message: string): Promise<SteerOutcome>;
73
80
  private revive;
81
+ private beginWatch;
74
82
  abort(initiator?: StopInitiator): Promise<boolean>;
75
83
  private handoverSource;
76
84
  private exportSettledSession;
@@ -1,2 +1,2 @@
1
- import{Ja as x}from"./chunk-BHUJL2CE.js";import{a as s,h as f,s as C}from"./chunk-GG527IQR.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-HVINJNTI.js.map
1
+ import{Ja as x}from"./chunk-IIQ52KJZ.js";import{a as s,i as f,t as C}from"./chunk-3TPZINCV.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-3P4DDY2M.js.map
@@ -1,2 +1,2 @@
1
- var P=Object.defineProperty;var t=(e,n)=>P(e,"name",{value:n,configurable:!0});function Y(e){return!e||e.length>128||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)}t(Y,"isUnsafeName");function _(e){return e.replace(/[\r\n]+/g," ").trim()}t(_,"toSingleLine");function E(e){return new Promise(n=>setTimeout(n,e))}t(E,"sleep");function z(e){return _(e instanceof Error?e.message:String(e))}t(z,"errorMessage");function C(e){if(typeof e!="string")return null;let n=e.indexOf("/");return n<=0?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}t(C,"parseModelKey");function X(e,n,r){if(!e)return r;let o=C(e);return o?n.find(o.provider,o.modelId)??r:r}t(X,"findModelInRegistry");function Z(e){if(e)return"model"in e?e.model.id:"harness"in e?e.name:void 0}t(Z,"modelChoiceName");function J(e){return e!=null&&"key"in e?e.key:void 0}t(J,"modelChoiceKey");var Q=5e3;function ee(e){throw new Error(`Unhandled variant: ${JSON.stringify(e)}`)}t(ee,"assertNever");import{randomBytes as N}from"node:crypto";import{Buffer as p}from"buffer";var c="0123456789ABCDEFGHJKMNPQRSTVWXYZ",R="*~$=U",y=class extends Error{static{t(this,"InvalidChecksumCharacterError")}constructor(n){super(n),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},h=class extends Error{static{t(this,"InvalidChecksumError")}constructor(n){super(n),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},g=class{static{t(this,"CrockfordBase32")}static encode(n,r){p.isBuffer(n)?n=p.from(n):n=this.createBuffer(n);let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(n)}let s=[],a=0,i=0;for(let d of n)for(i=i<<8|d,a+=8;a>=5;)s.push(i>>>a-5&31),a-=5;a>0&&s.push(i<<5-a&31);let l=s.map(d=>c.charAt(d)).join("");return u&&(l+=this.computeChecksum(n)),l}static computeChecksum(n){let r=0;for(let o of n)r=(r*256+o)%37;return(c+R).charAt(r)}static decode(n,r){n=n.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(n,r)}let s=null;if(u){if(n.length===0)throw new y("Cannot validate checksum: input is empty");let d=n.charAt(n.length-1);if((c+R).indexOf(d)===-1)throw new y(`Invalid checksum character: ${d}`);s=d,n=n.slice(0,-1)}let a=[],i=0,l=0;for(let d of n){let f=c.indexOf(d);if(f===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);i+=5,i>=8?(i-=8,a.push(l|f>>i),l=f<<8-i&255):l|=f<<8-i}if((l>0||i>=5)&&a.push(l),s!==null){let d=this.computeChecksum(a);if(s!==d)throw new h(`Checksum mismatch: expected '${d}' but found '${s}'`)}return r?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(n){try{return this.decode(n,{checksum:!0}),!0}catch{return!1}}static encodeUlid(n){if(n.length===0)return"";let r=0n;for(let s of n)r=r<<8n|BigInt(s);let o=[];for(;r>0n;){let s=Number(r%32n);o.unshift(c.charAt(s)),r/=32n}let u=Math.ceil(n.length*8/5);return o.join("").padStart(u,"0")}static decodeUlid(n,r){if(n.length===0)return r?.asNumber===!0?0n:p.from([]);let o=0n;for(let i of n){let l=c.indexOf(i);if(l===-1)throw new Error(`Invalid base 32 character found in string: ${i}`);o=o*32n+BigInt(l)}let u=Math.floor(n.length*5/8),s=[],a=o;for(;a>0n;)s.unshift(Number(a&0xffn)),a>>=8n;for(o===0n&&s.push(0);s.length<u;)s.unshift(0);return r?.asNumber===!0?this.asNumber(s):this.asBuffer(s)}static createBuffer(n){if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new Error("Input must be a safe integer");n=BigInt(n)}if(n<0n)throw new Error("Input cannot be a negative number");let r=[];for(;n>0n;)r.unshift(Number(n&0xffn)),n>>=8n;return p.from(r)}static asNumber(n){let r=0n;return n.forEach(o=>{r<<=8n,r|=BigInt(o)}),r}static asBuffer(n){return p.from(n.map(r=>r.toString(16).padStart(2,"0")).join(""),"hex")}};var b="0123456789abcdefghjkmnpqrstvwxyz",S=8,w=5,I=32,x=class extends Error{static{t(this,"SpawnIdExhaustedError")}constructor(n){super(`Could not mint a unique spawn id after ${n} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function v(){return g.encode(N(w)).toLowerCase()}t(v,"generateSpawnId");function de(e,n=v){for(let r=0;r<I;r++){let o=n();if(!e(o))return o}throw new x(I)}t(de,"generateUniqueSpawnId");var O=`[${b}]{${S}}`;function pe(e,n){return new RegExp(`^cow-${n}-${O}$`).test(e)}t(pe,"isTaskAgentName");function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}t(L,"isRecord");function fe(e){if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}t(fe,"nonEmpty");var D=["pi","pig","pi-bolt","opencode","codex","claude"],he="pi",T=["pi","pig","pi-bolt"];function xe(e){return T.some(n=>n===e)}t(xe,"isPiFamilyHarness");function Ee(e){return D.find(n=>n===e)}t(Ee,"parseHarnessId");var M=["PATH","HOME","SHELL","PWD","OLDPWD","IFS","CDPATH","GLOBIGNORE","PS1","PS2","PS3","PS4","BASH_ENV","ENV","NODE_OPTIONS","LD_PRELOAD","LD_AUDIT"],q=["DYLD_","HERDR_","COWBOY_"],H=Object.freeze([]),F=/^[A-Za-z_][A-Za-z0-9_]*$/;function Re(e){return F.test(e)}t(Re,"isEnvVarName");function Ie(e){return new RegExp("\\p{Cc}","u").test(e)}t(Ie,"hasControlCharacter");function B(e){return M.includes(e)||q.some(n=>e.startsWith(n))}t(B,"isUniversalReservedEnvVar");function be(e,n=H){return B(e)||n.includes(e)}t(be,"isReservedEnvVar");function Se(e){return e.reservedEnvVars?.()??H}t(Se,"reservedEnvVarsOf");var Le={pi:["PI_CODING_AGENT_DIR","PI_CODING_AGENT_SESSION_DIR","HERDR_AGENT"],opencode:["OPENCODE_CONFIG_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_CONTENT","OPENCODE_DISABLE_PROJECT_CONFIG","OPENCODE_DISABLE_AUTOUPDATE"],codex:["CODEX_HOME"],claude:["CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_DISABLE_CLAUDE_MDS","ANTHROPIC_API_KEY","COWBOY_API_KEY"]};function Ae(e,n){return{kind:"other",unmappedKind:typeof e=="string"&&e!==""?e:"unknown",content:n}}t(Ae,"otherRecord");function He(e){if(!L(e)||typeof e.content!="string")return m(e);let n=e.kind;if(typeof n!="string")return m(e);switch(n){case"user":case"assistant":case"thinking":case"tool-call":case"compaction":case"unparseable":return{kind:n,content:e.content};case"other":return typeof e.unmappedKind=="string"?{kind:n,unmappedKind:e.unmappedKind,content:e.content}:m(e);default:return m(e)}}t(He,"readHandoverRecord");function m(e){if(typeof e=="string")return{kind:"unparseable",content:e};try{return{kind:"unparseable",content:JSON.stringify(e)??String(e)}}catch{return{kind:"unparseable",content:String(e)}}}t(m,"unreadableRecord");var A=class extends Error{static{t(this,"SessionExportError")}fault;constructor(n,r){super(r),this.name="SessionExportError",this.fault=n}};function ke(e){return e.kind==="unavailable"?[]:e.entries}t(ke,"modelListEntries");function Pe(e){return e.kind==="listed"?void 0:e.notice}t(Pe,"modelListNotice");function _e(e){return e.readHandoverRecords!==void 0}t(_e,"canReadHandoverRecords");function V(e){return`'${e.replaceAll("'","'\\''")}'`}t(V,"singleQuoteShellWord");function ve(e,n){return e===null?n:`( . ${V(e)} && { ${n}; } )`}t(ve,"launchEnvBody");var k=5,$=2e3,U=250;function G(e){let n=e.indexOf("_");return n===-1?e:`${e.slice(0,n+1)}""${e.slice(n+1)}`}t(G,"splitMarker");async function Oe(e,n,r){let o=`${r.commandName}() { : "${r.signature}"; ${r.body}; }`,u=`typeset -f ${r.commandName} 2>/dev/null | grep -q "${r.signature}" && echo ${G(r.readyMarker)}`;for(let s=1;s<=k;s++){if(await e.run(n,o),await e.run(n,u),await W(e,n,r.readyMarker,$)){r.proof!==void 0&&await j(e,n,r.proof);return}s<k&&await E(U)}throw new Error(`failed to prepare pane ${n}: the ${r.commandName} launcher never landed`)}t(Oe,"installPaneLauncher");async function W(e,n,r,o){try{return await e.waitForOutput(n,r,o),!0}catch{return!1}}t(W,"panePrinted");async function j(e,n,r){await e.run(n,r.command);try{await e.waitForOutput(n,r.output,r.timeoutMs)}catch{throw new Error(r.failure)}}t(j,"requirePaneProof");export{t as a,S as b,v as c,de as d,Y as e,E as f,z as g,C as h,X as i,Z as j,J as k,Q as l,ee as m,pe as n,L as o,fe as p,D as q,he as r,xe as s,Ee as t,Re as u,Ie as v,B as w,be as x,Se as y,Le as z,Ae as A,He as B,A as C,ke as D,Pe as E,_e as F,V as G,ve as H,G as I,Oe as J};
2
- //# sourceMappingURL=chunk-GG527IQR.js.map
1
+ var P=Object.defineProperty;var t=(e,n)=>P(e,"name",{value:n,configurable:!0});function Y(e){return!e||e.length>128||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)}t(Y,"isUnsafeName");function _(e){return e.replace(/[\r\n]+/g," ").trim()}t(_,"toSingleLine");function E(e){return new Promise(n=>setTimeout(n,e))}t(E,"sleep");function z(e){return _(e instanceof Error?e.message:String(e))}t(z,"errorMessage");function C(e){if(typeof e!="string")return null;let n=e.indexOf("/");return n<=0?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}t(C,"parseModelKey");function X(e,n,r){if(!e)return r;let o=C(e);return o?n.find(o.provider,o.modelId)??r:r}t(X,"findModelInRegistry");function Z(e){if(e)return"model"in e?e.model.id:"harness"in e?e.name:void 0}t(Z,"modelChoiceName");function J(e){return e!=null&&"key"in e?e.key:void 0}t(J,"modelChoiceKey");var Q=5e3;function ee(e){throw new Error(`Unhandled variant: ${JSON.stringify(e)}`)}t(ee,"assertNever");import{randomBytes as N}from"node:crypto";import{Buffer as p}from"buffer";var c="0123456789ABCDEFGHJKMNPQRSTVWXYZ",R="*~$=U",y=class extends Error{static{t(this,"InvalidChecksumCharacterError")}constructor(n){super(n),this.name="InvalidChecksumCharacterError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},h=class extends Error{static{t(this,"InvalidChecksumError")}constructor(n){super(n),this.name="InvalidChecksumError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},g=class{static{t(this,"CrockfordBase32")}static encode(n,r){p.isBuffer(n)?n=p.from(n):n=this.createBuffer(n);let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.encodeUlid(n)}let s=[],a=0,i=0;for(let d of n)for(i=i<<8|d,a+=8;a>=5;)s.push(i>>>a-5&31),a-=5;a>0&&s.push(i<<5-a&31);let l=s.map(d=>c.charAt(d)).join("");return u&&(l+=this.computeChecksum(n)),l}static computeChecksum(n){let r=0;for(let o of n)r=(r*256+o)%37;return(c+R).charAt(r)}static decode(n,r){n=n.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1").replace(/-+/g,"");let o=r?.variant??"crockford",u=r?.checksum??!1;if(o==="ulid"){if(u)throw new Error("Checksums are not supported with the ulid variant");return this.decodeUlid(n,r)}let s=null;if(u){if(n.length===0)throw new y("Cannot validate checksum: input is empty");let d=n.charAt(n.length-1);if((c+R).indexOf(d)===-1)throw new y(`Invalid checksum character: ${d}`);s=d,n=n.slice(0,-1)}let a=[],i=0,l=0;for(let d of n){let f=c.indexOf(d);if(f===-1)throw new Error(`Invalid base 32 character found in string: ${d}`);i+=5,i>=8?(i-=8,a.push(l|f>>i),l=f<<8-i&255):l|=f<<8-i}if((l>0||i>=5)&&a.push(l),s!==null){let d=this.computeChecksum(a);if(s!==d)throw new h(`Checksum mismatch: expected '${d}' but found '${s}'`)}return r?.asNumber===!0?this.asNumber(a):this.asBuffer(a)}static verify(n){try{return this.decode(n,{checksum:!0}),!0}catch{return!1}}static encodeUlid(n){if(n.length===0)return"";let r=0n;for(let s of n)r=r<<8n|BigInt(s);let o=[];for(;r>0n;){let s=Number(r%32n);o.unshift(c.charAt(s)),r/=32n}let u=Math.ceil(n.length*8/5);return o.join("").padStart(u,"0")}static decodeUlid(n,r){if(n.length===0)return r?.asNumber===!0?0n:p.from([]);let o=0n;for(let i of n){let l=c.indexOf(i);if(l===-1)throw new Error(`Invalid base 32 character found in string: ${i}`);o=o*32n+BigInt(l)}let u=Math.floor(n.length*5/8),s=[],a=o;for(;a>0n;)s.unshift(Number(a&0xffn)),a>>=8n;for(o===0n&&s.push(0);s.length<u;)s.unshift(0);return r?.asNumber===!0?this.asNumber(s):this.asBuffer(s)}static createBuffer(n){if(typeof n=="number"){if(!Number.isSafeInteger(n))throw new Error("Input must be a safe integer");n=BigInt(n)}if(n<0n)throw new Error("Input cannot be a negative number");let r=[];for(;n>0n;)r.unshift(Number(n&0xffn)),n>>=8n;return p.from(r)}static asNumber(n){let r=0n;return n.forEach(o=>{r<<=8n,r|=BigInt(o)}),r}static asBuffer(n){return p.from(n.map(r=>r.toString(16).padStart(2,"0")).join(""),"hex")}};var b="0123456789abcdefghjkmnpqrstvwxyz",S=8,w=5,I=32,x=class extends Error{static{t(this,"SpawnIdExhaustedError")}constructor(n){super(`Could not mint a unique spawn id after ${n} attempts \u2014 the id space is exhausted or the taken-check is misreporting ids.`),this.name="SpawnIdExhaustedError"}};function v(){return g.encode(N(w)).toLowerCase()}t(v,"generateSpawnId");function de(e,n=v){for(let r=0;r<I;r++){let o=n();if(!e(o))return o}throw new x(I)}t(de,"generateUniqueSpawnId");var O=`[${b}]{${S}}`;function pe(e,n){return new RegExp(`^cow-${n}-${O}$`).test(e)}t(pe,"isTaskAgentName");function L(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}t(L,"isRecord");function fe(e){if(typeof e!="string")return;let n=e.trim();return n===""?void 0:n}t(fe,"nonEmpty");var D=["pi","pig","pi-bolt","opencode","codex","claude"],he="pi",T=["pi","pig","pi-bolt"];function xe(e){return T.some(n=>n===e)}t(xe,"isPiFamilyHarness");function Ee(e){return D.find(n=>n===e)}t(Ee,"parseHarnessId");var M=["PATH","HOME","SHELL","PWD","OLDPWD","IFS","CDPATH","GLOBIGNORE","PS1","PS2","PS3","PS4","BASH_ENV","ENV","NODE_OPTIONS","LD_PRELOAD","LD_AUDIT"],q=["DYLD_","HERDR_","COWBOY_"],H=Object.freeze([]),F=/^[A-Za-z_][A-Za-z0-9_]*$/;function Re(e){return F.test(e)}t(Re,"isEnvVarName");function Ie(e){return new RegExp("\\p{Cc}","u").test(e)}t(Ie,"hasControlCharacter");function B(e){return M.includes(e)||q.some(n=>e.startsWith(n))}t(B,"isUniversalReservedEnvVar");function be(e,n=H){return B(e)||n.includes(e)}t(be,"isReservedEnvVar");function Se(e){return e.reservedEnvVars?.()??H}t(Se,"reservedEnvVarsOf");var Le={pi:["PI_CODING_AGENT_DIR","PI_CODING_AGENT_SESSION_DIR","HERDR_AGENT"],opencode:["OPENCODE_CONFIG_DIR","OPENCODE_CONFIG","OPENCODE_CONFIG_CONTENT","OPENCODE_DISABLE_PROJECT_CONFIG","OPENCODE_DISABLE_AUTOUPDATE"],codex:["CODEX_HOME"],claude:["CLAUDE_CONFIG_DIR","CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CODE_DISABLE_CLAUDE_MDS","ANTHROPIC_API_KEY","COWBOY_API_KEY"]};function Ae(e,n){return{kind:"other",unmappedKind:typeof e=="string"&&e!==""?e:"unknown",content:n}}t(Ae,"otherRecord");function He(e){if(!L(e)||typeof e.content!="string")return m(e);let n=e.kind;if(typeof n!="string")return m(e);switch(n){case"user":case"assistant":case"thinking":case"tool-call":case"compaction":case"unparseable":return{kind:n,content:e.content};case"other":return typeof e.unmappedKind=="string"?{kind:n,unmappedKind:e.unmappedKind,content:e.content}:m(e);default:return m(e)}}t(He,"readHandoverRecord");function m(e){if(typeof e=="string")return{kind:"unparseable",content:e};try{return{kind:"unparseable",content:JSON.stringify(e)??String(e)}}catch{return{kind:"unparseable",content:String(e)}}}t(m,"unreadableRecord");var A=class extends Error{static{t(this,"SessionExportError")}fault;constructor(n,r){super(r),this.name="SessionExportError",this.fault=n}};function ke(e){return e.kind==="unavailable"?[]:e.entries}t(ke,"modelListEntries");function Pe(e){return e.kind==="listed"?void 0:e.notice}t(Pe,"modelListNotice");function _e(e){return e.readHandoverRecords!==void 0}t(_e,"canReadHandoverRecords");function V(e){return`'${e.replaceAll("'","'\\''")}'`}t(V,"singleQuoteShellWord");function ve(e,n){return e===null?n:`( . ${V(e)} && { ${n}; } )`}t(ve,"launchEnvBody");var k=5,$=2e3,U=250;function G(e){let n=e.indexOf("_");return n===-1?e:`${e.slice(0,n+1)}""${e.slice(n+1)}`}t(G,"splitMarker");async function Oe(e,n,r){let o=`${r.commandName}() { : "${r.signature}"; ${r.body}; }`,u=`typeset -f ${r.commandName} 2>/dev/null | grep -q "${r.signature}" && echo ${G(r.readyMarker)}`;for(let s=1;s<=k;s++){if(await e.run(n,o),await e.run(n,u),await W(e,n,r.readyMarker,$)){r.proof!==void 0&&await j(e,n,r.proof);return}s<k&&await E(U)}throw new Error(`failed to prepare pane ${n}: the ${r.commandName} launcher never landed`)}t(Oe,"installPaneLauncher");async function W(e,n,r,o){try{return await e.waitForOutput(n,r,o),!0}catch{return!1}}t(W,"panePrinted");async function j(e,n,r){await e.run(n,r.command);try{await e.waitForOutput(n,r.output,r.timeoutMs)}catch{throw new Error(r.failure)}}t(j,"requirePaneProof");export{t as a,b,S as c,v as d,de as e,Y as f,E as g,z as h,C as i,X as j,Z as k,J as l,Q as m,ee as n,pe as o,L as p,fe as q,D as r,he as s,xe as t,Ee as u,Re as v,Ie as w,B as x,be as y,Se as z,Le as A,Ae as B,He as C,A as D,ke as E,Pe as F,_e as G,V as H,ve as I,G as J,Oe as K};
2
+ //# sourceMappingURL=chunk-3TPZINCV.js.map
@@ -1,4 +1,4 @@
1
- import{A as wt,B as vt,C as kt,D as z,J as V,K as bt,M as xt,N as At,O as Q,b as lt,c as ct,e as ut,g as pt,i as ht,k as be,l as gt,p as mt,u as ft,v as Y,w as yt}from"./chunk-SUWDZ2JY.js";import{A as Ge,Aa as it,B as Ye,Ca as at,Ea as L,Ia as dt,L as ge,La as ke,N as et,O as me,R as fe,S as tt,U as q,V as T,W as I,Y as nt,aa as rt,b as ue,ba as ot,c as Be,k as B,l as Le,la as b,m as je,ma as F,n as pe,na as w,p as Ue,pa as y,qa as E,ra as ye,sa as we,u as We,ua as st,v as qe,xa as ve,y as Fe,ya as K,z as Ke,za as G}from"./chunk-BHUJL2CE.js";import{D as Ze,E as Je,a as r,g as $,i as he,j as ze,m as Ve,o as Qe,q as W,s as Xe}from"./chunk-GG527IQR.js";import{visibleWidth as Te}from"@earendil-works/pi-tui";var xe="\u{1F920}",Rt="\u{1F404}",pn="\u{1F4A9}",hn=2,gn=1e3,X=Te(Rt),mn="76;175;80";function fn(e){return`\x1B[48;2;${mn}m${e}\x1B[49m`}r(fn,"greenBackground");function It(e){return e===0?0:Math.max(hn,Math.ceil(Math.sqrt(2*e)))}r(It,"pastureEdge");function Et(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Et,"emptyPasture");function yn(e,t){let n=It(e.cows+e.droppings),o=Et(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(yn,"grazedPasture");function Z(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(Z,"cellsOf");function wn(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(wn,"neighboursOf");function St(e,t){return wn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(St,"openNeighboursOf");function vn(e,t){let n=Z(e,"cow").filter(d=>St(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=St(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(vn,"moveHerd");function Tt(e,t,n,o){for(let i=0;i<n;i+=1){let a=Z(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(Tt,"placeAtRandom");function kn(e,t,n,o){let i=Z(e,"cow"),a=Z(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}Tt(e,"cow",-s,o),Tt(e,"dropping",-d,o)}r(kn,"reconcileCounts");function bn(e,t,n){if(e===null)return yn(t,n);let o=It(t.cows+t.droppings),i=Et(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 kn(i,t.cows,t.droppings,n),i}r(bn,"reconcilePasture");var xn={anchor:"top-right",width:Te(xe),get offsetX(){return E()?.cowboyOffsetX??0},nonCapturing:!0},An={anchor:"top-right",offsetY:1,get width(){return E()?.pastureWidth??0},nonCapturing:!0};function Sn(e){return e==="cow"?Rt:e==="dropping"?pn:" ".repeat(X)}r(Sn,"cellText");function Tn(e,t){return e.map(n=>t(n.map(Sn).join("")))}r(Tn,"drawnRows");function Rn(){return we().list(["spawned"]).length}r(Rn,"liveAgentCount");function In(){return we().list(tt).length}r(In,"endedAgentCount");function En(){return{live:Rn(),ended:In()}}r(En,"agentCounts");function On(){return y().agent.grazingEnabled}r(On,"grazingEnabled");var Ae=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 Te(xe)}get pastureWidth(){return this.drawnPasture().length*X}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*X-(t*X-this.cowboyWidth)}render(){return this.frame(),[xe]}pastureRows(){return this.frame(),Tn(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(),gn))}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:vn(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:bn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Se=class{static{r(this,"PastureView")}render(){return E()?.pastureRows()??[]}invalidate(){}};function Ot(e){Re(),e.custom(t=>{let n=new Ae(t,En,On,fn,Math.random);return ye(n),n},{overlay:!0,overlayOptions:xn,onHandle:r(t=>E()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Se,{overlay:!0,overlayOptions:An,onHandle:r(t=>E()?.attachPasture(t),"onHandle")})}r(Ot,"showExtensionIndicator");function Re(){let e=E();ye(null),e?.dispose()}r(Re,"hideExtensionIndicator");function J(){return y().agent.extensionEnabled}r(J,"isExtensionEnabled");function Cn(){return J()&&y().agent.showActiveIndicator}r(Cn,"isActiveIndicatorShown");function ee(e){Cn()?Ot(e):Re()}r(ee,"syncExtensionIndicator");function so(e,t){y().mutate.agent.setShowActiveIndicator(t),ee(e)}r(so,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as jr}from"@earendil-works/pi-tui";import{Type as p}from"typebox";var _n="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",Pn=`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.`,Mn=`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.`,$n=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${W.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.`,Nn='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.',Hn=p.Object({prompt:p.String({description:_n}),task_name:p.String({description:Pn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:Mn})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:$n})),worktree:p.Optional(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:Nn}))},{additionalProperties:!1,required:["prompt","task_name"]}),O=p.Object({agents:p.Array(Hn,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Ie=Object.values(m),k={type:"json_schema",strict:"prefer"};var Ee="_configuredModel",Oe="_configuredThinking";function N(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(N,"readModelKey");function te(e){return N(e.thinking)??N(e[Oe])}r(te,"readThinkingRequest");function ne(e){let t=N(e.model);if(t)return{source:"call",key:t};let n=N(e[Ee]);if(n)return{source:"configured",key:n}}r(ne,"readModelRequest");function j(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(j,"withoutModel");function re(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(re,"modelChoiceFor");function U(e){return`${e.provider}/${e.id}`}r(U,"modelKey");function Dn(e,t){if(t!==void 0&&!me.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${me.options.join(", ")}); launching "${U(e)}" with "${t}".`}r(Dn,"undeclaredLevelWarning");function Ct(e,t){let n=Dn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Ct,"resolvedModel");function Bn(e){return`No API key found for "${e}"`}r(Bn,"missingCredential");function _t(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:$(o)}}return!Qe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Bn(t.provider)}}r(_t,"probeCredentials");function Ce(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ce,"refusal");function _e(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return j(i);let d=_t(n,o);if(d.verdict!=="unusable")return Ct(o,i);throw new Error(Ce(`The parent session's model "${U(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?he(e.key,n,void 0):he(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 j(i)}let s=_t(n,a);if(s.verdict!=="unusable")return Ct(a,i);throw e.source==="call"?new Error(Ce(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Ce(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(_e,"resolvePiModel");async function Ln(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Ln,"harnessModels");function jn(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(jn,"undeclaredLevelWarning");async function Pt(e,t){if(!e)return j(t.thinking);let n=await Ln(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=jn(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(Pt,"resolveForeignModel");async function oe(e,t){let{harness:n}=t;if(Xe(n))return _e(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Pt(e,o)}r(oe,"resolveSpawnModel");function H(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(H,"resultWithSeverity");function se(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(se,"foldSeverity");var Pe=`
1
+ import{A as wt,B as vt,C as kt,D as z,J as V,K as bt,M as xt,N as At,O as Q,b as lt,c as ct,e as ut,g as pt,i as ht,k as be,l as gt,p as mt,u as ft,v as Y,w as yt}from"./chunk-UY5D2K62.js";import{A as Ge,Aa as it,B as Ye,Ca as at,Ea as L,Ia as dt,L as ge,La as ke,N as et,O as me,R as fe,S as tt,U as q,V as T,W as I,Y as nt,aa as rt,b as ue,ba as ot,c as Be,k as B,l as Le,la as b,m as je,ma as F,n as pe,na as w,p as Ue,pa as y,qa as E,ra as ye,sa as we,u as We,ua as st,v as qe,xa as ve,y as Fe,ya as K,z as Ke,za as G}from"./chunk-IIQ52KJZ.js";import{E as Ze,F as Je,a as r,h as $,j as he,k as ze,n as Ve,p as Qe,r as W,t as Xe}from"./chunk-3TPZINCV.js";import{visibleWidth as Te}from"@earendil-works/pi-tui";var xe="\u{1F920}",Rt="\u{1F404}",pn="\u{1F4A9}",hn=2,gn=1e3,X=Te(Rt),mn="76;175;80";function fn(e){return`\x1B[48;2;${mn}m${e}\x1B[49m`}r(fn,"greenBackground");function It(e){return e===0?0:Math.max(hn,Math.ceil(Math.sqrt(2*e)))}r(It,"pastureEdge");function Et(e){return Array.from({length:e},()=>Array.from({length:e},()=>"empty"))}r(Et,"emptyPasture");function yn(e,t){let n=It(e.cows+e.droppings),o=Et(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(yn,"grazedPasture");function Z(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(Z,"cellsOf");function wn(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(wn,"neighboursOf");function St(e,t){return wn(e,t.length).filter(({row:n,col:o})=>t[n][o]==="empty")}r(St,"openNeighboursOf");function vn(e,t){let n=Z(e,"cow").filter(d=>St(d,e).length>0);if(n.length===0||t()>=.05)return e;let o=n[Math.floor(t()*n.length)],i=St(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(vn,"moveHerd");function Tt(e,t,n,o){for(let i=0;i<n;i+=1){let a=Z(e,"empty"),s=a[Math.floor(o()*a.length)];e[s.row][s.col]=t}}r(Tt,"placeAtRandom");function kn(e,t,n,o){let i=Z(e,"cow"),a=Z(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}Tt(e,"cow",-s,o),Tt(e,"dropping",-d,o)}r(kn,"reconcileCounts");function bn(e,t,n){if(e===null)return yn(t,n);let o=It(t.cows+t.droppings),i=Et(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 kn(i,t.cows,t.droppings,n),i}r(bn,"reconcilePasture");var xn={anchor:"top-right",width:Te(xe),get offsetX(){return E()?.cowboyOffsetX??0},nonCapturing:!0},An={anchor:"top-right",offsetY:1,get width(){return E()?.pastureWidth??0},nonCapturing:!0};function Sn(e){return e==="cow"?Rt:e==="dropping"?pn:" ".repeat(X)}r(Sn,"cellText");function Tn(e,t){return e.map(n=>t(n.map(Sn).join("")))}r(Tn,"drawnRows");function Rn(){return we().list(["spawned"]).length}r(Rn,"liveAgentCount");function In(){return we().list(tt).length}r(In,"endedAgentCount");function En(){return{live:Rn(),ended:In()}}r(En,"agentCounts");function On(){return y().agent.grazingEnabled}r(On,"grazingEnabled");var Ae=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 Te(xe)}get pastureWidth(){return this.drawnPasture().length*X}get cowboyOffsetX(){let t=this.drawnPasture().length;return t===0?0:Math.floor(t/2)*X-(t*X-this.cowboyWidth)}render(){return this.frame(),[xe]}pastureRows(){return this.frame(),Tn(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(),gn))}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:vn(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:bn(this.herd?.pasture??null,{cows:t,droppings:n},this.random)}}},Se=class{static{r(this,"PastureView")}render(){return E()?.pastureRows()??[]}invalidate(){}};function Ot(e){Re(),e.custom(t=>{let n=new Ae(t,En,On,fn,Math.random);return ye(n),n},{overlay:!0,overlayOptions:xn,onHandle:r(t=>E()?.attachCowboy(t),"onHandle")}),e.custom(()=>new Se,{overlay:!0,overlayOptions:An,onHandle:r(t=>E()?.attachPasture(t),"onHandle")})}r(Ot,"showExtensionIndicator");function Re(){let e=E();ye(null),e?.dispose()}r(Re,"hideExtensionIndicator");function J(){return y().agent.extensionEnabled}r(J,"isExtensionEnabled");function Cn(){return J()&&y().agent.showActiveIndicator}r(Cn,"isActiveIndicatorShown");function ee(e){Cn()?Ot(e):Re()}r(ee,"syncExtensionIndicator");function so(e,t){y().mutate.agent.setShowActiveIndicator(t),ee(e)}r(so,"setShowActiveIndicator");import{Type as M}from"typebox";import{Text as jr}from"@earendil-works/pi-tui";import{Type as p}from"typebox";var _n="Task instructions for the agent. If the task requires code changes, the agent works in an isolated branch and will review and commit its changes upon approval. Do not instruct the agent to avoid committing when code modifications are needed.",Pn=`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.`,Mn=`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.`,$n=`Optional harness that launches THIS agent, overriding the agent template's harness_type and the configured default harness. Available: the built-in harnesses (${W.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.`,Nn='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.',Hn=p.Object({prompt:p.String({description:_n}),task_name:p.String({description:Pn}),agent_type:p.Optional(p.Union([p.String(),p.Null()])),model:p.Optional(p.Union([p.String(),p.Null()],{description:Mn})),harness_type:p.Optional(p.Union([p.String(),p.Null()],{description:$n})),worktree:p.Optional(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:Nn}))},{additionalProperties:!1,required:["prompt","task_name"]}),O=p.Object({agents:p.Array(Hn,{minItems:1}),run_in_background:p.Optional(p.Boolean())},{additionalProperties:!1,required:["agents"]});var m={agent:"cowboy_agent",stopAgent:"stop_cowboy_agent",mergeBranch:"merge_cowboy_branch",steerAgent:"steer_cowboy_agent",handoverAgent:"handover_cowboy_agent",cleanupAgent:"cleanup_cowboy_agent"},Ie=Object.values(m),k={type:"json_schema",strict:"prefer"};var Ee="_configuredModel",Oe="_configuredThinking";function N(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}r(N,"readModelKey");function te(e){return N(e.thinking)??N(e[Oe])}r(te,"readThinkingRequest");function ne(e){let t=N(e.model);if(t)return{source:"call",key:t};let n=N(e[Ee]);if(n)return{source:"configured",key:n}}r(ne,"readModelRequest");function j(e){return{resolved:e===void 0?{kind:"none"}:{kind:"level",thinking:e},notices:[]}}r(j,"withoutModel");function re(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(re,"modelChoiceFor");function U(e){return`${e.provider}/${e.id}`}r(U,"modelKey");function Dn(e,t){if(t!==void 0&&!me.safeParse(t).success)return`Thinking level "${t}" is not recognized by Pi (valid: ${me.options.join(", ")}); launching "${U(e)}" with "${t}".`}r(Dn,"undeclaredLevelWarning");function Ct(e,t){let n=Dn(e,t);return{resolved:{kind:"resolved",model:e,modelKey:U(e),thinking:t??null},notices:n===void 0?[]:[n]}}r(Ct,"resolvedModel");function Bn(e){return`No API key found for "${e}"`}r(Bn,"missingCredential");function _t(e,t){let n;try{n=e.getProviderAuthStatus(t.provider)}catch(o){return{verdict:"inconclusive",reason:$(o)}}return!Qe(n)||typeof n.configured!="boolean"?{verdict:"inconclusive",reason:"the registry reported no credential status for the provider"}:n.configured?{verdict:"usable"}:{verdict:"unusable",reason:Bn(t.provider)}}r(_t,"probeCredentials");function Ce(e,t){return`${e}: ${t}. Nothing was spawned.`}r(Ce,"refusal");function _e(e,t){let{registry:n,parent:o,thinking:i}=t;if(!e){if(!o)return j(i);let d=_t(n,o);if(d.verdict!=="unusable")return Ct(o,i);throw new Error(Ce(`The parent session's model "${U(o)}" did not resolve credentials in this session`,d.reason))}let a=e.source==="call"?he(e.key,n,void 0):he(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 j(i)}let s=_t(n,a);if(s.verdict!=="unusable")return Ct(a,i);throw e.source==="call"?new Error(Ce(`Model "${U(a)}" cannot authenticate in this session`,s.reason)):new Error(Ce(`The subagent model "${U(a)}" for this configured default cannot authenticate in this session`,s.reason))}r(_e,"resolvePiModel");async function Ln(e){try{return await e.listModels(e.harness)}catch{return[]}}r(Ln,"harnessModels");function jn(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(jn,"undeclaredLevelWarning");async function Pt(e,t){if(!e)return j(t.thinking);let n=await Ln(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=jn(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(Pt,"resolveForeignModel");async function oe(e,t){let{harness:n}=t;if(Xe(n))return _e(e,{registry:t.registry,parent:t.parent,thinking:t.thinking});let o={harness:n,listModels:t.listModels,thinking:t.thinking};return Pt(e,o)}r(oe,"resolveSpawnModel");function H(e,t,n){return{content:[{type:"text",text:t}],details:{...n,severity:e}}}r(H,"resultWithSeverity");function se(e){return e.includes("error")?"error":e.includes("warning")?"warning":"success"}r(se,"foldSeverity");var Pe=`
2
2
 
3
3
  ---
4
4
 
@@ -10,5 +10,5 @@ ${Vn(u)}`,details:S}}let h=c;if(u.lifecycle.phase==="queued"){let S=w().listAgen
10
10
  `).map(n=>n.trim()).filter(n=>n!==""):[]}r(xr,"parseConflictFiles");function Ar(e,t){return e.includes(`branch "${t}" does not exist`)}r(Ar,"isUnknownBranchError");async function Sr(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=F().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 wr(b(),l),cwd:s??l}})(),d),"mergeScope");return R({toolName:"merge_cowboy_branch",param:"branches",detailsKey:"branches",items:t.branches,severity:vr,prepare:r(async()=>{be(a,"target");for(let l of t.branches)be(l.trim(),"branch");await c()},"prepare"),halt:{on:r(l=>l.kind==="conflict","on"),skip:r((l,v)=>{let g=l.trim(),u=`not attempted \u2014 the merge of "${v.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:v,cwd:g}=await c(),u=l.trim();try{let h=await gt(b(),{cwd:g,branch:u,target:a}),f=fr(h.mainRoot,v)?void 0:yr(h.mainRoot,v);if(f!==void 0)try{i.ui.notify(f,"warning")}catch{}let A=f!==void 0?`${f}
11
11
  `:"";return h.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${A}"${u}" is already merged into "${h.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:h.target,output:h.output},text:`${A}Merged "${u}" into "${h.target}" in ${h.mainRoot}.`+(h.output?`
12
12
  ${h.output}`:"")}}catch(h){let f=h instanceof Error?h.message:String(h);return br(f)?{outcome:{kind:"conflict",branch:u,target:a,files:xr(f)},text:`"${u}": ${f}`}:Ar(f,u)?{outcome:{kind:"unknown",branch:u},text:`"${u}": ${f}`}:{outcome:{kind:"failed",branch:u,error:f},text:`"${u}": ${f}`}}},"handleItem")})}r(Sr,"executeMergeBranchTool");import{Type as ae}from"typebox";var Tr="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.",Rr="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.",Qt=ae.Object({agent_ids:ae.Array(ae.String({minLength:1}),{minItems:1,description:Tr}),message:ae.String({description:Rr})},{additionalProperties:!1,required:["agent_ids","message"]});var Xt={name:m.steerAgent,label:m.steerAgent,description:"Send one message to one or more agents in one call: pass every id in `agent_ids` and the single `message` delivered to each. Each id is handled independently in input order \u2014 delivered, or refused with its reason \u2014 and one id's refusal never blocks the rest. A repeated id in `agent_ids` is rejected before anything is delivered \u2014 pass each id once. A spawned agent receives the message before its next model call; a SETTLED one is REVIVED \u2014 spawned again, given the message, and it sends you another completion message when it settles again. That second result arrives only as that completion message: the spawn's result promise closed with the first turn and never opens again. Delivery is fire-and-forget: nothing here waits for an agent to act on it, so do not poll for a reply. The message is entered into the agent's pi session, so it can also be a bash command: `!command` runs the command and sends its output to the agent's context; `!!command` runs it without adding the output to the agent's context. A QUEUED agent cannot be steered \u2014 it has no pane yet; wait for a concurrency slot first. An agent whose pane is gone (cleaned up) cannot be steered either, and neither can an agent being TORN DOWN (wait for its report) or handed over (wait for the handover to finish). Every refusal states its reason and what to do about it.",parameters:Qt,execute:Er,constrainedSampling:k};function Ir(e){switch(e.kind){case"delivered":return"success";case"delivered-not-revived":case"refused":return"warning"}}r(Ir,"steerSeverity");async function Er(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:Ir,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: ${C()}`;return{outcome:{kind:"refused",agentId:s,reason:g},text:`Agent ${s} was not steered: ${g}`}}let c=I(d.lifecycle),l;try{l=await w().steer(s,a)}catch(g){l={kind:"refused",reason:`steering failed: ${$(g)}`}}if(l.kind==="refused")return{outcome:{kind:"refused",agentId:s,reason:l.reason},text:`Agent ${s} was not steered (${c}): ${l.reason}`};if(l.kind==="delivered-not-revived")return{outcome:{kind:"delivered-not-revived",agentId:s,reason:l.reason},text:`Agent ${s} had settled (${c}) and the message reached its pane, but it was not revived: ${l.reason}`};let v=c!=="spawned"&&d.lifecycle.phase==="spawned";return{outcome:{kind:"delivered",agentId:s},text:v?`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(Er,"executeSteerAgentTool");function ri(e,t,n){return pe(e.ids(),t).filter(o=>o!==n)}r(ri,"handoverTargets");function Zt(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.`}}:je(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 ${pe(t.ids(),n).join(", ")}. Nothing was changed.`}}}r(Zt,"resolveHandoverTarget");import{Type as x}from"typebox";var Or="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.",Cr=`REQUIRED. The harness that executes the next run of this agent. Available: the built-in harnesses (${W.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.`,_r=`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.`,Pr="Optional thinking level for the next run, in the target harness's vocabulary. Omit it, or pass null, to leave it unset.",Jt=x.Object({agent_id:x.String({minLength:1,description:Or}),harness_type:x.String({description:Cr}),model:x.Optional(x.Union([x.String(),x.Null()],{description:_r})),thinking:x.Optional(x.Union([x.String(),x.Null()],{description:Pr}))},{additionalProperties:!1,required:["agent_id","harness_type"]});async function Mr(e,t){let n=Zt(e.harness_type,G(),at());if(n.kind==="faulted")return{kind:"faulted",fault:n.fault};let o=n.harness;try{let i=await oe(ne(e),{harness:o,registry:t.modelRegistry,parent:t.model,thinking:te(e),listModels:ie(t)});for(let a of i.notices)t.hasUI&&t.ui.notify(a,"warning");return{kind:"ready",harness:o,modelChoice:re(i.resolved)}}catch(i){return{kind:"faulted",fault:{kind:"request-refused",detail:$(i)}}}}r(Mr,"resolveIntent");function $r(e,t){return`Agent ${e} ${Nr(t)}`}r($r,"renderHandoverOutcome");function Nr(e){if(e.kind==="handed-over"){let t=e.loss===void 0?"":rt(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(Nr,"handoverReport");async function Hr(e,t,n,o,i){let a=t.agent_id.trim(),s=await Mr(t,i),d=s.kind==="faulted"?{kind:"faulted",fault:s.fault}:await w().handover(a,{harness:s.harness,modelChoice:s.modelChoice});return H(ot(d),$r(a,d),{agentId:a,outcome:d})}r(Hr,"executeHandoverAgentTool");var en={name:m.handoverAgent,label:m.handoverAgent,description:"Hand over one SETTLED agent to another harness in one call: pass its `agent_id` and the `harness_type` that executes its next run. The ended run is stopped, its session exported by the source harness, the run archived, and the next one launched in the same checkout with that session and its ID quoted in its task \u2014 so the work continues under the new harness instead of starting over. Nothing is removed: the ended run's pane and harness state stay until cleanup_cowboy_agent, which tears every run down at its own address. A live agent is REFUSED, never stopped \u2014 stop it with stop_cowboy_agent first. `harness_type` is required and, unlike a configured default, never falls back: if an ID was not registered in this session or cannot be launched on this machine, the call is refused before anything is stopped. The source harness must be able to export its own session; a harness that cannot is reported in the result, naming the harness, and nothing is stopped or changed. The next run reports through its own completion message; this call returns when that run has started, not when it finishes.",parameters:Jt,execute:Hr,constrainedSampling:k};import{Text as Dr}from"@earendil-works/pi-tui";var Br={success:"\u2713",warning:"!",error:"\u2717"};function Lr(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 Dr(`${n.fg(a,Br[a])} ${s}`,0,0)}r(Lr,"renderCowboyToolResult");function P(e){return{...e,renderResult:Lr}}r(P,"withCowboyRenderer");var Ur=Ie;function Wr(e){let t=M.Object({prompt:O.properties.agents.items.properties.prompt,task_name:O.properties.agents.items.properties.task_name,agent_type:M.Optional(M.Union([M.String(),M.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:O.properties.agents.items.properties.model,harness_type:O.properties.agents.items.properties.harness_type,worktree:O.properties.agents.items.properties.worktree},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:O.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Wr,"cowboyAgentsSchemaWithTypes");function tn(e){let t=Wr(yt()),n={name:m.agent,label:m.agent,description:"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.",parameters:t,execute:Dt,constrainedSampling:k};e.registerTool(P(n))}r(tn,"registerAgentTool");function qr(e,t){y().mutate.agent.setExtensionEnabled(t),t?Fr(e):Kr(e)}r(qr,"setExtensionEnabled");function Fr(e){let t=b();tn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Ur])]),ee(e)}r(Fr,"activateExtension");function Kr(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!Ie.includes(n))),ee(e)}r(Kr,"deactivateExtension");function Di(e){tn(e),e.registerTool(P(Bt)),e.registerTool(P(Vt)),e.registerTool(P(Xt)),e.registerTool(P(en)),e.registerTool(P(Kt)),e.registerMessageRenderer("subagent-result",(t,n,o)=>{let i=typeof t=="object"&&typeof t.content=="string"?t.content:"",a=/\b(error|stopped)\b/.test(i.slice(0,200)),s=o.fg(a?"error":"success",a?"\u2717":"\u2713");return new jr(`${s} ${i}`,0,0)})}r(Di,"registerTools");var nn="cowboy",Gr={wt:"worktree",sp:"spawn",st:"status"};function Bi(e,t){e.registerCommand(nn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Bi,"registerUnavailableCowboyCommand");function Li(e){e.registerCommand(nn,{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-EMMZJNA7.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{dt(n);let[o,...i]=t.trim().split(/\s+/),a=Gr[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&ke()===null){n.ui.notify(ge,"warning");return}if(J()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}qr(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(ke()===null){n.ui.notify(ge,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-4J2ZWMH4.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!J()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-EMMZJNA7.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-3AJUYRJR.js");await l(n,s,L()?.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-3AJUYRJR.js");await c(n,L()?.options??new Map)},"handler")})}r(Li,"registerCowboyCommand");import*as rn from"node:fs";import{tmpdir as Yr}from"node:os";import*as de from"node:path";async function on(e,t){try{return await lt(e).probe(t),B(Ue)}catch{return B(["checkout"])}}r(on,"detectCowAvailability");function sn(e){let t=de.resolve(e??Be());for(;;){try{if(rn.statSync(t).isDirectory())return t}catch{}let n=de.dirname(t);if(n===t)return Yr();t=n}}r(sn,"probeTargetFor");function zr(e){return(t,n,o)=>e.exec(t,n,o)}r(zr,"execOf");function Zi(e){return an(e,ve())}r(Zi,"startCowSupportProbe");function Ji(e){let t=ve();return K(t,Le()),an(e,t)}r(Ji,"refreshCowSupportProbe");function an(e,t){let n=sn(y().agent.worktreeRoot);return on(zr(e),n).then(o=>{K(t,o)},()=>{K(t,B(["checkout"]))})}r(an,"probe");import dn from"node:fs";var Vr="/tmp";function Qr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(Qr,"handoverNameField");function ln(e){return`cowboy-handover_${[e.worktree,e.harness,e.sessionId].map(Qr).join("_")}.md`}r(ln,"handoverFileName");function cn(e){return`${Vr}/${e}`}r(cn,"handoverFilePath");function Xr(e){return dn.existsSync(e)}r(Xr,"handoverFileExists");function ra(e,t){let n=Xr(e);return dn.writeFileSync(e,t,"utf8"),{replaced:n}}r(ra,"writeHandoverFile");function aa(e){return{kind:"prepared",path:cn(ln({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(aa,"handoverExportArtifact");function da(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 only a settled run has a session to export. 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(da,"handoverExportFaultReason");function la(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(la,"handoverExportSeverity");export{Me as a,zn as b,Vn as c,ws as d,Ut as e,As as f,Ss as g,ri as h,$r as i,Re as j,J as k,so as l,Xr as m,ra as n,aa as o,da as p,la as q,Zi as r,Ji as s,qr as t,Fr as u,Kr as v,Di as w,Bi as x,Li as y};
14
- //# sourceMappingURL=chunk-GNJQQ6UF.js.map
13
+ `),a=o.isError?"error":e.details?.severity??"success",s=a==="success"?i:n.fg(a,i);return new Dr(`${n.fg(a,Br[a])} ${s}`,0,0)}r(Lr,"renderCowboyToolResult");function P(e){return{...e,renderResult:Lr}}r(P,"withCowboyRenderer");var Ur=Ie;function Wr(e){let t=M.Object({prompt:O.properties.agents.items.properties.prompt,task_name:O.properties.agents.items.properties.task_name,agent_type:M.Optional(M.Union([M.String(),M.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:O.properties.agents.items.properties.model,harness_type:O.properties.agents.items.properties.harness_type,worktree:O.properties.agents.items.properties.worktree},{additionalProperties:!1,required:["prompt","task_name"]});return M.Object({agents:M.Array(t,{minItems:1}),run_in_background:O.properties.run_in_background},{additionalProperties:!1,required:["agents"]})}r(Wr,"cowboyAgentsSchemaWithTypes");function tn(e){let t=Wr(yt()),n={name:m.agent,label:m.agent,description:"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.",parameters:t,execute:Dt,constrainedSampling:k};e.registerTool(P(n))}r(tn,"registerAgentTool");function qr(e,t){y().mutate.agent.setExtensionEnabled(t),t?Fr(e):Kr(e)}r(qr,"setExtensionEnabled");function Fr(e){let t=b();tn(t),t.setActiveTools([...new Set([...t.getActiveTools(),...Ur])]),ee(e)}r(Fr,"activateExtension");function Kr(e){let t=b();t.setActiveTools(t.getActiveTools().filter(n=>!Ie.includes(n))),ee(e)}r(Kr,"deactivateExtension");function Di(e){tn(e),e.registerTool(P(Bt)),e.registerTool(P(Vt)),e.registerTool(P(Xt)),e.registerTool(P(en)),e.registerTool(P(Kt)),e.registerMessageRenderer("subagent-result",(t,n,o)=>{let i=typeof t=="object"&&typeof t.content=="string"?t.content:"",a=/\b(error|stopped)\b/.test(i.slice(0,200)),s=o.fg(a?"error":"success",a?"\u2717":"\u2713");return new jr(`${s} ${i}`,0,0)})}r(Di,"registerTools");var nn="cowboy",Gr={wt:"worktree",sp:"spawn",st:"status"};function Bi(e,t){e.registerCommand(nn,{description:t,handler:r(async(n,o)=>{o.ui.notify(t,"warning")},"handler")})}r(Bi,"registerUnavailableCowboyCommand");function Li(e){e.registerCommand(nn,{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-VL4BU7LP.js")).cowboyCompletions(t),"getArgumentCompletions"),handler:r(async(t,n)=>{dt(n);let[o,...i]=t.trim().split(/\s+/),a=Gr[o]??o,s=[a,...i].join(" ");if(s==="enable"||s==="disable"){let l=s==="enable";if(l&&ke()===null){n.ui.notify(ge,"warning");return}if(J()===l){n.ui.notify(`pi-cowboy is already ${l?"enabled":"disabled"}`,"info");return}qr(n.ui,l),n.ui.notify(l?"pi-cowboy enabled":"pi-cowboy disabled","info");return}if(ke()===null){n.ui.notify(ge,"warning");return}if(a==="worktree"){let{showWorktreeCommandMenu:l}=await import("./menu-worktree-command-OT7ANA4R.js");await l(n,i.join(" "));return}if((a==="model"||s==="spawn"||s==="status")&&!J()){n.ui.notify("pi-cowboy is disabled. Run /cowboy enable first.","warning");return}if(a==="model"){let{handleModelArg:l}=await import("./model-picker-VL4BU7LP.js");await l(i.join(" "),n);return}if(s==="spawn"||s==="status"){let{showAgentsActionMenu:l}=await import("./menus-OAVTJWLR.js");await l(n,s,L()?.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-OAVTJWLR.js");await c(n,L()?.options??new Map)},"handler")})}r(Li,"registerCowboyCommand");import*as rn from"node:fs";import{tmpdir as Yr}from"node:os";import*as de from"node:path";async function on(e,t){try{return await lt(e).probe(t),B(Ue)}catch{return B(["checkout"])}}r(on,"detectCowAvailability");function sn(e){let t=de.resolve(e??Be());for(;;){try{if(rn.statSync(t).isDirectory())return t}catch{}let n=de.dirname(t);if(n===t)return Yr();t=n}}r(sn,"probeTargetFor");function zr(e){return(t,n,o)=>e.exec(t,n,o)}r(zr,"execOf");function Zi(e){return an(e,ve())}r(Zi,"startCowSupportProbe");function Ji(e){let t=ve();return K(t,Le()),an(e,t)}r(Ji,"refreshCowSupportProbe");function an(e,t){let n=sn(y().agent.worktreeRoot);return on(zr(e),n).then(o=>{K(t,o)},()=>{K(t,B(["checkout"]))})}r(an,"probe");import dn from"node:fs";var Vr="/tmp";function Qr(e){return e.replace(/[^A-Za-z0-9._-]/g,"-")}r(Qr,"handoverNameField");function ln(e){return`cowboy-handover_${[e.worktree,e.harness,e.sessionId].map(Qr).join("_")}.md`}r(ln,"handoverFileName");function cn(e){return`${Vr}/${e}`}r(cn,"handoverFilePath");function Xr(e){return dn.existsSync(e)}r(Xr,"handoverFileExists");function ra(e,t){let n=Xr(e);return dn.writeFileSync(e,t,"utf8"),{replaced:n}}r(ra,"writeHandoverFile");function aa(e){return{kind:"prepared",path:cn(ln({worktree:e.worktree,harness:e.harness,sessionId:e.sessionId})),text:e.text,sessionId:e.sessionId,...e.loss===void 0?{}:{loss:e.loss}}}r(aa,"handoverExportArtifact");function da(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 only a settled run has a session to export. 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(da,"handoverExportFaultReason");function la(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(la,"handoverExportSeverity");export{Me as a,zn as b,Vn as c,ws as d,Ut as e,As as f,Ss as g,ri as h,$r as i,Re as j,J as k,so as l,Xr as m,ra as n,aa as o,da as p,la as q,Zi as r,Ji as s,qr as t,Fr as u,Kr as v,Di as w,Bi as x,Li as y};
14
+ //# sourceMappingURL=chunk-CRFTXDVY.js.map