@luminascale/shepherd 0.0.0-stage → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/.agents/agents/README.md +12 -0
  2. package/.agents/agents/planner.md +38 -0
  3. package/.agents/agents/reviewer.md +38 -0
  4. package/.agents/agents/scout.md +43 -0
  5. package/.agents/agents/worker.md +33 -0
  6. package/.agents/skills/smoke-test/SKILL.md +155 -0
  7. package/.agents/skills/smoke-test/references/forensics.md +46 -0
  8. package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
  9. package/.github/workflows/publish.yml +77 -0
  10. package/.pi/prompts/release.md +21 -0
  11. package/.prettierrc +10 -0
  12. package/AGENTS.md +88 -0
  13. package/CONTRIBUTING.md +177 -0
  14. package/LICENSE +201 -0
  15. package/README.md +397 -2
  16. package/docs/README.md +26 -0
  17. package/docs/guides/agent-definitions.md +42 -0
  18. package/docs/guides/diagnostics.md +199 -0
  19. package/docs/guides/installation.md +61 -0
  20. package/docs/guides/tool-reference.md +55 -0
  21. package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
  22. package/docs/plans/agent-labels.md +257 -0
  23. package/docs/plans/architecture.md +110 -0
  24. package/docs/plans/settings-scope.md +163 -0
  25. package/docs/plans/tool-surface-split.md +278 -0
  26. package/docs/reference/dictionary +26 -0
  27. package/docs/releasing.md +47 -0
  28. package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
  29. package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
  30. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
  31. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
  32. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
  33. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
  34. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
  35. package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
  36. package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
  37. package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
  38. package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
  39. package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
  40. package/index.ts +602 -0
  41. package/package.json +112 -4
  42. package/scripts/capture-system-prompt.mjs +45 -0
  43. package/scripts/extract-pi-system-prompt.mjs +277 -0
  44. package/scripts/host-impact.mjs +74 -0
  45. package/scripts/resolve-agent.mjs +43 -0
  46. package/scripts/show-shepherd-orchestrator.mjs +58 -0
  47. package/scripts/show-shepherd-prompt.mjs +96 -0
  48. package/scripts/verify-suites.mjs +67 -0
  49. package/specs/001-artifacts/spec.md +436 -0
  50. package/specs/002-simplify-agent-orchestration/plan.md +287 -0
  51. package/specs/002-simplify-agent-orchestration/spec.md +323 -0
  52. package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
  53. package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
  54. package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
  55. package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
  56. package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
  57. package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
  58. package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
  59. package/specs/005-per-workspace-settings/plan.md +230 -0
  60. package/specs/005-per-workspace-settings/spec.md +368 -0
  61. package/specs/005-per-workspace-settings/tasks.md +178 -0
  62. package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
  63. package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
  64. package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
  65. package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
  66. package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
  67. package/specs/007-unwatched-completion-notice/journal.md +145 -0
  68. package/specs/007-unwatched-completion-notice/plan.md +186 -0
  69. package/specs/007-unwatched-completion-notice/spec.md +284 -0
  70. package/specs/007-unwatched-completion-notice/tasks.md +147 -0
  71. package/specs/008-remote-machine-sheep/intent.md +174 -0
  72. package/specs/008-remote-machine-sheep/journal.md +57 -0
  73. package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
  74. package/specs/009-hc-runtime/intent.md +44 -0
  75. package/specs/009-hc-runtime/plan.md +49 -0
  76. package/specs/009-hc-runtime/spec.md +118 -0
  77. package/specs/009-hc-runtime/tasks.md +62 -0
  78. package/specs/010-unseen-watch-parity/intent.md +57 -0
  79. package/specs/010-unseen-watch-parity/journal.md +172 -0
  80. package/specs/010-unseen-watch-parity/plan.md +74 -0
  81. package/specs/010-unseen-watch-parity/spec.md +191 -0
  82. package/specs/010-unseen-watch-parity/tasks.md +119 -0
  83. package/specs/011-hc-background-poll/intent.md +57 -0
  84. package/specs/011-hc-background-poll/journal.md +95 -0
  85. package/specs/011-hc-background-poll/plan.md +87 -0
  86. package/specs/011-hc-background-poll/spec.md +141 -0
  87. package/specs/011-hc-background-poll/tasks.md +83 -0
  88. package/specs/012-steer-default/intent.md +12 -0
  89. package/specs/012-steer-default/journal.md +40 -0
  90. package/specs/012-steer-default/plan.md +7 -0
  91. package/specs/012-steer-default/spec.md +42 -0
  92. package/specs/012-steer-default/tasks.md +6 -0
  93. package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
  94. package/specs/013-opencode-shepherd/intent.md +59 -0
  95. package/specs/013-opencode-shepherd/plan.md +204 -0
  96. package/specs/013-opencode-shepherd/spec.md +258 -0
  97. package/specs/013-opencode-shepherd/tasks.md +263 -0
  98. package/src/core/artifact-sessions.ts +835 -0
  99. package/src/core/config.ts +329 -0
  100. package/src/core/discovery.ts +342 -0
  101. package/src/core/herdr.ts +1 -0
  102. package/src/core/host.ts +77 -0
  103. package/src/core/ids.ts +78 -0
  104. package/src/core/lifecycle.ts +1 -0
  105. package/src/core/messaging.ts +1 -0
  106. package/src/core/migration.ts +55 -0
  107. package/src/core/orchestration.ts +1 -0
  108. package/src/core/types.ts +143 -0
  109. package/src/core/unseen-completions.ts +114 -0
  110. package/src/extension/cli.ts +417 -0
  111. package/src/extension/config.ts +1 -0
  112. package/src/extension/settings-ui.ts +296 -0
  113. package/src/extension/shepherd-done.ts +768 -0
  114. package/src/extension/shepherd.ts +2548 -0
  115. package/src/extension/system-prompt.ts +38 -0
  116. package/src/extension/unseen-completions.ts +237 -0
  117. package/src/opencode/actions.ts +794 -0
  118. package/src/opencode/bridge.ts +777 -0
  119. package/src/opencode/display.ts +36 -0
  120. package/src/opencode/fieldnotes.ts +60 -0
  121. package/src/opencode/host.ts +62 -0
  122. package/src/opencode/orphans.ts +162 -0
  123. package/src/opencode/server.ts +458 -0
  124. package/src/runtimes/backend.ts +119 -0
  125. package/src/runtimes/detect.ts +102 -0
  126. package/src/runtimes/hc/hc.ts +527 -0
  127. package/src/runtimes/hc/runtime.ts +1898 -0
  128. package/src/runtimes/herdr/herdr.ts +912 -0
  129. package/src/runtimes/herdr/lifecycle.ts +1712 -0
  130. package/src/runtimes/herdr/messaging.ts +703 -0
  131. package/src/runtimes/herdr/orchestration.ts +1583 -0
  132. package/src/runtimes/herdr/runtime.ts +224 -0
  133. package/src/runtimes/runtime.ts +133 -0
  134. package/src/runtimes/settle-observations.ts +114 -0
  135. package/test/fixtures/context-project/AGENTS.md +2 -0
  136. package/test/fixtures/home/.agents/agents/same.md +6 -0
  137. package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
  138. package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
  139. package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
  140. package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
  141. package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
  142. package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
  143. package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
  144. package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
  145. package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
  146. package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
  147. package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
  148. package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
  149. package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
  150. package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
  151. package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
  152. package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
  153. package/test/fixtures/proj/.pi/agents/same.md +6 -0
  154. package/test/helpers/fake-clock.mjs +39 -0
  155. package/test/helpers/feature-contracts.mjs +44 -0
  156. package/test/helpers/test-utils.mjs +44 -0
  157. package/test/verify-artifact-sessions.mjs +258 -0
  158. package/test/verify-backend.mjs +297 -0
  159. package/test/verify-child-mislabel.mjs +135 -0
  160. package/test/verify-child-surface.mjs +321 -0
  161. package/test/verify-cli.mjs +197 -0
  162. package/test/verify-command-ux.mjs +100 -0
  163. package/test/verify-compat.mjs +32 -0
  164. package/test/verify-cross-host-notes.mjs +128 -0
  165. package/test/verify-delegate.mjs +161 -0
  166. package/test/verify-detect.mjs +151 -0
  167. package/test/verify-discovery.mjs +239 -0
  168. package/test/verify-done-nudge.mjs +238 -0
  169. package/test/verify-effective-prompt.mjs +98 -0
  170. package/test/verify-hc-matrix.mjs +246 -0
  171. package/test/verify-hc-poll.mjs +260 -0
  172. package/test/verify-host-docs.mjs +66 -0
  173. package/test/verify-host-impact.mjs +49 -0
  174. package/test/verify-ids.mjs +141 -0
  175. package/test/verify-launch.mjs +183 -0
  176. package/test/verify-message-routing.mjs +560 -0
  177. package/test/verify-messaging.mjs +303 -0
  178. package/test/verify-migration-notice.mjs +74 -0
  179. package/test/verify-multi-wait.mjs +42 -0
  180. package/test/verify-opencode-display.mjs +47 -0
  181. package/test/verify-opencode-fieldnotes.mjs +121 -0
  182. package/test/verify-opencode-notice.mjs +77 -0
  183. package/test/verify-opencode-nudge.mjs +116 -0
  184. package/test/verify-opencode-orphans.mjs +160 -0
  185. package/test/verify-opencode-surface.mjs +107 -0
  186. package/test/verify-packaging.mjs +82 -0
  187. package/test/verify-parent-surface.mjs +118 -0
  188. package/test/verify-phase0.mjs +95 -0
  189. package/test/verify-registry.mjs +124 -0
  190. package/test/verify-rename-migration.mjs +111 -0
  191. package/test/verify-rendering.mjs +379 -0
  192. package/test/verify-session-boundary.mjs +146 -0
  193. package/test/verify-settings.mjs +260 -0
  194. package/test/verify-stale-wait.mjs +339 -0
  195. package/test/verify-status-widget.mjs +377 -0
  196. package/test/verify-status.mjs +172 -0
  197. package/test/verify-task-completion.mjs +156 -0
  198. package/test/verify-task-failures.mjs +201 -0
  199. package/test/verify-task-mislabel.mjs +143 -0
  200. package/test/verify-task-registry.mjs +194 -0
  201. package/test/verify-task-watchers.mjs +217 -0
  202. package/test/verify-tool-schemas.mjs +120 -0
  203. package/test/verify-unseen-completions.mjs +1211 -0
  204. package/test/verify-watchers.mjs +181 -0
