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,444 @@
1
+ /**
2
+ * menu-agent-status.ts — the agent list (active and settled) and per-agent
3
+ * actions. Snapshot at construction; re-entry refreshes. Actions focus the
4
+ * subagent's herdr pane instead of an in-extension viewer.
5
+ * Exports: showAgentStatusMenu, buildAgentActionsList.
6
+ */
7
+ import { matchesKey, SelectList, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui";
8
+ import { ALL_AGENT_PHASES, hasOutcome, isActivePhase, lifecycleResult, lifecycleStartTime, lifecycleStatus, } from "../../types.js";
9
+ import { errorMessage } from "../../utils.js";
10
+ import { formatRetentionClause } from "../../infrastructure/git-client.js";
11
+ import { getDisplayName, agentBulletPrefix, formatMs, statusIcon, } from "../format.js";
12
+ import { getManagerOrNull, getRuntime } from "../../shell.js";
13
+ import { cleanupNeedsAttention, summarizeCleanupReport, } from "../../agents/cleanup-report.js";
14
+ import { ScreenHost, SwappableView, asListFields } from "./screen-host.js";
15
+ import { SEPARATOR_ID, actionReport, buildSelectListTheme, installSeparatorSkip, withVimKeys, } from "./helpers.js";
16
+ import { SettingsListWrapper } from "./wrappers/settings-list.js";
17
+ /** Focus the subagent's herdr tab. */
18
+ async function focusHerdrPane(ctx, spawn) {
19
+ const host = spawn.execution.host;
20
+ if (!host) {
21
+ ctx.ui.notify("Agent has no herdr pane yet (still queued)", "info");
22
+ return;
23
+ }
24
+ const runtime = getRuntime();
25
+ if (!runtime) {
26
+ ctx.ui.notify("Agent runtime is not initialized", "warning");
27
+ return;
28
+ }
29
+ // Focus the tab, not the agent: `agent focus` fails once the agent is gone
30
+ // while its pane is still open. A rejection (e.g. closed tab) is reported.
31
+ const action = actionReport(ctx.ui);
32
+ action.pending(`Focusing agent ${spawn.id}'s herdr pane`);
33
+ try {
34
+ await runtime.view.focus(host);
35
+ action.succeeded(`Focused agent ${spawn.id}'s herdr pane`);
36
+ }
37
+ catch (err) {
38
+ action.failed(`Failed to focus agent ${spawn.id}'s herdr pane`, err);
39
+ }
40
+ }
41
+ async function showTextViewer(ctx, spawn, kind, text) {
42
+ const titleSuffix = kind === "result" ? spawn.id : "Error";
43
+ const textLines = text.split("\n");
44
+ const displayName = getDisplayName(spawn.display.type);
45
+ const chromeLines = 5; // top border + title + sep + footer + bottom border
46
+ const MIN_VIEWPORT = 3;
47
+ const VIEWPORT_HEIGHT_PCT = 70;
48
+ let scrollOffset = 0;
49
+ let autoScroll = true;
50
+ await new ScreenHost(ctx).openOverlay(({ tui, theme, close }) => {
51
+ const border = theme.fg("border", "│");
52
+ const viewportHeight = () => {
53
+ const maxRows = Math.floor((tui.terminal.rows * VIEWPORT_HEIGHT_PCT) / 100);
54
+ return Math.max(MIN_VIEWPORT, maxRows - chromeLines);
55
+ };
56
+ return {
57
+ invalidate() { },
58
+ render(width) {
59
+ const innerW = width - 4;
60
+ const out = [
61
+ theme.fg("border", `\u256d${"\u2500".repeat(width - 2)}\u256e`),
62
+ ];
63
+ const titleStr = theme.bold(theme.fg("accent", `${displayName} \u00b7 ${titleSuffix}`));
64
+ const titlePad = Math.max(0, innerW - visibleWidth(titleStr));
65
+ out.push(`${border} ${truncateToWidth(titleStr + " ".repeat(titlePad), innerW, "...", true)} ${border}`);
66
+ out.push(`${border} ${theme.fg("dim", "\u2500".repeat(innerW))} ${border}`);
67
+ const vp = viewportHeight();
68
+ const maxScroll = Math.max(0, textLines.length - vp);
69
+ if (autoScroll)
70
+ scrollOffset = maxScroll;
71
+ const vs = Math.min(scrollOffset, maxScroll);
72
+ const visible = textLines.slice(vs, vs + vp);
73
+ for (let i = 0; i < vp; i++) {
74
+ const line = visible[i] ?? "";
75
+ const truncated = truncateToWidth(line, innerW, "...", true);
76
+ const padLen = Math.max(0, innerW - visibleWidth(truncated));
77
+ out.push(`${border} ${truncated}${" ".repeat(padLen)} ${border}`);
78
+ }
79
+ const scrollPct = textLines.length <= vp
80
+ ? "100%"
81
+ : `${Math.round(((vs + vp) / textLines.length) * 100)}%`;
82
+ const count = theme.fg("dim", `${textLines.length} lines \u00b7 ${scrollPct}`);
83
+ const footerText = theme.fg("dim", "q/Esc close");
84
+ const gap = Math.max(1, innerW - visibleWidth(count) - visibleWidth(footerText));
85
+ out.push(`${border} ${count}${" ".repeat(gap)}${footerText} ${border}`);
86
+ out.push(theme.fg("border", `\u2570${"\u2500".repeat(width - 2)}\u256f`));
87
+ return out;
88
+ },
89
+ handleInput(data) {
90
+ if (matchesKey(data, "q") || matchesKey(data, "escape")) {
91
+ close();
92
+ return;
93
+ }
94
+ const vp = viewportHeight();
95
+ const maxScroll = Math.max(0, textLines.length - vp);
96
+ if (matchesKey(data, "up")) {
97
+ scrollOffset = Math.max(0, scrollOffset - 1);
98
+ autoScroll = scrollOffset >= maxScroll;
99
+ }
100
+ else if (matchesKey(data, "down")) {
101
+ scrollOffset = Math.min(maxScroll, scrollOffset + 1);
102
+ autoScroll = scrollOffset >= maxScroll;
103
+ }
104
+ else if (matchesKey(data, "pageUp")) {
105
+ scrollOffset = Math.max(0, scrollOffset - vp);
106
+ autoScroll = false;
107
+ }
108
+ else if (matchesKey(data, "pageDown")) {
109
+ scrollOffset = Math.min(maxScroll, scrollOffset + vp);
110
+ autoScroll = scrollOffset >= maxScroll;
111
+ }
112
+ else if (matchesKey(data, "home") || data === "g") {
113
+ scrollOffset = 0;
114
+ autoScroll = false;
115
+ }
116
+ else if (data === "G") {
117
+ scrollOffset = maxScroll;
118
+ autoScroll = true;
119
+ }
120
+ },
121
+ };
122
+ });
123
+ }
124
+ /** How the off-menu helpers name the ids they were handed. */
125
+ function agentSubject(ids) {
126
+ return ids.length === 1 ? `agent ${ids[0]}` : `${ids.length} agent(s)`;
127
+ }
128
+ /**
129
+ * Stop agents without holding the menu open, and report the outcome once each
130
+ * stop settles. A stop waits on herdr's registry and the run's settle pass, so
131
+ * callers hand the UI back first and read the verdict here.
132
+ */
133
+ function stopAgentsOffMenu(ctx, ids) {
134
+ const manager = getManagerOrNull();
135
+ const subject = agentSubject(ids);
136
+ const action = actionReport(ctx.ui);
137
+ if (!manager) {
138
+ action.failed(`Failed to stop ${subject}`, "manager unavailable");
139
+ return;
140
+ }
141
+ void (async () => {
142
+ let stopped = 0;
143
+ const notStopped = [];
144
+ for (const id of ids) {
145
+ try {
146
+ if (await manager.abort(id, "user"))
147
+ stopped += 1;
148
+ // A false verdict means the run settled before the stop reached it.
149
+ else
150
+ notStopped.push({ id, reason: "already settled" });
151
+ }
152
+ catch (err) {
153
+ notStopped.push({ id, reason: errorMessage(err) });
154
+ }
155
+ }
156
+ if (notStopped.length === 0) {
157
+ action.succeeded(ids.length === 1
158
+ ? `Stopped ${ids[0]}`
159
+ : `Stopped ${ids.length} agent(s)`);
160
+ return;
161
+ }
162
+ const summary = notStopped
163
+ .map(({ id, reason }) => ids.length === 1 ? reason : `${id} (${reason})`)
164
+ .join(", ");
165
+ if (stopped > 0) {
166
+ action.succeeded(`Stopped ${stopped} of ${ids.length} agent(s); ${summary}`, "warning");
167
+ }
168
+ else {
169
+ action.failed(`Failed to stop ${subject}`, summary);
170
+ }
171
+ })();
172
+ }
173
+ /**
174
+ * Clean agents up without holding the menu open, and report each teardown as
175
+ * it lands. Cleanup closes panes, removes worktrees and deletes merged
176
+ * branches, so callers hand the UI back first.
177
+ */
178
+ function cleanupAgentsOffMenu(ctx, ids) {
179
+ const manager = getManagerOrNull();
180
+ const idSubject = agentSubject(ids);
181
+ const action = actionReport(ctx.ui);
182
+ if (!manager) {
183
+ action.failed(`Failed to clean up ${idSubject}`, "manager unavailable");
184
+ return;
185
+ }
186
+ void (async () => {
187
+ for (const id of ids) {
188
+ try {
189
+ const report = await manager.cleanup(id);
190
+ action.succeeded(summarizeCleanupReport(report), cleanupNeedsAttention(report) ? "warning" : "info");
191
+ }
192
+ catch (err) {
193
+ action.failed(`Failed to clean up agent ${id}`, err);
194
+ }
195
+ }
196
+ })();
197
+ }
198
+ /**
199
+ * Clear agents without holding the menu open, and report each one as its
200
+ * teardown lands. A clear that leaves its worktree behind keeps the spawn
201
+ * listed, so the report names it and why.
202
+ */
203
+ function clearAgentsOffMenu(ctx, ids) {
204
+ const manager = getManagerOrNull();
205
+ const subject = agentSubject(ids);
206
+ const action = actionReport(ctx.ui);
207
+ if (!manager) {
208
+ action.failed(`Failed to clear ${subject}`, "manager unavailable");
209
+ return;
210
+ }
211
+ void (async () => {
212
+ for (const id of ids) {
213
+ let outcome;
214
+ try {
215
+ outcome = await manager.clear(id);
216
+ }
217
+ catch (err) {
218
+ action.failed(`Failed to clear agent ${id}`, err);
219
+ continue;
220
+ }
221
+ switch (outcome.kind) {
222
+ case "cleared":
223
+ action.succeeded(`Cleaned up agent ${id}`);
224
+ break;
225
+ case "kept":
226
+ action.succeeded(`Kept agent ${id}'s worktree — ${formatRetentionClause(outcome.reason)} (${outcome.path})`, "warning");
227
+ break;
228
+ case "removal-failed":
229
+ action.failed(`Failed to clear agent ${id}`, `${outcome.detail} (${outcome.path})`);
230
+ break;
231
+ case "refused":
232
+ action.failed(`Failed to clear agent ${id}`, refusalText(outcome.reason));
233
+ break;
234
+ }
235
+ }
236
+ })();
237
+ }
238
+ /** Why a clear refused, in the menu's words. */
239
+ function refusalText(reason) {
240
+ switch (reason) {
241
+ case "unknown-id":
242
+ return "no such agent";
243
+ case "not-terminal":
244
+ return "the agent is not settled";
245
+ case "in-flight":
246
+ return "another teardown is already running";
247
+ }
248
+ }
249
+ /**
250
+ * Per-agent actions submenu for a delegating component.
251
+ * @param done — return to the parent agent list.
252
+ * @param setActive — swap the delegating component's active child.
253
+ * @param onClose — close the entire menu.
254
+ */
255
+ export function buildAgentActionsList(ctx, spawn, theme, done, setActive, onClose) {
256
+ const items = [];
257
+ // Spawn id is the full handle — printed whole, never sliced.
258
+ const id = spawn.id;
259
+ const activeSpawn = isActivePhase(spawn.lifecycle.phase);
260
+ const hasHerdrPane = !!spawn.execution.host;
261
+ // Result/error exist only on the settled outcome.
262
+ const resultText = lifecycleResult(spawn.lifecycle);
263
+ const errorText = hasOutcome(spawn.lifecycle) && spawn.lifecycle.status === "error"
264
+ ? spawn.lifecycle.error
265
+ : "";
266
+ const hasResult = resultText.length > 0;
267
+ const hasError = errorText.length > 0;
268
+ if (hasHerdrPane) {
269
+ items.push({
270
+ value: "focus-pane",
271
+ label: "View shell",
272
+ description: "Focus the subagent's herdr pane",
273
+ });
274
+ }
275
+ if (hasResult) {
276
+ items.push({ value: "view-result", label: "View result" });
277
+ }
278
+ if (hasError) {
279
+ items.push({ value: "view-error", label: "View error" });
280
+ }
281
+ if (activeSpawn) {
282
+ items.push({ value: "stop", label: "Stop" });
283
+ }
284
+ else {
285
+ items.push({
286
+ value: "clear",
287
+ label: "Clear",
288
+ description: spawn.display.worktree?.kind === "owned"
289
+ ? "Clear agent and remove its worktree"
290
+ : undefined,
291
+ });
292
+ items.push({
293
+ value: "cleanup",
294
+ label: "Clean up",
295
+ description: "Close its pane and remove its worktree and merged branch",
296
+ });
297
+ }
298
+ if (items.length === 0) {
299
+ ctx.ui.notify(`Agent ${id} — no actions available`, "info");
300
+ done();
301
+ return new SelectList([], 5, buildSelectListTheme(theme));
302
+ }
303
+ const list = withVimKeys(new SelectList(items, 10, buildSelectListTheme(theme)));
304
+ list.onSelect = async (item) => {
305
+ if (item.value === "focus-pane") {
306
+ await focusHerdrPane(ctx, spawn);
307
+ }
308
+ else if (item.value === "view-result") {
309
+ await showTextViewer(ctx, spawn, "result", resultText);
310
+ }
311
+ else if (item.value === "view-error") {
312
+ await showTextViewer(ctx, spawn, "error", errorText);
313
+ }
314
+ else if (item.value === "stop") {
315
+ actionReport(ctx.ui).pending(`Stopping agent ${id}`);
316
+ done();
317
+ stopAgentsOffMenu(ctx, [spawn.id]);
318
+ }
319
+ else if (item.value === "clear") {
320
+ actionReport(ctx.ui).pending(`Clearing agent ${id}`);
321
+ onClose();
322
+ clearAgentsOffMenu(ctx, [spawn.id]);
323
+ }
324
+ else if (item.value === "cleanup") {
325
+ // The spawn record goes with the artifacts, so the list it came from is
326
+ // stale either way: close, and report the teardown when it lands.
327
+ actionReport(ctx.ui).pending(`Cleaning up agent ${id}`);
328
+ onClose();
329
+ cleanupAgentsOffMenu(ctx, [spawn.id]);
330
+ }
331
+ };
332
+ list.onCancel = () => done();
333
+ return list;
334
+ }
335
+ export async function showAgentStatusMenu(ctx) {
336
+ // Settled spawns outlive their session, so list (and clear) them here.
337
+ const agents = getManagerOrNull()?.listAgents(ALL_AGENT_PHASES) ?? [];
338
+ if (agents.length === 0) {
339
+ ctx.ui.notify("No agents have been spawned this session", "info");
340
+ return;
341
+ }
342
+ // Active work is never cleared (ADR-0006).
343
+ const activeAgents = agents.filter((r) => isActivePhase(r.lifecycle.phase));
344
+ const finished = agents.filter((r) => !isActivePhase(r.lifecycle.phase));
345
+ const completed = agents.filter((r) => hasOutcome(r.lifecycle) && r.lifecycle.status === "completed");
346
+ await new ScreenHost(ctx).open(({ theme, close }) => {
347
+ const buildAgentItems = () => {
348
+ // One timestamp for every row keeps durations mutually consistent.
349
+ const now = Date.now();
350
+ const items = agents.map((spawn) => {
351
+ // Finished runs freeze at completion (completedAt is stamped on every terminal path).
352
+ const status = lifecycleStatus(spawn.lifecycle);
353
+ const active = isActivePhase(spawn.lifecycle.phase);
354
+ const end = hasOutcome(spawn.lifecycle)
355
+ ? spawn.lifecycle.completedAt
356
+ : now;
357
+ const duration = formatMs(end - lifecycleStartTime(spawn.lifecycle));
358
+ const ago = active ? "" : ` ${formatMs(now - end)} ago`;
359
+ const icon = statusIcon(status, theme);
360
+ const headline = spawn.display.description
361
+ ? spawn.display.description
362
+ : "";
363
+ const suffix = headline ? ` \u2014 ${headline}` : "";
364
+ const bullet = agentBulletPrefix(theme);
365
+ const wtInfo = spawn.display.worktree
366
+ ? ` wt:${spawn.display.worktree.branch}`
367
+ : "";
368
+ return {
369
+ value: spawn.id,
370
+ label: `${icon} ${spawn.id} ${bullet}${spawn.display.type} ${status} ${duration}${wtInfo}${suffix}${ago}`,
371
+ };
372
+ });
373
+ if (activeAgents.length > 0) {
374
+ items.push({ value: SEPARATOR_ID, label: " " });
375
+ items.push({
376
+ value: "__stop-all",
377
+ label: `Stop ${activeAgents.length} active agent(s)`,
378
+ });
379
+ }
380
+ if (finished.length > 0) {
381
+ // "Clear done" only when completed agents exist; clearing removes worktrees.
382
+ items.push({ value: SEPARATOR_ID, label: " " });
383
+ items.push({
384
+ value: "__cleanup-finished",
385
+ label: `Clean up ${finished.length} settled agent(s)`,
386
+ });
387
+ if (completed.length > 0) {
388
+ items.push({
389
+ value: "__clear-done",
390
+ label: "Clear done (remove worktrees)",
391
+ });
392
+ }
393
+ items.push({
394
+ value: "__clear-all",
395
+ label: "Clear all (remove worktrees)",
396
+ });
397
+ }
398
+ return items;
399
+ };
400
+ const agentList = withVimKeys(new SelectList(buildAgentItems(), 15, buildSelectListTheme(theme)));
401
+ // SelectList never lands on separators itself.
402
+ installSeparatorSkip(asListFields(agentList));
403
+ const view = new SwappableView(agentList);
404
+ agentList.onSelect = async (item) => {
405
+ if (item.value === "__stop-all") {
406
+ actionReport(ctx.ui).pending(`Stopping ${activeAgents.length} agent(s)`);
407
+ close();
408
+ stopAgentsOffMenu(ctx, activeAgents.map((r) => r.id));
409
+ return;
410
+ }
411
+ if (item.value === "__cleanup-finished") {
412
+ actionReport(ctx.ui).pending(`Cleaning up ${finished.length} settled agent(s)`);
413
+ close();
414
+ cleanupAgentsOffMenu(ctx, finished.map((r) => r.id));
415
+ return;
416
+ }
417
+ if (item.value === "__clear-all") {
418
+ actionReport(ctx.ui).pending(`Clearing ${finished.length} settled agent(s)`);
419
+ close();
420
+ clearAgentsOffMenu(ctx, finished.map((r) => r.id));
421
+ return;
422
+ }
423
+ if (item.value === "__clear-done") {
424
+ actionReport(ctx.ui).pending(`Clearing ${completed.length} completed agent(s)`);
425
+ close();
426
+ clearAgentsOffMenu(ctx, completed.map((r) => r.id));
427
+ return;
428
+ }
429
+ const spawn = agents.find((r) => r.id === item.value);
430
+ if (spawn) {
431
+ const actionsList = buildAgentActionsList(ctx, spawn, theme, () => {
432
+ view.activate(agentList);
433
+ }, view.activate.bind(view), () => close());
434
+ view.activate(actionsList);
435
+ }
436
+ };
437
+ agentList.onCancel = () => close();
438
+ return new SettingsListWrapper(view, {
439
+ title: "Status",
440
+ theme,
441
+ passthroughKeys: true,
442
+ });
443
+ });
444
+ }
@@ -0,0 +1,226 @@
1
+ /**
2
+ * menu-concurrency.ts — per-provider and per-model slot limits (ADR-0008 target levels).
3
+ * Values carry [session]/[project] tags when they come from those layers.
4
+ * Exports: showConcurrencySettingsMenu.
5
+ */
6
+ import { SettingsList } from "@earendil-works/pi-tui";
7
+ import { getStore } from "../../shell.js";
8
+ import { SEPARATOR_ID, buildSettingsListTheme, buildModelOptions, createSearchableSelect, extractConfiguredModels, } from "./helpers.js";
9
+ import { createNumericSubmenu } from "./submenus/numeric-input.js";
10
+ import { buildLevelItems, createClearPickerSubmenu, createLevelPickerSubmenu, createTargetSelectSubmenu, createClearAllSubmenu, } from "./submenus/target-select.js";
11
+ import { SettingsListWrapper } from "./wrappers/settings-list.js";
12
+ import { ScreenHost } from "./screen-host.js";
13
+ export async function showConcurrencySettingsMenu(ctx, modelOptions) {
14
+ const buildItems = (store, theme, modelOptions) => {
15
+ const providers = [
16
+ ...new Set(modelOptions.map((m) => m.split("/")[0])),
17
+ ].sort();
18
+ const items = [];
19
+ const projectOffered = store.isProjectWritable;
20
+ /** Whether the layer carries this concurrency entry. */
21
+ const layerHas = (layer, section, key) => section === "default"
22
+ ? layer.default !== undefined
23
+ : key !== undefined && layer[section]?.[key] !== undefined;
24
+ /** Layers carrying this entry; drives the remove/clear pickers. */
25
+ const entryLevels = (section, key) => ({
26
+ session: layerHas(store.sessionConcurrency, section, key),
27
+ global: layerHas(store.globalConcurrency, section, key),
28
+ project: layerHas(store.projectConcurrency, section, key),
29
+ });
30
+ /** " [session]" / " [project]" when the effective value comes from that layer. */
31
+ const limitTag = (section, key) => {
32
+ if (layerHas(store.sessionConcurrency, section, key))
33
+ return " [session]";
34
+ if (layerHas(store.projectConcurrency, section, key))
35
+ return " [project]";
36
+ return "";
37
+ };
38
+ // Target level, then numeric value.
39
+ const targetThenValueSubmenu = (initial, onPick) => (currentValue, done) => createTargetSelectSubmenu({
40
+ theme,
41
+ projectOffered,
42
+ onPick: (target, pickDone) => createNumericSubmenu(ctx, {
43
+ kind: "optional",
44
+ min: 1,
45
+ onValid: (parsed) => onPick(target, parsed),
46
+ })(initial, pickDone),
47
+ })(currentValue, done);
48
+ // Set at a target level, or Clear via a nested per-level picker.
49
+ const limitSubmenu = (currentLimit, onSet, onRemove, availableLevels) => (currentValue, done) => {
50
+ // A fresh default has an effective value but no raw key, so Clear needs a carrier.
51
+ const items = buildLevelItems({
52
+ offered: { session: true, global: true, project: projectOffered },
53
+ includeClear: availableLevels.session ||
54
+ availableLevels.global ||
55
+ availableLevels.project,
56
+ });
57
+ return createLevelPickerSubmenu({
58
+ theme,
59
+ items,
60
+ onPick: (id, subDone) => {
61
+ if (id === "clear") {
62
+ return createClearPickerSubmenu({
63
+ theme,
64
+ projectOffered,
65
+ availableLevels,
66
+ onClear: onRemove,
67
+ })("", subDone);
68
+ }
69
+ const target = id;
70
+ return createNumericSubmenu(ctx, {
71
+ kind: "optional",
72
+ min: 1,
73
+ onValid: (parsed) => onSet(target, parsed),
74
+ })(String(currentLimit), subDone);
75
+ },
76
+ })(currentValue, done);
77
+ };
78
+ // Searchable-pick an option, then target → numeric value.
79
+ const addPickThenValueSubmenu = (items, onPick) => (currentValue, done) => createSearchableSelect(items, {
80
+ // A limit needs a model key, so the inherit row cancels.
81
+ onSelect: (key) => {
82
+ if (key == null)
83
+ return done();
84
+ return targetThenValueSubmenu("1", (target, parsed) => onPick(key, target, parsed))(currentValue, done);
85
+ },
86
+ onCancel: () => done(),
87
+ }, theme);
88
+ items.push({
89
+ id: "defaultConcurrency",
90
+ label: "Default concurrency limit",
91
+ currentValue: `${store.concurrency.default}${limitTag("default")}`,
92
+ description: "Concurrent agents, whatever provider or model they use.",
93
+ submenu: limitSubmenu(store.concurrency.default, (target, parsed) => {
94
+ store.mutate.concurrency.setDefault(parsed, target);
95
+ ctx.ui.notify(`Default concurrency set to ${parsed} (${target})`, "info");
96
+ }, (target) => {
97
+ store.mutate.concurrency.removeDefault(target);
98
+ ctx.ui.notify(`Removed default concurrency limit (${target})`, "info");
99
+ }, entryLevels("default")),
100
+ });
101
+ items.push({ id: SEPARATOR_ID, label: " ", currentValue: "" });
102
+ items.push({
103
+ id: SEPARATOR_ID,
104
+ label: theme.bold(theme.fg("accent", "Per-provider limits")),
105
+ currentValue: "",
106
+ });
107
+ const providerLimits = store.concurrency.providers;
108
+ for (const provider of Object.keys(providerLimits)) {
109
+ const limit = providerLimits[provider];
110
+ items.push({
111
+ id: `provider:${provider}`,
112
+ label: provider,
113
+ currentValue: `${limit} slots${limitTag("providers", provider)}`,
114
+ description: `Concurrent slots reserved for agents using the ${provider} provider.`,
115
+ submenu: limitSubmenu(limit, (target, parsed) => {
116
+ store.mutate.concurrency.setProvider(provider, parsed, target);
117
+ ctx.ui.notify(`${provider} concurrency set to ${parsed} (${target})`, "info");
118
+ }, (target) => {
119
+ store.mutate.concurrency.removeProvider(provider, target);
120
+ ctx.ui.notify(`Removed per-provider limit for ${provider} (${target})`, "info");
121
+ }, entryLevels("providers", provider)),
122
+ });
123
+ }
124
+ items.push({
125
+ id: SEPARATOR_ID,
126
+ label: "─────────────────────────",
127
+ currentValue: "────────",
128
+ });
129
+ if (providers.length > 0) {
130
+ items.push({
131
+ id: "addProviderLimit",
132
+ label: "Add per-provider limit...",
133
+ currentValue: "",
134
+ description: "Cap how many agents run at once for a single provider.",
135
+ submenu: addPickThenValueSubmenu(providers.map((o) => ({ value: o, label: o })), (provider, target, parsed) => {
136
+ store.mutate.concurrency.setProvider(provider, parsed, target);
137
+ ctx.ui.notify(`${provider} concurrency set to ${parsed} (${target})`, "info");
138
+ }),
139
+ });
140
+ }
141
+ items.push({ id: SEPARATOR_ID, label: " ", currentValue: "" });
142
+ items.push({
143
+ id: SEPARATOR_ID,
144
+ label: theme.bold(theme.fg("accent", "Per-model limits")),
145
+ currentValue: "",
146
+ });
147
+ const models = store.concurrency.models;
148
+ for (const modelKey of Object.keys(models)) {
149
+ const limit = models[modelKey];
150
+ items.push({
151
+ id: `model:${modelKey}`,
152
+ label: modelKey,
153
+ currentValue: `${limit} slots${limitTag("models", modelKey)}`,
154
+ description: `Concurrent slots reserved for agents using the ${modelKey} model.`,
155
+ submenu: limitSubmenu(limit, (target, parsed) => {
156
+ store.mutate.concurrency.setModel(modelKey, parsed, target);
157
+ ctx.ui.notify(`${modelKey} concurrency set to ${parsed} (${target})`, "info");
158
+ }, (target) => {
159
+ store.mutate.concurrency.removeModel(modelKey, target);
160
+ ctx.ui.notify(`Removed per-model limit for ${modelKey} (${target})`, "info");
161
+ }, entryLevels("models", modelKey)),
162
+ });
163
+ }
164
+ items.push({
165
+ id: SEPARATOR_ID,
166
+ label: "─────────────────────────",
167
+ currentValue: "────────",
168
+ });
169
+ if (modelOptions.length > 0) {
170
+ const configuredModels = extractConfiguredModels(store.agentConfigSnapshot());
171
+ items.push({
172
+ id: "addModelLimit",
173
+ label: "Add per-model limit...",
174
+ currentValue: "",
175
+ description: "Cap how many agents run at once for a single model.",
176
+ submenu: addPickThenValueSubmenu(buildModelOptions(modelOptions, undefined, configuredModels), (modelKey, target, parsed) => {
177
+ store.mutate.concurrency.setModel(modelKey, parsed, target);
178
+ ctx.ui.notify(`${modelKey} concurrency set to ${parsed} (${target})`, "info");
179
+ }),
180
+ });
181
+ }
182
+ items.push({ id: SEPARATOR_ID, label: " ", currentValue: "" });
183
+ // One level is offered only when it carries entries; the row hides when none do.
184
+ const availableLevels = {
185
+ session: store.hasSessionConcurrencySettings,
186
+ global: store.hasGlobalConcurrencySettings,
187
+ project: store.hasProjectConcurrencySettings && projectOffered,
188
+ };
189
+ if (availableLevels.session ||
190
+ availableLevels.global ||
191
+ availableLevels.project) {
192
+ items.push({
193
+ id: "resetAll",
194
+ label: "Clear all concurrency limits...",
195
+ currentValue: "",
196
+ description: "Remove concurrency overrides at the chosen level (session, global, project, or all).",
197
+ submenu: createClearAllSubmenu({
198
+ theme,
199
+ projectOffered,
200
+ availableLevels,
201
+ message: (target) => `Clear all concurrency limits at the ${target} level?`,
202
+ onConfirm: (target) => {
203
+ store.mutate.concurrency.clearAll(target);
204
+ ctx.ui.notify(`Concurrency limits cleared (${target})`, "info");
205
+ },
206
+ }),
207
+ });
208
+ }
209
+ return items;
210
+ };
211
+ let rebuild;
212
+ await new ScreenHost(ctx).open(({ theme, close }) => {
213
+ const triggerRebuild = () => rebuild?.(buildItems(getStore(), theme, modelOptions));
214
+ const store = getStore();
215
+ const items = buildItems(store, theme, modelOptions);
216
+ const settingsList = new SettingsList(items, 15, buildSettingsListTheme(theme), (_id, _v) => triggerRebuild(), close);
217
+ return new SettingsListWrapper(settingsList, {
218
+ title: "Concurrency Settings",
219
+ theme,
220
+ onCancel: close,
221
+ onRebuild: (r) => {
222
+ rebuild = r;
223
+ },
224
+ });
225
+ });
226
+ }