pi-cowboy 0.4.1 → 0.8.5

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.
Files changed (70) hide show
  1. package/README.md +28 -10
  2. package/agents/explore.toml +1 -1
  3. package/dist/agents/agent-assets.js +3 -0
  4. package/dist/agents/agent-cleanup.js +20 -0
  5. package/dist/agents/agent-discovery.js +34 -28
  6. package/dist/agents/agent-manager.js +85 -29
  7. package/dist/agents/agent-runner.js +111 -69
  8. package/dist/agents/agent-template.js +107 -5
  9. package/dist/agents/agent-types.js +0 -1
  10. package/dist/agents/harness/claude/index.js +219 -0
  11. package/dist/agents/harness/claude/staging.js +102 -0
  12. package/dist/agents/harness/codex.js +249 -0
  13. package/dist/agents/harness/opencode/definition.js +65 -0
  14. package/dist/agents/harness/opencode/index.js +218 -0
  15. package/dist/agents/harness/opencode/npm-seed.js +74 -0
  16. package/dist/agents/harness/opencode/permissions.js +48 -0
  17. package/dist/agents/harness/opencode/staging.js +63 -0
  18. package/dist/agents/harness/pane-launcher.js +96 -0
  19. package/dist/agents/harness/pi-bolt.js +3 -3
  20. package/dist/agents/harness/pi-compatible.js +80 -37
  21. package/dist/agents/harness/pig.js +3 -3
  22. package/dist/agents/harness/registry.js +53 -4
  23. package/dist/agents/harness-family.js +23 -0
  24. package/dist/agents/harness.js +86 -8
  25. package/dist/agents/schemas/cowboy-agents.schema.js +16 -5
  26. package/dist/agents/spawn-defaults.js +48 -6
  27. package/dist/agents/subagent-session.js +45 -8
  28. package/dist/agents/tool-execution.js +9 -2
  29. package/dist/availability.js +7 -0
  30. package/dist/concurrency-pools.js +270 -0
  31. package/dist/config/concurrency-limit.js +14 -0
  32. package/dist/config/config-io.js +22 -5
  33. package/dist/config/config-store.js +128 -9
  34. package/dist/config/config-validation.js +87 -7
  35. package/dist/config/types.js +2 -0
  36. package/dist/events.js +2 -1
  37. package/dist/harness-availability-launch.js +19 -4
  38. package/dist/index.js +18 -3
  39. package/dist/infrastructure/git/cow-clone.js +9 -1
  40. package/dist/infrastructure/git/git-runner.js +22 -0
  41. package/dist/infrastructure/herdr/agents.js +9 -8
  42. package/dist/infrastructure/herdr-host.js +3 -2
  43. package/dist/models/foreign-model-resolver.js +55 -0
  44. package/dist/models/model-groups.js +3 -1
  45. package/dist/models/model-precedence.js +35 -8
  46. package/dist/models/model-request-types.js +46 -0
  47. package/dist/models/model-request.js +32 -101
  48. package/dist/models/pi-model-resolver.js +88 -0
  49. package/dist/orchestrators/default-orchestrators.js +1 -1
  50. package/dist/orchestrators/protocol.js +29 -10
  51. package/dist/prompt/subagent-system-prompt.js +10 -3
  52. package/dist/registration.js +33 -19
  53. package/dist/spawn/sandbox.js +3 -0
  54. package/dist/subagent/deliverable.js +4 -3
  55. package/dist/subagent/supervisor.js +5 -3
  56. package/dist/task-registry.js +12 -158
  57. package/dist/ui/format.js +7 -0
  58. package/dist/ui/menu/helpers.js +23 -9
  59. package/dist/ui/menu/menu-agent-settings.js +1 -1
  60. package/dist/ui/menu/menu-concurrency.js +282 -101
  61. package/dist/ui/menu/menu-model-settings.js +114 -30
  62. package/dist/ui/menu/menu-spawn-defaults.js +4 -2
  63. package/dist/ui/menu/menu-spawn-wizard.js +11 -7
  64. package/dist/ui/menu/menus.js +10 -10
  65. package/dist/ui/menu/model-picker.js +37 -21
  66. package/dist/ui/menu/submenus/model-select.js +4 -7
  67. package/dist/ui/menu/submenus/numeric-input.js +2 -2
  68. package/dist/utils.js +10 -0
  69. package/orchestrators/with-code-review.toml +1 -1
  70. package/package.json +4 -2
