pi-cowboy 0.29.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.
- package/README.md +2 -1
- package/dist/agents/agent-host.d.ts +3 -2
- package/dist/agents/agent-manager.d.ts +2 -0
- package/dist/agents/agent-reviver.d.ts +1 -2
- package/dist/agents/agent-spawn-store.d.ts +5 -0
- package/dist/agents/harness/harness-registry.d.ts +1 -7
- package/dist/agents/harness/model-list-catalog.d.ts +15 -0
- package/dist/agents/harness/model-list-read.d.ts +4 -0
- package/dist/agents/harness/steer.d.ts +2 -0
- package/dist/agents/harness.d.ts +10 -2
- package/dist/agents/run-state.d.ts +1 -0
- package/dist/agents/schemas/cowboy-agents.schema.d.ts +6 -0
- package/dist/agents/spawn-adoption.d.ts +13 -0
- package/dist/agents/spawn-journal.d.ts +22 -0
- package/dist/agents/spawn-record.d.ts +55 -0
- package/dist/agents/spawn-verification.d.ts +22 -0
- package/dist/agents/subagent-session.d.ts +9 -1
- package/dist/{chunk-GQCYX6VD.js → chunk-3P4DDY2M.js} +2 -2
- package/dist/{chunk-KOCSQ3ZV.js → chunk-3TPZINCV.js} +2 -2
- package/dist/chunk-CRFTXDVY.js +14 -0
- package/dist/chunk-IIQ52KJZ.js +54 -0
- package/dist/{chunk-FG6EPDPT.js → chunk-PBWQODAQ.js} +2 -2
- package/dist/{chunk-VQ2JXCQB.js → chunk-UY5D2K62.js} +2 -2
- package/dist/harness-availability-launch.d.ts +0 -2
- package/dist/index.js +19 -19
- package/dist/{menu-worktree-command-J7U2NV6J.js → menu-worktree-command-OT7ANA4R.js} +2 -2
- package/dist/menus-OAVTJWLR.js +11 -0
- package/dist/{model-picker-SXUEGCKV.js → model-picker-VL4BU7LP.js} +2 -2
- package/dist/orchestrators/protocol.d.ts +4 -1
- package/dist/plugin/index.d.ts +1 -1
- package/dist/plugin/index.js +1 -1
- package/dist/session-runtime.d.ts +3 -0
- package/dist/shell.d.ts +4 -0
- package/dist/spawn/worktree-policy.d.ts +28 -0
- package/dist/spawn-journal-session.d.ts +6 -0
- package/dist/types.d.ts +1 -0
- package/dist/ui/menu/menu-agent-handover.d.ts +2 -1
- package/dist/ui/menu/menu-model-settings.d.ts +1 -0
- package/dist/ui/menu/menu-spawn-worktree.d.ts +2 -9
- package/dist/ui/menu/submenus/model-select.d.ts +10 -0
- package/package.json +1 -1
- package/dist/chunk-HJRZSWB4.js +0 -14
- package/dist/chunk-LTAAWA6Q.js +0 -54
- package/dist/menus-AMT4U7FK.js +0 -9
package/README.md
CHANGED
|
@@ -168,7 +168,7 @@ Run the adversarial-review tool before you commit, and fix any glaring mistakes
|
|
|
168
168
|
'''
|
|
169
169
|
```
|
|
170
170
|
|
|
171
|
-
You can switch the active orchestrator at any time from `/cowboy` > `
|
|
171
|
+
You can switch the active orchestrator at any time from `/cowboy` > `Orchestrator`. See [Orchestrator Templates](https://github.com/electric-dragon-80000v/pi-cowboy/blob/main/docs/Orchestrator%20Templates.md) for details.
|
|
172
172
|
|
|
173
173
|
### Foreign harnesses
|
|
174
174
|
|
|
@@ -243,6 +243,7 @@ Each item in `agents[]` takes:
|
|
|
243
243
|
| `agent_type` | no | Agent template to use. Defaults to the type selected at `/cowboy` > `Agent`. |
|
|
244
244
|
| `model` | no | Model for this agent as `"provider/model-id"`. Resolved according to [Model resolution](#model-resolution). |
|
|
245
245
|
| `harness_type` | no | Harness that launches this agent: `pi`, `pig`, `pi-bolt`, `opencode`, `codex`, `claude`, or a harness a plugin registered in this session. Overrides the agent template's `harness_type` and the `agent.harnessType` setting. If the harness is not registered here, or this machine cannot launch it, the call fails before spawning. |
|
|
246
|
+
| `worktree` | no | Where the run executes. Omit it (or pass `"new"`) for a new isolated `cow-<task>-<id>` worktree. Pass `"inherit"` to run in the parent session's cwd with no worktree of its own, or `{"path": "/absolute/checkout"}` to run inside an existing worktree of this repository; a picked checkout is never removed by cleanup. |
|
|
246
247
|
|
|
247
248
|
### `steer_cowboy_agent`
|
|
248
249
|
|
|
@@ -36,7 +36,9 @@ export interface PaneControl {
|
|
|
36
36
|
launchEnvironment?(agentKind: AgentMultiplexerKind): Readonly<Record<string, string>>;
|
|
37
37
|
run(paneId: string, command: string): Promise<void>;
|
|
38
38
|
sendKeys(paneId: string, keys: readonly string[]): Promise<void>;
|
|
39
|
-
|
|
39
|
+
promptAgent?(paneId: string, message: string): Promise<DeliverOutcome>;
|
|
40
|
+
sendText?(paneId: string, text: string): Promise<void>;
|
|
41
|
+
submit?(paneId: string, text: string, pid: number, signal: AbortSignal): Promise<void>;
|
|
40
42
|
waitForVisibleOutput?(paneId: string, output: string, timeoutMs: number): Promise<void>;
|
|
41
43
|
waitForOutput(paneId: string, output: string, timeoutMs: number): Promise<void>;
|
|
42
44
|
}
|
|
@@ -84,7 +86,6 @@ export interface AgentHost {
|
|
|
84
86
|
repoCwd?: string;
|
|
85
87
|
}): Promise<boolean>;
|
|
86
88
|
findAttempts(taskSlug: string): Promise<LiveAttempt[]>;
|
|
87
|
-
deliver(ref: AgentHostRef, message: string): Promise<DeliverOutcome>;
|
|
88
89
|
}
|
|
89
90
|
export interface ExecutionRuntime {
|
|
90
91
|
readonly host: AgentHost;
|
|
@@ -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
|
|
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;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Availability } from "../../availability.js";
|
|
2
|
-
import { type AnyHarnessId, type Harness, type HarnessConfigIssue, type HarnessFamily, type HarnessLaunch, type
|
|
2
|
+
import { type AnyHarnessId, type Harness, type HarnessConfigIssue, type HarnessFamily, type HarnessLaunch, type ModelEntry, type PluginHarness } from "../harness.js";
|
|
3
3
|
export interface RegisteredHarness extends Harness<HarnessLaunch> {
|
|
4
4
|
readonly id: AnyHarnessId;
|
|
5
5
|
readonly displayName: string;
|
|
@@ -18,14 +18,8 @@ export interface HarnessRegistry {
|
|
|
18
18
|
runnable(availability: Availability<AnyHarnessId>): AnyHarnessId[];
|
|
19
19
|
config(id: AnyHarnessId): unknown;
|
|
20
20
|
resolve(configured: AnyHarnessId, availability: Availability<AnyHarnessId>): AnyHarnessId;
|
|
21
|
-
listModelOptions(request: HarnessListModelsRequest, availability: Availability<AnyHarnessId>): Promise<HarnessModelListing>;
|
|
22
21
|
}
|
|
23
22
|
export declare function createHarnessRegistry(): HarnessRegistry;
|
|
24
23
|
export declare function harnessFamilyOf(id: AnyHarnessId): HarnessFamily | undefined;
|
|
25
24
|
export type HarnessModelOptions = ReadonlyMap<AnyHarnessId, readonly ModelEntry[]>;
|
|
26
25
|
export declare function modelKeysOf(options: HarnessModelOptions, harness: AnyHarnessId): readonly string[];
|
|
27
|
-
export interface HarnessModelListing {
|
|
28
|
-
readonly options: HarnessModelOptions;
|
|
29
|
-
readonly notices: readonly string[];
|
|
30
|
-
}
|
|
31
|
-
export declare function mergeHarnessModelOptions(options: HarnessModelOptions): string[];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Availability } from "../../availability.js";
|
|
2
|
+
import type { AnyHarnessId, HarnessListModelsRequest, ModelEntry, ModelList } from "../harness.js";
|
|
3
|
+
import type { HarnessModelOptions, HarnessRegistry } from "./harness-registry.js";
|
|
4
|
+
export interface HarnessModelCatalog {
|
|
5
|
+
readonly options: HarnessModelOptions;
|
|
6
|
+
notices(): readonly string[];
|
|
7
|
+
list(harness: AnyHarnessId): Promise<ModelList>;
|
|
8
|
+
loadOptions(harness: AnyHarnessId): Promise<readonly ModelEntry[]>;
|
|
9
|
+
warm(): void;
|
|
10
|
+
}
|
|
11
|
+
export declare function createHarnessModelCatalog(options: {
|
|
12
|
+
readonly registry: HarnessRegistry;
|
|
13
|
+
readonly availability: Availability<AnyHarnessId>;
|
|
14
|
+
readonly request: HarnessListModelsRequest;
|
|
15
|
+
}): HarnessModelCatalog;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type AnyHarnessId, type ModelEntry, type ModelList } from "../harness.js";
|
|
3
|
+
export declare function readHarnessModelList(harness: AnyHarnessId, ctx: Pick<ExtensionContext, "modelRegistry">): Promise<ModelList>;
|
|
4
|
+
export declare function harnessModelReader(ctx: Pick<ExtensionContext, "hasUI" | "ui" | "modelRegistry">): (harness: AnyHarnessId) => Promise<readonly ModelEntry[]>;
|
package/dist/agents/harness.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import type { AgentMultiplexerKind, PaneControl } from "./agent-host.js";
|
|
2
|
+
import type { AgentMultiplexerKind, DeliverOutcome, PaneControl } from "./agent-host.js";
|
|
3
3
|
export declare const HARNESS_IDS: readonly ["pi", "pig", "pi-bolt", "opencode", "codex", "claude"];
|
|
4
4
|
export type HarnessId = (typeof HARNESS_IDS)[number];
|
|
5
5
|
export type AnyHarnessId = HarnessId | (string & {});
|
|
@@ -109,6 +109,14 @@ export interface HarnessStopRequest {
|
|
|
109
109
|
readonly paneId: string;
|
|
110
110
|
}
|
|
111
111
|
export type HarnessStop = (request: HarnessStopRequest) => Promise<void>;
|
|
112
|
+
export interface HarnessSteerRequest {
|
|
113
|
+
readonly pi: ExtensionAPI;
|
|
114
|
+
readonly pane: PaneControl;
|
|
115
|
+
readonly paneId: string;
|
|
116
|
+
readonly message: string;
|
|
117
|
+
readonly signal: AbortSignal;
|
|
118
|
+
}
|
|
119
|
+
export type HarnessSteer = (request: HarnessSteerRequest) => Promise<DeliverOutcome>;
|
|
112
120
|
export interface HarnessTeardownContext {
|
|
113
121
|
readonly paneId: string | null;
|
|
114
122
|
readonly cwd: string | null;
|
|
@@ -222,8 +230,8 @@ export interface Harness<L extends SubagentLaunchInputs = HarnessLaunch, C = unk
|
|
|
222
230
|
buildArgs(launch: L): string[];
|
|
223
231
|
teardown(request: HarnessTeardownRequest): Promise<void>;
|
|
224
232
|
readHandoverRecords?: ReadHandoverRecords;
|
|
233
|
+
steer: HarnessSteer;
|
|
225
234
|
listModels(request: HarnessListModelsRequest): Promise<ModelList>;
|
|
226
|
-
prefetchModels(pi: ExtensionAPI): void;
|
|
227
235
|
}
|
|
228
236
|
export declare function canReadHandoverRecords(harness: {
|
|
229
237
|
readonly readHandoverRecords?: ReadHandoverRecords;
|
|
@@ -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;
|
|
@@ -5,6 +5,9 @@ declare const CowboyAgentParamsSchema: Type.TObject<{
|
|
|
5
5
|
agent_type: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
6
6
|
model: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
7
7
|
harness_type: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
8
|
+
worktree: Type.TOptional<Type.TUnion<[Type.TLiteral<"new">, Type.TLiteral<"inherit">, Type.TObject<{
|
|
9
|
+
path: Type.TString;
|
|
10
|
+
}>, Type.TNull]>>;
|
|
8
11
|
}>;
|
|
9
12
|
export declare const CowboyAgentsSchema: Type.TObject<{
|
|
10
13
|
agents: Type.TArray<Type.TObject<{
|
|
@@ -13,6 +16,9 @@ export declare const CowboyAgentsSchema: Type.TObject<{
|
|
|
13
16
|
agent_type: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
14
17
|
model: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
15
18
|
harness_type: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
|
|
19
|
+
worktree: Type.TOptional<Type.TUnion<[Type.TLiteral<"new">, Type.TLiteral<"inherit">, Type.TObject<{
|
|
20
|
+
path: Type.TString;
|
|
21
|
+
}>, Type.TNull]>>;
|
|
16
22
|
}>>;
|
|
17
23
|
run_in_background: Type.TOptional<Type.TBoolean>;
|
|
18
24
|
}>;
|
|
@@ -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{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
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",
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
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
|
|
@@ -0,0 +1,14 @@
|
|
|
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
|
+
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
`,Un={agent_ids:{plural:"agent ids"},branches:{plural:"branches"}};async function R(e){let{items:t}=e;qn(t,e),await e.prepare?.();let n=Wn(e),o=[],i=[],a=r(({outcome:d,text:c})=>{o.push(d),i.push(c)},"record"),s;for(let d of t){let c=n.halt;if(c!==void 0&&s!==void 0){a(c.skip(d,s));continue}let l=await n.handle(d);a(l),c!==void 0&&c.halts(l.outcome)&&(s=d)}return H(se(o.map(e.severity)),i.join(Pe),{[e.detailsKey]:o})}r(R,"runBatch");function Wn(e){if("render"in e){let n=e.render,o=e.halt;return{handle:r(async i=>{let a=await e.handleItem(i);return{outcome:a,text:n(a)}},"handle"),halt:o===void 0?void 0:{halts:r(i=>o.on(i),"halts"),skip:r((i,a)=>{let s=o.skip(i,a);return{outcome:s,text:n(s)}},"skip")}}}let t=e.halt;return{handle:e.handleItem,halt:t===void 0?void 0:{halts:r(n=>t.on(n),"halts"),skip:t.skip}}}r(Wn,"batchSteps");function qn(e,{toolName:t,param:n}){let o=e.map(s=>s.trim()),i=o.filter((s,d)=>o.indexOf(s)!==d);if(i.length===0)return;let a=Un[n];throw new Error(`${t} received duplicate ${a.plural} in \`${n}\`: ${[...new Set(i)].join(", ")}. No item was handled.`)}r(qn,"rejectRepeatedKeys");var Mt={user:"STOPPED BY THE USER before completion \u2014 output is partial; the task was NOT finished",agent:"STOPPED BY YOU before completion \u2014 output is partial; the task was NOT finished"},Fn={user:"STOPPED BY THE USER before the agent started \u2014 the task was NOT attempted",agent:"STOPPED BY YOU before the agent started \u2014 the task was NOT attempted"};function Kn(e){if(!T(e)||e.status!=="stopped")return Mt.agent;let{stop:t}=e;return e.phase==="never-started"?Fn[t.initiator]:Mt[t.initiator]}r(Kn,"stopNote");function $t(e){return!T(e)||e.status!=="stopped"?"":` (${Kn(e)})`}r($t,"getStatusNote");async function Gn(e,t){let n=L();return n!==null?await n.list(e):await G().require(e).listModels({pi:b(),modelCatalog:it(t.modelRegistry)})}r(Gn,"readHarnessModelList");function ie(e){return async t=>{let n=await Gn(t,e),o=Je(n);return o!==void 0&&e.hasUI&&e.ui.notify(o,"warning"),Ze(n)}}r(ie,"harnessModelReader");function C(e=w()){let t=e.listAgents(fe).filter(n=>q(n.lifecycle.phase));return t.length===0?"none":t.map(n=>`${n.id} (${n.display.type})`).join(", ")}r(C,"formatActiveAgents");function Me(e,t){let n={type:e.display.type,description:e.display.description};e.display.taskSlug&&(n.taskSlug=e.display.taskSlug),e.display.worktree&&(n.worktreePath=e.display.worktree.path,n.worktreeBranch=e.display.worktree.branch),e.display.worktree?.kind==="owned"&&(n.worktreeManaged=!0);let o=e.execution.host;if(o&&(n.herdrAgent=o.name,n.herdrPane=o.paneId,n.herdrTab=o.tabId),t?.includeStatus&&(n.status=I(e.lifecycle)),t?.includeRunInfo){let i=T(e.lifecycle)?e.lifecycle.completedAt-nt(e.lifecycle):0;n.durationMs=i,n.modelName=e.display.invocation?.modelName,n.modelId=e.display.invocation?.modelName,n.thinkingLevel=e.display.invocation?.thinkingLevel}return n}r(Me,"buildAgentDetails");function Yn(e){if(!T(e))return{kind:"stopped"};switch(e.status){case"completed":return{kind:"completed",result:e.result};case"error":return{kind:"failed",error:e.error};case"stopped":return{kind:"stopped"};default:return Ve(e)}}r(Yn,"settledOutcome");function zn(e){return`[Cowboy agent "${e.display.type}" ${e.id} ${I(e.lifecycle)}]`}r(zn,"settledHeadline");function Vn(e){let t=e.lifecycle,n=T(t)?t.worktreeRetentionReason:void 0,o=e.display.orchestration,i=e.display.worktree?.kind==="owned"?e.display.worktree:void 0;return z(o.cues,"settled",kt({outcome:Yn(t),statusNote:$t(t)||void 0,worktree:i?{path:i.path,branch:i.branch,retention:n?mt(n):void 0,processAlive:t.phase==="settled"&&t.status==="completed"}:void 0,multiplexerId:y().multiplexer||et}))}r(Vn,"formatResultContent");async function Qn(e,t){let n=qe(e);if(n.kind!=="picked")return n;let o=ue(n.path),a=(o===void 0?null:await ht(b(),t.cwd))?.find(s=>ue(s.path)===o);if(a===void 0)throw new Error(`Worktree "${n.path}" is not an existing checkout of this repository \u2014 nothing was spawned. Pass an absolute path from \`git worktree list\`, or "new"/"inherit".`);return{kind:"picked",path:a.path,branch:We(a)}}r(Qn,"resolveWorktreeRequest");var $e=class e{static{r(this,"DelegationProtocol")}intent;constructor(t){this.intent=t}static async parse(t,n,o){let i=V(t.agent_type),a=t.prompt,s=typeof t.task_name=="string"?t.task_name.trim():"";if(!s)throw new Error('cowboy_agent requires a short 2-3 word task name (e.g. "fix login flow") via the `task_name` parameter \u2014 it names the agent\'s branch/tab/worktree/agent so you can recognize it at a glance.');let d=Fe(s),c=bt(),l=await ft(i,void 0,(S,le)=>{n.ui.notify(S,le)});if(l.kind==="ambiguous")throw new Error(`Ambiguous agent type: ${i}. Candidates: ${l.candidates.join(", ")}. Use the exact registered name \u2014 nothing was spawned.`);if(l.kind==="not-found")throw new Error(`Unknown agent type: ${i} \u2014 nothing was spawned. Use an exact registered name, or omit \`agent_type\` to use the configured default.`);let v=At(t.harness_type),g=Q(l.key,v),u=te(t),h=await oe(ne(t),{harness:g,registry:n.modelRegistry,parent:n.model,thinking:u,listModels:ie(n)});for(let S of h.notices)n.ui.notify(S,"warning");let f=await Qn(t.worktree,n),A=t.run_in_background!==!1;return new e({ctx:n,toolCallId:o,taskSlug:d,prompt:a,description:a.split(`
|
|
6
|
+
`)[0].slice(0,80)||a.slice(0,80),agentType:i,resolvedType:l.key,orchestrator:c,fork:Y(i)?.fork??!1,modelChoice:re(h.resolved),requestedHarness:v,worktree:f,isBackground:A})}async run(t){let{ctx:n,isBackground:o,taskSlug:i,resolvedType:a}=this.intent,s=b(),d=w().mintSpawnId(),c=await this.resolveWorktree(s,d),l=this.intent.modelChoice?.thinking??void 0,v=ze(this.intent.modelChoice),{agentId:g,spawn:u}=await st().spawn(n,{spawnId:d,type:a,prompt:this.intent.prompt,description:this.intent.description,taskSlug:i,orchestration:this.intent.orchestrator,modelChoice:this.intent.modelChoice,requestedHarness:this.intent.requestedHarness,fork:this.intent.fork,worktree:c,invocation:{modelName:v,thinkingLevel:l,fork:this.intent.fork},runInBackground:o,signal:o?void 0:t});if(this.intent.toolCallId&&(u.display.toolCallId=this.intent.toolCallId),!o){let S=Me(u,{includeRunInfo:!0,includeStatus:!0});if(S.agentId=g,T(u.lifecycle)&&u.lifecycle.status==="error")throw new Error(`agent ${g} stopped with an error: ${u.lifecycle.error||"no error message was recorded"}`);return{message:`${zn(u)}
|
|
7
|
+
|
|
8
|
+
${Vn(u)}`,details:S}}let h=c;if(u.lifecycle.phase==="queued"){let S=w().listAgents(fe).filter(un=>un.lifecycle.phase==="spawned").length,le=z(this.intent.orchestrator.cues,"queued",vt({agentId:g,worktree:h,queueRunning:S})),ce=Me(u);return ce.agentId=g,ce.status="queued",{message:`[Agent queued] ${le}`,details:ce}}let f=z(this.intent.orchestrator.cues,"spawned",wt({agentId:g,worktree:h})),A=Me(u);return A.agentId=g,A.status="spawned",{message:`[Agent spawned] ${f}`,details:A}}async resolveWorktree(t,n){let o=this.intent.worktree;switch(o.kind){case"inherit":return;case"picked":return o;case"new":return this.expectedWorktree(t,n)}}async expectedWorktree(t,n){let o=await pt(t,F().cwd).catch(()=>{});if(o===void 0)return;let i=Ye(y().agent.worktreeRoot,o);return{kind:"owned",path:Ge(i,this.intent.taskSlug,n),branch:Ke(this.intent.taskSlug,n)}}};async function Nt(e,t,n,o){if(e.agents.length>1&&e.run_in_background===!1)throw new Error("run_in_background: false requires exactly one agent");let i=e.agents.map(l=>({...l,run_in_background:e.run_in_background})),a=await Promise.all(i.map(l=>$e.parse(l,t,n)));Xn(a);let s=await Promise.all(a.map(l=>l.run(o))),d=s.map(l=>l.message).join(Pe),c={agents:s.map(l=>l.details)};return{message:d,details:c}}r(Nt,"runDelegationBatch");function Xn(e){let t=e.map(o=>o.intent.taskSlug),n=t.filter((o,i)=>t.indexOf(o)!==i);if(n.length!==0)throw new Error(`cowboy_agent received the same task_name more than once: ${[...new Set(n)].join(", ")} \u2014 nothing was spawned. Give every item in \`agents\` its own task_name.`)}r(Xn,"rejectRepeatedTaskSlugs");import{Type as Ne}from"typebox";var Zn="REQUIRED. One or more agent ids to stop (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order: stopped, reported as already settled, or reported unknown \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is stopped \u2014 pass each id once. Nothing is removed \u2014 the worktree and branch are preserved for inspection, merging (merge_cowboy_branch), or later cleanup (cleanup_cowboy_agent).",Ht=Ne.Object({agent_ids:Ne.Array(Ne.String({minLength:1}),{minItems:1,description:Zn})},{additionalProperties:!1,required:["agent_ids"]});function Jn(e){let t=Array.isArray(e.agents)?e.agents:[];return se(t.map(n=>typeof n=="object"&&n!==null&&n.status==="stopped"?"warning":"success"))}r(Jn,"delegationSeverity");async function Dt(e,t,n,o,i){let{message:a,details:s}=await Nt(t,i,e,n);return H(Jn(s),a,s)}r(Dt,"executeAgentTool");var Bt={name:m.stopAgent,label:m.stopAgent,description:"Stop one or more active agents in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 stopped, reported as already settled, or reported unknown \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is stopped \u2014 pass each id once. Stopping sends the agent's harness its own exit keys (its pane is left in place) and settles the agent as stopped once the process is confirmed gone. Nothing is removed \u2014 the worktree and branch are preserved.",parameters:Ht,execute:nr,constrainedSampling:k};function er(e){switch(e.kind){case"stopped":return"success";case"failed":return"error";case"already-settled":case"unknown":case"refused":return"warning"}}r(er,"stopSeverity");function tr(e){switch(e.kind){case"stopped":return`Stopped agent ${e.agentId}`;case"already-settled":return`Agent ${e.agentId} is already ${e.status}. Active agents: ${e.activeAgents}`;case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`;case"refused":return`Agent ${e.agentId} was not stopped: ${e.reason}`;case"failed":return`Failed to stop agent ${e.agentId}: ${e.error}`}}r(tr,"renderStopOutcome");async function nr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"stop_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:tr,severity:er,handleItem:r(async s=>{let d=w().getSpawn(s);if(!d)return{kind:"unknown",agentId:s,activeAgents:C()};if(w().isHandingOver(s))return{kind:"refused",agentId:s,reason:"it is being handed over to another harness \u2014 wait for the handover to finish, then stop the new run if you still want it stopped."};if(!q(d.lifecycle.phase))return{kind:"already-settled",agentId:s,status:I(d.lifecycle),activeAgents:C()};try{return await w().abort(s,"agent")?{kind:"stopped",agentId:s}:{kind:"failed",agentId:s,error:"the agent could not be stopped"}}catch(c){return{kind:"failed",agentId:s,error:c instanceof Error?c.message:String(c)}}},"handleItem")})}r(nr,"executeStopAgentTool");async function ws(e,t){if(e.toolName!=="cowboy_agent")return;let o=e.input.agents??[],i=t.model?`${t.model.provider}/${t.model.id}`:null;for(let a of o){let s=a.agent_type,d=V(s),c=Y(d),l=xt(a.harness_type),v=Q(d,l),g=N(a.model),u=g??y().modelFor(d,i,c,v);if(u&&!g&&(a[Ee]=u),a.thinking===void 0){let h=y().thinkingFor(d,c,v,t.thinkingLevel);h!==void 0&&(a[Oe]=h)}}}r(ws,"toolCallListener");import{Type as He}from"typebox";var rr="REQUIRED. One or more agent ids to clean up (as printed by the cowboy_agent spawn result or a completion message). Every id is handled independently in input order \u2014 located (the locator runs for ids the store no longer tracks), cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 one id's outcome never blocks the rest. A repeated id is rejected before anything is removed \u2014 pass each id once. An agent that is still active is refused for its item only (stop it with stop_cowboy_agent, then clean up once it has settled).",Lt=He.Object({agent_ids:He.Array(He.String({minLength:1}),{minItems:1,description:rr})},{additionalProperties:!1,required:["agent_ids"]});function jt(e){switch(e.kind){case"pane-absent":return"pane-absent";case"pane-not-working":return`pane-not-working: ${e.state}`;case"forced":return"forced";case"pane-working":return"pane-working";case"pane-unreadable":return`pane-unreadable: ${e.detail}`;case"artifacts-ambiguous":return"artifacts-ambiguous"}}r(jt,"formatBasis");function or(e){return e.kind==="recorded"?e.phase:`unrecorded (basis: ${jt(e.basis)})`}r(or,"formatSettlement");function Ut(e){switch(e.kind){case"dirty":return"has uncommitted changes";case"unverifiable":return`state could not be verified (${e.detail})`;case"agent-active":return`the agent is still ${e.phase} and has not reported a result \u2014 stop it with stop_cowboy_agent, then clean up`;case"recovered-refusal":return`no settlement was recorded and herdr still reports the agent at work (${jt(e.basis)}) \u2014 stop it before retrying`;case"ambiguous-artifacts":return`two artifacts answer to this id (${e.candidates.join(", ")}) \u2014 nothing was removed; work out which run owns the id before removing either by hand`}}r(Ut,"formatKeptReason");function sr(e){switch(e.kind){case"closed":return"closed";case"open":return"open";case"gone":return"gone (herdr has no such pane)";case"unknown":return"unknown (the pane was not read)"}}r(sr,"paneText");function ir(e){return e.length===0?"none (the agent never had a pane)":e.map(t=>`${t.paneId} ${sr(t)}`).join(", ")}r(ir,"panesText");function ar(e){switch(e.kind){case"closed":return"pane closed";case"open":return"pane left open";case"gone":return"pane already gone";case"unknown":return"pane state unknown"}}r(ar,"paneSummary");function dr(e){if(e.length===0)return"no pane";if(e.length===1)return ar(e[0]);let t=new Map;for(let o of e)t.set(o.kind,(t.get(o.kind)??0)+1);let n=[...t].map(([o,i])=>`${i} ${o}`).join(", ");return`${e.length} panes (${n})`}r(dr,"panesSummary");function Wt(e){switch(e.kind){case"removed":return`removed (${e.path})`;case"removal-failed":return`NOT removed \u2014 ${e.detail} (${e.path})`;case"kept":return`kept${e.path?` (${e.path})`:" (worktree path not recorded)"}`;case"absent":return`already gone (${e.path})`;case"none":return"none (agent ran without a worktree)"}}r(Wt,"worktreeText");function qt(e){let t=e.branch;return`${t.kind==="deleted"?"deleted":t.kind==="kept"?`kept (${t.reason})`:t.kind==="delete-failed"?`NOT deleted \u2014 ${t.detail}`:"not applicable"}${e.branchName?` (${e.branchName})`:""}`}r(qt,"branchText");function lr(e){return e?` forced${e.reason?` \u2014 ${Ut(e.reason)}`:""}`:""}r(lr,"forcedClause");function De(e){return e.outcome.kind==="refused"?`Did not clean up agent ${e.agentId}: ${Ut(e.outcome.reason)}`:`Cleaned up agent ${e.agentId}${lr(e.outcome.forced)}:`}r(De,"headline");function Ft(e){let t=[De(e),` agent status: ${or(e.settlement)}`,` panes: ${ir(e.panes)}`,` worktree: ${Wt(e.worktree)}`,` branch: ${qt(e)}`];if(e.source==="recovered"&&t.push(" recovered: no spawn record survived \u2014 this verdict rests on discovery (herdr's live read plus the worktree on disk)"),e.settlement.kind==="discovered"){let{path:n,present:o}=e.settlement.deliverable;t.push(o?` deliverable: UNREAD at ${n} \u2014 read it before deleting the directory`:` deliverable: none written (${n} does not exist)`)}return t.join(`
|
|
9
|
+
`)}r(Ft,"renderCleanupReport");function As(e){let t=dr(e.panes);return e.outcome.kind==="refused"?`${De(e)} ${t}`:`${De(e)} ${t}, worktree ${Wt(e.worktree)}, branch ${qt(e)}`}r(As,"summarizeCleanupReport");function Ss(e){return e.outcome.kind==="refused"||e.worktree.kind==="kept"||e.worktree.kind==="removal-failed"||e.branch.kind==="delete-failed"}r(Ss,"cleanupNeedsAttention");var Kt={name:m.cleanupAgent,label:m.cleanupAgent,description:"Remove one or more SETTLED agents' artifacts in one call: pass every id in `agent_ids`. Each id is handled independently in input order \u2014 located, cleaned up, and reported with its own agent status / pane / worktree / branch block \u2014 and one id's outcome never blocks the rest. A repeated id in `agent_ids` is rejected before anything is removed \u2014 pass each id once. Removes the herdr pane/tab, the worktree, and the cow- branch when it is merged into the parent HEAD. Gated on a reported result \u2014 an agent that is still active is REFUSED for its item only: nothing is stopped, removed, or released, and the report says why (stop it with stop_cowboy_agent, then clean up once it has settled). Best effort \u2014 each item's result is a structured report of what was done. A worktree with uncommitted changes, or whose state cannot be verified, is KEPT with the reason rather than destroyed (clean it, then retry). An unmerged branch does NOT block removal \u2014 the branch and its commits live in the repo, so the worktree is removed and the branch is kept for you to merge later. A torn-down run also loses its staging directory (<tmpdir>/pi-cowboy/<id>/) \u2014 those files may carry secrets, so they go with the run; a cleanup that keeps the worktree, and a refusal, removes nothing. An agent whose spawning session was replaced (/new, /resume, /fork) is still tracked, so pass the original full agent id from its spawn or completion result \u2014 and an id whose record did not survive a /reload is not rejected outright either: the artifacts themselves are located (herdr's worktree/pane registries, then the worktree root on disk by id) and cleaned up when the run is established as over. That recovered report marks the agent status `unrecorded` and states the evidence its verdict rests on: it refuses, keeping everything, while herdr still reports the pane `working` or when the pane cannot be read at all, and it refuses when two artifacts answer to the id (listing them). The recovered path is the one exception to the staging-directory removal: it has no record of the run, so it reports the agent's deliverable (<tmpdir>/pi-cowboy/<id>/result.md) instead of deleting it, and nothing the agent wrote is lost silently.",parameters:Lt,execute:pr,constrainedSampling:k};function cr(e){return e.kind==="unknown"?"warning":e.report.outcome.kind==="torn-down"?"success":"warning"}r(cr,"cleanupSeverity");function ur(e){switch(e.kind){case"cleaned":return Ft(e.report);case"unknown":return`Agent ${e.agentId} not found. Active agents: ${e.activeAgents}`}}r(ur,"renderCleanupOutcome");async function pr(e,t,n,o,i){let a=t.agent_ids;return R({toolName:"cleanup_cowboy_agent",param:"agent_ids",detailsKey:"agents",items:a,render:ur,severity:cr,handleItem:r(async s=>{let d=w();if(!d.getSpawn(s)&&(await d.locate(s)).kind==="not-found")return{kind:"unknown",agentId:s,activeAgents:C(d)};let c=await d.cleanup(s);return{kind:"cleaned",agentId:s,report:c}},"handleItem")})}r(pr,"executeCleanupAgentTool");import*as zt from"node:fs";import*as D from"node:path";import{Type as _}from"typebox";var hr="REQUIRED. One or more settled agent branches to merge (the `cow-<task>-<id>` branches from the cowboy_agent result notes). Every branch merges sequentially in input order into the same `target`: merged, reported as already merged, or reported per item on failure \u2014 a non-conflict failure never blocks the rest. A repeated branch is rejected before anything merges \u2014 pass each branch once. A conflict halts the batch: the conflicted merge is left in progress (never auto-resolved) and the remaining branches are reported as not attempted.",gr="Merge target branch (default: main). Applies to every branch in `branches`: the repo's main checkout must be on the target before anything merges.",mr="Any path inside the repo (default: the parent session's cwd). Applies to the whole call: the merge always runs in the repo's main checkout.",Gt=_.Object({branches:_.Array(_.String({minLength:1}),{minItems:1,description:hr}),target:_.Optional(_.String({description:gr})),repo:_.Optional(_.String({description:mr}))},{additionalProperties:!1,required:["branches"]});function Yt(e){let t=D.normalize(e),{root:n}=D.parse(t);return t.length>n.length?t.replace(/[/\\]+$/,""):t}r(Yt,"normalizeRepoRoot");function fr(e,t){return Yt(e)===Yt(t)}r(fr,"isSameRepoRoot");function yr(e,t){return`WARNING: merging in ${e}, outside your session repo (${t}) \u2014 verify this was intended.`}r(yr,"formatOutsideRepoWarning");async function wr(e,t){let n=new ct(e),o=await n.probe(["rev-parse","--show-toplevel"],t);if(o===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: ${t} is not inside a git repository (git rev-parse --show-toplevel failed). Refusing to merge without a repo-scope check \u2014 run the session from inside a git checkout or pass an explicit \`repo\` inside one.`);let i=await n.probe(["rev-parse","--git-common-dir"],o);if(i===void 0)throw new Error(`merge_cowboy_branch cannot verify the session repo: could not resolve the git directory for ${t}. Refusing to merge without a repo-scope check.`);let{mainRoot:a}=ut(i,o);if(!zt.existsSync(D.join(a,".git")))throw new Error(`merge_cowboy_branch cannot verify the session repo: no main checkout found for ${t} (unsupported repo layout). Refusing to merge without a repo-scope check.`);return a}r(wr,"resolveSessionMainRoot");var Vt={name:m.mergeBranch,label:m.mergeBranch,description:"Merge one or more settled agent branches in one call: pass every branch in `branches` (the `cow-<task>-<id>` branches from the cowboy_agent result notes). `target` and `repo` apply to the whole call. A repeated branch in `branches` is rejected before anything merges \u2014 pass each branch once. The repo's main checkout must be on the target branch and clean: the merge refuses when it is not on the target (a merge anywhere else would land on the wrong branch) and refuses when the checkout is dirty. Already-merged branches are reported without running a merge (the checkout is left untouched), and conflicts are never auto-resolved. Branches merge sequentially in input order; a conflict halts the batch \u2014 the conflicted merge is left in progress with the file list so you can resolve it, and the remaining branches are reported as not attempted.",parameters:Gt,execute:Sr,constrainedSampling:k};function vr(e){switch(e.kind){case"merged":return"success";case"already-merged":case"unknown":case"not-attempted":return"warning";case"conflict":case"failed":return"error"}}r(vr,"mergeSeverity");var kr="has conflicts in:";function br(e){return e.includes(kr)}r(br,"isConflictError");function xr(e){let t=e.match(/has conflicts in:\n([\s\S]*?)\nThe merge is still/);return t?t[1].split(`
|
|
10
|
+
`).map(n=>n.trim()).filter(n=>n!==""):[]}r(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
|
+
`:"";return h.alreadyMerged?{outcome:{kind:"already-merged",branch:u,target:a},text:`${A}"${u}" is already merged into "${h.target}" \u2014 nothing to do.`}:{outcome:{kind:"merged",branch:u,target:h.target,output:h.output},text:`${A}Merged "${u}" into "${h.target}" in ${h.mainRoot}.`+(h.output?`
|
|
12
|
+
${h.output}`:"")}}catch(h){let 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-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
|