package/index.ts ADDED
@@ -0,0 +1,602 @@
1
+ /**
2
+ * pi-shepherd — no-fuss pi extension: subagents + herding pi agents in Herdr.
3
+ *
4
+ * Entry point only. Engine lives in src/core/ (discovery, lifecycle, Herdr,
5
+ * registries, session persistence); the pi tool/command surface lives in
6
+ * src/extension/. Bundled agents are in .agents/agents/.
7
+ */
8
+
9
+ import type { ExtensionAPI, ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
10
+ import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
11
+ import { discoverAgents } from './src/core/discovery.ts';
12
+ import {
13
+ fieldnotesEnabled,
14
+ initializeSessionSettings,
15
+ loadSettings,
16
+ } from './src/core/config.ts';
17
+ import { openSettings } from './src/extension/settings-ui.ts';
18
+ import {
19
+ doAction,
20
+ registerShepherdTools,
21
+ setPromptWatcherSessionActive,
22
+ setTaskWatcherSessionActive,
23
+ setStaleWaitSessionActive,
24
+ setShepherdMessageSessionActive,
25
+ type ShepherdArgs,
26
+ } from './src/extension/shepherd.ts';
27
+ import { parseShepherdCli, tokenizeCli } from './src/extension/cli.ts';
28
+ import { configureUnseenCompletionBridge } from './src/extension/unseen-completions.ts';
29
+ import { lifecycleRegistry, bindSessionOwner } from './src/runtimes/herdr/orchestration.ts';
30
+ import {
31
+ shutdownPromptWatchers,
32
+ shutdownTaskWatchers,
33
+ shutdownStaleWaitMonitor,
34
+ } from './src/runtimes/herdr/lifecycle.ts';
35
+ import { resolveOrCreateParentArtifactSession } from './src/core/artifact-sessions.ts';
36
+ import { migrationNoticeOnce } from './src/core/migration.ts';
37
+ import {
38
+ isHerdrAvailable,
39
+ paneOwnedByCurrentSession,
40
+ workingOrWaitingSubagents,
41
+ activeTasksByPane,
42
+ loadCreatedPanes,
43
+ type HerdrAgentSummary,
44
+ } from './src/runtimes/herdr/herdr.ts';
45
+ import type { AgentTaskStatus } from './src/runtimes/herdr/orchestration.ts';
46
+
47
+ /**
48
+ * Persistent "below the editor" status box listing the subagents currently
49
+ * working (see tui.md Pattern 5 / widget-placement.ts). Polls the live herd
50
+ * into a snapshot every ~1s, then renders a bordered box at the real
51
+ * viewport width: one row per agent with a color-coded state icon and an
52
+ * mm:ss elapsed timer — shaped after the pi-interactive-subagents "Subagents"
53
+ * widget, but theme-driven rather than hard-coded ANSI hues. No-op when
54
+ * Herdr isn't reachable or there is nothing working.
55
+ */
56
+ interface WorkingSnapshotItem extends HerdrAgentSummary {
57
+ /** Recorded pane creation time (registry), or undefined for untracked panes. */
58
+ createdAt?: number;
59
+ /** Wall-clock ms when this agent started its current walking streak. */
60
+ walkStartMs?: number;
61
+ /** The agent's open tracked task, if any (independent of the process state). */
62
+ task?: AgentTaskStatus;
63
+ }
64
+
65
+ function registerSubagentStatusWidget(pi: ExtensionAPI): void {
66
+ const POLL_MS = 1_000;
67
+
68
+ pi.on('session_start', (_event, ctx) => {
69
+ if (!ctx.hasUI) return;
70
+ let snapshot: WorkingSnapshotItem[] = [];
71
+ // Walk origins: wall-clock time each agent entered its current
72
+ // "working" walk. Recorded on first observation and dropped once the
73
+ // walk ends, so every walk starts at age zero (right edge) and restarts
74
+ // from there if the agent goes working again later.
75
+ const walkStarts = new Map<string, number>();
76
+
77
+ const tick = (tui: { requestRender(): void }): void => {
78
+ // Poll Herdr + the registry once per tick, not per render frame.
79
+ // The created-panes registry is shared across all shepherd sessions;
80
+ // only the panes owned by THIS session belong in this widget.
81
+ const panes = loadCreatedPanes().filter(paneOwnedByCurrentSession);
82
+ const createdAtById = new Map(panes.map(p => [p.paneId, p.createdAt]));
83
+ const agents = workingOrWaitingSubagents();
84
+ const tasksByPane = activeTasksByPane();
85
+ const workingNow = new Set(agents.filter(s => s.state === 'working').map(s => s.paneId));
86
+ const now = Date.now();
87
+ for (const paneId of walkStarts.keys()) {
88
+ if (!workingNow.has(paneId)) walkStarts.delete(paneId);
89
+ }
90
+ for (const paneId of workingNow) {
91
+ if (!walkStarts.has(paneId)) walkStarts.set(paneId, now);
92
+ }
93
+ snapshot = agents.map(s => ({
94
+ ...s,
95
+ createdAt: createdAtById.get(s.paneId),
96
+ walkStartMs: walkStarts.get(s.paneId),
97
+ task: tasksByPane.get(s.paneId)?.task,
98
+ }));
99
+ tui.requestRender();
100
+ };
101
+
102
+ ctx.ui.setWidget(
103
+ 'pi-shepherd-working',
104
+ (tui, theme) => {
105
+ let sheepFrame = 0;
106
+ tick(tui);
107
+ const timer = setInterval(() => tick(tui), POLL_MS);
108
+ const animationTimer = setInterval(() => {
109
+ if (!snapshot.some(agent => agent.state === 'working')) return;
110
+ // Keeps the spinner and the sheep (a pure function of wall-clock
111
+ // age) re-rendering; the counter only feeds the spinner now.
112
+ sheepFrame += 1;
113
+ tui.requestRender();
114
+ }, SHEEP_FRAME_MS);
115
+ return {
116
+ render: (width: number) =>
117
+ snapshot.length > 0
118
+ ? renderWorkingAgents(
119
+ snapshot,
120
+ theme,
121
+ width,
122
+ sheepFrame,
123
+ loadSettings(currentCwd()).emojiSheep
124
+ )
125
+ : [],
126
+ invalidate: () => {
127
+ // Theme changed: rows are re-derived from the live snapshot,
128
+ // which the poll timer keeps fresh.
129
+ tui.requestRender();
130
+ },
131
+ dispose: () => {
132
+ clearInterval(timer);
133
+ clearInterval(animationTimer);
134
+ },
135
+ };
136
+ },
137
+ { placement: 'belowEditor' }
138
+ );
139
+ });
140
+ }
141
+
142
+ /** Elapsed since pane creation, mm:ss (the created-panes registry is the time source). */
143
+ function formatElapsedMMSS(createdAt: number, now = Date.now()): string {
144
+ const seconds = Math.max(0, Math.floor((now - createdAt) / 1000));
145
+ const m = Math.floor(seconds / 60);
146
+ const s = seconds % 60;
147
+ return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
148
+ }
149
+
150
+ /** Nature-inspired semantic color for a Herdr state. */
151
+ function stateColor(state: string): string {
152
+ switch (state) {
153
+ case 'working':
154
+ case 'done':
155
+ case 'completed':
156
+ return 'success';
157
+ case 'waiting':
158
+ return 'warning';
159
+ case 'error':
160
+ return 'error';
161
+ default:
162
+ return 'dim';
163
+ }
164
+ }
165
+
166
+ // Teal accent (#2aa198) for the box border and working spinner. The pi theme
167
+ // has no teal semantic color, so this is a fixed truecolor ANSI hue.
168
+ const TEAL_ANSI = '\u001b[38;2;42;161;152m';
169
+ const RESET_ANSI = '\u001b[0m';
170
+
171
+ function teal(text: string): string {
172
+ return `${TEAL_ANSI}${text}${RESET_ANSI}`;
173
+ }
174
+
175
+ /** Colored status icon per Herdr agent state (green Braille spinner, … waiting, ✗ error). */
176
+ function stateIcon(
177
+ state: string,
178
+ theme: { fg(color: string, text: string): string },
179
+ frame = 0
180
+ ): string {
181
+ const color = stateColor(state);
182
+ switch (state) {
183
+ case 'working':
184
+ // Teal spinner; the rest of the row stays neutral.
185
+ return teal(WORKING_SPINNER_FRAMES[frame % WORKING_SPINNER_FRAMES.length] ?? '⠋');
186
+ case 'waiting':
187
+ return theme.fg(color, '…');
188
+ case 'error':
189
+ return theme.fg(color, '✗');
190
+ case 'done':
191
+ case 'completed':
192
+ return theme.fg(color, '✓');
193
+ default:
194
+ return theme.fg(color, '○');
195
+ }
196
+ }
197
+
198
+ // The sheep walks right-to-left through the available gap after the active
199
+ // agent name. It jumps back to the right edge after reaching the left edge; it
200
+ // never walks back to the right. The glyph itself is not mirrored because
201
+ // Unicode/terminals do not provide a portable way to transform an emoji.
202
+ const SHEEP_SPEED = 1;
203
+ const SHEEP_FRAME_MS = 500;
204
+ const WORKING_SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
205
+
206
+ /**
207
+ * Sheep position for an agent's walk age. The position is a pure function of
208
+ * the milliseconds since the walk started (no shared frame counter), so the
209
+ * walk runs exactly one frame per SHEEP_FRAME_MS at any setting. Position
210
+ * wraps against this agent's track width, so different track widths never
211
+ * desync each other's rhythm. Age 0 starts at the right edge.
212
+ */
213
+ function animatedSheep(
214
+ ageMs: number,
215
+ useEmoji: boolean,
216
+ theme: { fg(color: string, text: string): string },
217
+ trackSpan: number
218
+ ): string {
219
+ const glyph = useEmoji ? '🐑' : 'o';
220
+ const cycleWidth = trackSpan + 1;
221
+ const position =
222
+ trackSpan -
223
+ ((((Math.floor(ageMs / SHEEP_FRAME_MS) * SHEEP_SPEED) % cycleWidth) + cycleWidth) % cycleWidth);
224
+ return `${' '.repeat(position + 1)}${theme.fg('text', glyph)}`;
225
+ }
226
+
227
+ /**
228
+ * Bordered "working" box, one line per agent, shaped after the pi-interactive-
229
+ * subagents widget:
230
+ *
231
+ * ╭─ shepherd ────────── 2 working ─╮
232
+ * │ ⠋ 01:23 planner 🐑 working │
233
+ * │ … 00:47 worker waiting │
234
+ * ╰───────────────────────────────────╯
235
+ *
236
+ * Left text (icon + elapsed + name) truncates; the right status label is
237
+ * preserved and right-aligned, padding the row to full terminal width.
238
+ */
239
+ function renderWorkingAgents(
240
+ agents: WorkingSnapshotItem[],
241
+ theme: {
242
+ fg(color: string, text: string): string;
243
+ },
244
+ width: number,
245
+ sheepFrame = 0,
246
+ useEmoji = true
247
+ ): string[] {
248
+ const title = 'shepherd';
249
+ // Process and task state are shown independently: a pane may be working
250
+ // with a running task, or idle while its task waits on a required reply.
251
+ const workingCount = agents.filter(agent => agent.state === 'working').length;
252
+ const waitingCount = agents.filter(agent => agent.task?.state === 'waiting').length;
253
+ const infoParts: string[] = [];
254
+ if (workingCount > 0) infoParts.push(`${workingCount} working`);
255
+ if (waitingCount > 0) infoParts.push(`${waitingCount} waiting`);
256
+ if (infoParts.length === 0 && agents.length > 0) infoParts.push(`${agents.length} active`);
257
+ const info = infoParts.join(' · ');
258
+
259
+ const lines: string[] = [borderTop(title, info, width, theme)];
260
+
261
+ for (const agent of agents) {
262
+ const task = agent.task;
263
+ const waitingOnReply = task?.state === 'waiting';
264
+ // An idle process that owns a waiting task renders as "waiting", not idle:
265
+ // the child is parked, not finished.
266
+ const iconState = waitingOnReply ? 'waiting' : agent.state;
267
+ const elapsed = agent.createdAt != null ? ` ${formatElapsedMMSS(agent.createdAt)}` : '';
268
+ const icon = stateIcon(iconState, theme, sheepFrame);
269
+ // Right side: the task state wins while the task is open (working process +
270
+ // waiting task → "waiting"), stale episodes are flagged distinctly.
271
+ let rightState = agent.state;
272
+ if (task) rightState = task.state;
273
+ if (waitingOnReply && task?.stale) rightState = 'waiting (stale)';
274
+ const right = ` ${theme.fg('text', rightState)} `;
275
+ const name = theme.fg('text', agent.name);
276
+ // Left side: waiting rows surface the elapsed wait and the expected-reply
277
+ // recipient so the operator sees what is being waited on.
278
+ let detail = '';
279
+ if (waitingOnReply && task) {
280
+ const waitingMins = Math.floor((task.waitingMs ?? 0) / 60_000);
281
+ detail = ` ⏳${waitingMins}m`;
282
+ if (task.waitingRecipient) detail += ` ←${task.waitingRecipient}`;
283
+ }
284
+ const prefix = ` ${icon}${elapsed} ${name}${detail}`;
285
+ const sheepGlyph = useEmoji ? '🐑' : 'o';
286
+ const sheepWidth = visibleWidth(theme.fg('text', sheepGlyph));
287
+ const leftWidth = Math.max(0, width - 2 - visibleWidth(right));
288
+ const trackSpan = leftWidth - visibleWidth(prefix) - sheepWidth - 1;
289
+ const sheep =
290
+ agent.state === 'working' && trackSpan >= 0 && agent.walkStartMs != null
291
+ ? animatedSheep(Date.now() - agent.walkStartMs, useEmoji, theme, trackSpan)
292
+ : '';
293
+ const left = `${prefix}${sheep}`;
294
+ lines.push(borderLine(left, right, width, theme));
295
+ }
296
+
297
+ lines.push(borderBottom(width, theme));
298
+ return lines;
299
+ }
300
+
301
+ /** Bordered top line: ╭─ title ──── info ─╮ (all chars within `width`). */
302
+ function borderTop(
303
+ title: string,
304
+ info: string,
305
+ width: number,
306
+ theme: { fg(color: string, text: string): string }
307
+ ): string {
308
+ if (width <= 0) return '';
309
+ if (width === 1) return teal('╭');
310
+ const inner = Math.max(0, width - 2); // inside ╭ and ╮
311
+ const titlePart = `─ ${title} `;
312
+ const infoPart = ` ${info} ─`;
313
+ const fillLen = Math.max(0, inner - titlePart.length - infoPart.length);
314
+ const fill = '─'.repeat(fillLen);
315
+ const content = `${titlePart}${fill}${infoPart}`.slice(0, inner).padEnd(inner, '─');
316
+ return `${teal('╭')}${teal(content)}${teal('╮')}`;
317
+ }
318
+
319
+ /** Bordered bottom line: ╰──────────────────╯ */
320
+ function borderBottom(width: number, theme: { fg(color: string, text: string): string }): string {
321
+ if (width <= 0) return '';
322
+ if (width === 1) return teal('╰');
323
+ const inner = Math.max(0, width - 2);
324
+ return `${teal('╰')}${teal('─'.repeat(inner))}${teal('╯')}`;
325
+ }
326
+
327
+ /**
328
+ * Bordered content line: │left right│ — left truncates, right is
329
+ * preserved and right-aligned, padded to fill `width` (both │ chars included).
330
+ */
331
+ function borderLine(
332
+ left: string,
333
+ right: string,
334
+ width: number,
335
+ theme: { fg(color: string, text: string): string }
336
+ ): string {
337
+ if (width <= 0) return '';
338
+ if (width === 1) return teal('│');
339
+ const contentWidth = Math.max(0, width - 2); // space inside the two │ chars
340
+ const rightVis = visibleWidth(right);
341
+
342
+ // If the status label alone is too wide, keep it compact rather than
343
+ // overflowing the terminal.
344
+ if (rightVis >= contentWidth) {
345
+ const truncRight = truncateToWidth(right, contentWidth);
346
+ const rightPad = Math.max(0, contentWidth - visibleWidth(truncRight));
347
+ return `${teal('│')}${theme.fg('muted', truncRight)}${' '.repeat(rightPad)}${teal('│')}`;
348
+ }
349
+
350
+ const maxLeft = Math.max(0, contentWidth - rightVis);
351
+ const truncLeft = truncateToWidth(left, maxLeft);
352
+ const leftVis = visibleWidth(truncLeft);
353
+ const pad = Math.max(0, contentWidth - leftVis - rightVis);
354
+ return `${teal('│')}${theme.fg('muted', truncLeft)}${' '.repeat(pad)}${theme.fg('muted', right)}${teal('│')}`;
355
+ }
356
+
357
+ function parentArtifactSessionForCommand(ctx: ExtensionCommandContext) {
358
+ if (!fieldnotesEnabled()) return undefined;
359
+ const parentPiSessionId = ctx.sessionManager?.getSessionId?.();
360
+ if (!parentPiSessionId) return undefined;
361
+ return resolveOrCreateParentArtifactSession({
362
+ parentPiSessionId,
363
+ parentSessionFile: ctx.sessionManager?.getSessionFile?.(),
364
+ projectRoot: ctx.cwd,
365
+ });
366
+ }
367
+
368
+ /**
369
+ * Delegate a command invocation to doAction() — the shared core that also backs
370
+ * the model-facing tools — and surface the result through notifications.
371
+ * Error results map to error-level notifications; thrown errors are caught so
372
+ * a failing action never escapes into an unhandled rejection.
373
+ */
374
+ async function runCommandAction(args: ShepherdArgs, ctx: ExtensionCommandContext): Promise<void> {
375
+ try {
376
+ const result = await doAction(args, {
377
+ cwd: ctx.cwd,
378
+ model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined,
379
+ thinkingLevel: ctx.thinkingLevel,
380
+ sessionManager: ctx.sessionManager as any,
381
+ ui: ctx.ui,
382
+ hasUI: true,
383
+ });
384
+ const text = result.content.find(c => c.type === 'text')?.text ?? '(no output)';
385
+ const hasError =
386
+ typeof result.details === 'object' && result.details !== null && 'error' in result.details;
387
+ ctx.ui?.notify(text, hasError ? 'error' : 'info');
388
+ } catch (error: any) {
389
+ ctx.ui?.notify(`pi-shepherd: ${error?.message ?? error}`, 'error');
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Cwd of the most recent pi session. Held in module scope because the
395
+ * /shepherd command's argument-completion callback receives only the typed
396
+ * prefix (no ExtensionCommandContext), and the status widget's render
397
+ * closure lives inside registerSubagentStatusWidget() — outside the
398
+ * export default body, so a local there would be unresolvable at render
399
+ * time. Falls back to the process cwd until session_start fires.
400
+ */
401
+ let activeSessionCwd: string | undefined;
402
+
403
+ function currentCwd(): string {
404
+ return activeSessionCwd ?? process.cwd();
405
+ }
406
+
407
+ export default function (pi: ExtensionAPI) {
408
+ pi.on('session_start', (_event, ctx) => {
409
+ // One-time farewell notice for the old package name. Display-only: it
410
+ // never wakes the model, and child sheep processes are skipped inside
411
+ // migrationNoticeOnce().
412
+ const notice = migrationNoticeOnce();
413
+ if (notice && typeof pi.sendMessage === 'function') {
414
+ try {
415
+ pi.sendMessage(
416
+ { customType: 'shepherd-migration-notice', content: notice, display: true },
417
+ { deliverAs: 'followUp', triggerTurn: false }
418
+ );
419
+ } catch {
420
+ /* best effort: marker is already consumed */
421
+ }
422
+ }
423
+ setPromptWatcherSessionActive(true);
424
+ setTaskWatcherSessionActive(true);
425
+ setStaleWaitSessionActive(true);
426
+ setShepherdMessageSessionActive(true);
427
+ activeSessionCwd = ctx.cwd;
428
+ // Fieldnotes are intentionally session-scoped. Persisted setting changes
429
+ // are applied when the next parent pi session starts.
430
+ initializeSessionSettings(ctx.cwd);
431
+ // Advance the in-memory lifecycle namespace when pi switches parent
432
+ // sessions. The extension module can survive a session switch, so labels
433
+ // and opaque lifecycle ids must not leak across the boundary.
434
+ const sessionId = ctx.sessionManager?.getSessionId?.();
435
+ lifecycleRegistry.beginSession(sessionId);
436
+ // Bind this session's identity so the panes it creates are tagged and the
437
+ // widget/registry views are scoped to its own sheep.
438
+ bindSessionOwner(sessionId);
439
+ });
440
+ pi.on('session_shutdown', (_event, _ctx) => {
441
+ // Watchers are parent-session scoped. Stop timers and discard delivery
442
+ // registrations, but leave prompts, child panes, result files, and notes
443
+ // untouched for normal lifecycle retention.
444
+ setPromptWatcherSessionActive(false);
445
+ setTaskWatcherSessionActive(false);
446
+ setStaleWaitSessionActive(false);
447
+ setShepherdMessageSessionActive(false);
448
+ shutdownPromptWatchers();
449
+ shutdownTaskWatchers();
450
+ shutdownStaleWaitMonitor();
451
+ // Drop the binding on teardown so a reload/new-session cycle without a
452
+ // fresh identity never attributes fresh panes to a stale session.
453
+ bindSessionOwner(undefined);
454
+ });
455
+
456
+ // Launched workers load the user extension set too, but their only Shepherd
457
+ // surface is the in-tab completion extension from shepherd-done.ts. Keep the
458
+ // parent orchestrator's tools, command, settings UI, and widget out of worker
459
+ // sessions; PI_SHEPHERD_SESSION is set by herdr.ts only for launched agents.
460
+ if (process.env.PI_SHEPHERD_SESSION) return;
461
+
462
+ // Tools for natural-language use.
463
+ registerShepherdTools(pi);
464
+ configureUnseenCompletionBridge(pi);
465
+ registerSubagentStatusWidget(pi);
466
+
467
+ pi.registerCommand('shepherd', {
468
+ description:
469
+ 'pi-shepherd: (no args) settings menu | agents | herd | spawn | status | read | settings',
470
+ // Keep completion aligned with the actions the command supports. Agent
471
+ // names (and live handle ids for status) are discovered fresh so
472
+ // user-defined agents and running agents are available here.
473
+ getArgumentCompletions: prefix => {
474
+ const parts = prefix.split(/\s+/);
475
+ const action = parts[0] ?? '';
476
+ const discoveredAgentNames = () =>
477
+ (() => {
478
+ const cwd = currentCwd();
479
+ const s = loadSettings(cwd);
480
+ return discoverAgents(cwd, s.agentScope, {
481
+ includeBundled: s.includeBundledAgents,
482
+ });
483
+ })()
484
+ .agents.filter(agent => agent.name.length > 0)
485
+ .map(agent => ({ name: agent.name, description: agent.description }));
486
+ const liveHandleIdPrefixes = () =>
487
+ lifecycleRegistry
488
+ .allAgents()
489
+ .map(handle => handle.id)
490
+ .filter(id => id.length > 0);
491
+ if (parts.length <= 1 && !prefix.endsWith(' ')) {
492
+ // Pi does not automatically invoke the completion provider again
493
+ // after applying an argument completion. When the user types
494
+ // `/shepherd spa`, show full `spawn <agent>` entries immediately
495
+ // instead of requiring a second completion cycle after `spawn`.
496
+ if (action.length >= 3 && 'spawn'.startsWith(action)) {
497
+ const names = discoveredAgentNames();
498
+ if (names.length > 0) {
499
+ return names.map(agent => ({
500
+ value: `spawn ${agent.name}`,
501
+ label: `spawn ${agent.name}`,
502
+ description: agent.description,
503
+ }));
504
+ }
505
+ }
506
+ if (action.length >= 3 && 'status'.startsWith(action)) {
507
+ const targets = [...discoveredAgentNames().map(a => a.name), ...liveHandleIdPrefixes()];
508
+ if (targets.length > 0) {
509
+ return targets.map(target => ({
510
+ value: `status ${target}`,
511
+ label: `status ${target}`,
512
+ }));
513
+ }
514
+ }
515
+ if (action.length >= 3 && 'read'.startsWith(action)) {
516
+ const targets = [...discoveredAgentNames().map(a => a.name), ...liveHandleIdPrefixes()];
517
+ if (targets.length > 0) {
518
+ return targets.map(target => ({ value: `read ${target}`, label: `read ${target}` }));
519
+ }
520
+ }
521
+ const actions = ['agents', 'herd', 'spawn', 'status', 'read', 'settings'];
522
+ const filtered = actions.filter(s => s.startsWith(action));
523
+ return filtered.length > 0 ? filtered.map(value => ({ value, label: value })) : null;
524
+ }
525
+ if (action === 'spawn') {
526
+ const agentPrefix = prefix.slice('spawn'.length).trim();
527
+ const filtered = discoveredAgentNames()
528
+ .map(agent => agent.name)
529
+ .filter(name => name.startsWith(agentPrefix));
530
+ // Command completion replaces the complete argument string, not just
531
+ // the final token. Preserve the action or Enter turns `spawn scout`
532
+ // into only `scout`.
533
+ return filtered.length > 0
534
+ ? filtered.map(value => ({ value: `spawn ${value}`, label: value }))
535
+ : null;
536
+ }
537
+ if (action === 'status' || action === 'read') {
538
+ const targetPrefix = prefix.slice(action.length).trim();
539
+ const targets = [
540
+ ...discoveredAgentNames().map(a => a.name),
541
+ // A registered agent name is preferred over its handle id; the
542
+ // parser resolves each to a handle through the live registry.
543
+ ...liveHandleIdPrefixes(),
544
+ ].filter(t => t.startsWith(targetPrefix));
545
+ return targets.length > 0
546
+ ? targets.map(value => ({ value: `${action} ${value}`, label: value }))
547
+ : null;
548
+ }
549
+ return null;
550
+ },
551
+ handler: async (args, ctx: ExtensionCommandContext) => {
552
+ const raw = (args ?? '').trim();
553
+ // Quote-aware tokenization (shared with the CLI preview renderer) so
554
+ // flags like --cwd="/a b" survive the split.
555
+ let tokens = raw ? tokenizeCli(raw) : [];
556
+ // With no arguments (or the explicit `settings` action), open the
557
+ // settings menu — the command's default behavior.
558
+ if (tokens.length === 0 || tokens[0] === 'settings') {
559
+ await openSettings(ctx);
560
+ return;
561
+ }
562
+ // Historical aliases remain accepted but are never offered in
563
+ // completions; `agents` is canonical.
564
+ if (tokens[0] === 'list' || tokens[0] === 'sheep') tokens = ['agents', ...tokens.slice(1)];
565
+ const parsed = parseShepherdCli(tokens);
566
+ if ('error' in parsed) {
567
+ ctx.ui?.notify(`pi-shepherd: ${parsed.error}`, 'warning');
568
+ return;
569
+ }
570
+ // Only `agents` is pure local discovery; everything else needs the
571
+ // Herdr runtime, so warn with the setup hint instead of a raw error.
572
+ if (parsed.action !== 'agents' && !isHerdrAvailable()) {
573
+ ctx.ui?.notify(
574
+ 'pi-shepherd: Herdr runtime not reachable. Start Herdr with `herdr`, or run pi inside a Herdr pane.',
575
+ 'warning'
576
+ );
577
+ return;
578
+ }
579
+ if (parsed.action === 'spawn') {
580
+ const agent = String(parsed.args.agent);
581
+ ctx.ui?.setStatus?.('pi-shepherd', `Starting ${agent}…`);
582
+ try {
583
+ await runCommandAction(
584
+ {
585
+ ...parsed.args,
586
+ // Pre-resolve tolerantly (undefined when fieldnotes are
587
+ // disabled or no session identity exists); 'artifactSession'
588
+ // in args makes doAction honor the explicit value instead of
589
+ // requiring one.
590
+ artifactSession: parentArtifactSessionForCommand(ctx),
591
+ } as unknown as ShepherdArgs,
592
+ ctx
593
+ );
594
+ } finally {
595
+ ctx.ui?.setStatus?.('pi-shepherd', undefined);
596
+ }
597
+ return;
598
+ }
599
+ await runCommandAction(parsed.args as ShepherdArgs, ctx);
600
+ },
601
+ });
602
+ }