pi-cowboy 0.5.0 → 0.9.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.
Files changed (71) hide show
  1. package/README.md +26 -18
  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 +65 -127
  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 +4 -1
  39. package/dist/infrastructure/git/cow-clone.js +9 -1
  40. package/dist/infrastructure/herdr/agents.js +9 -8
  41. package/dist/infrastructure/herdr-host.js +3 -2
  42. package/dist/models/foreign-model-resolver.js +55 -0
  43. package/dist/models/model-groups.js +3 -1
  44. package/dist/models/model-precedence.js +35 -8
  45. package/dist/models/model-request-types.js +46 -0
  46. package/dist/models/model-request.js +32 -101
  47. package/dist/models/pi-model-resolver.js +88 -0
  48. package/dist/orchestrators/default-orchestrators.js +1 -1
  49. package/dist/orchestrators/protocol.js +29 -10
  50. package/dist/prompt/subagent-system-prompt.js +10 -3
  51. package/dist/registration.js +16 -18
  52. package/dist/spawn/sandbox.js +3 -0
  53. package/dist/subagent/deliverable.js +4 -3
  54. package/dist/subagent/supervisor.js +5 -3
  55. package/dist/task-registry.js +12 -158
  56. package/dist/types.js +1 -1
  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-agent-status.js +8 -82
  61. package/dist/ui/menu/menu-concurrency.js +282 -101
  62. package/dist/ui/menu/menu-model-settings.js +114 -30
  63. package/dist/ui/menu/menu-spawn-defaults.js +4 -2
  64. package/dist/ui/menu/menu-spawn-wizard.js +11 -7
  65. package/dist/ui/menu/menus.js +10 -10
  66. package/dist/ui/menu/model-picker.js +37 -21
  67. package/dist/ui/menu/submenus/model-select.js +4 -7
  68. package/dist/ui/menu/submenus/numeric-input.js +2 -2
  69. package/dist/utils.js +10 -0
  70. package/package.json +5 -2
  71. package/orchestrators/with-code-review.toml +0 -20
