pi-cowboy 0.0.0 → 0.3.2

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 +288 -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 +110 -0
  85. package/dist/prompt/skill-loader.js +153 -0
  86. package/dist/prompt/subagent-system-prompt.js +173 -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 +160 -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 +109 -3
@@ -0,0 +1,315 @@
1
+ /**
2
+ * supervisor.ts — ProcessSupervisorEngine: one subagent process in a herdr pane.
3
+ *
4
+ * - `start(plan, ref)` launches pi into a caller-resolved host; the supervisor
5
+ * never creates a host, and returns on spawn acceptance, not registry presence.
6
+ * - `adopt(ref)` binds an already-spawned run without launching (the revive seam).
7
+ * - SETTLEMENT IS REPORT-ONLY: only the subagent's own report settles a run — a
8
+ * result deliverable held unchanged for one confirm poll — plus an explicit
9
+ * stop(). Herdr state never settles; a run with no report stays unsettled
10
+ * until the user stops it.
11
+ * - SETTLEMENT IS NOT THE END OF THE WATCH: the loop keeps polling after the
12
+ * first report, so a run that keeps working (or is steered) reports again.
13
+ * Each later report goes to onFollowUp; only the first one settles.
14
+ * - The watch ends at `stop()`, `detach()`, or `abandon()`.
15
+ * - `stop(graceMs)` is INTERRUPT-ONLY: ctrl+c, then wait — it NEVER closes the
16
+ * pane, since closing it breaks the worktree removal that runs AFTER stop()
17
+ * returns. A pending watch always ends `stopped`, even when the process survives.
18
+ * - `abandon()` is DISPOSAL ONLY for a discarded parent session (`/new`,
19
+ * `/reload`, `/fork`): polling stops, the pane/process/artifacts survive, and
20
+ * watch() never settles.
21
+ * - Artifacts are NOT this engine's to remove: a settled run stays watched, so
22
+ * its result directory survives settlement and is removed when the run is
23
+ * dropped (see removeResultArtifacts).
24
+ * - One supervisor per run: re-delegation and revive each use a fresh instance.
25
+ */
26
+ import { createLogger } from "../logger.js";
27
+ import { errorMessage } from "../utils.js";
28
+ const log = createLogger("supervisor");
29
+ const DEFAULT_POLL_MS = 2_000;
30
+ /** A promise with its resolver, for a cell that is filled in exactly once. */
31
+ function deferred() {
32
+ // The executor runs synchronously, so the resolver exists before the promise leaves this call.
33
+ let resolve;
34
+ const promise = new Promise((r) => {
35
+ resolve = r;
36
+ });
37
+ return { promise, resolve };
38
+ }
39
+ export class ProcessSupervisorEngine {
40
+ host;
41
+ ipc;
42
+ pollMs;
43
+ stopInitiator;
44
+ onFollowUp;
45
+ phase = { kind: "idle" };
46
+ /**
47
+ * The run's one terminal decision, written once and never overwritten: the
48
+ * first report or stop() sets it, and later reports are follow-ups instead.
49
+ */
50
+ outcome = null;
51
+ /** The one settlement cell: watch() hands out this promise, settle() fills it in. */
52
+ settlement = deferred();
53
+ /** watch() hands out one promise per instance, so a second call has to be refused. */
54
+ watchIssued = false;
55
+ /** Ends the loop's wait; set only while the loop sleeps between polls. */
56
+ wakeLoop = null;
57
+ /** The last report confirmed stable and handed on, settlement or follow-up. */
58
+ delivered = null;
59
+ /** A report seen once; a report still being written is not final. */
60
+ held = null;
61
+ watchStartedAt = 0;
62
+ constructor(host, ipc, options = {}) {
63
+ this.host = host;
64
+ this.ipc = ipc;
65
+ this.pollMs = options.pollMs ?? DEFAULT_POLL_MS;
66
+ this.stopInitiator = options.stopInitiator ?? "user";
67
+ this.onFollowUp = options.onFollowUp;
68
+ }
69
+ /**
70
+ * Launch pi into the caller's pane (never created or closed here). Returns on
71
+ * spawn acceptance, not registry presence. One launch per instance; a failed
72
+ * launch reverts to idle so the caller may retry.
73
+ */
74
+ async start(plan, ref) {
75
+ if (this.phase.kind !== "idle") {
76
+ throw new Error("ProcessSupervisor.start() may launch once per supervisor — create a fresh instance per attempt");
77
+ }
78
+ this.phase = { kind: "watching", ref };
79
+ try {
80
+ await this.host.start(ref, {
81
+ name: plan.name ?? "subagent",
82
+ piArgs: plan.piArgs,
83
+ });
84
+ }
85
+ catch (err) {
86
+ // A failed launch is not a run: revert so the caller may retry, unless
87
+ // something settled the run while the launch was in flight.
88
+ if (this.isWatching())
89
+ this.phase = { kind: "idle" };
90
+ throw err;
91
+ }
92
+ }
93
+ /**
94
+ * Bind an already-spawned run without launching. One adoption per instance —
95
+ * revive with a fresh engine. Throws when this instance is not idle.
96
+ */
97
+ adopt(ref) {
98
+ if (this.phase.kind !== "idle") {
99
+ throw new Error("ProcessSupervisor.adopt() supervises one run per supervisor — create a fresh instance per attempt");
100
+ }
101
+ this.phase = { kind: "watching", ref };
102
+ log.debug("adopted", {
103
+ paneId: ref.paneId,
104
+ pollMs: this.pollMs,
105
+ stopInitiator: this.stopInitiator,
106
+ });
107
+ }
108
+ /**
109
+ * Supervise until the run's own report artifacts supply a terminal outcome.
110
+ * Rejects when never started or a watch is pending; resolves immediately with
111
+ * the stored outcome after settlement. The run's single loop polls it, so a
112
+ * host round trip slower than the interval cannot stack observations.
113
+ */
114
+ watch() {
115
+ // A settled run replays its outcome; the loop may still be polling for
116
+ // follow-ups, which do not change what this promise carries.
117
+ if (this.outcome !== null)
118
+ return Promise.resolve(this.outcome);
119
+ switch (this.phase.kind) {
120
+ case "idle":
121
+ return Promise.reject(new Error("ProcessSupervisor.watch() requires start() or adopt() first"));
122
+ case "ended":
123
+ // Detached or abandoned with no outcome: nothing will ever settle it.
124
+ return this.settlement.promise;
125
+ case "watching":
126
+ break;
127
+ }
128
+ if (this.watchIssued) {
129
+ return Promise.reject(new Error("ProcessSupervisor.watch() is already active for this run"));
130
+ }
131
+ const { ref } = this.phase;
132
+ this.watchIssued = true;
133
+ this.watchStartedAt = performance.now();
134
+ log.debug("started", {
135
+ paneId: ref.paneId,
136
+ pollMs: this.pollMs,
137
+ stopInitiator: this.stopInitiator,
138
+ });
139
+ void this.runLoop().catch((err) => {
140
+ // The loop's own steps absorb their failures; this is a bug worth seeing.
141
+ log.error("poll loop failed", { errorMessage: errorMessage(err) });
142
+ });
143
+ return this.settlement.promise;
144
+ }
145
+ /**
146
+ * Interrupt-only stop: ctrl+c, then wait graceMs. NEVER closes the pane — the
147
+ * worktree removal runs AFTER this returns. True when the process is confirmed
148
+ * gone (including already-gone); always ends a pending watch `stopped`.
149
+ */
150
+ async stop(graceMs) {
151
+ const phase = this.phase;
152
+ if (phase.kind !== "watching") {
153
+ return false; // nothing live to stop
154
+ }
155
+ // A run that already reported is not this caller's to interrupt: its pane
156
+ // stays available for a steer, and its later reports arrive as follow-ups.
157
+ if (this.outcome !== null)
158
+ return false;
159
+ const { ref } = phase;
160
+ const stopped = await this.host
161
+ .stop(ref, { interruptGraceMs: graceMs, confirmMs: 0 })
162
+ .catch((err) => {
163
+ log.debug("host stop failed", {
164
+ errorMessage: errorMessage(err),
165
+ });
166
+ return false;
167
+ });
168
+ log.debug("stop requested", {
169
+ paneId: ref.paneId,
170
+ graceMs,
171
+ stopped,
172
+ initiator: this.stopInitiator,
173
+ });
174
+ this.settle({ kind: "stopped", initiator: this.stopInitiator });
175
+ // A stopped run is over: nothing written after this belongs to it.
176
+ this.stopPolling("stopped");
177
+ return stopped;
178
+ }
179
+ /**
180
+ * Disposal-only teardown for a discarded parent session: stop polling, leave
181
+ * watch() pending with NO outcome, and leave pane, process, and artifacts
182
+ * untouched. Idempotent; a no-op once finalized.
183
+ */
184
+ abandon() {
185
+ this.stopPolling("abandoned");
186
+ }
187
+ /** Stop watching a run the caller has stopped tracking. Idempotent. */
188
+ detach() {
189
+ this.stopPolling("detached");
190
+ }
191
+ /**
192
+ * End the poll loop and let the run rest where it is: the outcome is not
193
+ * changed, and the pane, process, and artifacts are untouched. A no-op once
194
+ * the loop is gone.
195
+ */
196
+ stopPolling(event) {
197
+ const phase = this.phase;
198
+ if (phase.kind !== "watching")
199
+ return;
200
+ log.debug(event, {
201
+ paneId: phase.ref.paneId,
202
+ pollMs: this.pollMs,
203
+ outcome: this.outcome?.kind ?? null,
204
+ });
205
+ this.phase = { kind: "ended" };
206
+ this.endWait();
207
+ }
208
+ /**
209
+ * Terminal transition: the one writer of a settled outcome, so a second
210
+ * caller (a report landing after a stop) can never overwrite the first. The
211
+ * loop is left running, since a settled run may still report again.
212
+ */
213
+ settle(outcome) {
214
+ if (this.phase.kind !== "watching" || this.outcome !== null)
215
+ return;
216
+ this.outcome = outcome;
217
+ log.debug("settlement decision", {
218
+ ...outcome,
219
+ paneId: this.phase.ref.paneId,
220
+ runDurationMs: this.watchStartedAt
221
+ ? performance.now() - this.watchStartedAt
222
+ : 0,
223
+ });
224
+ this.settlement.resolve(outcome);
225
+ }
226
+ /**
227
+ * The run's one loop: each pass waits out an interval, then polls. It keeps
228
+ * going past settlement, so a later report reaches onFollowUp; only a stop or
229
+ * a detach ends the wait.
230
+ */
231
+ async runLoop() {
232
+ for (;;) {
233
+ if (!(await this.pauseUntilNextPoll()))
234
+ return;
235
+ await this.pollOnce();
236
+ }
237
+ }
238
+ /**
239
+ * Wait out one poll interval. False once the watch is over — the one question
240
+ * a suspension point has to ask, and the only place the loop asks it. Unref'd,
241
+ * so a pending poll never holds the process open.
242
+ */
243
+ pauseUntilNextPoll() {
244
+ if (!this.isWatching())
245
+ return Promise.resolve(false);
246
+ return new Promise((resolve) => {
247
+ const timer = setTimeout(() => {
248
+ this.wakeLoop = null;
249
+ resolve(true);
250
+ }, this.pollMs);
251
+ timer.unref();
252
+ this.wakeLoop = () => {
253
+ clearTimeout(timer);
254
+ resolve(false);
255
+ };
256
+ });
257
+ }
258
+ /** End the loop's wait: the watch is over, so no further poll happens. */
259
+ endWait() {
260
+ this.wakeLoop?.();
261
+ this.wakeLoop = null;
262
+ }
263
+ /** One poll: read the run's report, then settle the run or announce a follow-up. */
264
+ async pollOnce() {
265
+ const report = await this.readDeliverable();
266
+ // No report yet: keep polling. No watchdog, turn limit, liveness probe, or
267
+ // failed turn ends a run — only a report or an explicit stop does.
268
+ if (report === null || report.content.trim().length === 0) {
269
+ this.held = null;
270
+ return;
271
+ }
272
+ // Byte-for-byte the report already handed on: nothing to announce, whichever
273
+ // turn wrote it.
274
+ if (this.delivered !== null && sameReport(this.delivered, report)) {
275
+ this.held = null;
276
+ return;
277
+ }
278
+ // First sighting or rewrite: hold one poll; a report still being edited is
279
+ // not final.
280
+ if (this.held === null || !sameReport(this.held, report)) {
281
+ this.held = report;
282
+ log.debug("deliverable held for confirmation");
283
+ return;
284
+ }
285
+ this.held = null;
286
+ this.delivered = report;
287
+ if (this.outcome === null) {
288
+ this.settle({ kind: "completed", deliverable: report.content });
289
+ return;
290
+ }
291
+ // The run already settled: this is work done after its recorded result.
292
+ if (this.isWatching())
293
+ this.onFollowUp?.(report.content);
294
+ }
295
+ /** One artifact read; a failed read is a poll with nothing in it. */
296
+ async readDeliverable() {
297
+ try {
298
+ return await this.ipc.readDeliverable();
299
+ }
300
+ catch (err) {
301
+ log.debug("readDeliverable failed", {
302
+ errorMessage: errorMessage(err),
303
+ });
304
+ return null;
305
+ }
306
+ }
307
+ /** Whether this engine is still watching a run: asked at each transition and at each wait's start. */
308
+ isWatching() {
309
+ return this.phase.kind === "watching";
310
+ }
311
+ }
312
+ /** Whether two reads are the same report: same words, same write. */
313
+ function sameReport(a, b) {
314
+ return a.content === b.content && a.mtime === b.mtime;
315
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * task-registry.ts — unified admission/execution-tracking layer for subagent tasks.
3
+ * Owns dedup (findTaskDedup / TaskDedup / TaskAlreadyInFlightError) and concurrency
4
+ * (independent level pools + FIFO queue + release). Admission is non-destructive: a
5
+ * duplicate is rejected and the existing attempt is never touched — the registry holds
6
+ * no kill capability. Shell-free: every external dependency is injected via
7
+ * TaskRegistryDeps (fakes in tests).
8
+ */
9
+ import { isActivePhase, lifecycleStatus } from "./types.js";
10
+ /**
11
+ * Decide whether a task is already in flight. In-memory spawns win (freshest signal — the
12
+ * placement may not be live in the backend yet); otherwise any live backend attempt owns
13
+ * the task, which also covers a parent reload. Ownership is binary and ends only the duplicate.
14
+ */
15
+ export function findTaskDedup(inFlightSpawns, liveAttempts) {
16
+ const spawn = inFlightSpawns.at(0);
17
+ if (spawn)
18
+ return { kind: "spawn", spawn };
19
+ const attempt = liveAttempts.at(0);
20
+ if (attempt)
21
+ return { kind: "herdr", attempt };
22
+ return { kind: "none" };
23
+ }
24
+ /** A spawn was requested for a task with a live agent. Throwing is the whole consequence. */
25
+ export class TaskAlreadyInFlightError extends Error {
26
+ taskSlug;
27
+ /** Dedup evidence behind the error: the live spawn, or the live herdr attempt. */
28
+ dedup;
29
+ constructor(dedup, taskSlug) {
30
+ const inMemory = dedup.kind === "spawn";
31
+ const label = inMemory ? `agent ${dedup.spawn.id}` : dedup.attempt.name;
32
+ // Only the knowable state is reported: nothing about a herdr attempt's prompt is probed.
33
+ const state = inMemory ? lifecycleStatus(dedup.spawn.lifecycle) : "live";
34
+ super(`Task "${taskSlug}" is already in flight as ${label} (state: ${state}). No second agent was spawned.`);
35
+ this.name = "TaskAlreadyInFlightError";
36
+ this.taskSlug = taskSlug;
37
+ this.dedup = dedup;
38
+ }
39
+ }
40
+ // --- Concurrency machinery ---
41
+ /** The global concurrency limit every spawn counts against. */
42
+ export const DEFAULT_CONCURRENCY_LIMIT = 4;
43
+ /** Limits are floored at one: a configured 0 means one at a time, never "no limit". */
44
+ function clampLimit(limit) {
45
+ return Math.max(1, limit);
46
+ }
47
+ /** The provider half of a "provider/modelId" key. */
48
+ function providerOf(modelKey) {
49
+ return modelKey.split("/")[0];
50
+ }
51
+ /** Unified admission/execution-tracking layer: `admit` gates (dedup, then concurrency); `release` frees and drains. */
52
+ export class HerdrTaskRegistry {
53
+ deps;
54
+ /** Per-model pools keyed by "provider/modelId". */
55
+ modelPools = new Map();
56
+ /** Per-provider pools — one pool shared by every model from that provider. */
57
+ providerPools = new Map();
58
+ /** The global pool. It is never replaced, so a config change cannot lose its count. */
59
+ globalPool = {
60
+ limit: DEFAULT_CONCURRENCY_LIMIT,
61
+ spawned: 0,
62
+ };
63
+ /** Spawns waiting for room, FIFO. */
64
+ queue = [];
65
+ /** The pools each spawned agent counts against, so release can give them back. */
66
+ reservations = new WeakMap();
67
+ /** Tail of the admission chain per task slug, so two requests for one slug cannot interleave. */
68
+ admissionBySlug = new Map();
69
+ constructor(deps, initialConcurrency) {
70
+ this.deps = deps;
71
+ this.setLimits(initialConcurrency ?? { default: DEFAULT_CONCURRENCY_LIMIT });
72
+ }
73
+ /**
74
+ * Admit a spawn request. Rejections carry the conflict's identity and never throw — the caller converts them.
75
+ * A slug serializes its admissions: the dedup check and the spawn must not straddle another
76
+ * request for the same slug, or a batch of duplicate task names starts twice.
77
+ */
78
+ async admit(intent) {
79
+ const slug = intent.taskSlug;
80
+ if (slug === undefined)
81
+ return this.admitOne(intent);
82
+ const previous = this.admissionBySlug.get(slug);
83
+ const mine = (previous ?? Promise.resolve())
84
+ .catch(() => { })
85
+ .then(() => this.admitOne(intent));
86
+ this.admissionBySlug.set(slug, mine);
87
+ try {
88
+ return await mine;
89
+ }
90
+ finally {
91
+ if (this.admissionBySlug.get(slug) === mine) {
92
+ this.admissionBySlug.delete(slug);
93
+ }
94
+ }
95
+ }
96
+ /** One admission: dedup first, then the synchronous spawn that registers the spawn in the store. */
97
+ async admitOne(intent) {
98
+ // Verify-only: a conflict rejects the NEW request and leaves the existing attempt alone.
99
+ if (intent.taskSlug) {
100
+ const inFlight = this.deps
101
+ .listAgents()
102
+ .filter((a) => a.display.taskSlug === intent.taskSlug &&
103
+ isActivePhase(a.lifecycle.phase));
104
+ const dedup = findTaskDedup(inFlight, await this.deps.findTaskAttempts(intent.taskSlug));
105
+ if (dedup.kind !== "none") {
106
+ // The rejection is the entire consequence; leftovers end explicitly (Cleanup/stop_cowboy_agent).
107
+ return {
108
+ status: "rejected",
109
+ reason: "already_in_flight",
110
+ conflictingId: dedup.kind === "spawn" ? dedup.spawn.id : dedup.attempt.name,
111
+ };
112
+ }
113
+ }
114
+ // The manager folds concurrency admission (reservation or queue) into the spawn call.
115
+ const { type, prompt, runInBackground, signal, ...config } = intent;
116
+ const spawnOptions = {
117
+ ...config,
118
+ isBackground: runInBackground,
119
+ signal,
120
+ };
121
+ const agentId = this.deps.spawn(type, prompt, spawnOptions);
122
+ // Phase right after the synchronous spawn tells admitted (spawned) vs queued.
123
+ const spawn = this.deps.getSpawn(agentId);
124
+ if (spawn?.lifecycle.phase === "queued") {
125
+ return {
126
+ status: "queued",
127
+ agentId,
128
+ queuePosition: this.queuePositionOf(agentId),
129
+ };
130
+ }
131
+ return { status: "admitted", agentId };
132
+ }
133
+ /** Release a spawn's pools and drain the queue. Idempotent. */
134
+ async release(agentId) {
135
+ const spawn = this.deps.getSpawn(agentId);
136
+ if (spawn) {
137
+ const reservation = this.reservations.get(spawn);
138
+ if (reservation) {
139
+ for (const pool of reservation) {
140
+ pool.spawned = Math.max(0, pool.spawned - 1);
141
+ }
142
+ this.reservations.delete(spawn);
143
+ }
144
+ }
145
+ // A queued spawn holds no pool; still drop its entry so the id never lingers.
146
+ this.cancelQueued(agentId);
147
+ this.drainQueue();
148
+ }
149
+ /** Concurrency admission at spawn time: a reservation now, or a FIFO queue entry. */
150
+ admitSpawn(modelKey, queued) {
151
+ const reservation = this.applicablePools(modelKey);
152
+ if (!this.hasRoom(reservation)) {
153
+ this.queue.push({ id: queued.id, modelKey, start: queued.start });
154
+ return { kind: "queue" };
155
+ }
156
+ return { kind: "start", reservation };
157
+ }
158
+ /** Charge every pool in the reservation and remember it, so release can give them back. */
159
+ reserve(spawn, reservation) {
160
+ for (const pool of reservation)
161
+ pool.spawned++;
162
+ this.reservations.set(spawn, reservation);
163
+ }
164
+ /**
165
+ * Charge a run that returns to active without an admission, which is a revived turn.
166
+ * The message is already in the agent's pane, so the run cannot wait for room: a pool
167
+ * that is full is charged past its limit, and the next admission reads the true count.
168
+ */
169
+ reacquire(spawn, modelKey) {
170
+ if (this.reservations.has(spawn))
171
+ return;
172
+ this.reserve(spawn, this.applicablePools(modelKey));
173
+ }
174
+ /** Drop a queued spawn (queued stop). */
175
+ cancelQueued(id) {
176
+ this.queue = this.queue.filter((entry) => entry.id !== id);
177
+ }
178
+ /** Drop every queued spawn (manager dispose). */
179
+ clearQueue() {
180
+ this.queue = [];
181
+ }
182
+ /** Update the configured limits and drain the queue. */
183
+ setConcurrency(config) {
184
+ this.setLimits(config);
185
+ this.drainQueue();
186
+ }
187
+ // ── Private ──
188
+ /**
189
+ * Bring the three levels in line with the config. A pool that stays configured keeps
190
+ * its counter and only takes the new ceiling, so raising or lowering a limit cannot
191
+ * lose track of the spawns already charged to it.
192
+ */
193
+ setLimits(config) {
194
+ this.globalPool.limit = clampLimit(config.default);
195
+ this.syncPools(this.providerPools, config.providers ?? {});
196
+ this.syncPools(this.modelPools, config.models ?? {});
197
+ }
198
+ /**
199
+ * Give every configured key a pool and drop the pools whose key the config no longer
200
+ * names. A dropped pool's spawns keep counting against the levels that still apply to
201
+ * them; only the level that no longer exists stops counting them.
202
+ */
203
+ syncPools(pools, configured) {
204
+ for (const [key, limit] of Object.entries(configured)) {
205
+ const pool = pools.get(key);
206
+ if (pool)
207
+ pool.limit = clampLimit(limit);
208
+ else
209
+ pools.set(key, { limit: clampLimit(limit), spawned: 0 });
210
+ }
211
+ for (const key of pools.keys()) {
212
+ if (!(key in configured))
213
+ pools.delete(key);
214
+ }
215
+ }
216
+ /**
217
+ * The pools one spawn counts against, most specific first: its model's pool when the
218
+ * model has a limit, its provider's pool when the provider has one, and the global
219
+ * pool, which every spawn counts against. A spawn with no model selection has only
220
+ * the global pool.
221
+ */
222
+ applicablePools(modelKey) {
223
+ const pools = [];
224
+ if (modelKey) {
225
+ const modelPool = this.modelPools.get(modelKey);
226
+ if (modelPool)
227
+ pools.push(modelPool);
228
+ const providerPool = this.providerPools.get(providerOf(modelKey));
229
+ if (providerPool)
230
+ pools.push(providerPool);
231
+ }
232
+ pools.push(this.globalPool);
233
+ return pools;
234
+ }
235
+ /** Every pool in the reservation must have room; one full level queues the spawn. */
236
+ hasRoom(reservation) {
237
+ return reservation.every((pool) => pool.spawned < pool.limit);
238
+ }
239
+ /** Start queued spawns whose pools all have room, FIFO. */
240
+ drainQueue() {
241
+ const kept = [];
242
+ for (const entry of this.queue) {
243
+ const reservation = this.applicablePools(entry.modelKey);
244
+ if (!this.hasRoom(reservation)) {
245
+ kept.push(entry);
246
+ continue;
247
+ }
248
+ // Every other outcome ends the entry: a started spawn leaves the queue, and a
249
+ // refused start means the session is gone or is no longer queued.
250
+ entry.start(reservation);
251
+ }
252
+ this.queue = kept;
253
+ }
254
+ /** 1-based FIFO position of a queued spawn, or 0 when it is not queued. */
255
+ queuePositionOf(agentId) {
256
+ return this.queue.findIndex((entry) => entry.id === agentId) + 1;
257
+ }
258
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * template-files.ts — Generic `.toml` template-file helpers shared by the
3
+ * agent and orchestrator discovery layers: TOML reader, single-line error
4
+ * formatter, and directory scanner.
5
+ *
6
+ * The scanner is shell-free: the warning sink and the parse/name accessors
7
+ * are caller-supplied, so each layer keeps its own schema and wording.
8
+ */
9
+ import * as fs from "node:fs";
10
+ import * as path from "node:path";
11
+ import { parse, TomlError } from "smol-toml";
12
+ import { z } from "zod";
13
+ const TEMPLATE_FILE_EXTENSION = ".toml";
14
+ /** Read TOML into an untrusted value for the caller's Zod schema to narrow. A leading byte-order mark is stripped — an editor artefact, not TOML syntax. */
15
+ export function parseTemplateToml(content) {
16
+ return parse(content.replace(/^\uFEFF/, ""));
17
+ }
18
+ export function compactDefined(obj) {
19
+ return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v !== undefined));
20
+ }
21
+ // --- Parse-error reporting ---
22
+ /** One Zod issue as `path: message` (`message` alone for a root issue). */
23
+ function describeZodIssue(issue) {
24
+ const route = issue.path.join(".");
25
+ return route ? `${route}: ${issue.message}` : issue.message;
26
+ }
27
+ /** Collapse a parse error to one line for the scanner's skip warning (TOML errors carry a multi-line code frame). A ZodError reads per field as `cues.spawned: Invalid input: expected string, received number`. */
28
+ export function describeParseError(err) {
29
+ if (err instanceof z.ZodError) {
30
+ return err.issues
31
+ .map(describeZodIssue)
32
+ .join("; ")
33
+ .replace(/\s+/g, " ")
34
+ .trim();
35
+ }
36
+ if (err instanceof TomlError) {
37
+ // Keep message and position; drop the code frame (the path is already in the warning).
38
+ const [head] = err.message.split("\n\n");
39
+ return `${head} (line ${err.line}, column ${err.column})`;
40
+ }
41
+ const message = err instanceof Error ? err.message : String(err);
42
+ return message.replace(/\s+/g, " ").trim();
43
+ }
44
+ const DEFAULT_WARNING = {
45
+ label: "File",
46
+ problem: "was skipped",
47
+ };
48
+ /**
49
+ * Scan a directory for `.toml` templates; empty array when it doesn't exist.
50
+ * Kept when `parse` succeeds AND `getName` returns a name — an unnamed file
51
+ * is not a template, dropped silently. A parse throw is dropped with a
52
+ * one-line `notify` warning; a read failure stays quiet (nothing to report).
53
+ */
54
+ export async function scanTemplateFilesInDir(dirPath, parseFile, getName, notify, warning = DEFAULT_WARNING) {
55
+ try {
56
+ await fs.promises.access(dirPath);
57
+ }
58
+ catch {
59
+ return [];
60
+ }
61
+ const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
62
+ const templateFiles = entries.filter((e) => e.isFile() && e.name.endsWith(TEMPLATE_FILE_EXTENSION));
63
+ const templates = [];
64
+ for (const entry of templateFiles) {
65
+ const filePath = path.join(dirPath, entry.name);
66
+ let content;
67
+ try {
68
+ content = await fs.promises.readFile(filePath, "utf-8");
69
+ }
70
+ catch {
71
+ continue;
72
+ }
73
+ try {
74
+ const parsed = parseFile(content);
75
+ if (getName(parsed)) {
76
+ templates.push(parsed);
77
+ }
78
+ }
79
+ catch (err) {
80
+ notify?.(`[cowboy] ${warning.label} file ${filePath} ${warning.problem}: ${describeParseError(err)}`, "warning");
81
+ }
82
+ }
83
+ return templates;
84
+ }