pi-cowboy 0.0.0-stage → 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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -2
  3. package/agents/explore.toml +40 -0
  4. package/dist/agents/agent-assets.js +261 -0
  5. package/dist/agents/agent-cleanup.js +284 -0
  6. package/dist/agents/agent-discovery.js +108 -0
  7. package/dist/agents/agent-host.js +10 -0
  8. package/dist/agents/agent-manager.js +367 -0
  9. package/dist/agents/agent-reviver.js +64 -0
  10. package/dist/agents/agent-runner.js +289 -0
  11. package/dist/agents/agent-spawn-store.js +57 -0
  12. package/dist/agents/agent-template.js +46 -0
  13. package/dist/agents/agent-types.js +144 -0
  14. package/dist/agents/batch.js +92 -0
  15. package/dist/agents/cleanup-policy.js +194 -0
  16. package/dist/agents/cleanup-report.js +128 -0
  17. package/dist/agents/default-agents.js +19 -0
  18. package/dist/agents/harness/pi-bolt.js +15 -0
  19. package/dist/agents/harness/pi-compatible.js +68 -0
  20. package/dist/agents/harness/pig.js +16 -0
  21. package/dist/agents/harness/registry.js +27 -0
  22. package/dist/agents/harness.js +32 -0
  23. package/dist/agents/result-file-permissions.js +29 -0
  24. package/dist/agents/run-state.js +270 -0
  25. package/dist/agents/schemas/cleanup-batch.schema.js +19 -0
  26. package/dist/agents/schemas/cowboy-agents.schema.js +39 -0
  27. package/dist/agents/schemas/merge-batch.schema.js +25 -0
  28. package/dist/agents/schemas/steer-batch.schema.js +22 -0
  29. package/dist/agents/schemas/stop-batch.schema.js +18 -0
  30. package/dist/agents/spawn-defaults.js +70 -0
  31. package/dist/agents/subagent-session.js +601 -0
  32. package/dist/agents/tool-cleanup.js +57 -0
  33. package/dist/agents/tool-execution.js +125 -0
  34. package/dist/agents/tool-merge.js +190 -0
  35. package/dist/agents/tool-result.js +17 -0
  36. package/dist/agents/tool-steer.js +89 -0
  37. package/dist/agents/types.js +1 -0
  38. package/dist/availability.js +38 -0
  39. package/dist/config/config-io.js +261 -0
  40. package/dist/config/config-store.js +321 -0
  41. package/dist/config/config-validation.js +173 -0
  42. package/dist/config/layered-config.js +117 -0
  43. package/dist/config/types.js +23 -0
  44. package/dist/cow-support-launch.js +43 -0
  45. package/dist/events.js +146 -0
  46. package/dist/extension-toggle.js +28 -0
  47. package/dist/harness-availability-launch.js +23 -0
  48. package/dist/index.js +52 -0
  49. package/dist/infrastructure/exec-path.js +35 -0
  50. package/dist/infrastructure/git/cow-clone.js +398 -0
  51. package/dist/infrastructure/git/git-materializer.js +342 -0
  52. package/dist/infrastructure/git/git-merger.js +234 -0
  53. package/dist/infrastructure/git/git-retention.js +43 -0
  54. package/dist/infrastructure/git/git-runner.js +145 -0
  55. package/dist/infrastructure/git/git-worktree.js +143 -0
  56. package/dist/infrastructure/git/index.js +11 -0
  57. package/dist/infrastructure/git-client.js +11 -0
  58. package/dist/infrastructure/herdr/agent-stopper.js +60 -0
  59. package/dist/infrastructure/herdr/agents.js +329 -0
  60. package/dist/infrastructure/herdr/herdr-client.js +36 -0
  61. package/dist/infrastructure/herdr/herdr-transport.js +158 -0
  62. package/dist/infrastructure/herdr/index.js +15 -0
  63. package/dist/infrastructure/herdr/panes.js +174 -0
  64. package/dist/infrastructure/herdr/polling.js +44 -0
  65. package/dist/infrastructure/herdr/worktrees.js +76 -0
  66. package/dist/infrastructure/herdr-client.js +6 -0
  67. package/dist/infrastructure/herdr-host.js +163 -0
  68. package/dist/logger.js +79 -0
  69. package/dist/models/model-groups.js +72 -0
  70. package/dist/models/model-precedence.js +50 -0
  71. package/dist/models/model-request.js +108 -0
  72. package/dist/orchestrators/briefing-section.js +14 -0
  73. package/dist/orchestrators/context.js +116 -0
  74. package/dist/orchestrators/cues.js +90 -0
  75. package/dist/orchestrators/default-orchestrators.js +36 -0
  76. package/dist/orchestrators/orchestrator-discovery.js +68 -0
  77. package/dist/orchestrators/orchestrator-template.js +43 -0
  78. package/dist/orchestrators/orchestrator-types.js +78 -0
  79. package/dist/orchestrators/protocol.js +292 -0
  80. package/dist/orchestrators/types.js +7 -0
  81. package/dist/paths.js +66 -0
  82. package/dist/pi-settings.js +7 -0
  83. package/dist/predicates.js +25 -0
  84. package/dist/prompt/prompts.js +111 -0
  85. package/dist/prompt/skill-loader.js +154 -0
  86. package/dist/prompt/subagent-system-prompt.js +174 -0
  87. package/dist/registration.js +220 -0
  88. package/dist/shell.js +225 -0
  89. package/dist/spawn/cow-support.js +53 -0
  90. package/dist/spawn/herdr-launcher.js +80 -0
  91. package/dist/spawn/repo-lock.js +34 -0
  92. package/dist/spawn/sandbox.js +286 -0
  93. package/dist/spawn/spawn-coordinator.js +255 -0
  94. package/dist/spawn/spawn-id.js +39 -0
  95. package/dist/spawn/worktree-policy.js +137 -0
  96. package/dist/status-note.js +30 -0
  97. package/dist/subagent/ipc-protocol.js +68 -0
  98. package/dist/subagent/ipc.js +110 -0
  99. package/dist/subagent/pane-supervisor.js +24 -0
  100. package/dist/subagent/socket-ipc.js +240 -0
  101. package/dist/subagent/supervisor.js +315 -0
  102. package/dist/task-registry.js +258 -0
  103. package/dist/templates/template-files.js +84 -0
  104. package/dist/types.js +84 -0
  105. package/dist/ui/action-report.js +21 -0
  106. package/dist/ui/format.js +47 -0
  107. package/dist/ui/indicator.js +480 -0
  108. package/dist/ui/menu/helpers.js +227 -0
  109. package/dist/ui/menu/menu-agent-settings.js +182 -0
  110. package/dist/ui/menu/menu-agent-status.js +444 -0
  111. package/dist/ui/menu/menu-concurrency.js +226 -0
  112. package/dist/ui/menu/menu-model-settings.js +244 -0
  113. package/dist/ui/menu/menu-spawn-defaults.js +71 -0
  114. package/dist/ui/menu/menu-spawn-wizard.js +367 -0
  115. package/dist/ui/menu/menu-spawn-worktree.js +107 -0
  116. package/dist/ui/menu/menu-system-prompt.js +104 -0
  117. package/dist/ui/menu/menu-worktree-command.js +150 -0
  118. package/dist/ui/menu/menus.js +187 -0
  119. package/dist/ui/menu/model-picker.js +161 -0
  120. package/dist/ui/menu/screen-host.js +87 -0
  121. package/dist/ui/menu/submenus/confirm.js +23 -0
  122. package/dist/ui/menu/submenus/model-select.js +42 -0
  123. package/dist/ui/menu/submenus/name-field.js +43 -0
  124. package/dist/ui/menu/submenus/numeric-input.js +61 -0
  125. package/dist/ui/menu/submenus/target-select.js +129 -0
  126. package/dist/ui/menu/submenus/text-editor.js +49 -0
  127. package/dist/ui/menu/submenus/worktree-command-name.js +73 -0
  128. package/dist/ui/menu/submenus/worktree-name.js +53 -0
  129. package/dist/ui/menu/wrappers/settings-list.js +101 -0
  130. package/dist/ui/searchable-select.js +147 -0
  131. package/dist/ui/types.js +1 -0
  132. package/dist/utils.js +70 -0
  133. package/docs/assets/grazing.png +0 -0
  134. package/docs/assets/herdr-containers.png +0 -0
  135. package/docs/assets/logo-transparent.png +0 -0
  136. package/orchestrators/with-code-review.toml +20 -0
  137. package/package.json +111 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 electric-dragon-80000v
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,282 @@
1
- # Temporary Holding Version
1
+ <img src="./docs/assets/logo-transparent.png" alt="logo" style="zoom:33%;" />
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ **License:** MIT
6
+
7
+ pi-cowboy is an agent orchestrator for [pi](https://pi.dev). It is designed for step-by-step task decomposition and supervision. It coordinates multiple agents in the background while keeping their work visible and actionable. Each agent gets a dedicated pi process and an isolated Herdr workspace backed by its own copy-on-write worktree. pi-cowboy creates those worktrees and cleans them up for you automatically.
8
+
9
+ ## Why should I use it?
10
+
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
+
13
+ - **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.
15
+
16
+ | Method | Including untracked | Size on disk |
17
+ | ------------------------------ | ------------------- | ------------ |
18
+ | Pi-cowboy's copy-on-write | yes | 75 MiB |
19
+ | Classic `git worktree add` | no | 479 MiB |
20
+ | Classic wt + copy of untracked | yes | 27 GiB |
21
+
22
+ - **Herdr integration:** Each task gets its own shell, a visible pane, and notifications when an agent needs your attention.
23
+
24
+ - **Custom workflows:** You can specify custom workflows via agent and orchestrator templates to fit your environment and working style.
25
+
26
+ - **Grazing cows and a cowboy on your screen**:
27
+
28
+ ![image-20260930022747492](./docs/assets/grazing.png)
29
+
30
+ Who wouldn’t want their agents visualized as cow emojis? Go on… guess. That's exactly right. No one.
31
+
32
+ ## Requirements
33
+
34
+ - Linux/macOS
35
+ - `herdr` 0.8 or later
36
+ - `herdr` pi integration
37
+ - macOS also needs `python3` for copy-on-write worktrees
38
+
39
+ - macOS has shipped no `python3` since 12.3. Install the Xcode Command Line Tools: `xcode-select --install`
40
+
41
+ - Copy-on-write capable filesystem (APFS on macOS, BTRFS, and ZFS on Linux)
42
+
43
+ - ext4 does not support CoW. If you use ext4, `agent.worktreeMaterialization` falls back to `checkout`.
44
+
45
+ ## Install
46
+
47
+ Install from npm:
48
+
49
+ <code>pi install npm:pi-cowboy</code>
50
+
51
+ ## Usage
52
+
53
+ ##### Delegating a task
54
+
55
+ <hr>
56
+ <code>Based on the security audit, group the relevant files into 10 groups, and launch parallel cowboy agents to address their audit results.</code>
57
+
58
+ <hr>
59
+
60
+ pi-cowboy spawns agents for the tasks in the background.
61
+
62
+ <code>✓ Spawned agent b7g2nspx (general-purpose)</code><br>
63
+ <code>✓ Spawned agent 5m1xx7fa (general-purpose)</code><br>
64
+ <code>...</code>
65
+
66
+ Depending on your concurrency settings, some of the tasks queue. The default global concurrency is 4, so 6 of them queue and start as soon as a spot opens.
67
+
68
+ ##### Agent isolation
69
+
70
+ ![herdr-containers](./docs/assets/herdr-containers.png)
71
+
72
+ 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
+
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.
75
+
76
+ The agents work in separate git worktrees placed under `$HOME/.pi/agent/pi-cowboy/worktrees/`.
77
+
78
+ ##### Agent completion
79
+
80
+ When an agent settles, its result arrives in the parent session that started it:
81
+
82
+ <code>✓ [Cowboy agent "general-purpose" b7g2nspx completed]</code><br>
83
+ <br>
84
+ <code>Addressed all the points raised in the security audit for the given set of files.</code><br>
85
+ <br>
86
+ <code>(Worktree: $HOME/.pi/agent/pi-cowboy/worktrees/cow-audit-perms-b7g2nspx (branch cow-audit-perms-b7g2nspx). The agent process and its herdr pane stay until you call cleanup_cowboy_agent — its pane is closed, which ends that process. The worktree stays until you call cleanup_cowboy_agent to remove it — call it once the branch is merged or rejected.)</code>
87
+
88
+ The orchestrator then follows your instructions and the agent's report.
89
+
90
+ ##### Merging
91
+
92
+ pi-cowboy calls the `merge_cowboy_branch` tool, which merges the branch in your repository's main working tree:
93
+
94
+ <code>✓ Merged "cow-audit-perms-b7g2nspx" into "main" in pi-mono.</code>
95
+
96
+ ##### Cleanup
97
+
98
+ The orchestrator cleans up the branches after merging when your instructions call for it. If it has not, tell it to clean up.
99
+
100
+ <hr>
101
+ <code>Clean up perms audit agent.</code>
102
+
103
+ <hr>
104
+
105
+ Clean up comes last. The tool refuses an agent that is still running, removes a branch only once you have merged it, and keeps any worktree that still holds uncommitted changes.
106
+
107
+ pi-cowboy calls the `cleanup_cowboy_agent` tool, which removes the agent's artifacts and reports the results:
108
+
109
+ <code>✓ Cleaned up agent b7g2nspx:</code><br>
110
+ <code>agent status: completed</code><br>
111
+ <code>pane: closed</code><br>
112
+ <code>worktree: removed ($HOME/.pi/agent/pi-cowboy/worktrees/cow-audit-perms-b7g2nspx)</code><br>
113
+ <code>branch: deleted (cow-audit-perms-b7g2nspx)</code>
114
+
115
+ The `cleanup_cowboy_agent` tool removes the pane, its tab, the worktree, and the branch.
116
+ If pi-cowboy cannot remove one of them, it reports the failure and completes the removals it can.
117
+
118
+ ## Commands
119
+
120
+ `/cowboy` opens a menu. See [Menu](docs/Menu.md).
121
+
122
+ <code>/cowboy                         # pi-cowboy menu</code><br>
123
+ <code>/cowboy status                  # List spawned, queued, and settled agents</code><br>
124
+ <code>/cowboy spawn                   # Spawn an agent manually</code><br>
125
+ <code>/cowboy worktree                # Create a git worktree with no agent attached</code><br>
126
+ <code>/cowboy model                   # Model selection for the agents</code><br>
127
+ <code>/cowboy model provider/model-id # Set the model for this session</code><br>
128
+ <code>/cowboy model clear             # Clear the model set for this session</code><br>
129
+ <code>/cowboy enable                  # Enables pi-cowboy</code><br>
130
+ <code>/cowboy disable.                # Disables pi-cowboy</code>
131
+
132
+ ## Tools
133
+
134
+ ### `cowboy_agent`
135
+
136
+ Delegates one or more tasks to cowboy agents. Each cowboy agent runs in its own pi process and works in its own branch. The call returns immediately, one agent ID per task. Results arrive as a message as each agent settles.
137
+
138
+ | Parameter | Required | Description |
139
+ | ------------------- | -------- | ------------------------------------------------------------------------------------------------ |
140
+ | `agents[]` | yes | One object per task. |
141
+ | `run_in_background` | no | Set to `false` to wait for the result in the same turn. Only allowed when `agents` has one task. |
142
+
143
+ `agents[]`:
144
+
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). |
151
+
152
+ ### `steer_cowboy_agent`
153
+
154
+ 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.
155
+ 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.
156
+
157
+ | Parameter | Required | Description |
158
+ | ------------- | -------- | ------------------------------------- |
159
+ | `agent_ids[]` | yes | Agent ids to send the message to. |
160
+ | `message` | yes | The message to deliver to each agent. |
161
+
162
+ ### `stop_cowboy_agent`
163
+
164
+ Stops one or more running agents. The agent's worktree and branch are preserved.
165
+
166
+ | Parameter | Required | Description |
167
+ | ------------- | -------- | ------------------ |
168
+ | `agent_ids[]` | yes | Agent ids to stop. |
169
+
170
+ ### `merge_cowboy_branch`
171
+
172
+ Merges one or more settled agent branches into a target branch in your repository's main working tree. A merge conflict stays in place for you to resolve. The main working tree must be on the target branch and have no uncommitted changes.
173
+
174
+ | Parameter | Required | Description |
175
+ | ------------ | -------- | ------------------------------------------------------------------------------- |
176
+ | `branches[]` | yes | The `cow-<task>-<id>` branches from the agent results. |
177
+ | `target` | no | Branch to merge into. Defaults to `main`. |
178
+ | `repo` | no | Path inside the repository. Defaults to the parent session's working directory. |
179
+
180
+ ### `cleanup_cowboy_agent`
181
+
182
+ Removes the pane, its tab, the worktree, and the branch of one or more settled agents.
183
+ The tool reports the result for each agent.
184
+
185
+ A removal that fails does not throw. The branch is removed only after you have merged it, and a worktree with uncommitted changes is kept and reported instead of removed.
186
+
187
+ | Parameter | Required | Description |
188
+ | ------------- | -------- | ------------------------------------------------------------------------------------- |
189
+ | `agent_ids[]` | yes | Agent ids to clean up. `cleanup_cowboy_agent` refuses an agent that is still running. |
190
+
191
+ ## Model resolution
192
+
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).
194
+
195
+ ## Concurrency
196
+
197
+ 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:
198
+
199
+ - **Per-model** — `concurrency.models["<provider>/<model-id>"]`
200
+ - **Per-provider** — `concurrency.providers.<provider>`
201
+ - **Global** — `concurrency.default` (default `4`), which every agent counts against
202
+
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.
204
+ 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
+
206
+ An agent with no model selection counts against the global limit alone.
207
+
208
+ pi-cowboy floors limits at one, so `0` and a negative number both mean one at a time. See [Configuration](docs/Configuration.md#concurrency).
209
+
210
+ A steered agent that settled and starts again is a second live process. It counts against its limits at once, even when it then exceeds a limit. The message is already in the pane of that agent, so its second turn cannot wait for room.
211
+
212
+ These settings can be configured via the configuration file or via the menu `/cowboy` > `Settings` > `Concurrency Settings`.
213
+
214
+ ## Agent templates
215
+
216
+ You can define custom agent templates for tasks that keep coming back and would otherwise make you repeat the same instructions.
217
+
218
+ As an example, a release notes template may look like this:
219
+
220
+ ```toml
221
+ name = "release-notes"
222
+ description = "Prepares release notes."
223
+ system_prompt = '''
224
+ You prepare release notes for this repository. Read the history and tags
225
+ (git log, git tag) and report the changes as a message.
226
+ '''
227
+ ```
228
+
229
+ You can then refer to this in the parent session to trigger it:
230
+
231
+ <hr>
232
+ <code>> Spawn a cowboy agent using release notes template to prepare the release notes for the most recent changes.</code>
233
+
234
+ <hr>
235
+
236
+ Agent templates have more configuration options. See [Agent Templates](docs/Agent%20Templates.md) for the full list.
237
+
238
+ ## Orchestrator templates
239
+
240
+ You can define custom orchestrator templates when the same instructions should apply to every agent you spawn, no matter the task.
241
+
242
+ If you have an adversarial review tool installed, you can define an "adversarial-review" orchestrator:
243
+
244
+ ```toml
245
+ name = "adversarial-review"
246
+ guidance = '''
247
+ Run the adversarial-review tool before you commit, and fix any glaring mistakes that the review finds and then commit.
248
+ '''
249
+ ```
250
+
251
+ You can switch orchestrators during a session at `/cowboy` > `Default orchestrator`. See [Menu](docs/Menu.md).
252
+
253
+ Orchestrator templates also allow you to customize how the agent communicates with the orchestrator. See [Orchestrator Templates](docs/Orchestrator%20Templates.md) for more details.
254
+
255
+ ## FAQ
256
+
257
+ ### Why is my agent queued, not running?
258
+
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).
260
+
261
+ ### Why did my worktree survive cleanup?
262
+
263
+ `cleanup_cowboy_agent` will not remove a worktree that has uncommitted changes or whose state it cannot read. Commit or discard the changes, stop the agent if it is still running, then call the tool again. See [`cleanup_cowboy_agent`](#cleanup_cowboy_agent).
264
+
265
+ ### Isn't one pi process per agent too much overhead?
266
+
267
+ It can be. For a single small task the overhead can cost more time than the task itself. pi-cowboy is built for many tasks at once, where that overhead is amortized by parallelization.
268
+
269
+ 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
+
271
+ ### I don't like the emojis, can I turn them off?
272
+
273
+ 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).
274
+
275
+ ## References
276
+
277
+ The settings, screens and template files mentioned above are documented in these four pages.
278
+
279
+ - [Configuration](docs/Configuration.md)
280
+ - [Menu](docs/Menu.md)
281
+ - [Agent Templates](docs/Agent%20Templates.md)
282
+ - [Orchestrator Templates](docs/Orchestrator%20Templates.md)
@@ -0,0 +1,40 @@
1
+ name = "Explore"
2
+ display_name = "Explore"
3
+ description = "Fast codebase exploration agent (read-only)"
4
+
5
+ system_prompt = '''
6
+ # CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
7
+
8
+ You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
9
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
10
+
11
+ You are STRICTLY PROHIBITED from:
12
+
13
+ - Creating new files
14
+ - Modifying existing files
15
+ - Deleting files
16
+ - Moving or copying files
17
+ - Creating temporary files anywhere, including /tmp
18
+ - Using redirect operators (>, >>, |) or heredocs to write to files
19
+ - Running ANY commands that change system state
20
+
21
+ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
22
+
23
+ # Tool Usage
24
+
25
+ - Use the find tool for file pattern matching (NOT the bash find command)
26
+ - Use the grep tool for content search (NOT bash grep/rg command)
27
+ - Use the read tool for reading files (NOT bash cat/head/tail)
28
+ - Use Bash ONLY for read-only operations
29
+ - Make independent tool calls in parallel for efficiency
30
+ - Adapt search approach based on thoroughness level specified
31
+
32
+ # Output
33
+
34
+ - Use absolute file paths in all references
35
+ - Report findings as regular messages
36
+ - Do not use emojis
37
+ - Be thorough and precise'''
38
+
39
+ [harness]
40
+ tools = ["read", "bash", "grep", "find"]
@@ -0,0 +1,261 @@
1
+ /**
2
+ * agent-assets.ts — located-artifacts seam: locate a run's work, then act on it.
3
+ * AgentAssets: locate/observe/deliverable + actuators. AgentAssetsDeps: raw probes it composes.
4
+ * LocateResult: Located (tracked/recovered) | Ambiguous | NotFound.
5
+ * CleanupDeps: injected host/git actuators. PaneRef/LocatedCandidate: addresses.
6
+ * createAgentAssets: bind over probes. createHerdrAgentAssets: bind to the real planes.
7
+ * Authority is per-asset: provenance (worktreeManaged/paneCreated) is memory-only;
8
+ * addresses (workspace/pane/branch/path) are live probes (memory can be stale, not just absent).
9
+ * Unreadable registries degrade to memory's answer, never to absence.
10
+ */
11
+ import * as fs from "node:fs";
12
+ import * as path from "node:path";
13
+ import { deleteWorktreeBranch, isWorktreeDirty, removeGitWorktree, resolveMainCheckout, } from "../infrastructure/git-client.js";
14
+ import { getAgentInfo, listAgentRecords, listWorktrees, normalizeHerdrPath, } from "../infrastructure/herdr-client.js";
15
+ import { createHerdrHost } from "../infrastructure/herdr-host.js";
16
+ import { getSessionCtx, getStore, subagentResultFileFor } from "../shell.js";
17
+ import { buildWorktreeBranch, isExtensionWorktree, isSpawnArtifactName, resolveWorktreeRoot, slugifyWorktreeType, } from "../spawn/worktree-policy.js";
18
+ async function probeList(read) {
19
+ try {
20
+ return { ok: true, entries: await read() };
21
+ }
22
+ catch {
23
+ // Unreadable is not empty: callers keep memory's answer rather than concluding absence.
24
+ return { ok: false };
25
+ }
26
+ }
27
+ function matchWorktree(entries, worktreePath) {
28
+ const wanted = normalizeHerdrPath(worktreePath);
29
+ return entries?.find((entry) => normalizeHerdrPath(entry.path) === wanted);
30
+ }
31
+ function paneOf(record) {
32
+ return {
33
+ paneId: record.paneId,
34
+ tabId: record.tabId,
35
+ workspaceId: record.workspaceId,
36
+ };
37
+ }
38
+ function paneInWorktree(records, worktreePath) {
39
+ const wanted = normalizeHerdrPath(worktreePath);
40
+ const record = records?.find((entry) => entry.cwd !== undefined && normalizeHerdrPath(entry.cwd) === wanted);
41
+ return record === undefined ? undefined : paneOf(record);
42
+ }
43
+ function paneInWorkspace(records, workspaceId) {
44
+ if (workspaceId === undefined)
45
+ return undefined;
46
+ const record = records?.find((entry) => entry.workspaceId === workspaceId);
47
+ return record === undefined ? undefined : paneOf(record);
48
+ }
49
+ /** Bind the seam over injected probes. */
50
+ export function createAgentAssets(deps) {
51
+ async function root() {
52
+ try {
53
+ return await deps.worktreeRoot();
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ /**
60
+ * Extension-owned worktrees answering to `id` (basename IS the branch, so
61
+ * matching is exact). Herdr's registry first; the root scan covers trees
62
+ * created but never adopted (failed launches herdr never heard of). Outside
63
+ * a resolvable root is not ours.
64
+ */
65
+ async function discoverCandidates(id, entries) {
66
+ const worktreeRoot = await root();
67
+ const out = [];
68
+ const seen = new Set();
69
+ const push = (candidate) => {
70
+ const key = normalizeHerdrPath(candidate.path);
71
+ if (seen.has(key))
72
+ return;
73
+ seen.add(key);
74
+ out.push(candidate);
75
+ };
76
+ for (const entry of entries ?? []) {
77
+ const base = path.basename(entry.path);
78
+ if (!isSpawnArtifactName(base, id))
79
+ continue;
80
+ if (worktreeRoot !== undefined &&
81
+ !isExtensionWorktree(entry.path, worktreeRoot))
82
+ continue;
83
+ push({
84
+ path: entry.path,
85
+ // Basename is the branch by construction; herdr's report wins when it agrees on the id (catches directory/branch drift).
86
+ branch: entry.branch !== undefined && isSpawnArtifactName(entry.branch, id)
87
+ ? entry.branch
88
+ : base,
89
+ workspaceId: entry.openWorkspaceId,
90
+ });
91
+ }
92
+ // Scan only when the registry answered nothing: adopted checkouts are already listed.
93
+ if (out.length > 0 || worktreeRoot === undefined)
94
+ return out;
95
+ for (const name of await deps.listRootEntries(worktreeRoot)) {
96
+ if (!isSpawnArtifactName(name, id))
97
+ continue;
98
+ push({ path: path.join(worktreeRoot, name), branch: name });
99
+ }
100
+ return out;
101
+ }
102
+ function candidateSummary(candidate) {
103
+ return {
104
+ worktreePath: candidate.path,
105
+ branch: candidate.branch,
106
+ workspaceId: candidate.workspaceId,
107
+ };
108
+ }
109
+ async function locateTracked(id, hint, entries, records) {
110
+ const recorded = hint.execution.host;
111
+ const worktreeCoords = hint.display.worktree;
112
+ // Ownership rides with the coordinates: a picked tree is never owned,
113
+ // so memory's path is read only for owned runs.
114
+ const managed = worktreeCoords?.kind === "owned";
115
+ const recordedPane = recorded
116
+ ? {
117
+ paneId: recorded.paneId,
118
+ tabId: recorded.tabId,
119
+ workspaceId: recorded.workspaceId,
120
+ }
121
+ : null;
122
+ const source = "tracked";
123
+ let worktreePath = worktreeCoords?.kind === "owned" ? worktreeCoords.path : undefined;
124
+ let workspaceId = recorded?.workspaceId;
125
+ if (worktreePath !== undefined) {
126
+ // Prefer herdr's live workspace (restarts/re-adopts mint new ids; a dead recorded one fails removal); no open workspace means the git plane removes it.
127
+ const entry = matchWorktree(entries, worktreePath);
128
+ if (entry !== undefined)
129
+ workspaceId = entry.openWorkspaceId;
130
+ }
131
+ const pane = worktreePath === undefined
132
+ ? recordedPane
133
+ : (paneInWorktree(records, worktreePath) ?? recordedPane);
134
+ const worktree = worktreePath === undefined
135
+ ? null
136
+ : {
137
+ path: worktreePath,
138
+ workspaceId,
139
+ repoCwd: await deps.resolveRepoCwd(worktreePath),
140
+ };
141
+ return {
142
+ kind: "located",
143
+ source,
144
+ id,
145
+ // The run's branch: its worktree's when it has one, else the pinned
146
+ // `cow-<task>-<id>` name parent-cwd runs launch under.
147
+ branch: worktreeCoords?.branch ??
148
+ buildWorktreeBranch(hint.display.taskSlug ?? slugifyWorktreeType(hint.display.type), hint.id),
149
+ worktreeManaged: managed || worktree !== null,
150
+ paneCreated: recorded?.paneCreated === true,
151
+ worktree,
152
+ pane,
153
+ };
154
+ }
155
+ async function locateDiscovered(id, entries, records) {
156
+ const candidates = await discoverCandidates(id, entries);
157
+ if (candidates.length === 0)
158
+ return { kind: "not-found", id };
159
+ if (candidates.length > 1) {
160
+ return {
161
+ kind: "ambiguous",
162
+ id,
163
+ candidates: candidates.map(candidateSummary),
164
+ };
165
+ }
166
+ const found = candidates[0];
167
+ const pane = paneInWorktree(records, found.path) ??
168
+ paneInWorkspace(records, found.workspaceId) ??
169
+ null;
170
+ return {
171
+ kind: "located",
172
+ source: "recovered",
173
+ id,
174
+ branch: found.branch,
175
+ // Discovery yields only extension-owned checkouts, but nobody survived to claim the pane: adopted, never closed.
176
+ worktreeManaged: true,
177
+ paneCreated: false,
178
+ worktree: {
179
+ path: found.path,
180
+ workspaceId: found.workspaceId,
181
+ repoCwd: await deps.resolveRepoCwd(found.path),
182
+ },
183
+ pane,
184
+ };
185
+ }
186
+ async function locate(id, hint) {
187
+ const worktrees = await probeList(deps.listWorktrees);
188
+ const records = await probeList(deps.listAgentRecords);
189
+ const entries = worktrees.ok ? worktrees.entries : undefined;
190
+ const live = records.ok ? records.entries : undefined;
191
+ return hint === undefined
192
+ ? locateDiscovered(id, entries, live)
193
+ : locateTracked(id, hint, entries, live);
194
+ }
195
+ return {
196
+ locate,
197
+ observe: (pane) => deps.readPane(pane.paneId),
198
+ deliverable: deps.deliverable,
199
+ isWorktreeDirty: deps.isWorktreeDirty,
200
+ worktreeExists: deps.worktreeExists,
201
+ removeWorktree: deps.removeWorktree,
202
+ removeGitWorktree: deps.removeGitWorktree,
203
+ deleteBranch: deps.deleteBranch,
204
+ closePane: deps.closePane,
205
+ };
206
+ }
207
+ /* ── The herdr composition ─────────────────────────────────────────────── */
208
+ /** Bind the seam to the real planes: failed repo derivation is `undefined` (never a borrowed cwd); failed pane reads throw (unreadable is not gone). */
209
+ export function createHerdrAgentAssets(pi) {
210
+ const host = createHerdrHost(pi);
211
+ return createAgentAssets({
212
+ deliverable: (id) => {
213
+ const resultFile = subagentResultFileFor(id);
214
+ return { path: resultFile, present: fs.existsSync(resultFile) };
215
+ },
216
+ listWorktrees: () => listWorktrees(pi),
217
+ listAgentRecords: () => listAgentRecords(pi),
218
+ readPane: async (paneId) => {
219
+ const info = await getAgentInfo(pi, paneId);
220
+ return info === undefined ? undefined : { state: info.state };
221
+ },
222
+ worktreeRoot: async () => {
223
+ const cwd = getSessionCtx().cwd;
224
+ if (!cwd)
225
+ return undefined;
226
+ const repoRoot = await resolveMainCheckout(pi, cwd).catch(() => undefined);
227
+ return repoRoot === undefined
228
+ ? undefined
229
+ : resolveWorktreeRoot(getStore().agent.worktreeRoot, repoRoot);
230
+ },
231
+ listRootEntries: async (worktreeRoot) => {
232
+ try {
233
+ return await fs.promises.readdir(worktreeRoot);
234
+ }
235
+ catch {
236
+ // A missing root holds no worktrees — a genuine empty answer.
237
+ return [];
238
+ }
239
+ },
240
+ resolveRepoCwd: async (worktreePath) => {
241
+ try {
242
+ return await resolveMainCheckout(pi, worktreePath);
243
+ }
244
+ catch {
245
+ // No cwd beats a borrowed one (a wrong-repo cwd aims `git branch -D` at another repo's branch).
246
+ return undefined;
247
+ }
248
+ },
249
+ isWorktreeDirty: (worktreePath) => isWorktreeDirty(pi, worktreePath),
250
+ worktreeExists: async (worktreePath) => fs.existsSync(worktreePath),
251
+ removeWorktree: (ref) => host.release(ref, "worktree-association"),
252
+ removeGitWorktree: async (worktreePath, repoCwd) => {
253
+ await removeGitWorktree(pi, repoCwd, worktreePath);
254
+ return !fs.existsSync(worktreePath);
255
+ },
256
+ deleteBranch: (options) => deleteWorktreeBranch(pi, options, (candidate) => host.isAttached(candidate, { repoCwd: options.repoCwd })),
257
+ closePane: async (ref) => {
258
+ await host.release(ref, "placement");
259
+ },
260
+ });
261
+ }