package/README.md CHANGED
@@ -10,8 +10,10 @@ 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. Do you need support for something else? Create an issue on [Github](https://github.com/electric-dragon-80000v/pi-cowboy/issues/new).
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
- 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.
16
+ The numbers below are from a Git repository containing 153,607 files in total. The tracked files occupy 479 MiB, while the repository is 27 GiB in total, including untracked files.
15
17
 
16
18
  | Method | Including untracked | Size on disk |
17
19
  | ------------------------------ | ------------------- | ------------ |
@@ -71,9 +73,9 @@ 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 — 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.
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. pi-cowboy needs a git repository because each agent works in a worktree of it; outside a repository 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
- The agents work in separate git worktrees placed under `$HOME/.pi/agent/pi-cowboy/worktrees/`.
78
+ The agents work in separate git worktrees placed under `<agent dir>/pi-cowboy/worktrees/` (`~/.pi/agent` by default).
77
79
 
78
80
  ##### Agent completion
79
81
 
@@ -135,7 +137,7 @@ If pi-cowboy cannot remove one of them, it reports the failure and completes the
135
137
 
136
138
  <code>/cowboy enable                  # Enables pi-cowboy</code><br>
137
139
 
138
- <code>/cowboy disable.                # Disables pi-cowboy</code>
140
+ <code>/cowboy disable # Disables pi-cowboy</code>
139
141
 
140
142
  ## Tools
141
143
 
@@ -150,17 +152,18 @@ Delegates one or more tasks to cowboy agents. Each cowboy agent runs in its own
150
152
 
151
153
  `agents[]`:
152
154
 
153
- | Field | Required | Description |
154
- | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
155
- | `prompt` | yes | Task instructions for the cowboy agent. |
156
- | `task_name` | yes | Short 2-3-word name (e.g. "fix login flow") that names the agent's branch, worktree, and tab. |
157
- | `agent_type` | no | Agent type to use. Defaults to the type set at `/cowboy` > `Agent`. |
158
- | `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. |
159
162
 
160
163
  ### `steer_cowboy_agent`
161
164
 
162
165
  Sends a message to one or more agents. `steer_cowboy_agent` revives a settled agent for another turn: the same agent in its pane picks the message up, and you get another completion message when it settles again.
163
- A queued agent cannot be steered — it has no pane yet. Neither can an agent whose pane is gone (cleaned up), whose id is unknown, or that is being cleaned up.
166
+ A queued agent cannot be steered, because it has no pane yet. Neither can an agent whose pane is gone (cleaned up), whose id is unknown, or that is being cleaned up.
164
167
 
165
168
  | Parameter | Required | Description |
166
169
  | ------------- | -------- | ------------------------------------- |
@@ -198,17 +201,18 @@ A removal that fails does not throw. The branch is removed only after you have m
198
201
 
199
202
  ## Model resolution
200
203
 
201
- 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).
202
205
 
203
206
  ## Concurrency
204
207
 
205
208
  A running agent holds a place in every concurrency limit that applies to it. pi-cowboy releases those places when the agent settles, then the next queued agent starts. You can define concurrency limits as follows:
206
209
 
207
- - **Per-model** — `concurrency.models["<provider>/<model-id>"]`
208
- - **Per-provider** — `concurrency.providers.<provider>`
209
- - **Global** — `concurrency.default` (default `4`), which every agent counts against
210
+ - Per model: `concurrency.models["<provider>/<model-id>"]`
211
+ - Per provider: `concurrency.providers.<provider>`
212
+ - Per harness: `concurrency.harnesses.<harness-id>`
213
+ - Global: `concurrency.default` (default `4`), which every agent counts against
210
214
 
211
- 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.
212
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.
213
217
 
214
218
  An agent with no model selection counts against the global limit alone.
@@ -260,11 +264,15 @@ You can switch orchestrators during a session at `/cowboy` > `Default orchestrat
260
264
 
261
265
  Orchestrator templates also allow you to customize how the agent communicates with the orchestrator. See [Orchestrator Templates](docs/Orchestrator%20Templates.md) for more details.
262
266
 
267
+ ### Foreign harnesses
268
+
269
+ pi-cowboy can also orchestrate Codex, Claude Code, and OpenCode. It auto-detects them, so you can reference them directly (e.g., "Launch an OpenCode agent for this task") or configure them as defaults in your [settings](docs/Configuration.md#agentharnesstype) and [agent templates](docs/Agent%20Templates.md).
270
+
263
271
  ## FAQ
264
272
 
265
273
  ### Why is my agent queued, not running?
266
274
 
267
- 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).
275
+ 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).
268
276
 
269
277
  ### Why did my worktree survive cleanup?
270
278
 
@@ -278,7 +286,7 @@ To avoid the overhead, pi-cowboy has support for [pig](https://github.com/Michae
278
286
 
279
287
  ### I don't like the emojis, can I turn them off?
280
288
 
281
- 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).
289
+ Yes. You can disable both the cowboy and the grazing in settings. See [Configuration](docs/Configuration.md).
282
290
 
283
291
  ## References
284
292
 
@@ -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,
@@ -1,60 +1,46 @@
1
1
  /**
2
2
  * agent-manager.ts — Fleet controller for independently running subagents.
3
- * Exports AgentManager, ClearOutcome/ClearRefusal; re-exports spawn and steer
4
- * types.
3
+ * Exports AgentManager; re-exports spawn and steer types.
5
4
  */
6
5
  import { getAgentSpawns, getCoordinatorOrNull, getPiInstance, getSessionCtx, } from "../shell.js";
7
6
  import { subagentResultFileFor } from "../paths.js";
8
7
  import { createHerdrRuntime } from "../infrastructure/herdr-host.js";
9
- import { HerdrTaskRegistry, } from "../task-registry.js";
8
+ import { HerdrTaskRegistry } from "../task-registry.js";
10
9
  import { createLogger } from "../logger.js";
11
10
  import { errorMessage } from "../utils.js";
