@luminascale/shepherd 0.0.0-stage → 0.6.0

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 (203) 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 +424 -2
  16. package/docs/README.md +25 -0
  17. package/docs/guides/agent-definitions.md +42 -0
  18. package/docs/guides/diagnostics.md +199 -0
  19. package/docs/guides/tool-reference.md +55 -0
  20. package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
  21. package/docs/plans/agent-labels.md +257 -0
  22. package/docs/plans/architecture.md +110 -0
  23. package/docs/plans/settings-scope.md +163 -0
  24. package/docs/plans/tool-surface-split.md +278 -0
  25. package/docs/reference/dictionary +26 -0
  26. package/docs/releasing.md +47 -0
  27. package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
  28. package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
  29. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
  30. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
  31. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
  32. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
  33. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
  34. package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
  35. package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
  36. package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
  37. package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
  38. package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
  39. package/index.ts +599 -0
  40. package/package.json +112 -4
  41. package/scripts/capture-system-prompt.mjs +45 -0
  42. package/scripts/extract-pi-system-prompt.mjs +277 -0
  43. package/scripts/host-impact.mjs +74 -0
  44. package/scripts/resolve-agent.mjs +43 -0
  45. package/scripts/show-shepherd-orchestrator.mjs +58 -0
  46. package/scripts/show-shepherd-prompt.mjs +96 -0
  47. package/scripts/verify-suites.mjs +67 -0
  48. package/specs/001-artifacts/spec.md +436 -0
  49. package/specs/002-simplify-agent-orchestration/plan.md +287 -0
  50. package/specs/002-simplify-agent-orchestration/spec.md +323 -0
  51. package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
  52. package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
  53. package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
  54. package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
  55. package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
  56. package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
  57. package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
  58. package/specs/005-per-workspace-settings/plan.md +230 -0
  59. package/specs/005-per-workspace-settings/spec.md +368 -0
  60. package/specs/005-per-workspace-settings/tasks.md +178 -0
  61. package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
  62. package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
  63. package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
  64. package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
  65. package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
  66. package/specs/007-unwatched-completion-notice/journal.md +145 -0
  67. package/specs/007-unwatched-completion-notice/plan.md +186 -0
  68. package/specs/007-unwatched-completion-notice/spec.md +284 -0
  69. package/specs/007-unwatched-completion-notice/tasks.md +147 -0
  70. package/specs/008-remote-machine-sheep/intent.md +174 -0
  71. package/specs/008-remote-machine-sheep/journal.md +57 -0
  72. package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
  73. package/specs/009-hc-runtime/intent.md +44 -0
  74. package/specs/009-hc-runtime/plan.md +49 -0
  75. package/specs/009-hc-runtime/spec.md +118 -0
  76. package/specs/009-hc-runtime/tasks.md +62 -0
  77. package/specs/010-unseen-watch-parity/intent.md +57 -0
  78. package/specs/010-unseen-watch-parity/journal.md +172 -0
  79. package/specs/010-unseen-watch-parity/plan.md +74 -0
  80. package/specs/010-unseen-watch-parity/spec.md +191 -0
  81. package/specs/010-unseen-watch-parity/tasks.md +119 -0
  82. package/specs/011-hc-background-poll/intent.md +57 -0
  83. package/specs/011-hc-background-poll/journal.md +95 -0
  84. package/specs/011-hc-background-poll/plan.md +87 -0
  85. package/specs/011-hc-background-poll/spec.md +141 -0
  86. package/specs/011-hc-background-poll/tasks.md +83 -0
  87. package/specs/012-steer-default/intent.md +12 -0
  88. package/specs/012-steer-default/journal.md +40 -0
  89. package/specs/012-steer-default/plan.md +7 -0
  90. package/specs/012-steer-default/spec.md +42 -0
  91. package/specs/012-steer-default/tasks.md +6 -0
  92. package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
  93. package/specs/013-opencode-shepherd/intent.md +59 -0
  94. package/specs/013-opencode-shepherd/plan.md +204 -0
  95. package/specs/013-opencode-shepherd/spec.md +258 -0
  96. package/specs/013-opencode-shepherd/tasks.md +259 -0
  97. package/src/core/artifact-sessions.ts +835 -0
  98. package/src/core/config.ts +329 -0
  99. package/src/core/discovery.ts +342 -0
  100. package/src/core/herdr.ts +1 -0
  101. package/src/core/host.ts +77 -0
  102. package/src/core/ids.ts +78 -0
  103. package/src/core/lifecycle.ts +1 -0
  104. package/src/core/messaging.ts +1 -0
  105. package/src/core/migration.ts +55 -0
  106. package/src/core/orchestration.ts +1 -0
  107. package/src/core/types.ts +143 -0
  108. package/src/core/unseen-completions.ts +114 -0
  109. package/src/extension/cli.ts +417 -0
  110. package/src/extension/config.ts +1 -0
  111. package/src/extension/settings-ui.ts +296 -0
  112. package/src/extension/shepherd-done.ts +768 -0
  113. package/src/extension/shepherd.ts +2548 -0
  114. package/src/extension/system-prompt.ts +38 -0
  115. package/src/extension/unseen-completions.ts +237 -0
  116. package/src/opencode/actions.ts +794 -0
  117. package/src/opencode/bridge.ts +777 -0
  118. package/src/opencode/display.ts +36 -0
  119. package/src/opencode/fieldnotes.ts +60 -0
  120. package/src/opencode/host.ts +62 -0
  121. package/src/opencode/orphans.ts +162 -0
  122. package/src/opencode/server.ts +458 -0
  123. package/src/runtimes/backend.ts +119 -0
  124. package/src/runtimes/detect.ts +102 -0
  125. package/src/runtimes/hc/hc.ts +527 -0
  126. package/src/runtimes/hc/runtime.ts +1898 -0
  127. package/src/runtimes/herdr/herdr.ts +912 -0
  128. package/src/runtimes/herdr/lifecycle.ts +1712 -0
  129. package/src/runtimes/herdr/messaging.ts +703 -0
  130. package/src/runtimes/herdr/orchestration.ts +1583 -0
  131. package/src/runtimes/herdr/runtime.ts +224 -0
  132. package/src/runtimes/runtime.ts +133 -0
  133. package/src/runtimes/settle-observations.ts +114 -0
  134. package/test/fixtures/context-project/AGENTS.md +2 -0
  135. package/test/fixtures/home/.agents/agents/same.md +6 -0
  136. package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
  137. package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
  138. package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
  139. package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
  140. package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
  141. package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
  142. package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
  143. package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
  144. package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
  145. package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
  146. package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
  147. package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
  148. package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
  149. package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
  150. package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
  151. package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
  152. package/test/fixtures/proj/.pi/agents/same.md +6 -0
  153. package/test/helpers/fake-clock.mjs +39 -0
  154. package/test/helpers/feature-contracts.mjs +44 -0
  155. package/test/helpers/test-utils.mjs +44 -0
  156. package/test/verify-artifact-sessions.mjs +258 -0
  157. package/test/verify-backend.mjs +297 -0
  158. package/test/verify-child-mislabel.mjs +135 -0
  159. package/test/verify-child-surface.mjs +321 -0
  160. package/test/verify-cli.mjs +197 -0
  161. package/test/verify-command-ux.mjs +100 -0
  162. package/test/verify-compat.mjs +32 -0
  163. package/test/verify-cross-host-notes.mjs +128 -0
  164. package/test/verify-delegate.mjs +161 -0
  165. package/test/verify-detect.mjs +151 -0
  166. package/test/verify-discovery.mjs +239 -0
  167. package/test/verify-done-nudge.mjs +238 -0
  168. package/test/verify-effective-prompt.mjs +98 -0
  169. package/test/verify-hc-matrix.mjs +246 -0
  170. package/test/verify-hc-poll.mjs +260 -0
  171. package/test/verify-host-docs.mjs +35 -0
  172. package/test/verify-host-impact.mjs +49 -0
  173. package/test/verify-ids.mjs +141 -0
  174. package/test/verify-launch.mjs +183 -0
  175. package/test/verify-message-routing.mjs +560 -0
  176. package/test/verify-messaging.mjs +303 -0
  177. package/test/verify-migration-notice.mjs +69 -0
  178. package/test/verify-multi-wait.mjs +42 -0
  179. package/test/verify-opencode-display.mjs +47 -0
  180. package/test/verify-opencode-fieldnotes.mjs +121 -0
  181. package/test/verify-opencode-notice.mjs +77 -0
  182. package/test/verify-opencode-nudge.mjs +116 -0
  183. package/test/verify-opencode-orphans.mjs +160 -0
  184. package/test/verify-opencode-surface.mjs +107 -0
  185. package/test/verify-packaging.mjs +82 -0
  186. package/test/verify-parent-surface.mjs +118 -0
  187. package/test/verify-phase0.mjs +95 -0
  188. package/test/verify-registry.mjs +124 -0
  189. package/test/verify-rename-migration.mjs +111 -0
  190. package/test/verify-rendering.mjs +379 -0
  191. package/test/verify-session-boundary.mjs +146 -0
  192. package/test/verify-settings.mjs +260 -0
  193. package/test/verify-stale-wait.mjs +339 -0
  194. package/test/verify-status-widget.mjs +377 -0
  195. package/test/verify-status.mjs +172 -0
  196. package/test/verify-task-completion.mjs +156 -0
  197. package/test/verify-task-failures.mjs +201 -0
  198. package/test/verify-task-mislabel.mjs +143 -0
  199. package/test/verify-task-registry.mjs +194 -0
  200. package/test/verify-task-watchers.mjs +217 -0
  201. package/test/verify-tool-schemas.mjs +120 -0
  202. package/test/verify-unseen-completions.mjs +1211 -0
  203. package/test/verify-watchers.mjs +181 -0