package/README.md CHANGED
@@ -10,6 +10,8 @@ pi-cowboy is an agent orchestrator for [pi](https://pi.dev). It is designed for
10
10
 
11
11
  - **Improved code understanding:** Give each agent a smaller, isolated subtask. A single focused task with clear guidance leaves little room for error; a long list of tasks and expectations creates more room for drift and over-engineering. Smaller tasks therefore improve code quality and yield results that are easier to review: each agent commits to its own branch, so a subtask is reviewed and merged on its own, separately from the others.
12
12
 
13
+ - **Foreign harness support:** pi-cowboy can orchestrate Claude Code, Codex, OpenCode, and more: start work on Pi, continue on Claude Code, finish on OpenCode.
14
+
13
15
  - **Parallel work with minimal disk overhead:** Multiple agents can edit, build, and run tests concurrently without interfering with each other. Copy-on-write unlocks more parallelism by reducing the disk overhead of the worktrees.
14
16
  The numbers below are from a Git repository containing 153,607 files in total. The tracked files occupy 479 MB, while the repository is 27 GB in total, including untracked files.
15
17
 
@@ -71,7 +73,7 @@ Depending on your concurrency settings, some of the tasks queue. The default glo
71
73
 
72
74
  Each agent runs as a separate pi process in its own Herdr workspace. Open a workspace at any time to monitor the agent or to steer it.
73
75
 
74
- Three Herdr terms recur below: a **workspace** is the outermost Herdr container and holds tabs, a **tab** holds panes, and a **pane** is one terminal session — the one the agent's pi process runs in. pi-cowboy gives each agent its own workspace and tab, and puts the agent in that tab's root pane. Outside a git repository there is no worktree to open, so the agent gets a tab in your current workspace instead. The pane id is the durable handle `cleanup_cowboy_agent` uses to find that pane again.
76
+ Three Herdr terms recur below: a **workspace** is the outermost Herdr container and holds tabs, a **tab** holds panes, and a **pane** is one terminal session — the one the agent's pi process runs in. pi-cowboy gives each agent its own workspace and tab, and puts the agent in that tab's root pane — which is why pi-cowboy needs a git repository: outside one there is no worktree to open, so the extension stays inactive for that session. The pane id is the durable handle `cleanup_cowboy_agent` uses to find that pane again.
75
77
 
76
78
  The agents work in separate git worktrees placed under `$HOME/.pi/agent/pi-cowboy/worktrees/`.
77
79
 
@@ -120,13 +122,21 @@ If pi-cowboy cannot remove one of them, it reports the failure and completes the
120
122
  `/cowboy` opens a menu. See [Menu](docs/Menu.md).
121
123
 
122
124
  <code>/cowboy                         # pi-cowboy menu</code><br>
125
+
123
126
  <code>/cowboy status                  # List spawned, queued, and settled agents</code><br>
127
+
124
128
  <code>/cowboy spawn                   # Spawn an agent manually</code><br>
129
+
125
130
  <code>/cowboy worktree                # Create a git worktree with no agent attached</code><br>
131
+
126
132
  <code>/cowboy model                   # Model selection for the agents</code><br>
133
+
127
134
  <code>/cowboy model provider/model-id # Set the model for this session</code><br>
135
+
128
136
  <code>/cowboy model clear             # Clear the model set for this session</code><br>
137
+
129
138
  <code>/cowboy enable                  # Enables pi-cowboy</code><br>
139
+
130
140
  <code>/cowboy disable.                # Disables pi-cowboy</code>
131
141
 
132
142
  ## Tools
@@ -142,12 +152,13 @@ Delegates one or more tasks to cowboy agents. Each cowboy agent runs in its own
142
152
 
143
153
  `agents[]`:
144
154
 
145
- | Field | Required | Description |
146
- | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
147
- | `prompt` | yes | Task instructions for the cowboy agent. |
148
- | `task_name` | yes | Short 2-3-word name (e.g. "fix login flow") that names the agent's branch, worktree, and tab. |
149
- | `agent_type` | no | Agent type to use. Defaults to the type set at `/cowboy` > `Agent`. |
150
- | `model` | no | Model for this cowboy agent as `"provider/model-id"`. Defaults are resolved in the order under [Model resolution](#model-resolution). |
155
+ | Field | Required | Description |
156
+ | -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
157
+ | `prompt` | yes | Task instructions for the cowboy agent. |
158
+ | `task_name` | yes | Short 2-3-word name (e.g. "fix login flow") that names the agent's branch, worktree, and tab. |
159
+ | `agent_type` | no | Agent type to use. Defaults to the type set at `/cowboy` > `Agent`. |
160
+ | `model` | no | Model for this cowboy agent as `"provider/model-id"`. Defaults are resolved in the order under [Model resolution](#model-resolution). |
161
+ | `harness_type` | no | Harness that launches this agent: `pi`, `pig`, `pi-bolt`, `opencode`, `codex`, or `claude`. Overrides the agent template's `harness_type` and the `agent.harnessType` setting. If this machine cannot launch the harness, the call fails before anything spawns. |
151
162
 
152
163
  ### `steer_cowboy_agent`
153
164
 
@@ -190,7 +201,7 @@ A removal that fails does not throw. The branch is removed only after you have m
190
201
 
191
202
  ## Model resolution
192
203
 
193
- A model set in the `cowboy_agent` call wins over everything; below it come the session overrides, the agent template, and finally the model of the parent session. The authoritative order is in [Configuration](docs/Configuration.md#model-keys).
204
+ A model set in the `cowboy_agent` call wins over everything; below it come the session per-type override, the config per-type override, the agent template, the session default, the launching harness's default, and finally — under the pi family — the model of the parent session. The authoritative order is in [Configuration](docs/Configuration.md#model-keys).
194
205
 
195
206
  ## Concurrency
196
207
 
@@ -198,9 +209,10 @@ A running agent holds a place in every concurrency limit that applies to it. pi-
198
209
 
199
210
  - **Per-model** — `concurrency.models["<provider>/<model-id>"]`
200
211
  - **Per-provider** — `concurrency.providers.<provider>`
212
+ - **Per-harness** — `concurrency.harnesses.<harness-id>`
201
213
  - **Global** — `concurrency.default` (default `4`), which every agent counts against
202
214
 
203
- The levels are independent: an agent whose model and provider both have limits counts against both of them and against the global limit, so you have to free room at every level that applies.
215
+ The levels are independent: an agent whose model, provider, and harness all have limits counts against all of them and against the global limit, so you have to free room at every level that applies.
204
216
  pi-cowboy starts the first waiting agent whose every level has room: an agent that waits for one limit to clear does not hold back an agent behind it.
205
217
 
206
218
  An agent with no model selection counts against the global limit alone.
@@ -256,7 +268,7 @@ Orchestrator templates also allow you to customize how the agent communicates wi
256
268
 
257
269
  ### Why is my agent queued, not running?
258
270
 
259
- Every running agent holds a place in every concurrency limit that applies to it: the limit of its model, the limit of its provider, and the global limit. pi-cowboy queues the other agents until every one of those limits has room. Raise the limit in `/cowboy` > `Settings` > `Concurrency Settings`, or in the `concurrency` config keys. See [Concurrency](#concurrency).
271
+ Every running agent holds a place in every concurrency limit that applies to it: the limit of its model, the limit of its provider, the limit of its harness, and the global limit. Model and provider keys may carry a harness qualifier (`opencode:provider/model`); a bare key names pi's pool. pi-cowboy queues the other agents until every one of those limits has room. Raise the limit in `/cowboy` > `Settings` > `Concurrency Settings`, or in the `concurrency` config keys. See [Concurrency](#concurrency).
260
272
 
261
273
  ### Why did my worktree survive cleanup?
262
274
 
@@ -268,6 +280,12 @@ It can be. For a single small task the overhead can cost more time than the task
268
280
 
269
281
  To avoid the overhead, pi-cowboy has support for [pig](https://github.com/MichaelKinsy/PiG), a drop-in replacement for pi written in Go, and for [pi-bolt](https://github.com/opensec-git/Pi-Bolt), faster, lighter Pi variant compiled ahead of time. They start up fast and have a lower memory footprint. See `agent.harnessType` in [Configuration](docs/Configuration.md).
270
282
 
283
+ pi-cowboy can also launch [opencode](https://opencode.ai), where its binary is on `PATH`. Set `harness_type = "opencode"` in a template, or pass `harness_type` on a `cowboy_agent` call, and the agent runs opencode instead of pi.
284
+
285
+ pi-cowboy can also launch [codex](https://developers.openai.com/codex), where its binary is on `PATH`. Set `harness_type = "codex"` in a template, or pass `harness_type` on a `cowboy_agent` call, and the agent runs codex instead of pi.
286
+
287
+ pi-cowboy can also launch [Claude Code](https://code.claude.com/docs), where its `claude` binary is on `PATH`. Set `harness_type = "claude"` in a template, or pass `harness_type` on a `cowboy_agent` call, and the agent runs the interactive Claude Code TUI instead of pi. Its model catalogue is claude's own (`anthropic/sonnet`, `anthropic/opus`, `anthropic/haiku`), and its tool lists are written in claude's own tool names under `[harness.claude]`.
288
+
271
289
  ### I don't like the emojis, can I turn them off?
272
290
 
273
291
  I don't understand who in their right mind would ever want to do such a thing... but yes. You can disable both the cowboy and the grazing in settings. See [Configuration](docs/Configuration.md).
@@ -36,5 +36,5 @@ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find,
36
36
  - Do not use emojis
37
37
  - Be thorough and precise'''
38
38
 
39
- [harness]
39
+ [harness.pi]
40
40
  tools = ["read", "bash", "grep", "find"]
@@ -16,6 +16,7 @@ import { createHerdrHost } from "../infrastructure/herdr-host.js";
16
16
  import { getSessionCtx, getStore } from "../shell.js";
17
17
  import { subagentResultFileFor } from "../paths.js";
18
18
  import { buildWorktreeBranch, isExtensionWorktree, isSpawnArtifactName, resolveWorktreeRoot, slugifyWorktreeType, } from "../spawn/worktree-policy.js";
19
+ import { harnessFor } from "./harness/registry.js";
19
20
  async function probeList(read) {
20
21
  try {
21
22
  return { ok: true, entries: await read() };
@@ -203,6 +204,7 @@ export function createAgentAssets(deps) {
203
204
  removeGitWorktree: deps.removeGitWorktree,
204
205
  deleteBranch: deps.deleteBranch,
205
206
  closePane: deps.closePane,
207
+ harnessTeardown: deps.harnessTeardown,
206
208
  };
207
209
  }
208
210
  /* ── The herdr composition ─────────────────────────────────────────────── */
@@ -258,5 +260,6 @@ export function createHerdrAgentAssets(pi) {
258
260
  closePane: async (ref) => {
259
261
  await host.release(ref, "placement");
260
262
  },
263
+ harnessTeardown: (harness, context) => harnessFor(harness).teardown({ pi, ...context }),
261
264
  });
262
265
  }
@@ -9,8 +9,10 @@
9
9
  * ordered: gate before removal, workspace before pane, branch only after confirmed checkout removal.
10
10
  */
11
11
  import { hasOutcome } from "../types.js";
12
+ import { createLogger } from "../logger.js";
12
13
  import { errorMessage } from "../utils.js";
13
14
  import { ambiguousReport, assembleReport, assessRemovability, keptReport, paneDispositionFor, planRecovered, recordedSettlement, recoveryGate, recoveryRefusalReason, removalMechanismOf, shouldDropSpawn, } from "./cleanup-policy.js";
15
+ const log = createLogger("cleanup");
14
16
  /* ── Addresses ─────────────────────────────────────────────────────────── */
15
17
  /** Actuator address: memory's ref refreshed from herdr's live report; recovered runs rebuild it with `paneCreated` false; no pane address means no ref (git plane removes the checkout). */
16
18
  function hostRefFor(located) {
@@ -240,6 +242,24 @@ export function createCleanup(assets) {
240
242
  if (verdict.kind === "refused") {
241
243
  return keptReport(agentId, located.source, plan, verdict.settlement, verdict.reason, "open");
242
244
  }
245
+ // Ordered before the dirty probe — see Harness.teardown.
246
+ const harness = hint?.execution.harness;
247
+ if (harness !== undefined) {
248
+ try {
249
+ await assets.harnessTeardown(harness, {
250
+ paneId: located.pane?.paneId ?? null,
251
+ cwd: located.worktree?.path ?? null,
252
+ subagentId: agentId,
253
+ });
254
+ }
255
+ catch (err) {
256
+ log.warn("harness teardown failed during cleanup", {
257
+ spawnId: agentId,
258
+ harness,
259
+ error: errorMessage(err),
260
+ });
261
+ }
262
+ }
243
263
  if (plan.kind === "worktree-unlocatable") {
244
264
  // An unlocatable tree whose path is absent from disk is already gone:
245
265
  // absence is established from the path alone (no repo cwd can address
@@ -30,25 +30,6 @@ export function mergeAgents(defaults, userAgents, sharedAgents, projectAgents) {
30
30
  mergeAgentOverrides(result, projectAgents);
31
31
  return result;
32
32
  }
33
- /** Arbitrate the one runtime boundary that can see both tool filter arms (parsed .toml): whitelist (string[]) wins, else blacklist. */
34
- function arbitrateFilters(config) {
35
- const { tools, excludeTools, ...rest } = config;
36
- const out = { ...rest };
37
- if (tools !== undefined && excludeTools !== undefined) {
38
- if (Array.isArray(tools))
39
- out.tools = tools;
40
- else
41
- out.excludeTools = excludeTools;
42
- }
43
- else {
44
- if (tools !== undefined)
45
- out.tools = tools;
46
- if (excludeTools !== undefined)
47
- out.excludeTools = excludeTools;
48
- }
49
- // The arbitration above guarantees a single arm; the compiler cannot infer that.
50
- return out;
51
- }
52
33
  function mergeAgentOverrides(result, agents) {
53
34
  for (const template of agents) {
54
35
  if (!template.name)
@@ -61,20 +42,45 @@ function mergeAgentOverrides(result, agents) {
61
42
  displayName: template.display_name,
62
43
  description: template.description ?? "",
63
44
  };
64
- result.set(template.name, arbitrateFilters({
45
+ const incoming = fromTemplate(template);
46
+ const modelsByFamily = mergeModelsByFamily(existing.modelsByFamily, incoming.modelsByFamily);
47
+ const toolsByFamily = mergeToolsByFamily(existing.toolsByFamily, incoming.toolsByFamily);
48
+ result.set(template.name, {
65
49
  ...existing,
66
- ...fromTemplate(template),
50
+ ...incoming,
51
+ ...(modelsByFamily ? { modelsByFamily } : {}),
52
+ ...(toolsByFamily ? { toolsByFamily } : {}),
67
53
  ...identity,
68
- }));
54
+ });
69
55
  }
70
56
  else {
71
- result.set(template.name, arbitrateFilters({ ...BASE_DEFAULTS, ...fromTemplate(template) }));
57
+ result.set(template.name, {
58
+ ...BASE_DEFAULTS,
59
+ ...fromTemplate(template),
60
+ });
72
61
  }
73
62
  }
74
63
  }
75
64
  /**
76
- * Only explicitly-set fields (undefined falls through). May carry both filter
77
- * arms; arbitrated by the caller. An empty `inlined_skills` list is a set value,
65
+ * Per-family merge of the layers' model keys: a later layer's key for one
66
+ * family replaces that family's and leaves every other family's intact, the
67
+ * same per-field precedence the rest of the config follows.
68
+ */
69
+ function mergeModelsByFamily(existing, incoming) {
70
+ const merged = { ...existing, ...incoming };
71
+ return Object.keys(merged).length > 0 ? merged : undefined;
72
+ }
73
+ /**
74
+ * Per-family merge of the layers' tool filters: a later layer's slice for one
75
+ * family replaces that family's and leaves every other family's intact, the
76
+ * same per-field precedence the rest of the config follows.
77
+ */
78
+ function mergeToolsByFamily(existing, incoming) {
79
+ const merged = { ...existing, ...incoming };
80
+ return Object.keys(merged).length > 0 ? merged : undefined;
81
+ }
82
+ /**
83
+ * Only explicitly-set fields (undefined falls through). An empty `inlined_skills` list is a set value,
78
84
  * so a higher layer clears inlining with it.
79
85
  */
80
86
  function fromTemplate(template) {
@@ -84,13 +90,13 @@ function fromTemplate(template) {
84
90
  displayName: template.display_name,
85
91
  description: template.description,
86
92
  harnessType: template.harness_type,
87
- tools: harness?.tools,
88
- excludeTools: harness?.exclude_tools,
93
+ toolsByFamily: harness?.toolsByFamily,
89
94
  extensions: harness?.extensions,
90
95
  skills: harness?.skills,
91
96
  inlinedSkills: harness?.inlined_skills,
92
- model: harness?.model,
97
+ modelsByFamily: harness?.modelsByFamily,
93
98
  thinkingLevel: harness?.thinking,
99
+ variant: harness?.variant,
94
100
  hidden: template.hidden,
95
101
  fork: harness?.fork,
96
102
  includeContextFiles: harness?.include_context_files,
@@ -6,15 +6,17 @@
6
6
  import { getAgentSpawns, getCoordinatorOrNull, getPiInstance, getSessionCtx, } from "../shell.js";
7
7
  import { subagentResultFileFor } from "../paths.js";
8
8
  import { createHerdrRuntime } from "../infrastructure/herdr-host.js";
9
- import { HerdrTaskRegistry, } from "../task-registry.js";
9
+ import { HerdrTaskRegistry } from "../task-registry.js";
10
10
  import { createLogger } from "../logger.js";
11
11
  import { errorMessage } from "../utils.js";
12
12
  import { ACTIVE_AGENT_PHASES, ALL_AGENT_PHASES, hasOutcome, lifecycleStartTime, lifecycleStatus, } from "../types.js";
13
13
  import { FileDeliverable } from "../subagent/deliverable.js";
14
14
  import { removeResultArtifacts } from "../subagent/result-artifacts.js";
15
15
  import { createCleanup } from "./agent-cleanup.js";
16
+ import { harnessFor } from "./harness/registry.js";
16
17
  import { createHerdrAgentAssets, } from "./agent-assets.js";
17
18
  import { DISPOSE_QUEUED_MESSAGE, SubagentSession, } from "./subagent-session.js";
19
+ import { resolveHarnessType } from "./spawn-defaults.js";
18
20
  /** The transport the manager wires its sessions with unless the caller supplies one. */
19
21
  export const defaultAgentManagerTransport = {
20
22
  createHost: (pi) => createHerdrRuntime(pi).host,
@@ -69,24 +71,26 @@ export class AgentManager {
69
71
  * the running one instead of racing it for the same checkout.
70
72
  */
71
73
  teardowns = new Map();
74
+ /** The resource limiter the fleet drives directly; sessions charge their capacity to it. */
75
+ pools;
76
+ /** Task identity and admission serialization; pool accounting lives in `pools`. */
72
77
  registry;
73
- constructor(onComplete, concurrency, registry, transport = defaultAgentManagerTransport) {
78
+ constructor(pools, transport = defaultAgentManagerTransport) {
74
79
  this.transport = transport;
75
- this.onComplete = onComplete;
76
- this.registry =
77
- registry ??
78
- new HerdrTaskRegistry({
79
- listAgents: () => this.listAgents(ACTIVE_AGENT_PHASES),
80
- spawn: (type, prompt, options) => this.spawn(getPiInstance(), getSessionCtx(), type, prompt, options),
81
- getSpawn: (id) => this.getSpawn(id),
82
- findTaskAttempts: (taskSlug) => this.transport.createHost(getPiInstance()).findAttempts(taskSlug),
83
- }, concurrency);
80
+ this.pools = pools;
81
+ this.registry = new HerdrTaskRegistry({
82
+ listAgents: () => this.listAgents(ACTIVE_AGENT_PHASES),
83
+ spawn: (type, prompt, options) => this.spawn(getPiInstance(), getSessionCtx(), type, prompt, options),
84
+ getSpawn: (id) => this.getSpawn(id),
85
+ findTaskAttempts: (taskSlug) => this.transport.createHost(getPiInstance()).findAttempts(taskSlug),
86
+ queuePosition: (id) => this.pools.queuePosition(id),
87
+ });
84
88
  }
85
89
  getRegistry() {
86
90
  return this.registry;
87
91
  }
88
92
  setConcurrency(config) {
89
- this.registry.setConcurrency(config);
93
+ this.pools.setConcurrency(config);
90
94
  }
91
95
  setOnComplete(cb) {
92
96
  this.onComplete = cb;
@@ -104,8 +108,19 @@ export class AgentManager {
104
108
  spawn(pi, ctx, type, prompt, options) {
105
109
  // The caller mints the id, so it matches the branch/worktree/herdr suffix.
106
110
  const id = options.spawnId;
107
- const args = { pi, ctx, type, prompt, options };
108
- const admission = this.registry.admitSpawn(options.modelSelection?.key, {
111
+ // Resolve the harness once, on the spawn path: the pool identity, a queued
112
+ // drain, a revived turn, and the launch plan all read this one value. The
113
+ // caller's validated `harness_type` wins over the template/config chain.
114
+ const { requestedHarness, ...rest } = options;
115
+ const resolvedOptions = {
116
+ ...rest,
117
+ harness: resolveHarnessType(type, requestedHarness),
118
+ };
119
+ const args = { pi, ctx, type, prompt, options: resolvedOptions };
120
+ const admission = this.pools.admitSpawn({
121
+ harness: resolvedOptions.harness,
122
+ modelKey: resolvedOptions.modelSelection?.key,
123
+ }, {
109
124
  id,
110
125
  start: (reservation) => this.startSession(id, args, reservation),
111
126
  });
@@ -117,18 +132,18 @@ export class AgentManager {
117
132
  args,
118
133
  deps: {
119
134
  transport: this.transport,
120
- slots: this.registry,
135
+ pools: this.pools,
121
136
  onRunEnded: (spawn) => this.notifyComplete(spawn),
122
137
  onFollowUpResult: (spawn, deliverable) => this.notifyFollowUp(spawn, deliverable),
123
138
  },
124
139
  });
125
140
  }
126
141
  catch (err) {
127
- void this.registry.release(id);
142
+ this.pools.release(id);
128
143
  throw err;
129
144
  }
130
145
  this.sessions.set(id, session);
131
- if (options.signal?.aborted) {
146
+ if (resolvedOptions.signal?.aborted) {
132
147
  void session.abort("user");
133
148
  return id;
134
149
  }
@@ -139,7 +154,7 @@ export class AgentManager {
139
154
  }
140
155
  catch (err) {
141
156
  session.rollbackStart();
142
- void this.registry.release(id);
157
+ this.pools.release(id);
143
158
  this.sessions.delete(id);
144
159
  // A start that never happened leaves no spawn: an orphan would trip dedup on retry.
145
160
  getAgentSpawns().drop(id);
@@ -222,6 +237,29 @@ export class AgentManager {
222
237
  // while it runs; a second removal of the same checkout would race the first.
223
238
  if (this.teardowns.has(id))
224
239
  return { kind: "refused", reason: "in-flight" };
240
+ // Claimed in the same turn as the check: the invoked removal runs only
241
+ // its synchronous prefix and returns a pending promise, so a clear
242
+ // arriving while one runs still reads the claim instead of duplicating it.
243
+ const removal = this.runClearRemoval(spawn);
244
+ this.teardowns.set(id, removal);
245
+ try {
246
+ return await removal;
247
+ }
248
+ finally {
249
+ // A cleanup may have queued behind this removal and taken the id over.
250
+ if (this.teardowns.get(id) === removal)
251
+ this.teardowns.delete(id);
252
+ }
253
+ }
254
+ /**
255
+ * One clear's work, in order: the harness's state leaves the checkout
256
+ * before the removal path probes or removes anything (see cleanupAgent's
257
+ * teardown), then the owned checkout goes.
258
+ */
259
+ async runClearRemoval(spawn) {
260
+ if (spawn.execution.harness !== undefined) {
261
+ await this.teardownHarnessState(spawn);
262
+ }
225
263
  const address = removalAddressFor(spawn);
226
264
  if (address.kind === "none") {
227
265
  this.dropSpawn(spawn);
@@ -235,16 +273,7 @@ export class AgentManager {
235
273
  this.recordRetention(spawn, reason);
236
274
  return { kind: "kept", path: address.path, reason };
237
275
  }
238
- const removal = this.runRemoval(spawn, address.target);
239
- this.teardowns.set(id, removal);
240
- try {
241
- return await removal;
242
- }
243
- finally {
244
- // A cleanup may have queued behind this removal and taken the id over.
245
- if (this.teardowns.get(id) === removal)
246
- this.teardowns.delete(id);
247
- }
276
+ return this.runRemoval(spawn, address.target);
248
277
  }
249
278
  /** Tear one owned checkout down and settle the spawn on what it did. */
250
279
  async runRemoval(spawn, target) {
@@ -314,6 +343,33 @@ export class AgentManager {
314
343
  lifecycle.worktreeRetentionReason = reason;
315
344
  }
316
345
  }
346
+ /**
347
+ * Tear down the harness recorded at launch — never a re-resolution: the
348
+ * harness that prepared the pane is the one that undoes its state.
349
+ * Best-effort and ordered before the dirty probe — see Harness.teardown.
350
+ */
351
+ async teardownHarnessState(spawn) {
352
+ const harnessId = spawn.execution.harness;
353
+ if (harnessId === undefined)
354
+ return;
355
+ try {
356
+ await harnessFor(harnessId).teardown({
357
+ pi: getPiInstance(),
358
+ paneId: spawn.execution.host?.paneId ?? null,
359
+ cwd: spawn.display.worktree?.kind === "owned"
360
+ ? spawn.display.worktree.path
361
+ : null,
362
+ subagentId: spawn.id,
363
+ });
364
+ }
365
+ catch (error) {
366
+ log.warn("harness teardown failed before worktree removal", {
367
+ spawnId: spawn.id,
368
+ harness: harnessId,
369
+ error: errorMessage(error),
370
+ });
371
+ }
372
+ }
317
373
  /**
318
374
  * Drop runtime session and store entry for good, and with them the run's
319
375
  * staging directory. The removal is keyed on the id, not the session: a
@@ -366,7 +422,7 @@ export class AgentManager {
366
422
  * spawns must stay cleanable and untracked live ones stay visible.
367
423
  */
368
424
  dispose() {
369
- this.registry.clearQueue();
425
+ this.pools.clearQueue();
370
426
  for (const session of this.sessions.values())
371
427
  session.settleForDispose();
372
428
  this.sessions.clear();