@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
@@ -0,0 +1,1712 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import {
5
+ discoverAgents,
6
+ resolveDelegatedModel,
7
+ resolveDelegatedThinking,
8
+ type AgentThinkingLevel,
9
+ } from '../../core/discovery.ts';
10
+ import {
11
+ createEnvelope,
12
+ createParentBroker,
13
+ publishFromParent,
14
+ pollParentInbox,
15
+ registerChild,
16
+ unregisterChild,
17
+ closeBrokerWhenChildrenGone,
18
+ type ParentBroker,
19
+ type ShepherdDelivery,
20
+ type ShepherdMessageEnvelope,
21
+ type PublishResult,
22
+ } from './messaging.ts';
23
+ import { DEFAULT_SETTINGS, loadSettings } from '../../core/config.ts';
24
+ import {
25
+ ensureHerdrRuntime,
26
+ getHerdrWorkspaceId,
27
+ createHerdrInstance,
28
+ waitForHerdrShellReady,
29
+ waitForHerdrAgentDetected,
30
+ launchPiInPane,
31
+ setCreatedPaneDir,
32
+ herdrExec,
33
+ herdrExecSync,
34
+ loadCreatedPanes,
35
+ paneExists,
36
+ removeCreatedPaneDir,
37
+ readPaneTail,
38
+ readLastAssistantText,
39
+ readCompletionSignal,
40
+ readLaunchExitCode,
41
+ } from './herdr.ts';
42
+ import {
43
+ lifecycleRegistry,
44
+ type AgentHandle,
45
+ type AgentHandleInput,
46
+ type PromptHandle,
47
+ type PromptHandleInput,
48
+ type PromptResult,
49
+ type WatcherCompletion,
50
+ type WatcherNotification,
51
+ type WatcherRegistration,
52
+ type AgentStatus,
53
+ formatAgentName,
54
+ validateAgentLabel,
55
+ sessionOwner,
56
+ LifecycleError,
57
+ type CreateTaskOptions,
58
+ type TaskHandle,
59
+ type TaskResult,
60
+ type TaskHandleInput,
61
+ type TaskRecord,
62
+ type TaskWatcherCompletion,
63
+ type TaskWatcherRegistration,
64
+ type TaskWatcherNotification,
65
+ type TaskWatcherCallback,
66
+ } from './orchestration.ts';
67
+ import {
68
+ reserveArtifacts,
69
+ markArtifactStarted,
70
+ finalizeArtifact,
71
+ type ShepherdSession,
72
+ type ArtifactReservation,
73
+ } from '../../core/artifact-sessions.ts';
74
+ import { mintMessageId } from '../../core/ids.ts';
75
+
76
+ let parentBroker: ParentBroker | undefined;
77
+ let parentBrokerSessionId: string | undefined;
78
+ let parentBrokerTimer: ReturnType<typeof setInterval> | undefined;
79
+ let parentBrokerTicking = false;
80
+ let lastTrackedTaskRuntimeCheck = 0;
81
+
82
+ function startParentBrokerMonitor(): void {
83
+ if (parentBrokerTimer) return;
84
+ parentBrokerTimer = setInterval(() => void processParentBrokerMessages(), 250);
85
+ (parentBrokerTimer as any).unref?.();
86
+ }
87
+
88
+ function stopParentBrokerMonitor(): void {
89
+ if (parentBrokerTimer) clearInterval(parentBrokerTimer);
90
+ parentBrokerTimer = undefined;
91
+ parentBrokerTicking = false;
92
+ lastTrackedTaskRuntimeCheck = 0;
93
+ shutdownStaleWaitMonitor();
94
+ }
95
+
96
+ /** Ensure one parent-owned mailbox exists for the current Shepherd session. */
97
+ export function ensureParentBroker(sessionId?: string): ParentBroker {
98
+ const id = sessionId?.trim() || sessionOwner();
99
+ if (!id) throw new Error('Unable to resolve the parent Shepherd session identity.');
100
+ if (parentBroker && !parentBroker.closed && parentBrokerSessionId === id) return parentBroker;
101
+ parentBroker = createParentBroker(id);
102
+ parentBrokerSessionId = id;
103
+ startParentBrokerMonitor();
104
+ return parentBroker;
105
+ }
106
+
107
+ export function currentParentBroker(): ParentBroker | undefined {
108
+ return parentBroker && !parentBroker.closed ? parentBroker : undefined;
109
+ }
110
+
111
+ /**
112
+ * Close the broker only after the Herdr integration confirms all child panes
113
+ * are gone. Returning false preserves the mailbox for live children.
114
+ */
115
+ export function shutdownParentBroker(childrenGone: () => boolean): boolean {
116
+ if (!parentBroker) return true;
117
+ const closed = closeBrokerWhenChildrenGone(parentBroker, childrenGone);
118
+ if (closed) {
119
+ stopParentBrokerMonitor();
120
+ parentBroker = undefined;
121
+ parentBrokerSessionId = undefined;
122
+ }
123
+ return closed;
124
+ }
125
+
126
+ export interface StartOptions {
127
+ cwd?: string;
128
+ placement?: 'pane_right' | 'pane_down' | 'tab' | 'workspace';
129
+ label?: string;
130
+ /** Internal parent-bound artifact session, resolved by the parent tool. */
131
+ artifactSession?: ShepherdSession;
132
+ /**
133
+ * Child launch overrides. The Pi path omits this (Pi CLI defaults);
134
+ * other hosts pass their binary/command and env prefix here.
135
+ */
136
+ launch?: {
137
+ binary?: string;
138
+ extensionEntry?: string;
139
+ envPrefix?: string;
140
+ command?: string;
141
+ };
142
+ }
143
+
144
+ export async function startAgent(
145
+ name: string,
146
+ options: StartOptions = {},
147
+ ctx: {
148
+ cwd: string;
149
+ model?: { provider: string; id: string };
150
+ thinkingLevel?: AgentThinkingLevel;
151
+ hasUI?: boolean;
152
+ ui?: any;
153
+ sessionId?: string;
154
+ }
155
+ ): Promise<AgentHandle> {
156
+ const cwd = options.cwd ?? ctx.cwd;
157
+ const label = validateAgentLabel(options.label);
158
+ const settings = loadSettings(cwd);
159
+ // Agent scope and project approval are settings-owned; callers cannot
160
+ // override them per spawn.
161
+ const agentScope = settings.agentScope;
162
+ const confirmProjectAgents = settings.confirmProjectAgents;
163
+ const discovered = discoverAgents(cwd, agentScope, {
164
+ includeBundled: settings.includeBundledAgents,
165
+ }).agents;
166
+ const found = discovered.find(a => a.name === name);
167
+ if (!found) {
168
+ const available = discovered.map(a => a.name).join(', ');
169
+ const suggestion = discovered.find(a => a.name.toLowerCase() === name.trim().toLowerCase());
170
+ throw new Error(
171
+ `Unknown agent "${name}" in ${agentScope} scope.` +
172
+ (suggestion ? ` Did you mean "${suggestion.name}"?` : '') +
173
+ (available ? ` Available agents: ${available}.` : ' No agents are available.') +
174
+ ' Call shepherd with action "agents" to list exact names.'
175
+ );
176
+ }
177
+ if (found.source === 'project' && confirmProjectAgents && ctx.hasUI) {
178
+ const ok = await ctx.ui.confirm(
179
+ 'Run project-local agent?',
180
+ `Agent: ${name}\nSource: ${found.filePath}`
181
+ );
182
+ if (!ok) throw new Error('Project-local agent was not approved.');
183
+ }
184
+ await ensureHerdrRuntime();
185
+ const broker = ensureParentBroker(ctx.sessionId);
186
+ const reservedAgentId = lifecycleRegistry.allocateAgentId();
187
+ const childCapability = registerChild(broker, reservedAgentId);
188
+ const placement = options.placement ?? 'tab';
189
+ const herdrPlacement =
190
+ placement === 'pane_right' || placement === 'pane_down' ? 'pane' : placement;
191
+ const direction = placement === 'pane_down' ? 'down' : 'right';
192
+ let paneId = '';
193
+ let tabId = '';
194
+ let workspaceId = '';
195
+ try {
196
+ // The agent definition is the only source of an explicit child model;
197
+ // otherwise inherit the parent Shepherd's current provider/model.
198
+ const delegatedModel = resolveDelegatedModel(found.model, ctx.model);
199
+ // Thinking follows the parent unless the definition requests an explicit
200
+ // level. Pi clamps unsupported levels to the child model's capabilities.
201
+ const delegatedThinking = resolveDelegatedThinking(found.thinking, ctx.thinkingLevel);
202
+ const created = createHerdrInstance(
203
+ formatAgentName(name, label),
204
+ cwd,
205
+ herdrPlacement,
206
+ herdrPlacement === 'workspace' ? undefined : getHerdrWorkspaceId(),
207
+ direction
208
+ );
209
+ paneId = created.paneId;
210
+ tabId = created.tabId;
211
+ workspaceId = created.workspaceId;
212
+ await waitForHerdrShellReady(paneId, { timeoutMs: 15_000 });
213
+ const files = launchPiInPane(paneId, {
214
+ name,
215
+ label,
216
+ persistent: true,
217
+ childBroker: { rootDir: broker.rootDir, ...childCapability },
218
+ systemPrompt: found.systemPrompt,
219
+ // Prompt-shaping options belong to the discovered agent definition.
220
+ omitSystemPrompt: found.omitSystemPrompt,
221
+ omitPiDocumentation: found.omitPiDocumentation === true,
222
+ omitContextFiles: found.omitContextFiles === true,
223
+ // The agent definition selects the model; absent a definition, inherit
224
+ // the parent Shepherd's current provider/model.
225
+ model: delegatedModel,
226
+ thinking: delegatedThinking,
227
+ tools: found.tools,
228
+ // Host launch overrides (other hosts boot their own CLI); Pi omits.
229
+ ...(options.launch?.binary !== undefined ? { binary: options.launch.binary } : {}),
230
+ ...(options.launch?.extensionEntry !== undefined
231
+ ? { extensionEntry: options.launch.extensionEntry }
232
+ : {}),
233
+ ...(options.launch?.envPrefix !== undefined ? { envPrefix: options.launch.envPrefix } : {}),
234
+ ...(options.launch?.command !== undefined ? { command: options.launch.command } : {}),
235
+ });
236
+ setCreatedPaneDir(paneId, files.dir);
237
+ // Keep the launch directory registered while the persistent child is alive;
238
+ // its completion sidecar is also the reliable fast-completion signal.
239
+ const ready = await waitForHerdrAgentDetected(paneId, { timeoutMs: 20_000 });
240
+ if (!ready.detected) {
241
+ const returnCode = ready.exitCode ?? (await readLaunchExitCode(paneId));
242
+ const output = (await readPaneTail(paneId)).trim();
243
+ const suffix = returnCode === null ? '' : ` (return code ${returnCode})`;
244
+ const wording =
245
+ returnCode !== null && returnCode !== 0 ? 'failed to start' : 'did not become ready';
246
+ throw Object.assign(
247
+ new Error(`Agent "${name}" ${wording}${suffix}.${output ? `\n${output}` : ''}`),
248
+ { returnCode: returnCode ?? 1, code: 'agent_not_ready' }
249
+ );
250
+ }
251
+ return lifecycleRegistry.registerAgent(
252
+ {
253
+ id: reservedAgentId,
254
+ agent: name,
255
+ label,
256
+ model: delegatedModel,
257
+ paneId,
258
+ tabId,
259
+ workspaceId,
260
+ cwd,
261
+ },
262
+ {
263
+ completionSignalPath: `${files.sessionFile}.exit`,
264
+ completionResultPath: files.sessionFile,
265
+ artifactSession: options.artifactSession,
266
+ childCapability,
267
+ }
268
+ );
269
+ } catch (error) {
270
+ try {
271
+ unregisterChild(broker, reservedAgentId);
272
+ } catch {}
273
+ if (paneId) {
274
+ try {
275
+ herdrExecSync(['pane', 'close', paneId]);
276
+ } catch {}
277
+ if (!paneExists(paneId)) removeCreatedPaneDir(paneId);
278
+ }
279
+ throw error;
280
+ }
281
+ }
282
+
283
+ function artifactContext(session: ShepherdSession, artifact: ArtifactReservation): string {
284
+ return [
285
+ '\n\n--- Shepherd fieldnotes context ---',
286
+ `Shared session: ${session.sessionPath}`,
287
+ `Shared fieldnotes: ${session.mocPath}`,
288
+ `Assigned note: ${artifact.filePath}`,
289
+ `Project-relative note: ${artifact.relativePath}`,
290
+ 'Read the shared fieldnotes before working. Write your findings only to the assigned note; do not create another Shepherd session.',
291
+ '--- End Shepherd fieldnotes context ---',
292
+ ].join('\n');
293
+ }
294
+
295
+ function finalizePromptArtifact(handle: PromptHandle, result: PromptResult): void {
296
+ const { session, artifact } = lifecycleRegistry.promptArtifact(handle);
297
+ if (!session || !artifact) return;
298
+ const status =
299
+ result.status === 'timeout'
300
+ ? 'timed-out'
301
+ : result.status === 'cancelled'
302
+ ? 'cancelled'
303
+ : result.ok
304
+ ? 'completed'
305
+ : 'failed';
306
+ finalizeArtifact(session, artifact, { status, output: result.text, error: result.error });
307
+ }
308
+
309
+ function finalizeTaskArtifact(handle: TaskHandle, result: TaskResult): void {
310
+ const { session, artifact } = lifecycleRegistry.taskArtifact(handle);
311
+ if (!session || !artifact) return;
312
+ const status =
313
+ result.status === 'timed_out'
314
+ ? 'timed-out'
315
+ : result.status === 'cancelled'
316
+ ? 'cancelled'
317
+ : result.status === 'completed'
318
+ ? 'completed'
319
+ : result.status === 'blocked'
320
+ ? 'failed'
321
+ : 'failed';
322
+ finalizeArtifact(session, artifact, { status, output: result.text, error: result.error });
323
+ }
324
+
325
+ export interface DelegateOptions extends CreateTaskOptions {
326
+ /** Parent pi session identity used for broker creation in tests/startup. */
327
+ sessionId?: string;
328
+ /** Internal parent-bound artifact session, resolved by the parent tool. */
329
+ artifactSession?: ShepherdSession;
330
+ }
331
+
332
+ /**
333
+ * Submit a tracked task through the parent broker. This returns after the task
334
+ * envelope is queued; completion is intentionally handled by shepherd_done in
335
+ * a later phase rather than by this call or by a child turn ending.
336
+ */
337
+ export async function delegateAgent(
338
+ handle: AgentHandleInput,
339
+ description: string,
340
+ options: DelegateOptions = {}
341
+ ): Promise<TaskHandle> {
342
+ if (typeof description !== 'string' || !description.trim())
343
+ throw new Error('Delegated task description must not be empty.');
344
+ const canonical = lifecycleRegistry.canonicalAgentHandle(handle);
345
+ const record = lifecycleRegistry.getAgent(canonical);
346
+ if (!record.handle.paneId) throw new Error('Agent handle has no pane.');
347
+ const detected = await waitForHerdrAgentDetected(record.handle.paneId, { timeoutMs: 15_000 });
348
+ if (!detected.detected) throw new Error(`Agent "${canonical.id}" is not detected.`);
349
+
350
+ const broker = ensureParentBroker(options.sessionId);
351
+ let childCapability = lifecycleRegistry.agentChildCapability(canonical);
352
+ if (!childCapability) {
353
+ childCapability = registerChild(broker, canonical.id);
354
+ lifecycleRegistry.attachAgentChildCapability(canonical, childCapability);
355
+ }
356
+
357
+ const task = lifecycleRegistry.createTask(canonical, description, {
358
+ timeoutMs: options.timeoutMs,
359
+ deadlineAt: options.deadlineAt,
360
+ artifactSession: options.artifactSession ?? lifecycleRegistry.artifactSession(canonical),
361
+ });
362
+ const session = options.artifactSession ?? lifecycleRegistry.artifactSession(canonical);
363
+ try {
364
+ if (session) {
365
+ const artifact = reserveArtifacts(session, [
366
+ { agent: record.handle.agent, mode: 'single', task: description },
367
+ ])[0];
368
+ markArtifactStarted(session, artifact, { taskId: task.id, agentId: task.agentId });
369
+ lifecycleRegistry.attachTaskArtifact(task, session, artifact, result =>
370
+ finalizeTaskArtifact(task, result)
371
+ );
372
+ }
373
+ const envelope = createEnvelope(
374
+ { sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: broker.parentId },
375
+ {
376
+ kind: 'task',
377
+ targetId: canonical.id,
378
+ taskId: task.id,
379
+ delivery: 'followUp',
380
+ content: description,
381
+ }
382
+ );
383
+ publishFromParent(broker, envelope);
384
+ lifecycleRegistry.setTaskRunning(task);
385
+ return task;
386
+ } catch (error) {
387
+ lifecycleRegistry.settleTask(
388
+ task,
389
+ {
390
+ status: 'failed',
391
+ ok: false,
392
+ returnCode: 1,
393
+ error: String((error as any)?.message ?? error),
394
+ },
395
+ { source: 'delegate-submission-failure' }
396
+ );
397
+ throw new Error(`Task submission failed: ${String((error as any)?.message ?? error)}`);
398
+ }
399
+ }
400
+
401
+ const TERMINAL_TASK_STATES: ReadonlySet<TaskRecord['state']> = new Set([
402
+ 'completed',
403
+ 'blocked',
404
+ 'failed',
405
+ 'cancelled',
406
+ 'timed_out',
407
+ ]);
408
+
409
+ /**
410
+ * Record a diagnostic for a child completion in the broker's rejected store so
411
+ * a completion the parent could not apply is observable on disk instead of
412
+ * being silently acked.
413
+ */
414
+ function writeTaskDoneDiagnostic(
415
+ kind: 'dropped' | 'mismatch',
416
+ envelope: ShepherdMessageEnvelope,
417
+ reason: string
418
+ ): void {
419
+ const broker = currentParentBroker();
420
+ if (!broker) return;
421
+ try {
422
+ const rejectedPath = path.join(broker.rootDir, 'rejected');
423
+ fs.mkdirSync(rejectedPath, { recursive: true });
424
+ fs.writeFileSync(
425
+ path.join(rejectedPath, `task-done-${kind}-${randomUUID()}.json`),
426
+ JSON.stringify({ at: Date.now(), reason, envelope }, null, 2),
427
+ 'utf8'
428
+ );
429
+ } catch {
430
+ // Diagnostics must never break broker polling.
431
+ }
432
+ }
433
+
434
+ /** Warn the parent session about a completion the registry could not apply. */
435
+ function dropUnappliedTaskDone(envelope: ShepherdMessageEnvelope, reason: string): void {
436
+ writeTaskDoneDiagnostic('dropped', envelope, reason);
437
+ notifyParentMessage('task_done_dropped', envelope, reason);
438
+ }
439
+
440
+ /**
441
+ * Apply one explicit child completion to the parent task registry.
442
+ *
443
+ * The child LLM can fabricate the task id it echoes back (it can mimic a
444
+ * Herdr pane-id string that no task uses). The envelope's sender, in
445
+ * contrast, is authenticated by the broker, and each agent holds at most one
446
+ * active tracked task. So a task id that does not resolve to the sender's
447
+ * own task is re-anchored on the sender's active task before anything is
448
+ * settled, and a completion with no resolvable task at all is dropped
449
+ * observably rather than silently.
450
+ */
451
+ function applyTaskDoneEnvelope(envelope: ShepherdMessageEnvelope): TaskResult | undefined {
452
+ if (envelope.kind !== 'task_done' || !envelope.status) return undefined;
453
+
454
+ let task: TaskRecord | undefined;
455
+ if (envelope.taskId) {
456
+ try {
457
+ task = lifecycleRegistry.getTask(envelope.taskId);
458
+ } catch {
459
+ // Unknown session-local task id: the child may have fabricated it.
460
+ // Never create a record for it; fall through to sender correlation.
461
+ }
462
+ }
463
+
464
+ let senderAgentId: string | undefined;
465
+ try {
466
+ senderAgentId = lifecycleRegistry.getAgent(envelope.senderId).handle.id;
467
+ } catch {
468
+ senderAgentId = undefined;
469
+ }
470
+ const senderActiveTask =
471
+ senderAgentId !== undefined
472
+ ? lifecycleRegistry.activeTaskForAgent({ id: senderAgentId })
473
+ : undefined;
474
+
475
+ if (task && TERMINAL_TASK_STATES.has(task.state)) {
476
+ return lifecycleRegistry.taskResult(task.taskId);
477
+ }
478
+
479
+ let effective = task;
480
+ if (task && senderAgentId !== undefined && task.agentId !== senderAgentId) {
481
+ // The named task belongs to a different agent: the child mislabeled its
482
+ // own completion, so prefer the only task the sender actually owns.
483
+ effective = senderActiveTask;
484
+ }
485
+ if (!effective) effective = senderActiveTask;
486
+
487
+ if (!effective || senderAgentId === undefined) {
488
+ const named = task ? `task "${task.taskId}"` : `task id "${envelope.taskId ?? '<none>'}"`;
489
+ const reason = task
490
+ ? `${named} is not owned by the sender and the sender has no active task`
491
+ : `no active task matches ${named} for the sender`;
492
+ dropUnappliedTaskDone(envelope, reason);
493
+ return undefined;
494
+ }
495
+
496
+ if (envelope.status === 'completed' && effective.pendingRequestIds.length > 0) {
497
+ // A child cannot declare success while required replies remain pending.
498
+ // Leave the task waiting so the reply or an explicit blocked/failed
499
+ // result can resolve it later.
500
+ return undefined;
501
+ }
502
+
503
+ const idMismatched = (envelope.taskId ?? '') !== effective.taskId;
504
+ try {
505
+ const result = lifecycleRegistry.settleTaskForAgent(
506
+ effective.taskId,
507
+ { id: senderAgentId },
508
+ {
509
+ status: envelope.status,
510
+ text: envelope.summary ?? envelope.content,
511
+ error: envelope.error,
512
+ }
513
+ );
514
+ if (idMismatched) {
515
+ writeTaskDoneDiagnostic(
516
+ 'mismatch',
517
+ envelope,
518
+ `child reported task id "${envelope.taskId ?? '<none>'}"; completion applied to the sender's active task "${effective.taskId}"`
519
+ );
520
+ }
521
+ return result;
522
+ } catch {
523
+ // Ownership and lifecycle failures are rejected at the registry boundary;
524
+ // a completion lost here must stay observable instead of being acked away.
525
+ dropUnappliedTaskDone(
526
+ envelope,
527
+ `settlement of "${effective.taskId}" was rejected by the registry`
528
+ );
529
+ return undefined;
530
+ }
531
+ }
532
+
533
+ /**
534
+ * Drain parent control messages and observe external terminal failures. This
535
+ * is deliberately separate from prompt watchers: idle and turn-settled states
536
+ * are never considered successful task completion.
537
+ */
538
+ function extractAgentError(output: string): string | undefined {
539
+ const match = output.match(/(?:^|\n)\s*Error:\s*(.+)/i);
540
+ if (!match) return undefined;
541
+ const message = match[1].trim();
542
+ return /api key|authentication|authenticat|provider|model|failed to load/i.test(message)
543
+ ? message
544
+ : undefined;
545
+ }
546
+
547
+ async function readImmediateAgentError(paneId: string): Promise<string | undefined> {
548
+ return extractAgentError((await readPaneTail(paneId)).trim());
549
+ }
550
+
551
+ // ── Phase 6: asynchronous message routing ──────────────────────────────────
552
+ // The parent Shepherd is the message hub: it owns request (expectsReply)
553
+ // correlation and task waiting state. Children publish into the parent-owned
554
+ // broker; parent→child publishes go straight to the target inbox, child→parent
555
+ // events are consumed by processParentBrokerMessages() below.
556
+
557
+ export interface ParentMessageInput {
558
+ target: string;
559
+ message: string;
560
+ taskId?: string;
561
+ threadId?: string;
562
+ replyTo?: string;
563
+ delivery?: 'followUp' | 'steer';
564
+ expectsReply?: boolean;
565
+ }
566
+
567
+ export interface ParentMessageResult {
568
+ messageId: string;
569
+ accepted: true;
570
+ delivery: 'queued' | 'duplicate';
571
+ requestId?: string;
572
+ targetId: string;
573
+ targetTaskState?: string;
574
+ }
575
+
576
+ function messageTargetError(target: string): LifecycleError {
577
+ return new LifecycleError(
578
+ 'invalid_target',
579
+ `Unknown message target "${target}". shepherd_message requires the exact opaque agent id returned by shepherd_spawn (for example "shepherd-agent-..."); do not use an agent name such as "planner", a display label, a Herdr pane id, or a placeholder such as "<planner agent ID>".`
580
+ );
581
+ }
582
+
583
+ /**
584
+ * Send a parent-originated message to an owned child. With `expectsReply` and
585
+ * a task id the task enters `waiting` until a matching reply arrives.
586
+ */
587
+ export function sendParentMessage(input: ParentMessageInput): ParentMessageResult {
588
+ if (typeof input.message !== 'string' || !input.message.trim()) {
589
+ throw new LifecycleError('invalid_task', 'Message content must not be empty.');
590
+ }
591
+ const broker = currentParentBroker() ?? ensureParentBroker();
592
+ let agent;
593
+ try {
594
+ // Message targets are lifecycle ids, never agent definition names or
595
+ // display labels. Resolve strictly by the exact id returned by spawn.
596
+ agent = lifecycleRegistry.getAgent({ id: input.target });
597
+ } catch (error) {
598
+ if (
599
+ error instanceof LifecycleError &&
600
+ ['unknown_handle', 'invalid_handle'].includes(error.code)
601
+ ) {
602
+ throw messageTargetError(input.target);
603
+ }
604
+ throw error;
605
+ }
606
+ if (agent.state === 'closed') {
607
+ throw new LifecycleError('closed_handle', `Agent "${input.target}" is closed.`);
608
+ }
609
+ const replyDeadline = input.expectsReply
610
+ ? Date.now() + loadSettings(agent.handle.cwd ?? process.cwd()).timeout * 60_000
611
+ : undefined;
612
+ if (input.expectsReply && input.taskId) {
613
+ // Open the request before publishing so the task never waits on a
614
+ // question the broker refused to queue. The question envelope id becomes
615
+ // the correlation key for the reply.
616
+ if (lifecycleRegistry.getTask(input.taskId).agentId !== agent.handle.id) {
617
+ throw new LifecycleError(
618
+ 'task_agent_mismatch',
619
+ `Task "${input.taskId}" is owned by another agent than the message target.`
620
+ );
621
+ }
622
+ const provisional = createEnvelope(
623
+ { sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: broker.parentId },
624
+ {
625
+ kind: 'message',
626
+ targetId: agent.handle.id,
627
+ messageId: mintMessageId(),
628
+ taskId: input.taskId,
629
+ threadId: input.threadId,
630
+ replyTo: input.replyTo,
631
+ expectsReply: true,
632
+ delivery: input.delivery === 'followUp' ? 'followUp' : 'steer',
633
+ content: input.message,
634
+ createdAt: Date.now(),
635
+ }
636
+ );
637
+ lifecycleRegistry.openPendingRequest(input.taskId, {
638
+ messageId: provisional.messageId,
639
+ targetAgentId: agent.handle.id,
640
+ deadlineAt: replyDeadline,
641
+ text: input.message,
642
+ });
643
+ staleWaitMonitor.kick();
644
+ try {
645
+ const envelope = provisional;
646
+ const accepted = publishFromParent(broker, envelope);
647
+ return {
648
+ messageId: envelope.messageId,
649
+ accepted: true,
650
+ delivery: accepted.delivery,
651
+ requestId: envelope.messageId,
652
+ targetId: agent.handle.id,
653
+ targetTaskState: 'waiting',
654
+ };
655
+ } catch (error) {
656
+ lifecycleRegistry.clearPendingReply(input.taskId);
657
+ throw error;
658
+ }
659
+ }
660
+ const envelope = createEnvelope(
661
+ { sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: broker.parentId },
662
+ {
663
+ kind: input.replyTo ? 'reply' : 'message',
664
+ targetId: agent.handle.id,
665
+ messageId: mintMessageId(),
666
+ taskId: input.taskId,
667
+ threadId: input.threadId,
668
+ replyTo: input.replyTo,
669
+ ...(replyDeadline !== undefined ? { deadlineAt: replyDeadline } : {}),
670
+ delivery: input.delivery === 'followUp' ? 'followUp' : 'steer',
671
+ content: input.message,
672
+ }
673
+ );
674
+ const accepted = publishFromParent(broker, envelope);
675
+ // The parent is also the owner of child-originated request state. When the
676
+ // parent answers one of those requests, resolve it here after successful
677
+ // publication instead of requiring the child to echo a second reply merely
678
+ // to unblock its own task. Child/peer replies are still resolved by the
679
+ // parent inbox path in processParentBrokerMessages().
680
+ if (input.replyTo && input.taskId) {
681
+ try {
682
+ lifecycleRegistry.resolveReplyForTask(input.taskId, input.replyTo);
683
+ } catch {
684
+ // A non-tracked or already-resolved reply is harmless and remains
685
+ // deliverable as an ordinary correlated message.
686
+ }
687
+ }
688
+ let targetTaskState: string | undefined;
689
+ if (input.taskId) {
690
+ targetTaskState = lifecycleRegistry.getTask(input.taskId).state;
691
+ }
692
+ return {
693
+ messageId: envelope.messageId,
694
+ accepted: true,
695
+ delivery: accepted.delivery,
696
+ targetId: agent.handle.id,
697
+ ...(targetTaskState ? { targetTaskState } : {}),
698
+ };
699
+ }
700
+
701
+ export type ParentMessageKind = 'message' | 'reply' | 'runtime' | 'task_done_dropped';
702
+ export type ParentMessageNotifier = (notification: {
703
+ kind: ParentMessageKind;
704
+ envelope: ShepherdMessageEnvelope;
705
+ reason?: string;
706
+ }) => void;
707
+
708
+ let parentMessageNotifier: ParentMessageNotifier | undefined;
709
+
710
+ /** Bridge child-originated messages and runtime events into the parent session. */
711
+ export function configureParentMessageNotifications(
712
+ notifier: ParentMessageNotifier | undefined
713
+ ): void {
714
+ parentMessageNotifier = notifier;
715
+ }
716
+
717
+ function notifyParentMessage(
718
+ kind: ParentMessageKind,
719
+ envelope: ShepherdMessageEnvelope,
720
+ reason?: string
721
+ ): void {
722
+ try {
723
+ parentMessageNotifier?.({ kind, envelope, reason });
724
+ } catch {
725
+ // Delivery diagnostics must never break broker polling.
726
+ }
727
+ }
728
+
729
+ /**
730
+ * Drain the parent mailbox and observe external terminal failures. Task
731
+ * completions and failures settle into the registry; child messages and
732
+ * request/reply correlation are applied for task state and surfaced to the
733
+ * parent delivery bridge. This deliberately does NOT treat idle turns, agent
734
+ * end, or agent_settled states as successful task completion.
735
+ */
736
+ export async function processParentBrokerMessages(): Promise<TaskResult[]> {
737
+ const broker = currentParentBroker();
738
+ if (!broker || parentBrokerTicking) return [];
739
+ parentBrokerTicking = true;
740
+ const settled: TaskResult[] = [];
741
+ try {
742
+ for (const envelope of pollParentInbox(broker)) {
743
+ const result =
744
+ envelope.kind === 'task_done'
745
+ ? applyTaskDoneEnvelope(envelope)
746
+ : applyMessageEnvelope(broker, envelope);
747
+ if (result) settled.push(result);
748
+ }
749
+ const now = Date.now();
750
+ if (now - lastTrackedTaskRuntimeCheck >= 1_000) {
751
+ lastTrackedTaskRuntimeCheck = now;
752
+ for (const task of lifecycleRegistry.allTasks()) {
753
+ if (!['created', 'running', 'waiting'].includes(task.state)) continue;
754
+ let agent: AgentHandle;
755
+ try {
756
+ agent = lifecycleRegistry.getAgent({ id: task.agentId }).handle;
757
+ } catch {
758
+ continue;
759
+ }
760
+ if (!agent.paneId) continue;
761
+ if (!paneExists(agent.paneId)) {
762
+ const result = lifecycleRegistry.settleTask(task.taskId, {
763
+ status: 'failed',
764
+ error: 'Agent pane disappeared before the task completed.',
765
+ });
766
+ settled.push(result);
767
+ continue;
768
+ }
769
+ if (
770
+ task.state === 'waiting' &&
771
+ task.pendingReplyDeadlineAt !== undefined &&
772
+ now >= task.pendingReplyDeadlineAt
773
+ ) {
774
+ const result = lifecycleRegistry.settleTask(task.taskId, {
775
+ status: 'blocked',
776
+ ok: false,
777
+ text: `Timed out waiting for a reply from ${task.pendingReplyTargetAgentId ?? 'the target agent'} (message ${task.pendingReplyMessageId ?? 'unknown'} never answered).`,
778
+ error: 'Tracked reply deadline reached.',
779
+ });
780
+ settled.push(result);
781
+ continue;
782
+ }
783
+ const providerError = await readImmediateAgentError(agent.paneId);
784
+ if (providerError) {
785
+ const result = lifecycleRegistry.settleTask(task.taskId, {
786
+ status: 'failed',
787
+ returnCode: 1,
788
+ error: providerError,
789
+ });
790
+ settled.push(result);
791
+ }
792
+ }
793
+ }
794
+ } finally {
795
+ parentBrokerTicking = false;
796
+ }
797
+ return settled;
798
+ }
799
+
800
+ /**
801
+ * Apply one child-originated message to request/task state. Returns a settled
802
+ * task result when the envelope is an explicit completion; everything else
803
+ * updates correlation state and surfaces to the parent delivery bridge.
804
+ */
805
+ function applyMessageEnvelope(
806
+ broker: ParentBroker,
807
+ envelope: ShepherdMessageEnvelope
808
+ ): TaskResult | undefined {
809
+ switch (envelope.kind) {
810
+ case 'runtime': {
811
+ if (envelope.replyReceived === true && envelope.taskId && envelope.replyTo) {
812
+ // Peer replies are delivered directly to the recipient's inbox. The
813
+ // child also sends this parent-only mirror so the parent can clear the
814
+ // requester's waiting task without relaying a duplicate reply.
815
+ try {
816
+ lifecycleRegistry.resolveReplyForTask(envelope.taskId, envelope.replyTo);
817
+ } catch {
818
+ // Unknown, duplicate, or already-resolved replies are harmless.
819
+ }
820
+ return undefined;
821
+ }
822
+ if (envelope.requestOpen === true && envelope.taskId && envelope.replyTo) {
823
+ try {
824
+ const task = lifecycleRegistry.getTask(envelope.taskId);
825
+ if (
826
+ ['running', 'waiting'].includes(task.state) &&
827
+ task.pendingReplyMessageId !== envelope.replyTo
828
+ ) {
829
+ try {
830
+ lifecycleRegistry.openPendingRequest(envelope.taskId, {
831
+ messageId: envelope.replyTo,
832
+ targetAgentId: envelope.requestTargetId,
833
+ text: envelope.summary ?? envelope.content,
834
+ });
835
+ staleWaitMonitor.kick();
836
+ } catch {
837
+ // The task already has an outstanding tracked reply; keep the
838
+ // first one per the one-request policy.
839
+ }
840
+ }
841
+ } catch {
842
+ // Unknown task ids (e.g. session-local tasks from another process)
843
+ // are ignored; the mailbox ack already consumed the mirrored event.
844
+ }
845
+ }
846
+ return undefined;
847
+ }
848
+ case 'reply': {
849
+ if (envelope.replyTo && envelope.taskId) {
850
+ try {
851
+ const resolution = lifecycleRegistry.resolveReplyForTask(
852
+ envelope.taskId,
853
+ envelope.replyTo
854
+ );
855
+ // Relay the answer to the task owner, but only when the answer came
856
+ // from a different participant: the parent already holds answers to
857
+ // its own questions, and echoing them back to the owner's inbox
858
+ // would create a self-addressed user message.
859
+ if (resolution.resolved && resolution.agentId !== envelope.senderId) {
860
+ const asker = lifecycleRegistry.getAgent({ id: resolution.agentId });
861
+ const relayed = createEnvelope(
862
+ { sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: broker.parentId },
863
+ {
864
+ kind: 'reply',
865
+ targetId: asker.handle.id,
866
+ messageId: mintMessageId(),
867
+ taskId: envelope.taskId,
868
+ threadId: envelope.threadId,
869
+ replyTo: envelope.replyTo,
870
+ originSenderId: envelope.senderId,
871
+ delivery: envelope.delivery,
872
+ content: envelope.content,
873
+ }
874
+ );
875
+ publishFromParent(broker, relayed);
876
+ }
877
+ } catch {
878
+ // Invalid replies (unknown task or mismatched replyTo) leave the
879
+ // request pending so the owner can still block/cancel it explicitly.
880
+ }
881
+ }
882
+ notifyParentMessage('reply', envelope);
883
+ return undefined;
884
+ }
885
+ default:
886
+ notifyParentMessage('message', envelope);
887
+ return undefined;
888
+ }
889
+ }
890
+
891
+ export async function promptAgent(
892
+ handle: AgentHandleInput,
893
+ message: string,
894
+ options: { timeout?: number } = {}
895
+ ): Promise<PromptHandle> {
896
+ if (!message.trim()) throw new Error('Prompt message must not be empty.');
897
+ const canonical = lifecycleRegistry.canonicalAgentHandle(handle);
898
+ const record = lifecycleRegistry.getAgent(canonical);
899
+ if (!record.handle.paneId) throw new Error('Agent handle has no pane.');
900
+ const detected = await waitForHerdrAgentDetected(record.handle.paneId, {
901
+ timeoutMs: Math.min(options.timeout ?? 120000, 15000),
902
+ });
903
+ if (!detected.detected) throw new Error(`Agent "${canonical.id}" is not detected.`);
904
+ // Reserve the single active slot before submission, so concurrent callers
905
+ // cannot both pass validation. Failed submission is settled immediately and
906
+ // never returned as a usable handle.
907
+ let baselineStateChangeSeq: number | undefined;
908
+ try {
909
+ const before: any = herdrExecSync(['agent', 'get', record.handle.paneId]);
910
+ const seq = before?.result?.agent?.state_change_seq;
911
+ if (typeof seq === 'number') baselineStateChangeSeq = seq;
912
+ } catch {}
913
+ const signalPath = lifecycleRegistry.completionSignalPath(canonical);
914
+ const baselineCompletionSignalId = signalPath
915
+ ? readCompletionSignal(signalPath)?.signalId
916
+ : undefined;
917
+ const prompt = lifecycleRegistry.createPrompt(
918
+ canonical,
919
+ undefined, // waitPrompts owns the timeout; promptAgent must not arm one
920
+ baselineStateChangeSeq,
921
+ baselineCompletionSignalId
922
+ );
923
+ const session = lifecycleRegistry.artifactSession(canonical);
924
+ let artifact: ArtifactReservation | undefined;
925
+ try {
926
+ if (session) {
927
+ artifact = reserveArtifacts(session, [
928
+ { agent: record.handle.agent, mode: 'single', task: message },
929
+ ])[0];
930
+ markArtifactStarted(session, artifact, { promptId: prompt.id, agentId: prompt.agentId });
931
+ lifecycleRegistry.attachPromptArtifact(prompt, session, artifact, result =>
932
+ finalizePromptArtifact(prompt, result)
933
+ );
934
+ }
935
+ // No --wait: submission returns as soon as Herdr accepts the message.
936
+ await herdrExec([
937
+ 'agent',
938
+ 'prompt',
939
+ record.handle.paneId,
940
+ message + (session && artifact ? artifactContext(session, artifact) : ''),
941
+ ]);
942
+ // Provider validation can fail immediately after Herdr accepts the
943
+ // prompt. Give the child a short bounded window to print that error so
944
+ // shepherd_prompt reports it directly instead of returning a prompt that
945
+ // can only fail later as a wait timeout.
946
+ for (let attempt = 0; attempt < 5; attempt++) {
947
+ const error = await readImmediateAgentError(record.handle.paneId);
948
+ if (error) throw new Error(`Agent prompt failed: ${error}`);
949
+ if (attempt < 4) await new Promise(resolve => setTimeout(resolve, 100));
950
+ }
951
+ return prompt;
952
+ } catch (error) {
953
+ lifecycleRegistry.settlePrompt(prompt, {
954
+ promptId: prompt.id,
955
+ agentId: prompt.agentId,
956
+ status: 'failed',
957
+ ok: false,
958
+ returnCode: 1,
959
+ error: String((error as any)?.message ?? error),
960
+ });
961
+ throw new Error(`Prompt submission failed: ${String((error as any)?.message ?? error)}`);
962
+ }
963
+ }
964
+
965
+ export type PromptWatcherNotifier = (notification: WatcherNotification) => void | Promise<void>;
966
+
967
+ /**
968
+ * Non-blocking prompt completion observer. The registry owns settlement and
969
+ * watcher deduplication; this service only polls Herdr for prompts that have
970
+ * no completion result yet and bridges completions to the parent extension.
971
+ *
972
+ * This is the legacy prompt path. Tracked delegated tasks must not reuse its
973
+ * idle/done inference: a child may be idle while its task is waiting for a
974
+ * peer reply. The task path will settle only from shepherd_done or an explicit
975
+ * failure, cancellation, or timeout event.
976
+ */
977
+ export class PromptWatcherService {
978
+ private timer?: ReturnType<typeof setInterval>;
979
+ private ticking = false;
980
+ private notifier?: PromptWatcherNotifier;
981
+ private readonly registry: typeof lifecycleRegistry;
982
+ private readonly intervalMs: number;
983
+ private readonly coalesceMs: number;
984
+ private readonly queued = new Map<string, WatcherCompletion[]>();
985
+ private readonly promptOrder = new Map<string, Map<string, number>>();
986
+ private readonly remaining = new Map<string, number>();
987
+ private readonly flushTimers = new Map<string, ReturnType<typeof setTimeout>>();
988
+
989
+ constructor(
990
+ registry = lifecycleRegistry,
991
+ notifier?: PromptWatcherNotifier,
992
+ intervalMs = 500,
993
+ coalesceMs = 25
994
+ ) {
995
+ this.registry = registry;
996
+ this.notifier = notifier;
997
+ this.intervalMs = intervalMs;
998
+ this.coalesceMs = coalesceMs;
999
+ }
1000
+
1001
+ setNotifier(notifier?: PromptWatcherNotifier): void {
1002
+ this.notifier = notifier;
1003
+ }
1004
+
1005
+ watch(handles: PromptHandleInput | PromptHandleInput[]): WatcherRegistration {
1006
+ // Registration is synchronous, so the id is assigned before any later
1007
+ // settlement can invoke this callback. Keeping it in this closure avoids
1008
+ // putting watcher identity into durable prompt results.
1009
+ let watcherId = '';
1010
+ const registration = this.registry.watchPrompts(handles, completion => {
1011
+ this.queue(watcherId, completion);
1012
+ });
1013
+ watcherId = registration.watcherId;
1014
+ if (registration.pending.length > 0) {
1015
+ this.promptOrder.set(
1016
+ watcherId,
1017
+ new Map(registration.promptIds.map((promptId, index) => [promptId, index]))
1018
+ );
1019
+ this.remaining.set(watcherId, registration.pending.length);
1020
+ this.start();
1021
+ }
1022
+ return registration;
1023
+ }
1024
+
1025
+ /** Stop polling and discard delivery state for the parent session. */
1026
+ shutdown(): void {
1027
+ if (this.timer) clearInterval(this.timer);
1028
+ this.timer = undefined;
1029
+ this.ticking = false;
1030
+ for (const timer of this.flushTimers.values()) clearTimeout(timer);
1031
+ this.flushTimers.clear();
1032
+ this.queued.clear();
1033
+ this.promptOrder.clear();
1034
+ this.remaining.clear();
1035
+ this.registry.clearWatchers();
1036
+ }
1037
+
1038
+ private start(): void {
1039
+ if (this.timer) return;
1040
+ this.timer = setInterval(() => void this.tick(), this.intervalMs);
1041
+ // A watcher is lifecycle state, not a reason for a test/host process to
1042
+ // remain alive after its parent has gone away.
1043
+ (this.timer as any).unref?.();
1044
+ void this.tick();
1045
+ }
1046
+
1047
+ private stopIfIdle(): void {
1048
+ if (this.registry.watchedPromptIds().length > 0) return;
1049
+ if (this.timer) clearInterval(this.timer);
1050
+ this.timer = undefined;
1051
+ }
1052
+
1053
+ private queue(watcherId: string, completion: WatcherCompletion): void {
1054
+ if (!watcherId) return;
1055
+ const list = this.queued.get(watcherId) ?? [];
1056
+ list.push({ ...completion });
1057
+ this.queued.set(watcherId, list);
1058
+ const remaining = this.remaining.get(watcherId);
1059
+ if (remaining !== undefined) this.remaining.set(watcherId, Math.max(0, remaining - 1));
1060
+ if (!this.flushTimers.has(watcherId)) {
1061
+ const timer = setTimeout(() => this.flush(watcherId), this.coalesceMs);
1062
+ (timer as any).unref?.();
1063
+ this.flushTimers.set(watcherId, timer);
1064
+ }
1065
+ this.stopIfIdle();
1066
+ }
1067
+
1068
+ private flush(watcherId: string): void {
1069
+ this.flushTimers.delete(watcherId);
1070
+ const completions = this.queued.get(watcherId);
1071
+ this.queued.delete(watcherId);
1072
+ if (!completions || completions.length === 0) return;
1073
+ // A watcher still reports prompts as they settle, but when several
1074
+ // completions are coalesced into one notification, keep the array in the
1075
+ // caller's input order. This makes the result deterministic without
1076
+ // delaying an individual completion until earlier prompts finish.
1077
+ const order = this.promptOrder.get(watcherId);
1078
+ if (order) {
1079
+ completions.sort(
1080
+ (left, right) =>
1081
+ (order.get(left.promptId) ?? Number.MAX_SAFE_INTEGER) -
1082
+ (order.get(right.promptId) ?? Number.MAX_SAFE_INTEGER)
1083
+ );
1084
+ }
1085
+ const notification = { watcherId, completions };
1086
+ if (this.remaining.get(watcherId) === 0) {
1087
+ this.promptOrder.delete(watcherId);
1088
+ this.remaining.delete(watcherId);
1089
+ }
1090
+ try {
1091
+ const result = this.notifier?.(notification);
1092
+ if (result && typeof (result as Promise<void>).catch === 'function') {
1093
+ (result as Promise<void>).catch(() => undefined);
1094
+ }
1095
+ } catch {
1096
+ // The prompt result is already durable; an unavailable parent message
1097
+ // bridge must not corrupt settlement or fieldnote finalization.
1098
+ }
1099
+ }
1100
+
1101
+ private async tick(): Promise<void> {
1102
+ if (this.ticking) return;
1103
+ this.ticking = true;
1104
+ try {
1105
+ const promptIds = this.registry.watchedPromptIds();
1106
+ if (promptIds.length === 0) {
1107
+ this.stopIfIdle();
1108
+ return;
1109
+ }
1110
+ await Promise.all(promptIds.map(promptId => this.observe(promptId)));
1111
+ } finally {
1112
+ this.ticking = false;
1113
+ this.stopIfIdle();
1114
+ }
1115
+ }
1116
+
1117
+ private async observe(promptId: string): Promise<void> {
1118
+ let record: any;
1119
+ try {
1120
+ record = this.registry.getPrompt(promptId);
1121
+ } catch {
1122
+ return;
1123
+ }
1124
+ if (record.settled) return;
1125
+ let agent: any;
1126
+ try {
1127
+ agent = this.registry.getAgent({ id: record.handle.agentId } as AgentHandle);
1128
+ } catch {
1129
+ return;
1130
+ }
1131
+ const paneId = agent.handle.paneId;
1132
+ if (!paneId) return;
1133
+ const signalPath = this.registry.completionSignalPath(agent.handle);
1134
+ const resultPath = this.registry.completionResultPath(agent.handle);
1135
+ const readText = async (): Promise<string> => {
1136
+ if (resultPath) {
1137
+ const text = readLastAssistantText(resultPath).trim();
1138
+ if (text) return text;
1139
+ }
1140
+ return (await readPaneTail(paneId)).trim();
1141
+ };
1142
+ const readError = async (): Promise<string | undefined> => {
1143
+ return extractAgentError(await readPaneTail(paneId));
1144
+ };
1145
+ try {
1146
+ // Use the async Herdr bridge here: watcher registration must return
1147
+ // without synchronously waiting on a child or the Herdr CLI.
1148
+ const out: any = await herdrExec(['agent', 'get', paneId]);
1149
+ const state = String(out?.result?.agent?.agent_status ?? 'unknown').toLowerCase();
1150
+ const seq = out?.result?.agent?.state_change_seq;
1151
+ if (state === 'working') this.registry.observeWorking(record.handle);
1152
+ const signal: any = signalPath ? readCompletionSignal(signalPath) : undefined;
1153
+ const tracking = this.registry.promptTracking(record.handle);
1154
+ if (signal?.signalId && signal.signalId !== tracking.baselineCompletionSignalId) {
1155
+ const failed = signal.type === 'error';
1156
+ this.registry.settlePrompt(record.handle, {
1157
+ promptId,
1158
+ agentId: record.handle.agentId,
1159
+ status: failed ? 'failed' : 'done',
1160
+ ok: !failed,
1161
+ text: await readText(),
1162
+ ...(failed && signal.errorMessage ? { error: signal.errorMessage } : {}),
1163
+ ...(typeof signal.returnCode === 'number' ? { returnCode: signal.returnCode } : {}),
1164
+ });
1165
+ return;
1166
+ }
1167
+ const error = await readError();
1168
+ if (error) {
1169
+ this.registry.settlePrompt(record.handle, {
1170
+ promptId,
1171
+ agentId: record.handle.agentId,
1172
+ status: 'failed',
1173
+ ok: false,
1174
+ returnCode: 1,
1175
+ error,
1176
+ });
1177
+ return;
1178
+ }
1179
+ const sequenceAdvanced =
1180
+ tracking.baselineStateChangeSeq === undefined ||
1181
+ (typeof seq === 'number' && seq !== tracking.baselineStateChangeSeq);
1182
+ if (
1183
+ ['idle', 'done', 'blocked'].includes(state) &&
1184
+ (tracking.observedWorking || sequenceAdvanced)
1185
+ ) {
1186
+ this.registry.settlePrompt(record.handle, {
1187
+ promptId,
1188
+ agentId: record.handle.agentId,
1189
+ status: state === 'blocked' ? 'blocked' : state === 'done' ? 'done' : 'idle',
1190
+ ok: state !== 'blocked',
1191
+ text: await readText(),
1192
+ });
1193
+ }
1194
+ } catch {
1195
+ const error = await readError();
1196
+ if (error) {
1197
+ this.registry.settlePrompt(record.handle, {
1198
+ promptId,
1199
+ agentId: record.handle.agentId,
1200
+ status: 'failed',
1201
+ ok: false,
1202
+ returnCode: 1,
1203
+ error,
1204
+ });
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+
1210
+ export const promptWatcherService = new PromptWatcherService();
1211
+
1212
+ export function configurePromptWatcherNotifications(notifier?: PromptWatcherNotifier): void {
1213
+ promptWatcherService.setNotifier(notifier);
1214
+ }
1215
+
1216
+ export function shutdownPromptWatchers(): void {
1217
+ promptWatcherService.shutdown();
1218
+ }
1219
+
1220
+ export type TaskWatcherNotifier = (notification: TaskWatcherNotification) => void | Promise<void>;
1221
+
1222
+ /**
1223
+ * Non-blocking terminal-state observer for tracked delegated tasks.
1224
+ *
1225
+ * Unlike {@link PromptWatcherService}, the task path settles only from explicit
1226
+ * lifecycle events — a child calling `shepherd_done` or an explicit failure,
1227
+ * cancellation, or timeout. A child becoming idle, ending a turn
1228
+ * (`agent_end`/`agent_settled`), or entering `waiting` is deliberately NOT a
1229
+ * completion signal, so the registry drives the watcher directly from
1230
+ * `settleTask`; this service only coalesces and delivers those completions to
1231
+ * the parent without polling.
1232
+ */
1233
+ export class TaskWatcherService {
1234
+ private notifier?: TaskWatcherNotifier;
1235
+ private readonly registry: typeof lifecycleRegistry;
1236
+ private readonly coalesceMs: number;
1237
+ private readonly queued = new Map<string, TaskWatcherCompletion[]>();
1238
+ private readonly taskOrder = new Map<string, Map<string, number>>();
1239
+ private readonly remaining = new Map<string, number>();
1240
+ private readonly flushTimers = new Map<string, ReturnType<typeof setTimeout>>();
1241
+
1242
+ constructor(registry = lifecycleRegistry, notifier?: TaskWatcherNotifier, coalesceMs = 25) {
1243
+ this.registry = registry;
1244
+ this.notifier = notifier;
1245
+ this.coalesceMs = coalesceMs;
1246
+ }
1247
+
1248
+ setNotifier(notifier?: TaskWatcherNotifier): void {
1249
+ this.notifier = notifier;
1250
+ }
1251
+
1252
+ /**
1253
+ * Register a one-shot watcher for one task id or a non-empty array. Returns
1254
+ * synchronously with already-completed results and pending ids; later
1255
+ * terminal outcomes arrive via the notifier exactly once per task. Agent ids
1256
+ * and Herdr pane ids are rejected by the registry (unknown task id).
1257
+ */
1258
+ watch(handles: TaskHandleInput | TaskHandleInput[]): TaskWatcherRegistration {
1259
+ let watcherId = '';
1260
+ const registration = this.registry.watchTasks(handles, completion => {
1261
+ this.queue(watcherId, completion);
1262
+ });
1263
+ watcherId = registration.watcherId;
1264
+ if (registration.pending.length > 0) {
1265
+ this.taskOrder.set(
1266
+ watcherId,
1267
+ new Map(registration.taskIds.map((taskId, index) => [taskId, index]))
1268
+ );
1269
+ this.remaining.set(watcherId, registration.pending.length);
1270
+ }
1271
+ return registration;
1272
+ }
1273
+
1274
+ /** Stop delivery state for the parent session and drop any live registrations. */
1275
+ shutdown(): void {
1276
+ for (const timer of this.flushTimers.values()) clearTimeout(timer);
1277
+ this.flushTimers.clear();
1278
+ this.queued.clear();
1279
+ this.taskOrder.clear();
1280
+ this.remaining.clear();
1281
+ this.registry.clearWatchers();
1282
+ }
1283
+
1284
+ private queue(watcherId: string, completion: TaskWatcherCompletion): void {
1285
+ if (!watcherId) return;
1286
+ const list = this.queued.get(watcherId) ?? [];
1287
+ list.push({ ...completion });
1288
+ this.queued.set(watcherId, list);
1289
+ const remaining = this.remaining.get(watcherId);
1290
+ if (remaining !== undefined) this.remaining.set(watcherId, Math.max(0, remaining - 1));
1291
+ if (!this.flushTimers.has(watcherId)) {
1292
+ const timer = setTimeout(() => this.flush(watcherId), this.coalesceMs);
1293
+ (timer as any).unref?.();
1294
+ this.flushTimers.set(watcherId, timer);
1295
+ }
1296
+ }
1297
+
1298
+ private flush(watcherId: string): void {
1299
+ this.flushTimers.delete(watcherId);
1300
+ const completions = this.queued.get(watcherId);
1301
+ this.queued.delete(watcherId);
1302
+ if (!completions || completions.length === 0) return;
1303
+ // When several completions coalesce into one notification, keep the array
1304
+ // in the caller's input order so the result is deterministic without
1305
+ // delaying an individual completion until earlier tasks finish.
1306
+ const order = this.taskOrder.get(watcherId);
1307
+ if (order) {
1308
+ completions.sort(
1309
+ (left, right) =>
1310
+ (order.get(left.taskId) ?? Number.MAX_SAFE_INTEGER) -
1311
+ (order.get(right.taskId) ?? Number.MAX_SAFE_INTEGER)
1312
+ );
1313
+ }
1314
+ const notification: TaskWatcherNotification = {
1315
+ watcherId,
1316
+ completions: completions as TaskResult[],
1317
+ };
1318
+ if (this.remaining.get(watcherId) === 0) {
1319
+ this.taskOrder.delete(watcherId);
1320
+ this.remaining.delete(watcherId);
1321
+ }
1322
+ try {
1323
+ const result = this.notifier?.(notification);
1324
+ if (result && typeof (result as Promise<void>).catch === 'function') {
1325
+ (result as Promise<void>).catch(() => undefined);
1326
+ }
1327
+ } catch {
1328
+ // The task result is already durable in the registry; a missing parent
1329
+ // bridge must not corrupt settlement or fieldnote finalization.
1330
+ }
1331
+ }
1332
+ }
1333
+
1334
+ export const taskWatcherService = new TaskWatcherService();
1335
+
1336
+ export function configureTaskWatcherNotifications(notifier?: TaskWatcherNotifier): void {
1337
+ taskWatcherService.setNotifier(notifier);
1338
+ }
1339
+
1340
+ export function shutdownTaskWatchers(): void {
1341
+ taskWatcherService.shutdown();
1342
+ }
1343
+
1344
+ /**
1345
+ * One stale-wait observation, produced when a task has been waiting on a
1346
+ * required reply for longer than the configured threshold. Delivered to the
1347
+ * parent once per waiting episode (it is information, never a settlement).
1348
+ */
1349
+ export interface StaleWaitInfo {
1350
+ taskId: string;
1351
+ agentId: string;
1352
+ agent?: string;
1353
+ label?: string;
1354
+ description: string;
1355
+ waitingSince: number;
1356
+ /** Milliseconds the task has been waiting as of the observation. */
1357
+ elapsedMs: number;
1358
+ /** The pending request (message) id being waited on. */
1359
+ requestMessageId: string;
1360
+ /** The question the recipient was asked. */
1361
+ question: string;
1362
+ recipientId?: string;
1363
+ recipientName?: string;
1364
+ /** The recipient agent's own lifecycle state (idle/working/...). */
1365
+ recipientState?: string;
1366
+ /** Configured threshold, in minutes, that was crossed. */
1367
+ thresholdMinutes: number;
1368
+ }
1369
+
1370
+ export type StaleWaitNotifier = (info: StaleWaitInfo) => void | Promise<void>;
1371
+
1372
+ /**
1373
+ * Watches tasks that are waiting on a required reply and surfaces one
1374
+ * non-repeating, non-settling reminder to the parent once the configured
1375
+ * `staleWaitThreshold` is crossed. It inspects task state (not raw agent
1376
+ * state), so an idle agent without a waiting task, or a completed task, never
1377
+ * raises a stale notification. It only starts when a waiting task exists and
1378
+ * stops once none remain, and its timer is unref'd so it never keeps the
1379
+ * process alive.
1380
+ */
1381
+ export class StaleWaitMonitor {
1382
+ private timer?: ReturnType<typeof setInterval>;
1383
+ private readonly notifier?: StaleWaitNotifier;
1384
+ private readonly registry: typeof lifecycleRegistry;
1385
+ private readonly intervalMs: number;
1386
+
1387
+ constructor(registry = lifecycleRegistry, notifier?: StaleWaitNotifier, intervalMs = 1_000) {
1388
+ this.registry = registry;
1389
+ this.notifier = notifier;
1390
+ this.intervalMs = intervalMs;
1391
+ }
1392
+
1393
+ /** Begin watching; idempotent — called when a task enters `waiting`. */
1394
+ kick(): void {
1395
+ this.ensureStarted();
1396
+ void this.poll();
1397
+ }
1398
+
1399
+ /** Stop the monitor and drop it (parent session teardown). */
1400
+ shutdown(): void {
1401
+ if (this.timer) clearInterval(this.timer);
1402
+ this.timer = undefined;
1403
+ }
1404
+
1405
+ setNotifier(notifier?: StaleWaitNotifier): void {
1406
+ this.notifier = notifier;
1407
+ }
1408
+
1409
+ private ensureStarted(): void {
1410
+ if (this.timer) return;
1411
+ this.timer = setInterval(() => void this.poll(), this.intervalMs);
1412
+ // A stale-wait reminder is lifecycle state, not a reason for the parent
1413
+ // host process to stay alive.
1414
+ (this.timer as any).unref?.();
1415
+ }
1416
+
1417
+ private maybeStop(): void {
1418
+ if (this.waitingTasks().length === 0 && this.timer) {
1419
+ clearInterval(this.timer);
1420
+ this.timer = undefined;
1421
+ }
1422
+ }
1423
+
1424
+ private waitingTasks() {
1425
+ return this.registry
1426
+ .allTasks()
1427
+ .filter(t => t.state === 'waiting' && t.pendingReplyMessageId !== undefined);
1428
+ }
1429
+
1430
+ /** Scan waiting tasks and emit at most one reminder per episode. */
1431
+ async poll(): Promise<void> {
1432
+ const now = Date.now();
1433
+ const waiting = this.waitingTasks();
1434
+ if (waiting.length === 0) {
1435
+ this.maybeStop();
1436
+ return;
1437
+ }
1438
+ for (const task of waiting) {
1439
+ const thresholdMinutes = (() => {
1440
+ try {
1441
+ return loadSettings(
1442
+ task.cwd ?? this.registry.getAgent({ id: task.agentId }).handle.cwd ?? process.cwd()
1443
+ ).staleWaitThreshold;
1444
+ } catch {
1445
+ return DEFAULT_SETTINGS.staleWaitThreshold;
1446
+ }
1447
+ })();
1448
+ // A threshold below 1 minute disables stale-wait reminders entirely.
1449
+ if (thresholdMinutes < 1) continue;
1450
+ const thresholdMs = thresholdMinutes * 60_000;
1451
+ const waitingSince = task.waitingSince ?? now;
1452
+ const elapsedMs = now - waitingSince;
1453
+ if (elapsedMs < thresholdMs) continue;
1454
+ // One notification per episode: `staleNotifiedAt` is set below and is
1455
+ // cleared whenever the episode ends (a reply, a resume, or settlement),
1456
+ // so the next episode is allowed its own reminder.
1457
+ if (task.staleNotifiedAt !== undefined) continue;
1458
+ const info = await this.buildInfo(task, elapsedMs, thresholdMinutes);
1459
+ try {
1460
+ this.registry.markStaleNotified(task.taskId);
1461
+ const result = this.notifier?.(info);
1462
+ if (result && typeof (result as Promise<void>).catch === 'function') {
1463
+ (result as Promise<void>).catch(() => undefined);
1464
+ }
1465
+ } catch {
1466
+ // The reminder is best-effort; task state is unchanged and the reply
1467
+ // deadline (a settlement) is authoritative.
1468
+ }
1469
+ }
1470
+ this.maybeStop();
1471
+ }
1472
+
1473
+ private async buildInfo(
1474
+ task: any,
1475
+ elapsedMs: number,
1476
+ thresholdMinutes: number
1477
+ ): Promise<StaleWaitInfo> {
1478
+ let ownerHandle: AgentHandle | undefined;
1479
+ try {
1480
+ ownerHandle = this.registry.getAgent({ id: task.agentId }).handle;
1481
+ } catch {
1482
+ /* owner may have been closed; still report what we can */
1483
+ }
1484
+ let recipientName: string | undefined;
1485
+ let recipientState: string | undefined;
1486
+ if (task.pendingReplyTargetAgentId) {
1487
+ try {
1488
+ const recipient = this.registry.getAgent({ id: task.pendingReplyTargetAgentId });
1489
+ recipientName = recipient.handle.agent
1490
+ ? recipient.handle.label
1491
+ ? `${recipient.handle.agent}: ${recipient.handle.label}`
1492
+ : recipient.handle.agent
1493
+ : recipient.handle.label;
1494
+ recipientState = recipient.state;
1495
+ } catch {
1496
+ /* unknown recipient: leave these empty */
1497
+ }
1498
+ }
1499
+ return {
1500
+ taskId: task.taskId,
1501
+ agentId: task.agentId,
1502
+ ...(ownerHandle ? { agent: ownerHandle.agent, label: ownerHandle.label } : {}),
1503
+ description: task.description,
1504
+ waitingSince: task.waitingSince ?? Date.now(),
1505
+ elapsedMs,
1506
+ requestMessageId: task.pendingReplyMessageId ?? '',
1507
+ question: task.pendingReplyText ?? '',
1508
+ ...(task.pendingReplyTargetAgentId ? { recipientId: task.pendingReplyTargetAgentId } : {}),
1509
+ ...(recipientName ? { recipientName } : {}),
1510
+ ...(recipientState ? { recipientState } : {}),
1511
+ thresholdMinutes,
1512
+ };
1513
+ }
1514
+ }
1515
+
1516
+ export const staleWaitMonitor = new StaleWaitMonitor();
1517
+
1518
+ export function configureStaleWaitNotifications(notifier?: StaleWaitNotifier): void {
1519
+ staleWaitMonitor.setNotifier(notifier);
1520
+ }
1521
+
1522
+ export function shutdownStaleWaitMonitor(): void {
1523
+ staleWaitMonitor.shutdown();
1524
+ }
1525
+
1526
+ async function waitOne(handle: PromptHandleInput, timeoutMs = 120000): Promise<PromptResult> {
1527
+ const failed = (error: unknown): PromptResult => ({
1528
+ promptId:
1529
+ typeof handle === 'object' && handle && typeof handle.id === 'string' ? handle.id : 'unknown',
1530
+ agentId:
1531
+ typeof handle === 'object' && handle && typeof handle.agentId === 'string'
1532
+ ? handle.agentId
1533
+ : 'unknown',
1534
+ status: 'failed',
1535
+ ok: false,
1536
+ returnCode: 1,
1537
+ error: String((error as any)?.message ?? error),
1538
+ });
1539
+ try {
1540
+ const canonical = lifecycleRegistry.canonicalPromptHandle(handle);
1541
+ const record = lifecycleRegistry.getPrompt(canonical);
1542
+ if (record.settled) return lifecycleRegistry.wait(canonical);
1543
+ const agent = lifecycleRegistry.getAgent({ id: canonical.agentId } as AgentHandle);
1544
+ const signalPath = lifecycleRegistry.completionSignalPath(agent.handle);
1545
+ const resultPath = lifecycleRegistry.completionResultPath(agent.handle);
1546
+ // Prefer the full final answer from the child's session file; the pane
1547
+ // tail only reflects the TUI rendering and is a fallback for short answers.
1548
+ const readResultText = async (): Promise<string> => {
1549
+ if (resultPath) {
1550
+ const text = readLastAssistantText(resultPath).trim();
1551
+ if (text) return text;
1552
+ }
1553
+ return agent.handle.paneId ? (await readPaneTail(agent.handle.paneId)).trim() : '';
1554
+ };
1555
+ const readAgentError = async (): Promise<string | undefined> => {
1556
+ if (!agent.handle.paneId) return undefined;
1557
+ const output = await readPaneTail(agent.handle.paneId);
1558
+ // Some provider failures happen before shepherd-done receives an
1559
+ // agent_end event, so there is no completion sidecar to observe. Catch
1560
+ // the terminal error here and turn it into a failed prompt result rather
1561
+ // than allowing the wait to time out.
1562
+ const match = output.match(/(?:^|\n)\s*Error:\s*(.+)/i);
1563
+ if (!match) return undefined;
1564
+ const message = match[1].trim();
1565
+ return /api key|authentication|authenticat|provider|model|failed to load/i.test(message)
1566
+ ? message
1567
+ : undefined;
1568
+ };
1569
+
1570
+ // Arm/replace the timeout on the prompt record (clears safety net from createPrompt).
1571
+ if (record.timeoutId) clearTimeout(record.timeoutId);
1572
+ record.timeoutId = setTimeout(
1573
+ () =>
1574
+ lifecycleRegistry.settlePrompt(canonical, {
1575
+ promptId: canonical.id,
1576
+ agentId: canonical.agentId,
1577
+ status: 'timeout',
1578
+ ok: false,
1579
+ error: `Timed out waiting for agent after ${timeoutMs >= 60000 ? Math.round(timeoutMs / 60000) + ' minutes' : Math.round(timeoutMs / 1000) + ' seconds'}`,
1580
+ }),
1581
+ timeoutMs
1582
+ );
1583
+
1584
+ const started = Date.now();
1585
+ while (Date.now() - started < timeoutMs) {
1586
+ try {
1587
+ const out: any = herdrExecSync(['agent', 'get', agent.handle.paneId!]);
1588
+ const state = String(out?.result?.agent?.agent_status ?? 'unknown').toLowerCase();
1589
+ const seq = out?.result?.agent?.state_change_seq;
1590
+ const tracking = lifecycleRegistry.promptTracking(canonical);
1591
+ if (state === 'working') lifecycleRegistry.observeWorking(canonical);
1592
+ const signal = signalPath ? readCompletionSignal(signalPath) : undefined;
1593
+ const signalAdvanced = Boolean(
1594
+ signal?.signalId && signal.signalId !== tracking.baselineCompletionSignalId
1595
+ );
1596
+ if (signalAdvanced) {
1597
+ const text = await readResultText();
1598
+ const failedSignal = signal?.type === 'error';
1599
+ return lifecycleRegistry.settlePrompt(canonical, {
1600
+ promptId: canonical.id,
1601
+ agentId: canonical.agentId,
1602
+ status: failedSignal ? 'failed' : 'done',
1603
+ ok: !failedSignal,
1604
+ text,
1605
+ ...(failedSignal && signal?.errorMessage ? { error: signal.errorMessage } : {}),
1606
+ });
1607
+ }
1608
+ const agentError = await readAgentError();
1609
+ if (agentError) {
1610
+ return lifecycleRegistry.settlePrompt(canonical, {
1611
+ promptId: canonical.id,
1612
+ agentId: canonical.agentId,
1613
+ status: 'failed',
1614
+ ok: false,
1615
+ returnCode: 1,
1616
+ error: agentError,
1617
+ });
1618
+ }
1619
+ const sequenceAdvanced =
1620
+ tracking.baselineStateChangeSeq === undefined ||
1621
+ (typeof seq === 'number' && seq !== tracking.baselineStateChangeSeq);
1622
+ // An idle/done state observed before this submission is not completion.
1623
+ // Require a post-submit state transition or a working observation first.
1624
+ if (
1625
+ ['idle', 'done', 'blocked'].includes(state) &&
1626
+ (tracking.observedWorking || sequenceAdvanced)
1627
+ ) {
1628
+ const text = await readResultText();
1629
+ return lifecycleRegistry.settlePrompt(canonical, {
1630
+ promptId: canonical.id,
1631
+ agentId: canonical.agentId,
1632
+ status: state === 'blocked' ? 'blocked' : state === 'done' ? 'done' : 'idle',
1633
+ ok: state !== 'blocked',
1634
+ text,
1635
+ });
1636
+ }
1637
+ } catch {
1638
+ // Herdr may stop recognizing the child as soon as Pi enters its
1639
+ // provider-error state. Still inspect the pane in that case; the
1640
+ // terminal error is the useful result, not a wait timeout.
1641
+ const agentError = await readAgentError();
1642
+ if (agentError) {
1643
+ return lifecycleRegistry.settlePrompt(canonical, {
1644
+ promptId: canonical.id,
1645
+ agentId: canonical.agentId,
1646
+ status: 'failed',
1647
+ ok: false,
1648
+ returnCode: 1,
1649
+ error: agentError,
1650
+ });
1651
+ }
1652
+ }
1653
+ await new Promise(r => setTimeout(r, 500));
1654
+ }
1655
+ // Loop exited without settling; the timeout callback will fire.
1656
+ // wait() will return the timeout result set by settlePrompt.
1657
+ return lifecycleRegistry.wait(canonical);
1658
+ } catch (error) {
1659
+ return failed(error);
1660
+ }
1661
+ }
1662
+
1663
+ export async function waitPrompts(
1664
+ handles: PromptHandleInput | PromptHandleInput[],
1665
+ options: { timeout?: number } = {}
1666
+ ): Promise<PromptResult | PromptResult[]> {
1667
+ const timeout = options.timeout ?? 120000;
1668
+ if (Array.isArray(handles)) {
1669
+ // Promise.all is intentionally concurrent and preserves input order. Each
1670
+ // waitOne converts operational failures into a result, so partial success is
1671
+ // never hidden by another prompt's failure.
1672
+ return Promise.all(handles.map(handle => waitOne(handle, timeout)));
1673
+ }
1674
+ return waitOne(handles, timeout);
1675
+ }
1676
+
1677
+ export function statusAgent(handle: AgentHandleInput): AgentStatus {
1678
+ const canonical = lifecycleRegistry.canonicalAgentHandle(handle);
1679
+ const status = lifecycleRegistry.status(canonical);
1680
+ if (status.state === 'closed' || !canonical.paneId) return status;
1681
+ try {
1682
+ const rec: any = (herdrExecSync(['agent', 'get', canonical.paneId]) as any)?.result?.agent;
1683
+ const state = String(rec?.agent_status ?? 'unknown').toLowerCase();
1684
+ const mapped = ['idle', 'working', 'blocked', 'done'].includes(state)
1685
+ ? (state as any)
1686
+ : 'unknown';
1687
+ return {
1688
+ ...status,
1689
+ state: mapped,
1690
+ paneId: rec?.pane_id ?? canonical.paneId,
1691
+ tabId: rec?.tab_id ?? canonical.tabId,
1692
+ workspaceId: rec?.workspace_id ?? canonical.workspaceId,
1693
+ };
1694
+ } catch {
1695
+ return { ...status, state: paneExists(canonical.paneId) ? 'unknown' : 'failed' };
1696
+ }
1697
+ }
1698
+
1699
+ export function closeAgent(handle: AgentHandleInput): AgentHandle {
1700
+ const canonical = lifecycleRegistry.canonicalAgentHandle(handle);
1701
+ const record = lifecycleRegistry.getAgent(canonical);
1702
+ if (!record.handle.paneId || !loadCreatedPanes().some(p => p.paneId === record.handle.paneId))
1703
+ throw new Error('Refusing to close an unowned pane.');
1704
+ lifecycleRegistry.close(canonical);
1705
+ try {
1706
+ herdrExecSync(['pane', 'close', record.handle.paneId]);
1707
+ } catch {
1708
+ if (paneExists(record.handle.paneId)) throw new Error('Could not close agent pane.');
1709
+ }
1710
+ if (!paneExists(record.handle.paneId)) removeCreatedPaneDir(record.handle.paneId);
1711
+ return canonical;
1712
+ }