@@ -0,0 +1,768 @@
1
+ /**
2
+ * Extension loaded into pi agents that pi-shepherd launches in Herdr tabs.
3
+ *
4
+ * Responsibilities:
5
+ * 1. Preserve the existing completion sidecar behavior for legacy prompt
6
+ * runs. The sidecar remains a process/turn observation until the parent
7
+ * task lifecycle is migrated to explicit shepherd_done handling.
8
+ * 2. Provide child-side shepherd_message and shepherd_done tools.
9
+ * 3. Poll the parent-owned mailbox and queue incoming messages into this Pi
10
+ * session using followUp or steer delivery.
11
+ * 4. Nudge a tracked task that was left open when a turn ended without
12
+ * shepherd_done (see the completion-nudge section below).
13
+ *
14
+ * The parent passes the mailbox capability through launch-time environment
15
+ * variables. Without those variables the child surface still loads, but its
16
+ * messaging tools return a structured broker-unavailable error.
17
+ */
18
+
19
+ import type { AgentToolResult, ExtensionAPI } from '@earendil-works/pi-coding-agent';
20
+ import { randomUUID } from 'node:crypto';
21
+ import { readFileSync, renameSync, writeFileSync } from 'node:fs';
22
+ import { Type } from 'typebox';
23
+ import {
24
+ createChildBroker,
25
+ createEnvelope,
26
+ pollChildInbox,
27
+ publishFromChild,
28
+ type ChildBroker,
29
+ type ShepherdDelivery,
30
+ type ShepherdMessageEnvelope,
31
+ } from '../runtimes/herdr/messaging.ts';
32
+ import { omitPiDocumentation, replacePiIdentity } from './system-prompt.ts';
33
+
34
+ /**
35
+ * Default number of completion nudges sent per task before the stall is
36
+ * escalated to the parent. One reminder is enough for the common "finished the
37
+ * work, forgot the signal" case; the escalation, not another reminder, is what
38
+ * keeps a stubborn child from looping.
39
+ */
40
+ const DEFAULT_DONE_NUDGE_LIMIT = 1;
41
+
42
+ /**
43
+ * Completion-nudge budget for this child. `PI_SHEPHERD_DONE_NUDGES` overrides
44
+ * it; 0 disables nudging (the parent task deadline remains the backstop).
45
+ */
46
+ function doneNudgeLimit(): number {
47
+ const raw = process.env.PI_SHEPHERD_DONE_NUDGES;
48
+ if (raw === undefined) return DEFAULT_DONE_NUDGE_LIMIT;
49
+ const parsed = Number.parseInt(raw, 10);
50
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_DONE_NUDGE_LIMIT;
51
+ }
52
+
53
+ /** The follow-up turn injected when a tracked task was left open at turn end. */
54
+ export function completionNudgeText(taskId: string, attempt: number, limit: number): string {
55
+ const remaining = Math.max(0, limit - attempt);
56
+ return [
57
+ '[Shepherd completion check]',
58
+ `You ended a turn without calling shepherd_done, so delegated task ${taskId} is still open and shepherd_watch is waiting for its result. Nothing was reported to the Shepherd.`,
59
+ '',
60
+ 'Do not start new work in this turn. Finish the task now and report exactly one terminal outcome with shepherd_done:',
61
+ '- status "completed" — the task is finished; summarize what you did.',
62
+ '- status "blocked" — you cannot proceed; state what blocks you.',
63
+ '- status "failed" — the task cannot be completed; give the reason.',
64
+ '',
65
+ 'If you are instead waiting for an answer from the Shepherd or a peer, end this turn without shepherd_done and reply when the answer arrives.',
66
+ 'If the Shepherd already cancelled or closed this task, ignore this reminder and end the turn.',
67
+ remaining > 0
68
+ ? `Reminder ${attempt} of ${limit}.`
69
+ : `Final reminder ${attempt} of ${limit}; if this task is still open after this turn, the Shepherd is told it stalled.`,
70
+ ].join('\n');
71
+ }
72
+
73
+ /** Parent-facing escalation for a task that stayed open past every nudge. */
74
+ export function stalledCompletionText(taskId: string, reason: string): string {
75
+ return [
76
+ '[Shepherd completion stalled]',
77
+ `Delegated task ${taskId} ended its turn(s) without shepherd_done and no further reminder is being sent: ${reason}`,
78
+ 'The task is still open in the Shepherd. Block, cancel, or close it, or wait for the task deadline.',
79
+ ].join('\n');
80
+ }
81
+
82
+ function writeSidecar(payload: Record<string, unknown>): void {
83
+ const sessionFile = process.env.PI_SHEPHERD_SESSION;
84
+ if (!sessionFile) return;
85
+ try {
86
+ // A unique signal makes repeated `done` payloads distinguishable across
87
+ // prompts. Rename is atomic, so the parent never parses a partial JSON file.
88
+ const target = `${sessionFile}.exit`;
89
+ const temporary = `${target}.${randomUUID()}.tmp`;
90
+ const taskId = process.env.PI_SHEPHERD_TASK_ID;
91
+ writeFileSync(
92
+ temporary,
93
+ JSON.stringify({ ...payload, ...(taskId ? { taskId } : {}), signalId: randomUUID() })
94
+ );
95
+ renameSync(temporary, target);
96
+ } catch {
97
+ // Best effort — the parent can still detect the terminal sentinel.
98
+ }
99
+ }
100
+
101
+ interface AssistantOutcome {
102
+ /** Whether the latest assistant turn permits auto-exit. */
103
+ exit: boolean;
104
+ error?: { errorMessage: string };
105
+ }
106
+
107
+ function latestAssistantOutcome(messages: any[] | undefined): AssistantOutcome {
108
+ if (!messages) return { exit: false };
109
+ for (let i = messages.length - 1; i >= 0; i--) {
110
+ const m = messages[i];
111
+ if (m?.role !== 'assistant') continue;
112
+ // Manual interruption (Escape) keeps the pane open for the user to
113
+ // further drive in the tab.
114
+ if (m.stopReason === 'aborted') return { exit: false };
115
+ if (m.stopReason === 'error') {
116
+ const raw = typeof m.errorMessage === 'string' ? m.errorMessage.trim() : '';
117
+ return {
118
+ exit: true,
119
+ error: {
120
+ errorMessage: raw || 'Agent finished with stopReason=error (no error message).',
121
+ },
122
+ };
123
+ }
124
+ return { exit: true };
125
+ }
126
+ return { exit: false };
127
+ }
128
+
129
+ const DeliverySchema = Type.Union([Type.Literal('followUp'), Type.Literal('steer')], {
130
+ description: 'Delivery mode; followUp waits for the current turn, steer is for urgent input.',
131
+ });
132
+ const StatusSchema = Type.Union(
133
+ [Type.Literal('completed'), Type.Literal('blocked'), Type.Literal('failed')],
134
+ { description: 'Terminal status for the delegated task.' }
135
+ );
136
+
137
+ function stringifyArguments(args: unknown): string {
138
+ return JSON.stringify(args ?? {});
139
+ }
140
+
141
+ function childResult(
142
+ toolName: string,
143
+ args: unknown,
144
+ service: string,
145
+ returnValue: unknown,
146
+ details: Record<string, unknown> = {},
147
+ returnCode = 0
148
+ ): AgentToolResult<Record<string, unknown>> {
149
+ const visibleDetails = Object.entries(details).map(([key, value]) => {
150
+ const rendered = typeof value === 'string' ? value : JSON.stringify(value);
151
+ return ` ${key.replace(/[A-Z]/g, letter => ` ${letter.toLowerCase()}`)}: ${rendered ?? 'null'}`;
152
+ });
153
+ const text = [
154
+ service,
155
+ '',
156
+ 'call:',
157
+ ` ${toolName} ${stringifyArguments(args)}`,
158
+ '',
159
+ 'return:',
160
+ ` ${JSON.stringify(returnValue)}`,
161
+ ...(visibleDetails.length ? ['', 'details:', ...visibleDetails] : []),
162
+ ].join('\n');
163
+ return {
164
+ content: [{ type: 'text', text }],
165
+ details: { returnValue, returnCode, ...details },
166
+ };
167
+ }
168
+
169
+ function unavailableToolResult(toolName: string, args: unknown, error: string) {
170
+ return childResult(
171
+ toolName,
172
+ args,
173
+ 'Shepherd child messaging is unavailable.',
174
+ { accepted: false, error },
175
+ { code: 'broker_unavailable', error },
176
+ 1
177
+ );
178
+ }
179
+
180
+ function brokerFromEnvironment(): { broker?: ChildBroker; error?: string } {
181
+ const rootDir = process.env.PI_SHEPHERD_BROKER_DIR;
182
+ const sessionId = process.env.PI_SHEPHERD_BROKER_SESSION_ID;
183
+ const brokerId = process.env.PI_SHEPHERD_BROKER_ID;
184
+ const agentId = process.env.PI_SHEPHERD_AGENT_ID;
185
+ const token = process.env.PI_SHEPHERD_BROKER_TOKEN;
186
+ const inboxPath = process.env.PI_SHEPHERD_AGENT_INBOX;
187
+ if (!rootDir || !sessionId || !brokerId || !agentId || !token || !inboxPath) {
188
+ return { error: 'No Shepherd broker capability was provided for this child.' };
189
+ }
190
+ try {
191
+ return {
192
+ broker: createChildBroker({ rootDir, sessionId, brokerId, agentId, token, inboxPath }),
193
+ };
194
+ } catch (error) {
195
+ return { error: String((error as any)?.message ?? error) };
196
+ }
197
+ }
198
+
199
+ function incomingMessageText(message: ShepherdMessageEnvelope): string {
200
+ // For parent-relayed replies the authenticated sender is the parent broker;
201
+ // originSenderId carries the true author so the recipient sees who wrote it.
202
+ const author = message.originSenderId ?? message.senderId;
203
+ const sender = author === 'shepherd' ? 'Shepherd' : author;
204
+ const title = message.kind === 'task' ? 'Shepherd delegated task' : 'Shepherd message';
205
+ const metadata = [
206
+ `Message ID: ${message.messageId}`,
207
+ message.taskId ? `Task ID: ${message.taskId}` : undefined,
208
+ message.threadId ? `Thread ID: ${message.threadId}` : undefined,
209
+ message.replyTo ? `Reply to: ${message.replyTo}` : undefined,
210
+ ]
211
+ .filter(Boolean)
212
+ .join('\n');
213
+ return `[${title} from ${sender}]\n${metadata}\n\n${message.content ?? message.summary ?? ''}`;
214
+ }
215
+
216
+ function deliveryMode(value: unknown): ShepherdDelivery {
217
+ // Steer is the default: sheep are task-driven, so an agent-authored
218
+ // message is almost always actionable. Pass followUp explicitly for
219
+ // passive FYI traffic. (012 steer default.)
220
+ return value === 'followUp' ? 'followUp' : 'steer';
221
+ }
222
+
223
+ function deliveryOptions(message: ShepherdMessageEnvelope): {
224
+ deliverAs: ShepherdDelivery;
225
+ triggerTurn: boolean;
226
+ } {
227
+ return {
228
+ deliverAs: deliveryMode(message.delivery),
229
+ // Passive messages wait for the child's next turn. Requests, replies,
230
+ // and delegated tasks must wake the child so waiting workflows can proceed.
231
+ triggerTurn:
232
+ message.kind === 'reply' || message.kind === 'task' || message.expectsReply === true,
233
+ };
234
+ }
235
+
236
+ export default function (pi: ExtensionAPI) {
237
+ const autoExit = process.env.PI_SHEPHERD_AUTO_EXIT === '1';
238
+ const stayOpen = process.env.PI_SHEPHERD_STAY_OPEN === '1';
239
+ const agentSystemPromptFile = process.env.PI_SHEPHERD_AGENT_SYSTEM_PROMPT_FILE;
240
+ const shouldOmitPiDocumentation = process.env.PI_SHEPHERD_OMIT_PI_DOCUMENTATION === '1';
241
+ const configuredTaskId = process.env.PI_SHEPHERD_TASK_ID;
242
+ let agentSystemPrompt = '';
243
+ let broker: ChildBroker | undefined;
244
+ let brokerError: string | undefined;
245
+ let pollTimer: ReturnType<typeof setInterval> | undefined;
246
+ const receivedMessageTaskIds = new Map<string, string | undefined>();
247
+ // Spawn-then-delegate children are launched without a task id; the
248
+ // delegated id arrives with the `kind: 'task'` envelope, so remember the
249
+ // most recently delegated task to validate shepherd_done against.
250
+ let lastDelegatedTaskId: string | undefined;
251
+ // Completion-nudge state (see nudgeForgottenCompletion). A tracked task is
252
+ // settled ONLY by shepherd_done, so a turn that simply ends would leave the
253
+ // parent watching a task that no longer has a worker.
254
+ const nudgeLimit = doneNudgeLimit();
255
+ /** Tasks with a published shepherd_done completion — never nudged again. */
256
+ const completedTasks = new Set<string>();
257
+ /** Nudges already sent, per task id; bounded by `nudgeLimit`. */
258
+ const nudgesSent = new Map<string, number>();
259
+ /** Ids of requests this child published with expectsReply and is awaiting. */
260
+ const outstandingRequests = new Set<string>();
261
+ /** Tasks whose stalled-completion escalation was already published. */
262
+ const escalatedTasks = new Set<string>();
263
+
264
+ if (agentSystemPromptFile) {
265
+ try {
266
+ agentSystemPrompt = readFileSync(agentSystemPromptFile, 'utf8').trim();
267
+ } catch {
268
+ // The launch directory is retained for the lifetime of the child, but
269
+ // a missing file should not prevent the agent from starting.
270
+ }
271
+ }
272
+
273
+ const ensureBroker = (): ChildBroker | undefined => {
274
+ if (broker || brokerError) return broker;
275
+ const loaded = brokerFromEnvironment();
276
+ broker = loaded.broker;
277
+ brokerError = loaded.error;
278
+ return broker;
279
+ };
280
+
281
+ const sendDeliveryFailure = (message: ShepherdMessageEnvelope, error: unknown): void => {
282
+ const active = ensureBroker();
283
+ if (!active) return;
284
+ try {
285
+ const diagnostic = createEnvelope(
286
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.agentId },
287
+ {
288
+ kind: 'runtime',
289
+ targetId: active.parentId,
290
+ taskId: message.taskId,
291
+ threadId: message.threadId,
292
+ delivery: 'followUp',
293
+ content: `Could not deliver Shepherd message ${message.messageId}: ${String((error as any)?.message ?? error)}`,
294
+ error: String((error as any)?.message ?? error),
295
+ }
296
+ );
297
+ publishFromChild(active, diagnostic);
298
+ } catch {
299
+ // Delivery diagnostics are best effort and must not crash the child.
300
+ }
301
+ };
302
+
303
+ const poll = (): void => {
304
+ const active = ensureBroker();
305
+ if (!active) return;
306
+ let messages: ShepherdMessageEnvelope[];
307
+ try {
308
+ messages = pollChildInbox(active);
309
+ } catch {
310
+ return;
311
+ }
312
+ for (const message of messages) {
313
+ if (message.taskId) lastDelegatedTaskId = message.taskId;
314
+ receivedMessageTaskIds.set(message.messageId, message.taskId);
315
+ // Parent relays use a fresh envelope id while preserving the original
316
+ // request in replyTo; replies from this child correlate to that original
317
+ // request id.
318
+ if (message.replyTo) {
319
+ receivedMessageTaskIds.set(message.replyTo, message.taskId);
320
+ // The answer arrived: ending a turn is no longer "waiting" for it.
321
+ outstandingRequests.delete(message.replyTo);
322
+ }
323
+ try {
324
+ pi.sendUserMessage(incomingMessageText(message), deliveryOptions(message));
325
+ } catch (error) {
326
+ sendDeliveryFailure(message, error);
327
+ }
328
+ }
329
+ };
330
+
331
+ /**
332
+ * Tell the parent that a task stayed open past every nudge. Published as a
333
+ * plain message (not a task_done envelope) so no terminal status is invented:
334
+ * the parent decides whether to block, cancel, or wait for the deadline.
335
+ */
336
+ const escalateStalledCompletion = (taskId: string, reason: string): void => {
337
+ if (escalatedTasks.has(taskId)) return;
338
+ escalatedTasks.add(taskId);
339
+ const active = ensureBroker();
340
+ if (!active) return;
341
+ try {
342
+ publishFromChild(
343
+ active,
344
+ createEnvelope(
345
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.agentId },
346
+ {
347
+ kind: 'message',
348
+ targetId: active.parentId,
349
+ taskId,
350
+ delivery: 'followUp',
351
+ content: stalledCompletionText(taskId, reason),
352
+ }
353
+ )
354
+ );
355
+ } catch {
356
+ // Best effort — the parent's task deadline is the remaining backstop.
357
+ }
358
+ };
359
+
360
+ /**
361
+ * Recover a task the child forgot to report.
362
+ *
363
+ * agent_end is the exact boundary where this is observable: pi drains queued
364
+ * messages right after it, so a nudge queued here starts one more turn
365
+ * instead of stalling the session. Guard rails keep the nudge from firing on
366
+ * legitimate turn ends:
367
+ * - only a tracked task this child still holds (plain prompts settle via
368
+ * the legacy completion sidecar and never had a shepherd_done to forget);
369
+ * - never after an aborted or errored turn (the user or provider drives it);
370
+ * - never while a tracked request is outstanding (ending the turn is how a
371
+ * child waits for an answer);
372
+ * - bounded per task, then escalated to the parent instead of looping.
373
+ */
374
+ const nudgeForgottenCompletion = (event: any): void => {
375
+ if (nudgeLimit <= 0) return;
376
+ // Drain the inbox first so a reply that already landed cancels the nudge
377
+ // and is delivered as its own turn.
378
+ poll();
379
+ const taskId = lastDelegatedTaskId ?? configuredTaskId;
380
+ if (taskId === undefined || completedTasks.has(taskId)) return;
381
+ const outcome = latestAssistantOutcome(event?.messages);
382
+ if (!outcome.exit) return;
383
+ if (outcome.error) return; // provider failure is reported through other paths
384
+ if (outstandingRequests.size > 0) return; // waiting for an answer is correct
385
+ const sent = nudgesSent.get(taskId) ?? 0;
386
+ if (sent >= nudgeLimit) {
387
+ escalateStalledCompletion(
388
+ taskId,
389
+ `the reminder budget (${nudgeLimit}) is exhausted and the task deadline is the only remaining settlement.`
390
+ );
391
+ return;
392
+ }
393
+ nudgesSent.set(taskId, sent + 1);
394
+ try {
395
+ pi.sendUserMessage(completionNudgeText(taskId, sent + 1, nudgeLimit), {
396
+ deliverAs: 'followUp',
397
+ triggerTurn: true,
398
+ });
399
+ } catch (error) {
400
+ escalateStalledCompletion(
401
+ taskId,
402
+ `the reminder could not be delivered to this session (${String((error as any)?.message ?? error)}).`
403
+ );
404
+ }
405
+ };
406
+
407
+ if (agentSystemPrompt || shouldOmitPiDocumentation) {
408
+ pi.on('before_agent_start', (event: any) => {
409
+ let systemPrompt = event.systemPrompt;
410
+ if (shouldOmitPiDocumentation) systemPrompt = omitPiDocumentation(systemPrompt);
411
+ if (agentSystemPrompt) systemPrompt = replacePiIdentity(systemPrompt, agentSystemPrompt);
412
+ return systemPrompt === event.systemPrompt ? undefined : { systemPrompt };
413
+ });
414
+ }
415
+
416
+ pi.registerTool({
417
+ name: 'shepherd_message',
418
+ label: 'Shepherd message',
419
+ description:
420
+ 'Send an asynchronous message to the Shepherd or another registered agent without waiting for a reply. For a peer, target MUST be the exact opaque agent id returned by shepherd_spawn; copy it verbatim. Never use an agent definition name such as "planner", a display label, a Herdr pane id, or a placeholder such as "<planner agent ID>"—the call will be rejected.',
421
+ promptSnippet:
422
+ 'send an asynchronous message using the exact opaque agent id returned by shepherd_spawn',
423
+ promptGuidelines: [
424
+ 'For peer messages, copy target from the id field in shepherd_spawn output. Do not infer or substitute an agent definition name, display label, pane id, or angle-bracket placeholder; invalid targets fail instead of being resolved by name.',
425
+ 'When replying with replyTo, use the task ID from the incoming request, not your own task ID. If the incoming message is in context, omit taskId and the child surface will infer it.',
426
+ "A reply must set replyTo to the exact incoming Message ID. Do not call shepherd_done while your task's required request remains unresolved.",
427
+ 'Requests and replies wake waiting agents automatically; after sending a request, end the turn and wait for the queued response rather than polling or sending acknowledgments.',
428
+ ],
429
+ parameters: Type.Object({
430
+ target: Type.String({
431
+ description:
432
+ 'Use "parent"/"shepherd" for the parent, or the exact opaque peer agent id returned by shepherd_spawn. Agent names (for example "planner"), labels, pane ids, and placeholders are rejected.',
433
+ }),
434
+ message: Type.String({ description: 'Non-empty message content.' }),
435
+ taskId: Type.Optional(
436
+ Type.String({
437
+ description: 'Active delegated task id, when this message belongs to a task.',
438
+ })
439
+ ),
440
+ threadId: Type.Optional(Type.String({ description: 'Conversation/thread correlation id.' })),
441
+ replyTo: Type.Optional(
442
+ Type.String({ description: 'Message id of the request being answered.' })
443
+ ),
444
+ expectsReply: Type.Optional(
445
+ Type.Boolean({ description: 'Track this message as a request that expects a reply.' })
446
+ ),
447
+ delivery: Type.Optional(DeliverySchema),
448
+ }),
449
+ async execute(_toolCallId, args) {
450
+ const active = ensureBroker();
451
+ if (!active)
452
+ return unavailableToolResult(
453
+ 'shepherd_message',
454
+ args,
455
+ brokerError ?? 'Broker unavailable.'
456
+ );
457
+ const referencedTaskId = args.replyTo ? receivedMessageTaskIds.get(args.replyTo) : undefined;
458
+ if (
459
+ args.replyTo &&
460
+ receivedMessageTaskIds.has(args.replyTo) &&
461
+ args.taskId !== undefined &&
462
+ args.taskId !== referencedTaskId
463
+ ) {
464
+ return childResult(
465
+ 'shepherd_message',
466
+ args,
467
+ 'Shepherd reply rejected: task mismatch.',
468
+ {
469
+ accepted: false,
470
+ error: `Reply ${args.replyTo} belongs to task ${referencedTaskId ?? 'none'}; use that task id, not ${args.taskId}.`,
471
+ },
472
+ {
473
+ code: 'reply_task_mismatch',
474
+ replyTo: args.replyTo,
475
+ expectedTaskId: referencedTaskId ?? null,
476
+ providedTaskId: args.taskId,
477
+ },
478
+ 1
479
+ );
480
+ }
481
+ const taskId =
482
+ args.replyTo && receivedMessageTaskIds.has(args.replyTo)
483
+ ? referencedTaskId
484
+ : (args.taskId ?? configuredTaskId);
485
+ try {
486
+ const message = createEnvelope(
487
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.agentId },
488
+ {
489
+ kind: args.replyTo ? 'reply' : 'message',
490
+ targetId: args.target,
491
+ taskId,
492
+ threadId: args.threadId,
493
+ replyTo: args.replyTo,
494
+ expectsReply: args.expectsReply,
495
+ delivery: deliveryMode(args.delivery),
496
+ content: args.message,
497
+ }
498
+ );
499
+ const accepted = publishFromChild(active, message);
500
+ if (
501
+ accepted.delivery === 'queued' &&
502
+ args.replyTo &&
503
+ !['shepherd', 'parent', active.parentId].includes(args.target)
504
+ ) {
505
+ // Peer replies are delivered directly to the peer inbox. Mirror only
506
+ // the correlation event to the parent so it can resume the requester's
507
+ // task; the parent must not relay a second copy of the reply.
508
+ const replyMirror = createEnvelope(
509
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.agentId },
510
+ {
511
+ kind: 'runtime',
512
+ targetId: active.parentId,
513
+ taskId,
514
+ replyTo: args.replyTo,
515
+ replyReceived: true,
516
+ summary: args.message,
517
+ delivery: 'followUp',
518
+ }
519
+ );
520
+ try {
521
+ publishFromChild(active, replyMirror);
522
+ } catch {
523
+ return childResult(
524
+ 'shepherd_message',
525
+ args,
526
+ 'Shepherd reply accepted; task correlation degraded (reply mirror failed).',
527
+ {
528
+ accepted: true,
529
+ messageId: message.messageId,
530
+ delivery: accepted.delivery,
531
+ requestTracking: 'degraded',
532
+ },
533
+ { messageId: message.messageId, taskId: taskId ?? null, delivery: accepted.delivery }
534
+ );
535
+ }
536
+ }
537
+ if (accepted.delivery === 'queued' && args.expectsReply === true) {
538
+ // A queued tracked request is why this child may legitimately end its
539
+ // turn without shepherd_done (see nudgeForgottenCompletion), so it is
540
+ // recorded before the correlation mirror is attempted.
541
+ outstandingRequests.add(message.messageId);
542
+ // Mirror the tracked request into the parent inbox so the parent
543
+ // can open the request on the task (running -> waiting). The
544
+ // question itself was published to the target; the mirror only
545
+ // carries correlation state, never a second copy of the content
546
+ // for delivery.
547
+ const mirrored = createEnvelope(
548
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.agentId },
549
+ {
550
+ kind: 'runtime',
551
+ targetId: active.parentId,
552
+ taskId,
553
+ threadId: args.threadId,
554
+ replyTo: message.messageId,
555
+ requestOpen: true,
556
+ requestTargetId: ['shepherd', 'parent'].includes(args.target)
557
+ ? active.parentId
558
+ : args.target,
559
+ summary: args.message,
560
+ delivery: 'followUp',
561
+ }
562
+ );
563
+ try {
564
+ publishFromChild(active, mirrored);
565
+ } catch {
566
+ // The question is already queued; a lost mirror only delays
567
+ // the task entering the waiting state and cannot corrupt it.
568
+ return childResult(
569
+ 'shepherd_message',
570
+ args,
571
+ 'Shepherd message accepted; reply tracking degraded (request mirror failed).',
572
+ {
573
+ accepted: true,
574
+ messageId: message.messageId,
575
+ delivery: accepted.delivery,
576
+ requestTracking: 'degraded',
577
+ },
578
+ { messageId: message.messageId, taskId: taskId ?? null, delivery: accepted.delivery }
579
+ );
580
+ }
581
+ }
582
+ return childResult(
583
+ 'shepherd_message',
584
+ args,
585
+ 'Shepherd message accepted for asynchronous delivery.',
586
+ accepted,
587
+ { messageId: message.messageId, taskId: taskId ?? null, delivery: accepted.delivery }
588
+ );
589
+ } catch (error) {
590
+ return childResult(
591
+ 'shepherd_message',
592
+ args,
593
+ 'Shepherd message was rejected.',
594
+ { accepted: false, error: String((error as any)?.message ?? error) },
595
+ {
596
+ code: (error as any)?.code ?? 'message_rejected',
597
+ error: String((error as any)?.message ?? error),
598
+ },
599
+ 1
600
+ );
601
+ }
602
+ },
603
+ });
604
+
605
+ pi.registerTool({
606
+ name: 'shepherd_done',
607
+ label: 'Shepherd task done',
608
+ description:
609
+ 'Explicitly complete, block, or fail the current delegated Shepherd task. This is the only signal that tells the parent a tracked task has finished.',
610
+ promptSnippet: 'explicitly complete the delegated Shepherd task',
611
+ promptGuidelines: [
612
+ 'Call shepherd_done when the delegated task is complete, blocked, or failed, before ending your turn. If you need input from the parent or a peer, send shepherd_message with expectsReply instead.',
613
+ 'Omit taskId to complete the current delegated task; the child context already knows it. If you do provide it, use the exact Task ID from the most recent delegated task.',
614
+ 'In the shepherd_done summary, state what was done and, when blocked or failed, what specifically prevents completion.',
615
+ ],
616
+ parameters: Type.Object({
617
+ taskId: Type.Optional(
618
+ Type.String({
619
+ description:
620
+ 'Optional. Omit to complete the current delegated task; if provided, it is verified against the delegated task id.',
621
+ })
622
+ ),
623
+ status: StatusSchema,
624
+ summary: Type.Optional(
625
+ Type.String({ description: 'Concise completion, blocked, or failure summary.' })
626
+ ),
627
+ }),
628
+ async execute(_toolCallId, args) {
629
+ const active = ensureBroker();
630
+ if (!active)
631
+ return unavailableToolResult('shepherd_done', args, brokerError ?? 'Broker unavailable.');
632
+ // The id is inferred, not pasted: one-shot launches pin the launch-time
633
+ // id in the environment, spawn-then-delegate children learn it from the
634
+ // delegated task envelope, and the most recent one wins.
635
+ const knownTaskId = lastDelegatedTaskId ?? configuredTaskId;
636
+ if (knownTaskId === undefined) {
637
+ const error =
638
+ 'No delegated task has been received in this child context. shepherd_done only applies to a task delivered through the Shepherd.';
639
+ return childResult(
640
+ 'shepherd_done',
641
+ args,
642
+ 'Shepherd task completion was rejected.',
643
+ { accepted: false, error },
644
+ { code: 'no_delegated_task', error },
645
+ 1
646
+ );
647
+ }
648
+ let idMismatch: string | undefined;
649
+ if (args.taskId !== undefined && args.taskId !== knownTaskId) {
650
+ if (knownTaskId === configuredTaskId) {
651
+ // A one-shot launch pins exactly one task: a mismatched id means the
652
+ // child is confused about which task it is completing, so reject.
653
+ const error = `Task id does not match this child context (${knownTaskId}).`;
654
+ return childResult(
655
+ 'shepherd_done',
656
+ args,
657
+ 'Shepherd task completion was rejected.',
658
+ { accepted: false, error },
659
+ { code: 'task_mismatch', error },
660
+ 1
661
+ );
662
+ }
663
+ // A fabricated or misremembered id is corrected to the id of the task
664
+ // this child actually holds, so the completion is not lost upstream
665
+ // (issue #13).
666
+ idMismatch = `Supplied task id "${args.taskId}" does not match the delegated task; the completion was recorded against ${knownTaskId}.`;
667
+ }
668
+ try {
669
+ const completion = createEnvelope(
670
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.agentId },
671
+ {
672
+ kind: 'task_done',
673
+ targetId: active.parentId,
674
+ taskId: knownTaskId,
675
+ status: args.status,
676
+ summary: args.summary,
677
+ content: args.summary,
678
+ delivery: 'followUp',
679
+ }
680
+ );
681
+ const accepted = publishFromChild(active, completion);
682
+ completedTasks.add(knownTaskId);
683
+ return childResult('shepherd_done', args,
684
+ idMismatch
685
+ ? 'Shepherd task completion accepted (task id corrected to the delegated task).'
686
+ : 'Shepherd task completion accepted.',
687
+ accepted,
688
+ {
689
+ taskId: knownTaskId,
690
+ status: args.status,
691
+ delivery: accepted.delivery,
692
+ ...(idMismatch ? { suppliedTaskId: args.taskId, idMismatch } : {}),
693
+ }
694
+ );
695
+ } catch (error) {
696
+ return childResult(
697
+ 'shepherd_done',
698
+ args,
699
+ 'Shepherd task completion was rejected.',
700
+ { accepted: false, error: String((error as any)?.message ?? error) },
701
+ {
702
+ code: (error as any)?.code ?? 'completion_rejected',
703
+ error: String((error as any)?.message ?? error),
704
+ },
705
+ 1
706
+ );
707
+ }
708
+ },
709
+ });
710
+
711
+ pi.on('session_start', (_event: any, ctx?: any) => {
712
+ // Show the agent identity (e.g. "writer" or "writer: draft") in the
713
+ // child pane's footer so a manually driven agent is recognizable.
714
+ const display = process.env.PI_SHEPHERD_AGENT_DISPLAY?.trim();
715
+ if (display && ctx?.hasUI) {
716
+ try {
717
+ const theme = ctx.ui?.theme;
718
+ const text = theme ? theme.fg('accent', `🐑 ${display}`) : `🐑 ${display}`;
719
+ ctx.ui?.setStatus?.('pi-shepherd-agent', text);
720
+ } catch {
721
+ // Footer status is best effort and must not prevent startup.
722
+ }
723
+ }
724
+ if (pollTimer) return;
725
+ ensureBroker();
726
+ poll();
727
+ pollTimer = setInterval(poll, 250);
728
+ (pollTimer as any).unref?.();
729
+ });
730
+
731
+ pi.on('session_shutdown', (_event?: any, ctx?: any) => {
732
+ try {
733
+ ctx?.ui?.setStatus?.('pi-shepherd-agent', undefined);
734
+ } catch {
735
+ // Best effort cleanup.
736
+ }
737
+ if (pollTimer) clearInterval(pollTimer);
738
+ pollTimer = undefined;
739
+ broker = undefined;
740
+ });
741
+
742
+ pi.on('agent_end', (event: any, ctx: { shutdown: () => void }) => {
743
+ // Independent of the legacy sidecar path: a tracked task left open at turn
744
+ // end gets one reminder turn before anything else is considered.
745
+ nudgeForgottenCompletion(event);
746
+ // Persistent shepherd agents stay alive, but must still publish a
747
+ // completion signal for the legacy prompt path. One-shot agents publish
748
+ // it and exit. A tracked task is different: a normal agent_end is only a
749
+ // turn observation, so it must not claim task success or shut down a child
750
+ // that may need to resume after a peer reply.
751
+ if (!autoExit && !stayOpen) return;
752
+ const outcome = latestAssistantOutcome(event?.messages);
753
+ if (!outcome.exit) return; // aborted / no assistant turn — leave open.
754
+ if (outcome.error) {
755
+ // Provider errors are still useful process-failure diagnostics for the
756
+ // parent, even when a tracked task is active.
757
+ writeSidecar({ type: 'error', errorMessage: outcome.error.errorMessage });
758
+ if (!stayOpen) ctx.shutdown();
759
+ return;
760
+ }
761
+ if (configuredTaskId) return;
762
+ writeSidecar({ type: 'done' });
763
+ // Stay open: report completion to the parent via the sidecar, but keep
764
+ // this pi session alive in the tab so the user can keep driving it.
765
+ if (stayOpen) return;
766
+ ctx.shutdown();
767
+ });
768
+ }