12
- import { ACTIVE_AGENT_PHASES, ALL_AGENT_PHASES, hasOutcome, lifecycleStartTime, lifecycleStatus, } from "../types.js";
11
+ import { ACTIVE_AGENT_PHASES, ALL_AGENT_PHASES, hasOutcome, lifecycleStartTime, } from "../types.js";
13
12
  import { FileDeliverable } from "../subagent/deliverable.js";
14
13
  import { removeResultArtifacts } from "../subagent/result-artifacts.js";
15
14
  import { createCleanup } from "./agent-cleanup.js";
16
15
  import { createHerdrAgentAssets, } from "./agent-assets.js";
17
16
  import { DISPOSE_QUEUED_MESSAGE, SubagentSession, } from "./subagent-session.js";
17
+ import { resolveHarnessType } from "./spawn-defaults.js";
18
18
  /** The transport the manager wires its sessions with unless the caller supplies one. */
19
19
  export const defaultAgentManagerTransport = {
20
20
  createHost: (pi) => createHerdrRuntime(pi).host,
21
21
  createDeliverable: (resultFile) => new FileDeliverable(resultFile),
22
22
  };
23
+ const log = createLogger("manager");
23
24
  /**
24
- * Removal address for a spawn's owned checkout. An owned checkout that no
25
- * recorded repository cwd can reach is `unaddressable`: its teardown has no
26
- * place to run, which is not the same as having none left to remove.
25
+ * The keep reason a cleanup report carries for a spawn that stays listed. A
26
+ * refusal for a live or contested run names no worktree state, so only a
27
+ * dirty or unverifiable reason is recordable; an unconfirmed removal is
28
+ * recorded as unverifiable with the removal's detail.
27
29
  */
