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
package/dist/types.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * pi reads a file whenever `--system-prompt`'s value is an existing path, so
3
+ * multi-line instructions ride out of herdr's single-line argv.
4
+ */
5
+ export const SUBAGENT_SYSTEM_FILE_NAME = "system.md";
6
+ /** The pane's `@<file>` initial message; holds the task text and nothing else. */
7
+ export const SUBAGENT_TASK_FILE_NAME = "prompt.md";
8
+ /**
9
+ * Built-in fallbacks for the configurable spawn defaults. A persisted setting
10
+ * that is unset or names a type/template that no longer resolves degrades to
11
+ * these — a removed registry entry never fails a spawn.
12
+ */
13
+ export const DEFAULT_AGENT_TYPE = "general-purpose";
14
+ export const DEFAULT_ORCHESTRATOR_NAME = "default";
15
+ /**
16
+ * Whether a run in each phase is over. The one declaration of the lattice:
17
+ * `satisfies Record<AgentPhase, boolean>` rejects a phase that is added,
18
+ * renamed, or dropped without an entry here, and the phase lists, the
19
+ * predicates, and every caller that filters spawns all read it.
20
+ */
21
+ const PHASE_IS_OVER = {
22
+ queued: false,
23
+ spawned: false,
24
+ settled: true,
25
+ "never-started": true,
26
+ };
27
+ /** The phases the table marks, in declaration order. */
28
+ function phasesWhere(over) {
29
+ return Object.keys(PHASE_IS_OVER).filter((phase) => PHASE_IS_OVER[phase] === over);
30
+ }
31
+ /** Spawns still in flight: the runs stop, steer, and clear act on. */
32
+ export const ACTIVE_AGENT_PHASES = phasesWhere(false);
33
+ /** Ended spawns — settled, or ended before they ever launched — retained until an explicit drop. */
34
+ export const TERMINAL_AGENT_PHASES = phasesWhere(true);
35
+ /** Every phase, ended ones included. */
36
+ export const ALL_AGENT_PHASES = [
37
+ ...ACTIVE_AGENT_PHASES,
38
+ ...TERMINAL_AGENT_PHASES,
39
+ ];
40
+ /** Whether the run is over. The one membership test; every ended/active check reads it. */
41
+ export function isEndedPhase(phase) {
42
+ return PHASE_IS_OVER[phase];
43
+ }
44
+ /** Whether the run is still in flight. */
45
+ export function isActivePhase(phase) {
46
+ return !PHASE_IS_OVER[phase];
47
+ }
48
+ /**
49
+ * Whether the run has a decided outcome. A narrowing predicate: the readers
50
+ * that want `completedAt`, `status`, or the retention reason get both ended
51
+ * phases at once instead of re-testing each.
52
+ */
53
+ export function hasOutcome(state) {
54
+ return isEndedPhase(state.phase);
55
+ }
56
+ /** The AgentStatus word for a lifecycle state. */
57
+ export function lifecycleStatus(state) {
58
+ switch (state.phase) {
59
+ case "queued":
60
+ return "queued";
61
+ case "spawned":
62
+ return "spawned";
63
+ case "settled":
64
+ case "never-started":
65
+ return state.status;
66
+ }
67
+ }
68
+ /** The agent's result text, or "" for outcomes without one (error/stop). */
69
+ export function lifecycleResult(state) {
70
+ return state.phase === "settled" && state.status === "completed"
71
+ ? state.result
72
+ : "";
73
+ }
74
+ /** When the run's clock starts: its queue time until it launches, its start time after. */
75
+ export function lifecycleStartTime(state) {
76
+ switch (state.phase) {
77
+ case "queued":
78
+ case "never-started":
79
+ return state.queuedAt;
80
+ case "spawned":
81
+ case "settled":
82
+ return state.startedAt;
83
+ }
84
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * action-report.ts — the three-stage report every slow /cowboy action uses.
3
+ *
4
+ * One shape for all of them: an in-progress line the moment the action is
5
+ * selected, then exactly one terminal line — the success it landed on, or an
6
+ * error naming the reason. Naming the stages in one place keeps them reading
7
+ * alike whether they surface in the spawn wizard, the status menu, or the
8
+ * launch coordinator. The terminal lines carry the same themed ✓ and ✗ the
9
+ * tool-result renderers use, so a landing reads alike wherever it lands.
10
+ */
11
+ import { errorMessage } from "../utils.js";
12
+ /** Bind the three stages to a UI context. */
13
+ export function actionReport(target) {
14
+ const check = target.theme.fg("success", "✓");
15
+ const cross = target.theme.fg("error", "✗");
16
+ return {
17
+ pending: (message) => target.notify(`${message} \u2026`, "info"),
18
+ succeeded: (message, kind = "info") => target.notify(`${check} ${message}`, kind),
19
+ failed: (message, reason) => target.notify(`${cross} ${message}: ${errorMessage(reason)}`, "error"),
20
+ };
21
+ }
@@ -0,0 +1,47 @@
1
+ /** Display formatting helpers shared by the UI layer. */
2
+ import { getAgentConfig } from "../agents/agent-types.js";
3
+ /** Single source of truth for per-agent status icons (tool call lines, status widget, conversation viewer). */
4
+ const STATUS_ICON = {
5
+ queued: { icon: "◆", color: "accent" },
6
+ spawned: { icon: "◈", color: "accent" },
7
+ completed: { icon: "✓", color: "success" },
8
+ error: { icon: "✗", color: "error" },
9
+ stopped: { icon: "■", color: "dim" },
10
+ };
11
+ /** Theme-colored icon for an agent status, or a muted ▸ when absent. */
12
+ export function statusIcon(status, theme) {
13
+ if (status === undefined)
14
+ return theme.fg("muted", "▸");
15
+ const entry = STATUS_ICON[status];
16
+ return theme.fg(entry.color, entry.icon);
17
+ }
18
+ /** Format milliseconds as a compact human-readable duration: "1h 1m 1s", "5m 37s", "10s", "<1s". */
19
+ export function formatMs(ms) {
20
+ if (!Number.isFinite(ms) || ms < 1000)
21
+ return "<1s";
22
+ const totalSeconds = Math.floor(ms / 1000);
23
+ const hours = Math.floor(totalSeconds / 3600);
24
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
25
+ const seconds = totalSeconds % 60;
26
+ const parts = [];
27
+ if (hours > 0)
28
+ parts.push(`${hours}h`);
29
+ if (minutes > 0)
30
+ parts.push(`${minutes}m`);
31
+ if (seconds > 0 || parts.length === 0)
32
+ parts.push(`${seconds}s`);
33
+ return parts.join(" ");
34
+ }
35
+ export function getDisplayName(type) {
36
+ const config = getAgentConfig(type);
37
+ return config?.displayName ?? config?.name ?? "Agent";
38
+ }
39
+ export function agentBulletPrefix(theme) {
40
+ return `${theme.fg("accent", "•")} `;
41
+ }
42
+ /** Shorten a path to its tail, prefixed with "..." when it is longer than `maxLength`. */
43
+ export function truncatePath(path, maxLength) {
44
+ if (path.length <= maxLength)
45
+ return path;
46
+ return "..." + path.slice(path.length - maxLength + 3);
47
+ }
@@ -0,0 +1,480 @@
1
+ /**
2
+ * indicator.ts — the extension's presence marker: 🤠 in the top-right corner
3
+ * of the screen while the extension is on, standing on his own row above a
4
+ * green pasture, centred over its middle column. The pasture is the smallest
5
+ * square of cells that can hold twice its stock — one 🐄 per live agent and one
6
+ * 💩 per agent that has ended and waits to be cleaned up — so at least half of
7
+ * it is always empty. It is drawn only while grazing is switched on, when its
8
+ * herd is dropped in at random and one cow may step to a neighbouring cell every
9
+ * second; a dropping stays where it fell. With grazing off the cowboy stands
10
+ * alone and the poll stops with the pasture; the fleet is counted again when it
11
+ * returns. Cowboy and pasture ride an overlay each rather than a widget, so they
12
+ * cost no line of the transcript. Both are anchored at the top-right with no
13
+ * margin: the cowboy takes row 0, in exactly his own two columns, and the pasture
14
+ * covers the rows below him rather than pushing content down. Each overlay is
15
+ * sized to what it draws, and the cowboy is shifted left over the pasture's
16
+ * middle column by an offset rather than by padding, so neither covers a cell
17
+ * it does not draw.
18
+ */
19
+ import { visibleWidth, } from "@earendil-works/pi-tui";
20
+ import { TERMINAL_AGENT_PHASES } from "../types.js";
21
+ import { getAgentSpawns, getIndicatorMarker, getStore, setIndicatorMarker, } from "../shell.js";
22
+ /** The extension's own presence: the cowboy, on his own row above the pasture. */
23
+ export const INDICATOR_MARKER = "🤠";
24
+ /** One live agent's presence, and one head of pasture stock. */
25
+ export const AGENT_MARKER = "🐄";
26
+ /** One ended agent's presence: a dropping that stays where it fell. */
27
+ export const DROPPING = "💩";
28
+ /** The smallest edge a pasture with stock in it can have. */
29
+ export const MIN_PASTURE_EDGE = 2;
30
+ /** How often the marker re-counts the fleet, and the herd rolls for a step while grazing. */
31
+ const POLL_INTERVAL_MS = 1_000;
32
+ /** One pasture cell's width in columns: the same for a cow and for a dropping. */
33
+ const CELL_WIDTH = visibleWidth(AGENT_MARKER);
34
+ /**
35
+ * The pasture's grass: an explicit truecolor green, back to the terminal's own
36
+ * background afterwards. It cannot come from the theme, whose palette has no
37
+ * green background, nor from the terminal's ANSI "green" — a colour scheme is
38
+ * free to map that to anything.
39
+ */
40
+ export const GRASS_RGB = "76;175;80";
41
+ /** Paints `text` with the grass's green behind it. */
42
+ export function greenBackground(text) {
43
+ return `\x1b[48;2;${GRASS_RGB}m${text}\x1b[49m`;
44
+ }
45
+ /**
46
+ * The pasture's edge for `occupants` head: the smallest square that is at least
47
+ * twice the stock, so half of its cells stay empty, and never an edge below the
48
+ * minimum. No stock needs no square, so their edge is 0.
49
+ */
50
+ export function pastureEdge(occupants) {
51
+ if (occupants === 0)
52
+ return 0;
53
+ return Math.max(MIN_PASTURE_EDGE, Math.ceil(Math.sqrt(2 * occupants)));
54
+ }
55
+ /** An `edge`×`edge` pasture with nothing standing in it. */
56
+ function emptyPasture(edge) {
57
+ return Array.from({ length: edge }, () => Array.from({ length: edge }, () => "empty"));
58
+ }
59
+ /**
60
+ * The pasture's stock dropped at random into the square sized for all of it:
61
+ * one roll per occupant, the cells drawn by a partial Fisher–Yates over the
62
+ * square's slots so a cell is handed to one occupant and never a second. Cows
63
+ * are placed before droppings.
64
+ */
65
+ export function grazedPasture(stock, random) {
66
+ const edge = pastureEdge(stock.cows + stock.droppings);
67
+ const pasture = emptyPasture(edge);
68
+ const spots = Array.from({ length: edge * edge }, (_, index) => index);
69
+ const occupants = [
70
+ ...Array.from({ length: stock.cows }, () => "cow"),
71
+ ...Array.from({ length: stock.droppings }, () => "dropping"),
72
+ ];
73
+ // Each occupant takes the slot the shuffle hands it, so a cell is drawn for
74
+ // one occupant and never a second.
75
+ for (let at = 0; at < occupants.length; at += 1) {
76
+ const pick = at + Math.floor(random() * (spots.length - at));
77
+ const spot = spots[pick];
78
+ spots[pick] = spots[at];
79
+ spots[at] = spot;
80
+ pasture[Math.floor(spot / edge)][spot % edge] = occupants[at];
81
+ }
82
+ return pasture;
83
+ }
84
+ /** Every cell of `kind`, in reading order. */
85
+ function cellsOf(pasture, kind) {
86
+ const cells = [];
87
+ for (let row = 0; row < pasture.length; row += 1) {
88
+ for (let col = 0; col < pasture[row].length; col += 1) {
89
+ if (pasture[row][col] === kind)
90
+ cells.push({ row, col });
91
+ }
92
+ }
93
+ return cells;
94
+ }
95
+ /** The cells a cow at `from` can step to: its orthogonal neighbours inside the pasture. */
96
+ function neighboursOf(from, edge) {
97
+ const around = [
98
+ { row: from.row - 1, col: from.col },
99
+ { row: from.row, col: from.col + 1 },
100
+ { row: from.row + 1, col: from.col },
101
+ { row: from.row, col: from.col - 1 },
102
+ ];
103
+ return around.filter(({ row, col }) => row >= 0 && row < edge && col >= 0 && col < edge);
104
+ }
105
+ /** The neighbours of `cow` standing in empty grass — never another cow, never a dropping. */
106
+ function openNeighboursOf(cow, pasture) {
107
+ return neighboursOf(cow, pasture.length).filter(({ row, col }) => pasture[row][col] === "empty");
108
+ }
109
+ /**
110
+ * One turn of grazing: one cow of the herd steps to an open neighbouring cell
111
+ * on a roll under one twentieth — so the herd moves on one turn in twenty and
112
+ * grazes where it stands on the rest. The cow and the cell are both drawn at
113
+ * random, from the cows that have somewhere to go. A dropping is never a mover,
114
+ * and no cow steps onto one; a pasture whose cows are all boxed in rolls no
115
+ * dice at all.
116
+ */
117
+ export function moveHerd(pasture, random) {
118
+ const movers = cellsOf(pasture, "cow").filter((cow) => openNeighboursOf(cow, pasture).length > 0);
119
+ if (movers.length === 0)
120
+ return pasture;
121
+ if (random() >= 0.05)
122
+ return pasture;
123
+ const cow = movers[Math.floor(random() * movers.length)];
124
+ const open = openNeighboursOf(cow, pasture);
125
+ const to = open[Math.floor(random() * open.length)];
126
+ const next = pasture.map((row) => row.slice());
127
+ next[cow.row][cow.col] = "empty";
128
+ next[to.row][to.col] = "cow";
129
+ return next;
130
+ }
131
+ /** The cells of `kind` to add, each taking a random empty cell: one roll apiece. */
132
+ function placeAtRandom(pasture, kind, count, random) {
133
+ for (let placed = 0; placed < count; placed += 1) {
134
+ const empties = cellsOf(pasture, "empty");
135
+ const pick = empties[Math.floor(random() * empties.length)];
136
+ pasture[pick.row][pick.col] = kind;
137
+ }
138
+ }
139
+ /**
140
+ * Turn a pasture's stock toward `cows` and `droppings` without ever moving a
141
+ * cell that can stay: a settling agent's cow becomes a dropping where it
142
+ * stands, a cleaned-up agent's dropping is cleared, and both take the last of
143
+ * their kind in reading order so a surplus leans on the cells away from the
144
+ * top-left. Only a deficit is placed, one roll per new occupant into a random
145
+ * empty cell.
146
+ */
147
+ function reconcileCounts(pasture, cows, droppings, random) {
148
+ const cowCells = cellsOf(pasture, "cow");
149
+ const dropCells = cellsOf(pasture, "dropping");
150
+ let cowSurplus = cowCells.length - cows;
151
+ let dropSurplus = dropCells.length - droppings;
152
+ while (cowSurplus > 0 && dropSurplus < 0) {
153
+ const cell = cowCells.pop();
154
+ pasture[cell.row][cell.col] = "dropping";
155
+ cowSurplus -= 1;
156
+ dropSurplus += 1;
157
+ }
158
+ while (cowSurplus > 0) {
159
+ const cell = cowCells.pop();
160
+ pasture[cell.row][cell.col] = "empty";
161
+ cowSurplus -= 1;
162
+ }
163
+ while (dropSurplus > 0) {
164
+ const cell = dropCells.pop();
165
+ pasture[cell.row][cell.col] = "empty";
166
+ dropSurplus -= 1;
167
+ }
168
+ placeAtRandom(pasture, "cow", -cowSurplus, random);
169
+ placeAtRandom(pasture, "dropping", -dropSurplus, random);
170
+ }
171
+ /**
172
+ * The pasture for a stock of `cows` live agents and `droppings` ended ones,
173
+ * grown or shrunk from `previous` — or placed fresh when there is none. The
174
+ * square is resized to the edge the total stock asks for, keeping every cell
175
+ * the new square can hold where it stands; the stock is then reconciled to the
176
+ * counts. Going from one count to another costs a roll only where the placement
177
+ * is at random: a resize itself rolls nothing, and a cow that settled keeps its
178
+ * cell.
179
+ */
180
+ export function reconcilePasture(previous, stock, random) {
181
+ if (previous === null)
182
+ return grazedPasture(stock, random);
183
+ const edge = pastureEdge(stock.cows + stock.droppings);
184
+ const pasture = emptyPasture(edge);
185
+ for (let row = 0; row < previous.length && row < edge; row += 1) {
186
+ for (let col = 0; col < previous[row].length && col < edge; col += 1) {
187
+ pasture[row][col] = previous[row][col];
188
+ }
189
+ }
190
+ reconcileCounts(pasture, stock.cows, stock.droppings, random);
191
+ return pasture;
192
+ }
193
+ /**
194
+ * The cowboy's own overlay: his two columns, pinned to the screen's top-right
195
+ * corner and shifted left over the pasture's middle column. The shift is read
196
+ * from the mounted marker on each frame, so the cowboy's box can stay his own
197
+ * two columns while the pasture under him grows and shrinks. Non-capturing, so
198
+ * the editor keeps the keyboard.
199
+ */
200
+ const COWBOY_OVERLAY = {
201
+ anchor: "top-right",
202
+ width: visibleWidth(INDICATOR_MARKER),
203
+ get offsetX() {
204
+ return getIndicatorMarker()?.cowboyOffsetX ?? 0;
205
+ },
206
+ nonCapturing: true,
207
+ };
208
+ /**
209
+ * The pasture's own overlay, on the row below the cowboy's. The overlay covers
210
+ * every cell of its box, so its width is read from the mounted marker on each
211
+ * frame: a box wider than the pasture would erase what it covers, and with no
212
+ * pasture to draw there is no box at all.
213
+ */
214
+ const PASTURE_OVERLAY = {
215
+ anchor: "top-right",
216
+ offsetY: 1,
217
+ get width() {
218
+ return getIndicatorMarker()?.pastureWidth ?? 0;
219
+ },
220
+ nonCapturing: true,
221
+ };
222
+ /** One cell as it prints: a cow, a dropping, or the empty grass between them. */
223
+ function cellText(cell) {
224
+ if (cell === "cow")
225
+ return AGENT_MARKER;
226
+ if (cell === "dropping")
227
+ return DROPPING;
228
+ return " ".repeat(CELL_WIDTH);
229
+ }
230
+ /**
231
+ * The rows the pasture draws: one per row of the square, each cell padded to
232
+ * its width and painted with `grass`. There are none for no pasture, and the
233
+ * cowboy is not among them — he rides an overlay of his own above them.
234
+ */
235
+ function drawnRows(pasture, grass) {
236
+ return pasture.map((row) => grass(row.map(cellText).join("")));
237
+ }
238
+ /** Only actively executing agents graze: a queued agent has no cow in the pasture yet. */
239
+ function liveAgentCount() {
240
+ return getAgentSpawns().list(["spawned"]).length;
241
+ }
242
+ /**
243
+ * Ended spawns awaiting cleanup, each of which leaves a dropping: completed,
244
+ * stopped, failed, or ended before it ever launched. All of them count here and
245
+ * are shown until they are dropped from the store.
246
+ */
247
+ function endedAgentCount() {
248
+ return getAgentSpawns().list(TERMINAL_AGENT_PHASES).length;
249
+ }
250
+ /** Both halves of the fleet read from the store, in one synchronous pass. */
251
+ function agentCounts() {
252
+ return { live: liveAgentCount(), ended: endedAgentCount() };
253
+ }
254
+ /**
255
+ * Read per frame rather than at mount, so flipping the setting takes the
256
+ * pasture down and brings it back without the marker itself being taken down.
257
+ */
258
+ function grazingEnabled() {
259
+ return getStore().agent.grazingEnabled;
260
+ }
261
+ /**
262
+ * The marker. It counts the fleet on a timer of its own rather than being told:
263
+ * the spawn store publishes no changes, and a run settles wherever it ends, so
264
+ * there is nothing here to react to. It is drawn by two overlays — the cowboy's
265
+ * row by the marker itself, the pasture's rows by `PastureView` — and the width
266
+ * pi hands to `render` goes unused: each overlay is sized from the accessors
267
+ * below instead.
268
+ */
269
+ export class PresenceMarker {
270
+ tui;
271
+ countAgents;
272
+ isGrazing;
273
+ grass;
274
+ random;
275
+ /**
276
+ * The herd the marker draws: set by the first frame, re-set by every poll
277
+ * that finds a different fleet. Null until a frame has counted.
278
+ */
279
+ herd = null;
280
+ cowboyHandle = null;
281
+ pastureHandle = null;
282
+ poll = null;
283
+ /** Whether the marker has been taken down: a taken-down marker takes no frame. */
284
+ disposed = false;
285
+ /**
286
+ * The grazing setting as of the last turn taken; null until the first frame.
287
+ * Remembered because a flip redraws the pasture — appearing or going — and
288
+ * only a changed pasture is repainted.
289
+ */
290
+ grazing = null;
291
+ constructor(tui, countAgents, isGrazing, grass, random) {
292
+ this.tui = tui;
293
+ this.countAgents = countAgents;
294
+ this.isGrazing = isGrazing;
295
+ this.grass = grass;
296
+ this.random = random;
297
+ }
298
+ /** The cowboy's footprint: his own two columns, which no pasture widens. */
299
+ get cowboyWidth() {
300
+ return visibleWidth(INDICATOR_MARKER);
301
+ }
302
+ /**
303
+ * The pasture overlay's width in columns: the square's edge in cells, and
304
+ * zero with no pasture to draw. Derived fresh, so a fleet that grows or
305
+ * shrinks never leaves the overlay wider than the square it draws.
306
+ */
307
+ get pastureWidth() {
308
+ return this.drawnPasture().length * CELL_WIDTH;
309
+ }
310
+ /**
311
+ * How far the cowboy is shifted from the right edge: the middle cell of the
312
+ * square starts this many columns left of the last two columns he stands in
313
+ * when he is flush right. A shift left is negative, as the overlay's offset
314
+ * takes it. There is nothing to stand over without a pasture, so the shift is
315
+ * 0.
316
+ */
317
+ get cowboyOffsetX() {
318
+ const edge = this.drawnPasture().length;
319
+ if (edge === 0)
320
+ return 0;
321
+ const middle = Math.floor(edge / 2) * CELL_WIDTH;
322
+ return middle - (edge * CELL_WIDTH - this.cowboyWidth);
323
+ }
324
+ /** The cowboy's own row: one line, and no padding around him. */
325
+ render() {
326
+ this.frame();
327
+ return [INDICATOR_MARKER];
328
+ }
329
+ /**
330
+ * The pasture's rows for the herd as it stands: none before the first frame,
331
+ * and none while grazing is off.
332
+ */
333
+ pastureRows() {
334
+ this.frame();
335
+ return drawnRows(this.drawnPasture(), this.grass);
336
+ }
337
+ invalidate() { }
338
+ /** The cowboy overlay's handle, once pi has shown it. */
339
+ attachCowboy(handle) {
340
+ this.cowboyHandle = handle;
341
+ }
342
+ /** The pasture overlay's handle, once pi has shown it. */
343
+ attachPasture(handle) {
344
+ this.pastureHandle = handle;
345
+ }
346
+ /** Take both overlays down, and the poll with them. */
347
+ dispose() {
348
+ this.disposed = true;
349
+ if (this.poll !== null) {
350
+ clearInterval(this.poll);
351
+ this.poll = null;
352
+ }
353
+ this.cowboyHandle?.hide();
354
+ this.cowboyHandle = null;
355
+ this.pastureHandle?.hide();
356
+ this.pastureHandle = null;
357
+ }
358
+ /**
359
+ * The pasture to draw as the herd stands: the herd's placement while grazing
360
+ * is on, and nothing before the first frame or while grazing is off.
361
+ */
362
+ drawnPasture() {
363
+ return this.herd === null || !this.isGrazing() ? [] : this.herd.pasture;
364
+ }
365
+ /**
366
+ * Take a frame: the first one counts the fleet and owns the poll from then on,
367
+ * and every frame after it reads the setting, so the poll runs exactly while
368
+ * grazing is on and the frame that finds it changed takes a turn. A marker that
369
+ * is never drawn neither reads the fleet nor leaves a timer behind. Either half
370
+ * being drawn takes the frame, because the cowboy and the pasture are drawn by
371
+ * overlays with no order between them.
372
+ */
373
+ frame() {
374
+ if (this.disposed)
375
+ return;
376
+ const grazing = this.isGrazing();
377
+ if (this.herd === null) {
378
+ this.herd = this.place(this.countAgents());
379
+ this.grazing = grazing;
380
+ }
381
+ else if (grazing !== this.grazing) {
382
+ this.recount();
383
+ }
384
+ this.pollWhile(grazing);
385
+ }
386
+ /**
387
+ * Run the poll exactly while grazing is on: started when the setting comes on
388
+ * and cleared when it goes off. A repeated frame neither starts a second poll
389
+ * nor stops the one that is already running.
390
+ */
391
+ pollWhile(grazing) {
392
+ if (!grazing && this.poll !== null) {
393
+ clearInterval(this.poll);
394
+ this.poll = null;
395
+ }
396
+ else if (grazing && this.poll === null) {
397
+ this.poll = setInterval(() => this.recount(), POLL_INTERVAL_MS);
398
+ }
399
+ }
400
+ /**
401
+ * Take a turn: a fleet that changed is re-placed, and a held herd that is
402
+ * grazing takes one step. A turn that finds the setting flipped repaints with
403
+ * both counts held, taking the pasture down or bringing it back, and takes the
404
+ * poll down with it.
405
+ */
406
+ recount() {
407
+ const { live, ended } = this.countAgents();
408
+ const grazing = this.isGrazing();
409
+ const flipped = grazing !== this.grazing;
410
+ if (this.herd === null ||
411
+ live !== this.herd.liveAgents ||
412
+ ended !== this.herd.endedAgents) {
413
+ this.herd = this.place({ live, ended });
414
+ }
415
+ else if (grazing && !flipped) {
416
+ this.herd = {
417
+ ...this.herd,
418
+ pasture: moveHerd(this.herd.pasture, this.random),
419
+ };
420
+ }
421
+ else if (!flipped) {
422
+ return;
423
+ }
424
+ this.grazing = grazing;
425
+ this.pollWhile(grazing);
426
+ // With grazing off there is no pasture to draw and nothing under the cowboy
427
+ // to shift, so a fleet that moves the herd changes nothing on screen. Only
428
+ // the flip repaints, taking the pasture down or bringing it back.
429
+ if (grazing || flipped)
430
+ this.tui.requestRender();
431
+ }
432
+ /** The herd a fleet feeds, reconciled from the herd the marker is holding. */
433
+ place({ live, ended }) {
434
+ return {
435
+ liveAgents: live,
436
+ endedAgents: ended,
437
+ pasture: reconcilePasture(this.herd?.pasture ?? null, { cows: live, droppings: ended }, this.random),
438
+ };
439
+ }
440
+ }
441
+ /**
442
+ * The pasture's half of the marker, mounted as an overlay of its own on the row
443
+ * under the cowboy's. It draws whatever marker the shell holds, so the two
444
+ * overlays are mounted and taken down without either knowing the other.
445
+ */
446
+ class PastureView {
447
+ render() {
448
+ return getIndicatorMarker()?.pastureRows() ?? [];
449
+ }
450
+ invalidate() { }
451
+ }
452
+ /**
453
+ * Show 🤠 in the top-right corner of the screen, over a pasture of one 🐄 per
454
+ * live agent and one 💩 per ended one, while grazing is on.
455
+ */
456
+ export function showExtensionIndicator(ui) {
457
+ hideExtensionIndicator();
458
+ void ui.custom((tui) => {
459
+ const marker = new PresenceMarker(tui, agentCounts, grazingEnabled, greenBackground, Math.random);
460
+ setIndicatorMarker(marker);
461
+ return marker;
462
+ }, {
463
+ overlay: true,
464
+ overlayOptions: COWBOY_OVERLAY,
465
+ // The factory ran first, so the marker in the shell is the one this handle controls.
466
+ onHandle: (handle) => getIndicatorMarker()?.attachCowboy(handle),
467
+ });
468
+ void ui.custom(() => new PastureView(), {
469
+ overlay: true,
470
+ overlayOptions: PASTURE_OVERLAY,
471
+ // The cowboy's factory ran first, so the shell already holds the marker this view draws.
472
+ onHandle: (handle) => getIndicatorMarker()?.attachPasture(handle),
473
+ });
474
+ }
475
+ /** Take the marker down: both its overlays, and the poll behind them. */
476
+ export function hideExtensionIndicator() {
477
+ const marker = getIndicatorMarker();
478
+ setIndicatorMarker(null);
479
+ marker?.dispose();
480
+ }