pi-cowboy 0.0.0 → 0.3.1
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/LICENSE +21 -0
- package/README.md +281 -2
- package/agents/explore.toml +40 -0
- package/dist/agents/agent-assets.js +261 -0
- package/dist/agents/agent-cleanup.js +284 -0
- package/dist/agents/agent-discovery.js +108 -0
- package/dist/agents/agent-host.js +10 -0
- package/dist/agents/agent-manager.js +367 -0
- package/dist/agents/agent-reviver.js +64 -0
- package/dist/agents/agent-runner.js +289 -0
- package/dist/agents/agent-spawn-store.js +57 -0
- package/dist/agents/agent-template.js +46 -0
- package/dist/agents/agent-types.js +144 -0
- package/dist/agents/batch.js +92 -0
- package/dist/agents/cleanup-policy.js +194 -0
- package/dist/agents/cleanup-report.js +128 -0
- package/dist/agents/default-agents.js +19 -0
- package/dist/agents/harness/pi-bolt.js +15 -0
- package/dist/agents/harness/pi-compatible.js +68 -0
- package/dist/agents/harness/pig.js +16 -0
- package/dist/agents/harness/registry.js +27 -0
- package/dist/agents/harness.js +32 -0
- package/dist/agents/result-file-permissions.js +29 -0
- package/dist/agents/run-state.js +270 -0
- package/dist/agents/schemas/cleanup-batch.schema.js +19 -0
- package/dist/agents/schemas/cowboy-agents.schema.js +39 -0
- package/dist/agents/schemas/merge-batch.schema.js +25 -0
- package/dist/agents/schemas/steer-batch.schema.js +22 -0
- package/dist/agents/schemas/stop-batch.schema.js +18 -0
- package/dist/agents/spawn-defaults.js +70 -0
- package/dist/agents/subagent-session.js +601 -0
- package/dist/agents/tool-cleanup.js +57 -0
- package/dist/agents/tool-execution.js +125 -0
- package/dist/agents/tool-merge.js +190 -0
- package/dist/agents/tool-result.js +17 -0
- package/dist/agents/tool-steer.js +89 -0
- package/dist/agents/types.js +1 -0
- package/dist/availability.js +38 -0
- package/dist/config/config-io.js +261 -0
- package/dist/config/config-store.js +321 -0
- package/dist/config/config-validation.js +173 -0
- package/dist/config/layered-config.js +117 -0
- package/dist/config/types.js +23 -0
- package/dist/cow-support-launch.js +43 -0
- package/dist/events.js +146 -0
- package/dist/extension-toggle.js +28 -0
- package/dist/harness-availability-launch.js +23 -0
- package/dist/index.js +52 -0
- package/dist/infrastructure/exec-path.js +35 -0
- package/dist/infrastructure/git/cow-clone.js +398 -0
- package/dist/infrastructure/git/git-materializer.js +342 -0
- package/dist/infrastructure/git/git-merger.js +234 -0
- package/dist/infrastructure/git/git-retention.js +43 -0
- package/dist/infrastructure/git/git-runner.js +145 -0
- package/dist/infrastructure/git/git-worktree.js +143 -0
- package/dist/infrastructure/git/index.js +11 -0
- package/dist/infrastructure/git-client.js +11 -0
- package/dist/infrastructure/herdr/agent-stopper.js +60 -0
- package/dist/infrastructure/herdr/agents.js +329 -0
- package/dist/infrastructure/herdr/herdr-client.js +36 -0
- package/dist/infrastructure/herdr/herdr-transport.js +158 -0
- package/dist/infrastructure/herdr/index.js +15 -0
- package/dist/infrastructure/herdr/panes.js +174 -0
- package/dist/infrastructure/herdr/polling.js +44 -0
- package/dist/infrastructure/herdr/worktrees.js +76 -0
- package/dist/infrastructure/herdr-client.js +6 -0
- package/dist/infrastructure/herdr-host.js +163 -0
- package/dist/logger.js +79 -0
- package/dist/models/model-groups.js +72 -0
- package/dist/models/model-precedence.js +50 -0
- package/dist/models/model-request.js +108 -0
- package/dist/orchestrators/briefing-section.js +14 -0
- package/dist/orchestrators/context.js +116 -0
- package/dist/orchestrators/cues.js +90 -0
- package/dist/orchestrators/default-orchestrators.js +36 -0
- package/dist/orchestrators/orchestrator-discovery.js +68 -0
- package/dist/orchestrators/orchestrator-template.js +43 -0
- package/dist/orchestrators/orchestrator-types.js +78 -0
- package/dist/orchestrators/protocol.js +292 -0
- package/dist/orchestrators/types.js +7 -0
- package/dist/paths.js +66 -0
- package/dist/pi-settings.js +7 -0
- package/dist/predicates.js +25 -0
- package/dist/prompt/prompts.js +111 -0
- package/dist/prompt/skill-loader.js +154 -0
- package/dist/prompt/subagent-system-prompt.js +174 -0
- package/dist/registration.js +220 -0
- package/dist/shell.js +225 -0
- package/dist/spawn/cow-support.js +53 -0
- package/dist/spawn/herdr-launcher.js +80 -0
- package/dist/spawn/repo-lock.js +34 -0
- package/dist/spawn/sandbox.js +286 -0
- package/dist/spawn/spawn-coordinator.js +255 -0
- package/dist/spawn/spawn-id.js +39 -0
- package/dist/spawn/worktree-policy.js +137 -0
- package/dist/status-note.js +30 -0
- package/dist/subagent/ipc-protocol.js +68 -0
- package/dist/subagent/ipc.js +110 -0
- package/dist/subagent/pane-supervisor.js +24 -0
- package/dist/subagent/socket-ipc.js +240 -0
- package/dist/subagent/supervisor.js +315 -0
- package/dist/task-registry.js +258 -0
- package/dist/templates/template-files.js +84 -0
- package/dist/types.js +84 -0
- package/dist/ui/action-report.js +21 -0
- package/dist/ui/format.js +47 -0
- package/dist/ui/indicator.js +480 -0
- package/dist/ui/menu/helpers.js +227 -0
- package/dist/ui/menu/menu-agent-settings.js +182 -0
- package/dist/ui/menu/menu-agent-status.js +444 -0
- package/dist/ui/menu/menu-concurrency.js +226 -0
- package/dist/ui/menu/menu-model-settings.js +244 -0
- package/dist/ui/menu/menu-spawn-defaults.js +71 -0
- package/dist/ui/menu/menu-spawn-wizard.js +367 -0
- package/dist/ui/menu/menu-spawn-worktree.js +107 -0
- package/dist/ui/menu/menu-system-prompt.js +104 -0
- package/dist/ui/menu/menu-worktree-command.js +150 -0
- package/dist/ui/menu/menus.js +187 -0
- package/dist/ui/menu/model-picker.js +161 -0
- package/dist/ui/menu/screen-host.js +87 -0
- package/dist/ui/menu/submenus/confirm.js +23 -0
- package/dist/ui/menu/submenus/model-select.js +42 -0
- package/dist/ui/menu/submenus/name-field.js +43 -0
- package/dist/ui/menu/submenus/numeric-input.js +61 -0
- package/dist/ui/menu/submenus/target-select.js +129 -0
- package/dist/ui/menu/submenus/text-editor.js +49 -0
- package/dist/ui/menu/submenus/worktree-command-name.js +73 -0
- package/dist/ui/menu/submenus/worktree-name.js +53 -0
- package/dist/ui/menu/wrappers/settings-list.js +101 -0
- package/dist/ui/searchable-select.js +147 -0
- package/dist/ui/types.js +1 -0
- package/dist/utils.js +70 -0
- package/docs/assets/grazing.png +0 -0
- package/docs/assets/herdr-containers.png +0 -0
- package/docs/assets/logo-transparent.png +0 -0
- package/orchestrators/with-code-review.toml +20 -0
- package/package.json +109 -3
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* subagent-session.ts — One subagent run's lifecycle and spawn projection.
|
|
3
|
+
* Exports SubagentSession, buildAgentSpawn, DISPOSE_QUEUED_MESSAGE, transport.
|
|
4
|
+
*/
|
|
5
|
+
import { createLogger } from "../logger.js";
|
|
6
|
+
import { createHerdrRuntime } from "../infrastructure/herdr-host.js";
|
|
7
|
+
import { worktreeRetentionReason } from "../infrastructure/git-client.js";
|
|
8
|
+
import { getAgentSpawns, getPiInstance, getStore, getWorktreeMaterialization, subagentResultFileFor, } from "../shell.js";
|
|
9
|
+
import { HerdrSubagentIPC, removeResultArtifacts } from "../subagent/ipc.js";
|
|
10
|
+
import { createPaneSupervisor } from "../subagent/pane-supervisor.js";
|
|
11
|
+
import { lifecycleResult } from "../types.js";
|
|
12
|
+
import { errorMessage } from "../utils.js";
|
|
13
|
+
import { buildWorktreeBranch, slugifyWorktreeType, } from "../spawn/worktree-policy.js";
|
|
14
|
+
import { AgentSandbox } from "../spawn/sandbox.js";
|
|
15
|
+
import { resolveWorktreeCheckoutType } from "./spawn-defaults.js";
|
|
16
|
+
import { harnessFor } from "./harness/registry.js";
|
|
17
|
+
import { buildLaunchPlan } from "./agent-runner.js";
|
|
18
|
+
import { abortQueuedRun, activateRun, createRun, disposeLiveRun, disposeQueuedRun, dropRun, enterSettling, failStart, finishSettling, projectLifecycle, reviveRun, startRun, } from "./run-state.js";
|
|
19
|
+
import { reviveSettledRun } from "./agent-reviver.js";
|
|
20
|
+
export { DISPOSE_QUEUED_MESSAGE } from "./run-state.js";
|
|
21
|
+
const log = createLogger("session");
|
|
22
|
+
export const defaultAgentManagerTransport = {
|
|
23
|
+
createHost: (pi) => createHerdrRuntime(pi).host,
|
|
24
|
+
createIpc: (options) => new HerdrSubagentIPC(options),
|
|
25
|
+
};
|
|
26
|
+
/** Spawn is born queued and mutated in place; its identity is public API. */
|
|
27
|
+
export function buildAgentSpawn(args, promise) {
|
|
28
|
+
const { type, options } = args;
|
|
29
|
+
return {
|
|
30
|
+
id: "",
|
|
31
|
+
lifecycle: { phase: "queued", queuedAt: Date.now() },
|
|
32
|
+
display: {
|
|
33
|
+
type,
|
|
34
|
+
description: options.description,
|
|
35
|
+
taskSlug: options.taskSlug,
|
|
36
|
+
invocation: options.invocation,
|
|
37
|
+
orchestration: options.orchestration,
|
|
38
|
+
worktree: options.worktree,
|
|
39
|
+
},
|
|
40
|
+
execution: {
|
|
41
|
+
promise,
|
|
42
|
+
abortController: new AbortController(),
|
|
43
|
+
host: options.hostRef,
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** One terminal writer for the completion promise, even when host calls race. */
|
|
48
|
+
class CompletionGate {
|
|
49
|
+
resolve;
|
|
50
|
+
promise;
|
|
51
|
+
constructor() {
|
|
52
|
+
this.promise = new Promise((resolve) => {
|
|
53
|
+
this.resolve = resolve;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
open(value) {
|
|
57
|
+
const resolve = this.resolve;
|
|
58
|
+
if (!resolve)
|
|
59
|
+
return;
|
|
60
|
+
this.resolve = undefined;
|
|
61
|
+
resolve(value);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Per-run lifecycle. State moves only through commit, which projects the
|
|
66
|
+
* spawn's lifecycle from the run, so the two cannot disagree. The supervisor
|
|
67
|
+
* stays an attachment, not state, so stop can detach it before waiting and
|
|
68
|
+
* its watcher cannot recurse. A settled session revives on steer (see revive
|
|
69
|
+
* below).
|
|
70
|
+
*/
|
|
71
|
+
export class SubagentSession {
|
|
72
|
+
id;
|
|
73
|
+
args;
|
|
74
|
+
deps;
|
|
75
|
+
gate = new CompletionGate();
|
|
76
|
+
stableSpawn;
|
|
77
|
+
run;
|
|
78
|
+
/** The run's launch artifacts; settlement keeps them and a revive resumes them. */
|
|
79
|
+
launchState;
|
|
80
|
+
/** Why an owned worktree was kept; only a settled run carries one. */
|
|
81
|
+
retention;
|
|
82
|
+
/** Live supervisor attachment: launched, or adopted on revive. */
|
|
83
|
+
supervisor;
|
|
84
|
+
/** The run's channel: bound before the launch, released when the run is over for us. */
|
|
85
|
+
ipc;
|
|
86
|
+
parentBinding;
|
|
87
|
+
constructor({ id, args, deps }) {
|
|
88
|
+
this.id = id;
|
|
89
|
+
this.args = args;
|
|
90
|
+
this.deps = deps;
|
|
91
|
+
this.stableSpawn = buildAgentSpawn(args, this.gate.promise);
|
|
92
|
+
this.stableSpawn.id = id;
|
|
93
|
+
const birth = this.stableSpawn.lifecycle;
|
|
94
|
+
// The spawn is born queued, so the run starts from its queued time.
|
|
95
|
+
this.run = createRun(birth.phase === "queued" ? birth.queuedAt : Date.now());
|
|
96
|
+
// Registered before queue/start/settle; leaves only on explicit drop, so
|
|
97
|
+
// the spawn outlives session disposal and stays listed and cleanable.
|
|
98
|
+
getAgentSpawns().add(this.stableSpawn);
|
|
99
|
+
this.bindParentSignal();
|
|
100
|
+
}
|
|
101
|
+
get spawn() {
|
|
102
|
+
return this.stableSpawn;
|
|
103
|
+
}
|
|
104
|
+
get promise() {
|
|
105
|
+
return this.gate.promise;
|
|
106
|
+
}
|
|
107
|
+
isQueued() {
|
|
108
|
+
return this.run.shell === "held" && this.run.process.kind === "queued";
|
|
109
|
+
}
|
|
110
|
+
isLaunching() {
|
|
111
|
+
return (this.run.shell !== "dropped" && this.run.process.kind === "launching");
|
|
112
|
+
}
|
|
113
|
+
isActive() {
|
|
114
|
+
return this.run.shell !== "dropped" && this.run.process.kind === "active";
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* A run whose terminal is decided is settled, even while the settle pass
|
|
118
|
+
* still runs its probes: steer observes this, so a message landing mid-pass
|
|
119
|
+
* delivers with settled semantics and revives the next turn.
|
|
120
|
+
*/
|
|
121
|
+
isSettled() {
|
|
122
|
+
return (this.run.shell === "held" &&
|
|
123
|
+
(this.run.process.kind === "settling" ||
|
|
124
|
+
this.run.process.kind === "settled"));
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The run's one writer: move the state, then project the spawn's lifecycle
|
|
128
|
+
* from it, so a reader can never see the spawn disagree with the run.
|
|
129
|
+
*/
|
|
130
|
+
commit(next) {
|
|
131
|
+
this.run = next;
|
|
132
|
+
this.spawn.lifecycle = projectLifecycle(next, this.artifacts);
|
|
133
|
+
}
|
|
134
|
+
/** What the projection reads off the session: the launch this run produced and the retention reason it recorded. */
|
|
135
|
+
get artifacts() {
|
|
136
|
+
return { launch: this.launchState, retention: this.retention };
|
|
137
|
+
}
|
|
138
|
+
/** Project the run before the async launch; a spawn that is not queued takes no pool. */
|
|
139
|
+
start(reservation) {
|
|
140
|
+
if (!this.isQueued())
|
|
141
|
+
return;
|
|
142
|
+
if (reservation)
|
|
143
|
+
this.deps.slots.reserve(this.spawn, reservation);
|
|
144
|
+
this.commit(startRun(this.run, Date.now()));
|
|
145
|
+
void this.launch();
|
|
146
|
+
}
|
|
147
|
+
rollbackStart() {
|
|
148
|
+
this.commit(dropRun(this.run, this.artifacts));
|
|
149
|
+
this.detachParentBinding();
|
|
150
|
+
this.gate.open("");
|
|
151
|
+
}
|
|
152
|
+
settleStartFailure(err) {
|
|
153
|
+
this.commit(failStart(this.run, errorMessage(err), Date.now()));
|
|
154
|
+
this.detachParentBinding();
|
|
155
|
+
this.gate.open("");
|
|
156
|
+
this.deps.onRunEnded(this.spawn);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Send a message to the agent's pane. Steering a settled session revives it:
|
|
160
|
+
* a fresh supervisor adopts the same host and settles the run again.
|
|
161
|
+
*/
|
|
162
|
+
async steer(message) {
|
|
163
|
+
if (this.isQueued()) {
|
|
164
|
+
return {
|
|
165
|
+
kind: "refused",
|
|
166
|
+
reason: `agent ${this.id} is queued — it has no pane yet, so it cannot receive a message. Wait for a concurrency slot (or stop it).`,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
const ref = this.spawn.execution.host;
|
|
170
|
+
if (!ref) {
|
|
171
|
+
// A missing host ref means different things along a run's life, so name
|
|
172
|
+
// the one this is rather than blaming cleanup every time.
|
|
173
|
+
const reason = this.isLaunching()
|
|
174
|
+
? `agent ${this.id} is still starting up — its pane does not exist yet, so it cannot receive a message. Retry in a moment.`
|
|
175
|
+
: this.spawn.lifecycle.phase === "never-started"
|
|
176
|
+
? `agent ${this.id} never started, so it has no pane and there is nobody to receive the message.`
|
|
177
|
+
: `agent ${this.id} has no pane (it was cleaned up), so there is nobody to receive the message.`;
|
|
178
|
+
return { kind: "refused", reason };
|
|
179
|
+
}
|
|
180
|
+
// Snapshot settlement up front: the message delivers as the run was.
|
|
181
|
+
const wasSettled = this.isSettled();
|
|
182
|
+
let submit;
|
|
183
|
+
try {
|
|
184
|
+
submit = await this.deps.transport
|
|
185
|
+
.createHost(getPiInstance())
|
|
186
|
+
.deliver(ref, message);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
submit = { kind: "not-submitted", detail: errorMessage(error) };
|
|
190
|
+
}
|
|
191
|
+
if (submit.kind === "not-submitted") {
|
|
192
|
+
return {
|
|
193
|
+
kind: "refused",
|
|
194
|
+
reason: `the message could not be delivered to agent ${this.id} — ${submit.detail}`,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
if (wasSettled) {
|
|
198
|
+
// The message is in the pane from here on, so a revive that throws is
|
|
199
|
+
// reported, not thrown: the steer landed and only the second turn's
|
|
200
|
+
// watch is missing.
|
|
201
|
+
try {
|
|
202
|
+
this.revive(ref);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
return {
|
|
206
|
+
kind: "delivered-not-revived",
|
|
207
|
+
reason: `the message reached its pane, but the agent could not be revived: ${errorMessage(error)}. No completion message will arrive — read the pane for the result.`,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return { kind: "delivered" };
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Return a settled run to the active lifecycle. Artifact policy (result-dir
|
|
215
|
+
* recreation, stale-report removal) and adoption live in agent-reviver.ts;
|
|
216
|
+
* the spawn's state resets here, in the attach seam, so the run stays its
|
|
217
|
+
* only writer. See agent-reviver.ts for the pane guardrails.
|
|
218
|
+
*/
|
|
219
|
+
revive(ref) {
|
|
220
|
+
const startedAt = Date.now();
|
|
221
|
+
reviveSettledRun({
|
|
222
|
+
spawn: this.spawn,
|
|
223
|
+
hostRef: ref,
|
|
224
|
+
transport: this.deps.transport,
|
|
225
|
+
supervisorOptions: this.supervisorOptions(),
|
|
226
|
+
attachSupervisor: (supervisor, launch) => {
|
|
227
|
+
// The settled turn's watch has done its job; the revived turn's reports
|
|
228
|
+
// are the new supervisor's to find.
|
|
229
|
+
this.supervisor?.detach();
|
|
230
|
+
// A revived turn is a live process again, so it takes the same pools the first
|
|
231
|
+
// turn held: its model's, its provider's, and the global limit.
|
|
232
|
+
this.deps.slots.reacquire(this.spawn, this.args.options.modelSelection?.key);
|
|
233
|
+
this.supervisor = supervisor;
|
|
234
|
+
this.launchState = launch;
|
|
235
|
+
// A revived run has not settled yet: no report, no retention reason.
|
|
236
|
+
this.retention = undefined;
|
|
237
|
+
this.commit(reviveRun(this.run, startedAt));
|
|
238
|
+
},
|
|
239
|
+
rebindParentSignal: () => this.bindParentSignal(),
|
|
240
|
+
reportOutcome: (supervisor, outcome) => {
|
|
241
|
+
void this.applySupervisorOutcome(supervisor, outcome);
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
async abort(initiator) {
|
|
246
|
+
const stopIssued = this.isLaunching() || this.isActive();
|
|
247
|
+
const run = this.run;
|
|
248
|
+
log.debug("abort requested", {
|
|
249
|
+
initiator,
|
|
250
|
+
process: run.shell === "dropped" ? "dropped" : run.process.kind,
|
|
251
|
+
shell: run.shell,
|
|
252
|
+
stopIssued,
|
|
253
|
+
});
|
|
254
|
+
if (this.isQueued()) {
|
|
255
|
+
this.deps.slots.cancelQueued(this.id);
|
|
256
|
+
this.commit(abortQueuedRun(this.run, initiator ?? "agent", Date.now()));
|
|
257
|
+
this.detachParentBinding();
|
|
258
|
+
this.gate.open("");
|
|
259
|
+
this.deps.onRunEnded(this.spawn);
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
if (!this.isLaunching() && !this.isActive())
|
|
263
|
+
return false;
|
|
264
|
+
this.spawn.execution.abortController.abort();
|
|
265
|
+
await this.stopPaneProcess();
|
|
266
|
+
// Re-read the run after the stop: disposal may have moved it meanwhile.
|
|
267
|
+
if (!this.isLaunching() && !this.isActive())
|
|
268
|
+
return false;
|
|
269
|
+
this.commit(enterSettling(this.run, { kind: "stopped", initiator: initiator ?? "agent" }, Date.now()));
|
|
270
|
+
await this.settle();
|
|
271
|
+
return true;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Unblock awaiters without touching the pane, and let the run's artifacts go:
|
|
275
|
+
* a dropped spawn has no reporters left, so its result directory is removed.
|
|
276
|
+
*/
|
|
277
|
+
drop() {
|
|
278
|
+
this.commit(dropRun(this.run, this.artifacts));
|
|
279
|
+
// The report watch outlives settlement, so dropping the spawn is what ends
|
|
280
|
+
// it; only a run whose removal is confirmed lets go of its artifacts.
|
|
281
|
+
this.supervisor?.detach();
|
|
282
|
+
this.supervisor = undefined;
|
|
283
|
+
this.closeChannel();
|
|
284
|
+
removeResultArtifacts(this.resultFilePath());
|
|
285
|
+
this.detachParentBinding();
|
|
286
|
+
this.gate.open("");
|
|
287
|
+
}
|
|
288
|
+
/** Parent disposal does not stop independent panes or report completion. */
|
|
289
|
+
settleForDispose() {
|
|
290
|
+
if (this.isQueued()) {
|
|
291
|
+
this.commit(disposeQueuedRun(this.run, Date.now()));
|
|
292
|
+
this.gate.open("");
|
|
293
|
+
}
|
|
294
|
+
else if (this.isLaunching() || this.isActive()) {
|
|
295
|
+
this.commit(disposeLiveRun(this.run));
|
|
296
|
+
this.gate.open("");
|
|
297
|
+
}
|
|
298
|
+
// Disposal stops tracking only: abandon the poll loop, leave pane and process alive.
|
|
299
|
+
this.supervisor?.abandon();
|
|
300
|
+
this.supervisor = undefined;
|
|
301
|
+
this.closeChannel();
|
|
302
|
+
this.detachParentBinding();
|
|
303
|
+
}
|
|
304
|
+
async launch() {
|
|
305
|
+
let placement = { kind: "none" };
|
|
306
|
+
let failure = { kind: "none" };
|
|
307
|
+
try {
|
|
308
|
+
const host = this.deps.transport.createHost(this.args.pi);
|
|
309
|
+
const { pi, ctx, type, prompt, options } = this.args;
|
|
310
|
+
// An owned checkout is provisioned here, once the run holds a slot: a
|
|
311
|
+
// queued run must not hold a worktree or a pane. A caller that already
|
|
312
|
+
// provisioned one (the spawn wizard) passes its own hostRef.
|
|
313
|
+
let ref = options.hostRef;
|
|
314
|
+
if (!ref && options.worktree?.kind === "owned") {
|
|
315
|
+
let sandbox;
|
|
316
|
+
try {
|
|
317
|
+
sandbox = await AgentSandbox.allocate(pi, {
|
|
318
|
+
naming: {
|
|
319
|
+
kind: "generated",
|
|
320
|
+
taskSlug: options.taskSlug ?? type,
|
|
321
|
+
id: this.spawn.id,
|
|
322
|
+
},
|
|
323
|
+
parentCwd: ctx.cwd,
|
|
324
|
+
worktreeRoot: getStore().agent.worktreeRoot,
|
|
325
|
+
materialization: getWorktreeMaterialization(),
|
|
326
|
+
dirtyCheckout: resolveWorktreeCheckoutType(type),
|
|
327
|
+
notify: (message, kind) => ctx.ui.notify(message, kind),
|
|
328
|
+
host,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
catch (err) {
|
|
332
|
+
// Allocation unwound itself: no checkout exists, so the failed settle
|
|
333
|
+
// must not name one.
|
|
334
|
+
options.worktree = undefined;
|
|
335
|
+
this.spawn.display.worktree = undefined;
|
|
336
|
+
throw err;
|
|
337
|
+
}
|
|
338
|
+
if (sandbox.worktree) {
|
|
339
|
+
options.worktree = { kind: "owned", ...sandbox.worktree };
|
|
340
|
+
this.spawn.display.worktree = options.worktree;
|
|
341
|
+
}
|
|
342
|
+
else {
|
|
343
|
+
// The parent left the repository since the spawn resolved: fall back
|
|
344
|
+
// to the parent cwd like any non-repo run.
|
|
345
|
+
options.worktree = undefined;
|
|
346
|
+
this.spawn.display.worktree = undefined;
|
|
347
|
+
}
|
|
348
|
+
ref = sandbox.hostRef;
|
|
349
|
+
}
|
|
350
|
+
// The herdr agent name: the worktree's branch for a worktree run,
|
|
351
|
+
// else the pinned `cow-<task>-<id>` the sandbox was allocated under.
|
|
352
|
+
const agentName = options.worktree?.branch ??
|
|
353
|
+
buildWorktreeBranch(options.taskSlug ?? slugifyWorktreeType(type), this.id);
|
|
354
|
+
const plan = await buildLaunchPlan(pi, ctx, type, prompt, {
|
|
355
|
+
agentId: this.id,
|
|
356
|
+
modelSelection: options.modelSelection,
|
|
357
|
+
thinkingLevel: options.thinkingLevel,
|
|
358
|
+
fork: options.fork,
|
|
359
|
+
cwd: options.worktree?.path,
|
|
360
|
+
projectTrusted: options.projectTrusted,
|
|
361
|
+
description: options.description,
|
|
362
|
+
worktree: options.worktree,
|
|
363
|
+
agentGuidance: options.orchestration.guidance,
|
|
364
|
+
});
|
|
365
|
+
const launch = { resultFile: plan.resultFile };
|
|
366
|
+
this.launchState = launch;
|
|
367
|
+
const harness = harnessFor(plan.harness);
|
|
368
|
+
ref =
|
|
369
|
+
ref ??
|
|
370
|
+
(await host.hostAt({
|
|
371
|
+
unit: "pane",
|
|
372
|
+
cwd: plan.cwd,
|
|
373
|
+
label: options.taskSlug ?? type,
|
|
374
|
+
name: agentName,
|
|
375
|
+
}));
|
|
376
|
+
placement = { kind: "held", host, ref };
|
|
377
|
+
if (!this.isLaunching())
|
|
378
|
+
return;
|
|
379
|
+
this.spawn.execution.host = ref;
|
|
380
|
+
// The pane exists now, so the harness can bring it into its launch state.
|
|
381
|
+
await harness.prepare({ pi, paneId: ref.paneId, cwd: plan.cwd });
|
|
382
|
+
const { supervisor, ipc } = createPaneSupervisor({
|
|
383
|
+
host,
|
|
384
|
+
resultFile: launch.resultFile,
|
|
385
|
+
supervisorOptions: this.supervisorOptions(),
|
|
386
|
+
transport: this.deps.transport,
|
|
387
|
+
agentId: this.spawn.id,
|
|
388
|
+
onFrame: (frame) => this.handleFrame(launch, frame),
|
|
389
|
+
});
|
|
390
|
+
this.supervisor = supervisor;
|
|
391
|
+
this.ipc = ipc;
|
|
392
|
+
// The child connects at boot, so the parent must already be listening.
|
|
393
|
+
await this.openChannel(launch);
|
|
394
|
+
await supervisor.start({
|
|
395
|
+
name: agentName,
|
|
396
|
+
cwd: plan.cwd,
|
|
397
|
+
piArgs: [...plan.piArgs, plan.initialMessage ?? ""],
|
|
398
|
+
taskSlug: options.taskSlug,
|
|
399
|
+
}, ref);
|
|
400
|
+
placement = { kind: "committed" };
|
|
401
|
+
if (!this.isLaunching())
|
|
402
|
+
return;
|
|
403
|
+
this.commit(activateRun(this.run));
|
|
404
|
+
void supervisor
|
|
405
|
+
.watch()
|
|
406
|
+
.then((outcome) => this.applySupervisorOutcome(supervisor, outcome));
|
|
407
|
+
}
|
|
408
|
+
catch (err) {
|
|
409
|
+
failure = { kind: "failed", error: err };
|
|
410
|
+
}
|
|
411
|
+
finally {
|
|
412
|
+
if (placement.kind === "held")
|
|
413
|
+
await placement.host
|
|
414
|
+
.release(placement.ref, "placement")
|
|
415
|
+
.catch(() => { });
|
|
416
|
+
}
|
|
417
|
+
if (failure.kind === "failed" && this.isLaunching()) {
|
|
418
|
+
this.commit(enterSettling(this.run, { kind: "failed", error: errorMessage(failure.error) }, Date.now()));
|
|
419
|
+
await this.settle();
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
/** Report-only: poll for the report; no liveness or turn policy. */
|
|
423
|
+
supervisorOptions() {
|
|
424
|
+
return {
|
|
425
|
+
stopInitiator: "agent",
|
|
426
|
+
onFollowUp: (deliverable) => this.deps.onFollowUpResult(this.spawn, deliverable),
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
/** Where the run's result artifacts live; a run that never launched still reserves the path. */
|
|
430
|
+
resultFilePath() {
|
|
431
|
+
return this.launchState?.resultFile ?? subagentResultFileFor(this.id);
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Bind the run's channel before the child launches, so the child finds its
|
|
435
|
+
* parent listening, and record what the channel can carry. A bind failure is
|
|
436
|
+
* not a launch failure: the handshake is observability, and the run's own
|
|
437
|
+
* reporting does not depend on it.
|
|
438
|
+
*/
|
|
439
|
+
async openChannel(launch) {
|
|
440
|
+
const { ipc } = this;
|
|
441
|
+
if (ipc === undefined || ipc.start === undefined) {
|
|
442
|
+
launch.handshake = {
|
|
443
|
+
kind: "unavailable",
|
|
444
|
+
reason: "no-channel",
|
|
445
|
+
};
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
try {
|
|
449
|
+
await ipc.start();
|
|
450
|
+
launch.handshake = { kind: "awaiting" };
|
|
451
|
+
}
|
|
452
|
+
catch (error) {
|
|
453
|
+
launch.handshake = {
|
|
454
|
+
kind: "unavailable",
|
|
455
|
+
reason: "bind-failed",
|
|
456
|
+
};
|
|
457
|
+
log.warn("subagent channel failed to bind", {
|
|
458
|
+
agentId: this.id,
|
|
459
|
+
errorMessage: errorMessage(error),
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Release the run's channel, leaving the artifacts alone: the run may still
|
|
465
|
+
* write reports to them, so only drop() removes the directory.
|
|
466
|
+
*/
|
|
467
|
+
closeChannel() {
|
|
468
|
+
const ipc = this.ipc;
|
|
469
|
+
this.ipc = undefined;
|
|
470
|
+
void ipc?.close?.().catch(() => { });
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* The child's frames. `ready` is the only kind the protocol defines so far, so
|
|
474
|
+
* there is nothing to dispatch on: a ready frame names the run's process, and
|
|
475
|
+
* only while the run is still awaiting one — a child reload announces again,
|
|
476
|
+
* and a run whose channel was unavailable never gets to this at all.
|
|
477
|
+
*/
|
|
478
|
+
handleFrame(launch, frame) {
|
|
479
|
+
if (launch.handshake?.kind === "awaiting") {
|
|
480
|
+
launch.handshake = { kind: "announced", pid: frame.pid };
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
async applySupervisorOutcome(supervisor, outcome) {
|
|
484
|
+
if (!this.isActive() || this.supervisor !== supervisor)
|
|
485
|
+
return;
|
|
486
|
+
log.debug("outcome mapped", {
|
|
487
|
+
kind: outcome.kind,
|
|
488
|
+
});
|
|
489
|
+
switch (outcome.kind) {
|
|
490
|
+
case "completed": {
|
|
491
|
+
this.commit(enterSettling(this.run, { kind: "completed", result: outcome.deliverable || "" }, Date.now()));
|
|
492
|
+
await this.settle();
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
case "stopped":
|
|
496
|
+
await this.abort(outcome.initiator);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
async stopPaneProcess() {
|
|
500
|
+
const supervisor = this.supervisor;
|
|
501
|
+
if (supervisor) {
|
|
502
|
+
this.supervisor = undefined;
|
|
503
|
+
await supervisor.stop(2_000);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
const ref = this.spawn.execution.host;
|
|
507
|
+
if (!ref)
|
|
508
|
+
return;
|
|
509
|
+
await this.deps.transport
|
|
510
|
+
.createHost(getPiInstance())
|
|
511
|
+
.stop(ref, { interruptGraceMs: 2_000, confirmMs: 10_000 });
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Settle passes serialize: a revive can move the run out of settling while
|
|
515
|
+
* a pass still awaits its probes, and the revived run settles through this
|
|
516
|
+
* same method. Chained, never concurrent — a second settlement waits for
|
|
517
|
+
* the in-flight pass instead of doubling its effects or racing its writes.
|
|
518
|
+
*/
|
|
519
|
+
settleChain = Promise.resolve();
|
|
520
|
+
async settle() {
|
|
521
|
+
if (this.run.shell !== "held" || this.run.process.kind !== "settling")
|
|
522
|
+
return;
|
|
523
|
+
const previous = this.settleChain;
|
|
524
|
+
let done;
|
|
525
|
+
const current = new Promise((resolve) => {
|
|
526
|
+
done = resolve;
|
|
527
|
+
});
|
|
528
|
+
this.settleChain = current;
|
|
529
|
+
await previous;
|
|
530
|
+
try {
|
|
531
|
+
await this.runSettlePass();
|
|
532
|
+
}
|
|
533
|
+
finally {
|
|
534
|
+
done();
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* One settlement's terminal pass. Past the first await a revive may have
|
|
539
|
+
* moved the run, so per-run writes apply only to the run that entered,
|
|
540
|
+
* matched by identity — the revived turn keeps its supervisor, its blank
|
|
541
|
+
* retention reason, and its rebound parent binding.
|
|
542
|
+
* First-settlement effects stay unconditional: a revive never re-acquires
|
|
543
|
+
* a slot, and the once-only gate keeps the first run's result.
|
|
544
|
+
*/
|
|
545
|
+
async runSettlePass() {
|
|
546
|
+
const settlingRun = this.run;
|
|
547
|
+
if (settlingRun.shell !== "held" || settlingRun.process.kind !== "settling")
|
|
548
|
+
return;
|
|
549
|
+
// The run is past its last frame: nothing will announce again.
|
|
550
|
+
this.closeChannel();
|
|
551
|
+
// The gate opens once: snapshot the entered run's result before a revive
|
|
552
|
+
// can re-project the lifecycle to spawned.
|
|
553
|
+
const result = lifecycleResult(this.spawn.lifecycle);
|
|
554
|
+
const retention = await this.readWorktreeRetention();
|
|
555
|
+
await this.deps.slots.release(this.id);
|
|
556
|
+
// The supervisor stays attached past settlement: its watch is what reports
|
|
557
|
+
// the follow-ups a later turn produces. A revive replaces it (see revive).
|
|
558
|
+
this.deps.onRunEnded(this.spawn);
|
|
559
|
+
// A revive rebound the parent signal for the next turn; detach only ours.
|
|
560
|
+
if (this.run === settlingRun)
|
|
561
|
+
this.detachParentBinding();
|
|
562
|
+
this.gate.open(result);
|
|
563
|
+
if (this.run === settlingRun) {
|
|
564
|
+
// Still ours: publish this run's probe answer, mapping the probe's clean
|
|
565
|
+
// (null) to the field's absent (undefined); a revive cleared the reason
|
|
566
|
+
// for the next turn, so writing after one would resurrect it.
|
|
567
|
+
this.retention = retention ?? undefined;
|
|
568
|
+
this.commit(finishSettling(this.run));
|
|
569
|
+
}
|
|
570
|
+
// A run revived mid-pass settles through its own chained pass, which runs
|
|
571
|
+
// that run's probe, release, and nudge; finishing it here would settle it
|
|
572
|
+
// ahead of all three.
|
|
573
|
+
}
|
|
574
|
+
async readWorktreeRetention() {
|
|
575
|
+
const worktree = this.spawn.display.worktree;
|
|
576
|
+
if (worktree?.kind !== "owned")
|
|
577
|
+
return null;
|
|
578
|
+
return worktreeRetentionReason(getPiInstance(), worktree.path);
|
|
579
|
+
}
|
|
580
|
+
detachParentBinding() {
|
|
581
|
+
const binding = this.parentBinding;
|
|
582
|
+
if (!binding)
|
|
583
|
+
return;
|
|
584
|
+
this.parentBinding = undefined;
|
|
585
|
+
binding.signal.removeEventListener("abort", binding.handler);
|
|
586
|
+
}
|
|
587
|
+
/** Parent abort stops this run; re-bound on revive since settlement detaches it. */
|
|
588
|
+
bindParentSignal() {
|
|
589
|
+
if (this.parentBinding)
|
|
590
|
+
return;
|
|
591
|
+
const signal = this.args.options.signal;
|
|
592
|
+
if (!signal || signal.aborted)
|
|
593
|
+
return;
|
|
594
|
+
const handler = () => {
|
|
595
|
+
log.debug("parent signal fired", { initiator: "user" });
|
|
596
|
+
void this.abort("user");
|
|
597
|
+
};
|
|
598
|
+
signal.addEventListener("abort", handler, { once: true });
|
|
599
|
+
this.parentBinding = { signal, handler };
|
|
600
|
+
}
|
|
601
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tool-cleanup.ts — cleanup_cowboy_agent tool implementation.
|
|
3
|
+
*
|
|
4
|
+
* Validates `agent_id` and renders the structured `CleanupReport`; the
|
|
5
|
+
* cleanup itself is the manager's `cleanup()`. Cleanup never stops a live
|
|
6
|
+
* agent — a run still in flight is refused, and an id with no spawn record
|
|
7
|
+
* (a `/reload` rebuilt the store) runs the locator first. An unsafe
|
|
8
|
+
* worktree (dirty, unverifiable) is kept with its reason, not destroyed.
|
|
9
|
+
*/
|
|
10
|
+
import { getManager } from "../shell.js";
|
|
11
|
+
import { formatActiveAgents } from "../orchestrators/protocol.js";
|
|
12
|
+
import { renderCleanupReport } from "./cleanup-report.js";
|
|
13
|
+
import { runBatch } from "./batch.js";
|
|
14
|
+
/** Per-item result block: the structured summary for a cleaned run, the not-found line for an unknown id. */
|
|
15
|
+
export function renderCleanupOutcome(outcome) {
|
|
16
|
+
switch (outcome.kind) {
|
|
17
|
+
case "cleaned":
|
|
18
|
+
return renderCleanupReport(outcome.report);
|
|
19
|
+
case "unknown":
|
|
20
|
+
return `Agent ${outcome.agentId} not found. Active agents: ${outcome.activeAgents}`;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* cleanup_cowboy_agent handler. Cleans up every id in `agent_ids` sequentially
|
|
25
|
+
* in input order — teardown shares herdr/git state, so items never run in
|
|
26
|
+
* parallel. Best effort: one id's outcome never blocks the rest. Cleanup
|
|
27
|
+
* never throws per item (refusals ride inside each report); `agent_ids` is
|
|
28
|
+
* non-empty by the schema boundary, so a whole-call throw (before anything is
|
|
29
|
+
* removed) only fires on a repeated id.
|
|
30
|
+
*/
|
|
31
|
+
export async function executeCleanupAgentTool(_toolCallId, params, _signal, _onUpdate, _ctx) {
|
|
32
|
+
const agentIds = params.agent_ids;
|
|
33
|
+
return runBatch({
|
|
34
|
+
toolName: "cleanup_cowboy_agent",
|
|
35
|
+
param: "agent_ids",
|
|
36
|
+
detailsKey: "agents",
|
|
37
|
+
items: agentIds,
|
|
38
|
+
render: renderCleanupOutcome,
|
|
39
|
+
handleItem: async (agentId) => {
|
|
40
|
+
const manager = getManager();
|
|
41
|
+
// A spawn outlives a replaced session (/new, /resume, /fork): the
|
|
42
|
+
// shell-owned spawn store keeps it for exactly this call.
|
|
43
|
+
if (!manager.getSpawn(agentId)) {
|
|
44
|
+
const located = await manager.locate(agentId);
|
|
45
|
+
if (located.kind === "not-found") {
|
|
46
|
+
return {
|
|
47
|
+
kind: "unknown",
|
|
48
|
+
agentId,
|
|
49
|
+
activeAgents: formatActiveAgents(manager),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const report = await manager.cleanup(agentId);
|
|
54
|
+
return { kind: "cleaned", agentId, report };
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
}
|