28
- function removalAddressFor(spawn) {
29
- const worktree = spawn.display.worktree;
30
- if (worktree?.kind !== "owned")
31
- return { kind: "none" };
32
- const repoCwd = spawn.execution.spawnCtx?.cwd;
33
- if (!repoCwd)
34
- return { kind: "unaddressable", path: worktree.path };
35
- const target = {
36
- workspaceId: spawn.execution.host?.workspaceId,
37
- worktreePath: worktree.path,
38
- repoCwd,
39
- branchName: worktree.branch,
40
- };
41
- const host = spawn.execution.host;
42
- return {
43
- kind: "owned",
44
- target: host === undefined
45
- ? { kind: "detached", worktree: target, pane: null }
46
- : {
47
- kind: "adopted",
48
- worktree: { ...target, workspaceId: host.workspaceId },
49
- pane: null,
50
- ref: host,
51
- },
52
- };
53
- }
54
- const log = createLogger("manager");
55
- function isTerminal(spawn) {
56
- const status = lifecycleStatus(spawn.lifecycle);
57
- return status !== "spawned" && status !== "queued";
30
+ function retentionForReport(report) {
31
+ if (report.outcome.kind === "refused") {
32
+ const reason = report.outcome.reason;
33
+ return reason.kind === "dirty" || reason.kind === "unverifiable"
34
+ ? reason
35
+ : undefined;
36
+ }
37
+ if (report.worktree.kind === "removal-failed") {
38
+ return {
39
+ kind: "unverifiable",
40
+ detail: `the removal was not confirmed (${report.worktree.detail})`,
41
+ };
42
+ }
43
+ return undefined;
58
44
  }
59
45
  /** Fleet controller; each session owns exactly one lifecycle. */
60
46
  export class AgentManager {
@@ -65,28 +51,30 @@ export class AgentManager {
65
51
  onFollowUp;
66
52
  /**
67
53
  * Teardowns in flight, by agent id. One teardown owns an id's artifacts at a
68
- * time: a clear that arrives during one is refused, and a cleanup waits for
69
- * the running one instead of racing it for the same checkout.
54
+ * time: a cleanup that arrives while one runs waits for it instead of racing
55
+ * it for the same checkout.
70
56
  */
71
57
  teardowns = new Map();
58
+ /** The resource limiter the fleet drives directly; sessions charge their capacity to it. */
59
+ pools;
60
+ /** Task identity and admission serialization; pool accounting lives in `pools`. */
72
61
  registry;
73
- constructor(onComplete, concurrency, registry, transport = defaultAgentManagerTransport) {
62
+ constructor(pools, transport = defaultAgentManagerTransport) {
74
63
  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);
64
+ this.pools = pools;
65
+ this.registry = new HerdrTaskRegistry({
66
+ listAgents: () => this.listAgents(ACTIVE_AGENT_PHASES),
67
+ spawn: (type, prompt, options) => this.spawn(getPiInstance(), getSessionCtx(), type, prompt, options),
68
+ getSpawn: (id) => this.getSpawn(id),
69
+ findTaskAttempts: (taskSlug) => this.transport.createHost(getPiInstance()).findAttempts(taskSlug),
70
+ queuePosition: (id) => this.pools.queuePosition(id),
71
+ });
84
72
  }
85
73
  getRegistry() {
86
74
  return this.registry;
87
75
  }
88
76
  setConcurrency(config) {
89
- this.registry.setConcurrency(config);
77
+ this.pools.setConcurrency(config);
90
78
  }
91
79
  setOnComplete(cb) {
92
80
  this.onComplete = cb;
@@ -104,8 +92,19 @@ export class AgentManager {
104
92
  spawn(pi, ctx, type, prompt, options) {
105
93
  // The caller mints the id, so it matches the branch/worktree/herdr suffix.
106
94
  const id = options.spawnId;
107
- const args = { pi, ctx, type, prompt, options };
108
- const admission = this.registry.admitSpawn(options.modelSelection?.key, {
95
+ // Resolve the harness once, on the spawn path: the pool identity, a queued
96
+ // drain, a revived turn, and the launch plan all read this one value. The
97
+ // caller's validated `harness_type` wins over the template/config chain.
98
+ const { requestedHarness, ...rest } = options;
99
+ const resolvedOptions = {
100
+ ...rest,
101
+ harness: resolveHarnessType(type, requestedHarness),
102
+ };
103
+ const args = { pi, ctx, type, prompt, options: resolvedOptions };
104
+ const admission = this.pools.admitSpawn({
105
+ harness: resolvedOptions.harness,
106
+ modelKey: resolvedOptions.modelSelection?.key,
107
+ }, {
109
108
  id,
110
109
  start: (reservation) => this.startSession(id, args, reservation),
111
110
  });
@@ -117,18 +116,18 @@ export class AgentManager {
117
116
  args,
118
117
  deps: {
119
118
  transport: this.transport,
120
- slots: this.registry,
119
+ pools: this.pools,
121
120
  onRunEnded: (spawn) => this.notifyComplete(spawn),
122
121
  onFollowUpResult: (spawn, deliverable) => this.notifyFollowUp(spawn, deliverable),
123
122
  },
124
123
  });
125
124
  }
126
125
  catch (err) {
127
- void this.registry.release(id);
126
+ this.pools.release(id);
128
127
  throw err;
129
128
  }
130
129
  this.sessions.set(id, session);
131
- if (options.signal?.aborted) {
130
+ if (resolvedOptions.signal?.aborted) {
132
131
  void session.abort("user");
133
132
  return id;
134
133
  }
@@ -139,7 +138,7 @@ export class AgentManager {
139
138
  }
140
139
  catch (err) {
141
140
  session.rollbackStart();
142
- void this.registry.release(id);
141
+ this.pools.release(id);
143
142
  this.sessions.delete(id);
144
143
  // A start that never happened leaves no spawn: an orphan would trip dedup on retry.
145
144
  getAgentSpawns().drop(id);
@@ -205,75 +204,6 @@ export class AgentManager {
205
204
  .list(phases)
206
205
  .sort((a, b) => lifecycleStartTime(b.lifecycle) - lifecycleStartTime(a.lifecycle));
207
206
  }
208
- /**
209
- * Clear a terminal spawn: tear its owned checkout down first and drop the
210
- * spawn only once the removal is confirmed. A kept or failed removal leaves
211
- * the spawn listed, with the reason recorded, so the caller can report it and
212
- * the operator can retry it. Spawn-keyed so a spawn whose session is gone
213
- * stays clearable.
214
- */
215
- async clear(id) {
216
- const spawn = getAgentSpawns().get(id);
217
- if (!spawn)
218
- return { kind: "refused", reason: "unknown-id" };
219
- if (!isTerminal(spawn))
220
- return { kind: "refused", reason: "not-terminal" };
221
- // The first teardown's verdict is the answer for every clear that arrives
222
- // while it runs; a second removal of the same checkout would race the first.
223
- if (this.teardowns.has(id))
224
- return { kind: "refused", reason: "in-flight" };
225
- const address = removalAddressFor(spawn);
226
- if (address.kind === "none") {
227
- this.dropSpawn(spawn);
228
- return { kind: "cleared" };
229
- }
230
- if (address.kind === "unaddressable") {
231
- const reason = {
232
- kind: "unverifiable",
233
- detail: "the run recorded no repository cwd",
234
- };
235
- this.recordRetention(spawn, reason);
236
- return { kind: "kept", path: address.path, reason };
237
- }
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
- }
248
- }
249
- /** Tear one owned checkout down and settle the spawn on what it did. */
250
- async runRemoval(spawn, target) {
251
- const outcome = await createCleanup(this.assets()).removeWorktree(target);
252
- switch (outcome.kind) {
253
- case "removed":
254
- case "absent":
255
- this.dropSpawn(spawn);
256
- return { kind: "cleared" };
257
- case "kept":
258
- this.recordRetention(spawn, outcome.reason);
259
- return { kind: "kept", path: outcome.path, reason: outcome.reason };
260
- case "removal-failed":
261
- this.recordRetention(spawn, {
262
- kind: "unverifiable",
263
- detail: `the removal was not confirmed (${outcome.detail})`,
264
- });
265
- log.warn("worktree removal failed after clear", {
266
- spawnId: spawn.id,
267
- path: outcome.path,
268
- detail: outcome.detail,
269
- });
270
- return {
271
- kind: "removal-failed",
272
- path: outcome.path,
273
- detail: outcome.detail,
274
- };
275
- }
276
- }
277
207
  async abort(id, initiator) {
278
208
  return (await this.sessions.get(id)?.abort(initiator)) ?? false;
279
209
  }
@@ -309,7 +239,7 @@ export class AgentManager {
309
239
  */
310
240
  recordRetention(spawn, reason) {
311
241
  const lifecycle = spawn.lifecycle;
312
- // Clear takes only an ended spawn, so the ended phases can carry the reason.
242
+ // The reason lives on the ended phases; an active spawn records none.
313
243
  if (hasOutcome(lifecycle)) {
314
244
  lifecycle.worktreeRetentionReason = reason;
315
245
  }
@@ -352,6 +282,14 @@ export class AgentManager {
352
282
  getSpawn: (rid) => this.getSpawn(rid),
353
283
  dropSpawn: (spawn) => this.dropSpawn(spawn),
354
284
  }, opts);
285
+ // A spawn the teardown kept stays listed with the reason its checkout
286
+ // survived; a dropped spawn has no record left to annotate.
287
+ const kept = this.getSpawn(id);
288
+ if (kept !== undefined) {
289
+ const retention = retentionForReport(report);
290
+ if (retention !== undefined)
291
+ this.recordRetention(kept, retention);
292
+ }
355
293
  // A teardown that finished the run takes the staging directory with it even
356
294
  // when its spawn is kept (a failed or unconfirmed removal): the artifacts
357
295
  // are ephemeral, and a later retry does not read them. A refusal removed
@@ -366,7 +304,7 @@ export class AgentManager {
366
304
  * spawns must stay cleanable and untracked live ones stay visible.
367
305
  */
368
306
  dispose() {
369
- this.registry.clearQueue();
307
+ this.pools.clearQueue();
370
308
  for (const session of this.sessions.values())
371
309
  session.settleForDispose();
372
310
  this.sessions.clear();