@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,1898 @@
1
+ /**
2
+ * hc implementation of the Shepherd runtime contract.
3
+ *
4
+ * Thin delegation layer over the hc terminal primitives in `./hc.ts`: it
5
+ * introduces no new behavior beyond mapping the backend-neutral contract onto
6
+ * `hc run / send / read / wait / kill` plus the shared parent-owned mailbox.
7
+ * Every id accepted or returned here is an opaque lifecycle id; terminal
8
+ * addresses stay internal to registry lookups (`read` resolves a handle to
9
+ * its terminal only for the diagnostic tail).
10
+ *
11
+ * Channel split (documented, not magic):
12
+ * - `spawn` boots pi via `hc run --bg` from the shared launch files.
13
+ * - `delegate` publishes a tracked task envelope into the mailbox — the
14
+ * child extension polls its inbox, exactly like on the pane-based backend.
15
+ * Task text is never pasted into the terminal: typing into a live agent
16
+ * would corrupt its input.
17
+ * - `message` without a task id pastes text with `hc send` (an untracked
18
+ * poke, the send/Enter analogue of a native prompt). Correlated traffic
19
+ * (taskId / expectsReply / replyTo) goes through the mailbox so reply
20
+ * correlation and waiting state stay identical on both backends.
21
+ * - `watch` drains the mailbox for `task_done` envelopes, observes the
22
+ * completion sidecar, and idles efficiently on `hc wait --timeout`.
23
+ * - `status`/`read` map onto `hc get`/`hc read`; `close` maps onto
24
+ * `hc kill` + `hc rm` for owned terminals only.
25
+ * - `message` with `expectsReply` opens a tracked reply with the same
26
+ * `staleWaitThreshold` reminder and `timeout->blocked` settlement as the
27
+ * pane backend; `status` reports `waitingOn` + `stale` identically.
28
+ *
29
+ * Phase 2 parity: resolver wiring, expectsReply/stale/blocked parity,
30
+ * fieldnotes bridge, docs. This module intentionally imports nothing
31
+ * from the pane-based backend; shared transport-independent helpers arrive
32
+ * re-exported through `./hc.ts`.
33
+ */
34
+
35
+ import { randomUUID } from 'node:crypto';
36
+ import * as fs from 'node:fs';
37
+ import * as path from 'node:path';
38
+ import type { ShepherdSession } from '../../core/artifact-sessions.ts';
39
+ import {
40
+ finalizeArtifact,
41
+ markArtifactStarted,
42
+ reserveArtifacts,
43
+ type ArtifactReservation,
44
+ } from '../../core/artifact-sessions.ts';
45
+ import type { AgentThinkingLevel } from '../../core/discovery.ts';
46
+ import {
47
+ discoverAgents,
48
+ resolveDelegatedModel,
49
+ resolveDelegatedThinking,
50
+ } from '../../core/discovery.ts';
51
+ import { DEFAULT_SETTINGS, loadSettings } from '../../core/config.ts';
52
+ import { mintId, mintMessageId, normalizeHandleId } from '../../core/ids.ts';
53
+ import {
54
+ createEnvelope,
55
+ createParentBroker,
56
+ hcExec,
57
+ launchPiInHcTerminal,
58
+ loadCreatedTerminals,
59
+ pollParentInbox,
60
+ publishFromParent,
61
+ readCompletionSignal,
62
+ readHcTerminalTail,
63
+ readLastAssistantText,
64
+ registerChild,
65
+ removeCreatedTerminalDir,
66
+ forgetCreatedTerminal,
67
+ killHcTerminal,
68
+ unregisterChild,
69
+ waitForHcAgentDetected,
70
+ HcError,
71
+ type ChildCapability,
72
+ type ParentBroker,
73
+ type ShepherdMessageEnvelope,
74
+ } from './hc.ts';
75
+ import type {
76
+ AgentHandle,
77
+ Completion,
78
+ MessageId,
79
+ RuntimeProcState,
80
+ RuntimeStatus,
81
+ RuntimeTaskState,
82
+ ShepherdRuntime,
83
+ SpawnPlacement,
84
+ TaskId,
85
+ } from '../runtime.ts';
86
+
87
+ /** Execution context captured by the adapter for the parent session it serves. */
88
+ export interface HcRuntimeContext {
89
+ cwd?: string;
90
+ model?: { provider: string; id: string };
91
+ thinkingLevel?: AgentThinkingLevel;
92
+ hasUI?: boolean;
93
+ ui?: any;
94
+ sessionId?: string;
95
+ /** Parent fieldnotes session, resolved by the calling surface. */
96
+ artifactSession?: ShepherdSession;
97
+ /**
98
+ * Child launch overrides (binary/command/env prefix). The Pi path omits
99
+ * this; other hosts pass their own CLI shape here.
100
+ */
101
+ launch?: {
102
+ binary?: string;
103
+ extensionEntry?: string;
104
+ envPrefix?: string;
105
+ command?: string;
106
+ };
107
+ }
108
+
109
+ export class HcRuntimeError extends Error {
110
+ readonly code:
111
+ | 'unknown_handle'
112
+ | 'closed_handle'
113
+ | 'active_task'
114
+ | 'unknown_task'
115
+ | 'task_agent_mismatch'
116
+ | 'invalid_handle'
117
+ | 'invalid_target'
118
+ | 'invalid_task'
119
+ | 'invalid_transition'
120
+ | 'timeout';
121
+ constructor(code: HcRuntimeError['code'], message: string) {
122
+ super(message);
123
+ this.name = 'HcRuntimeError';
124
+ this.code = code;
125
+ }
126
+ }
127
+
128
+ type AgentState = 'idle' | 'working' | 'blocked' | 'done' | 'failed' | 'closed';
129
+
130
+ interface AgentRecord {
131
+ handle: {
132
+ id: string;
133
+ agent: string;
134
+ label: string;
135
+ model?: string;
136
+ terminalId?: string;
137
+ cwd?: string;
138
+ };
139
+ state: AgentState;
140
+ activeTaskId?: string;
141
+ completionSignalPath?: string;
142
+ completionResultPath?: string;
143
+ artifactSession?: ShepherdSession;
144
+ childCapability?: ChildCapability;
145
+ baselineCompletionSignalId?: string;
146
+ }
147
+
148
+ type InternalTaskState = 'created' | 'running' | 'waiting' | 'completed' | 'blocked' | 'failed' | 'cancelled' | 'timed_out';
149
+
150
+ interface TaskRecord {
151
+ taskId: string;
152
+ agentId: string;
153
+ description: string;
154
+ state: InternalTaskState;
155
+ createdAt: number;
156
+ deadlineAt?: number;
157
+ timeoutId?: ReturnType<typeof setTimeout>;
158
+ waitingSince?: number;
159
+ pendingReplyMessageId?: string;
160
+ pendingReplyTargetAgentId?: string;
161
+ pendingReplyDeadlineAt?: number;
162
+ pendingReplyText?: string;
163
+ pendingRequestIds: Set<string>;
164
+ /** Set when the stale-wait monitor has reminded for this wait episode. */
165
+ staleNotifiedAt?: number;
166
+ result?: TaskResultInternal;
167
+ onSettled?: (result: TaskResultInternal) => void;
168
+ artifactSession?: ShepherdSession;
169
+ artifact?: ArtifactReservation;
170
+ }
171
+
172
+ interface TaskResultInternal {
173
+ taskId: string;
174
+ agentId: string;
175
+ status: 'completed' | 'blocked' | 'failed' | 'cancelled' | 'timed_out';
176
+ ok: boolean;
177
+ returnCode: number;
178
+ text?: string;
179
+ error?: string;
180
+ completedAt: number;
181
+ }
182
+
183
+ function validateAgentLabel(value: unknown): string {
184
+ if (value == null) return '';
185
+ if (typeof value !== 'string') throw new Error('Agent label must be a string.');
186
+ const label = value.trim();
187
+ if (!label) return '';
188
+ if (label.length > 64) throw new Error('Agent label must be at most 64 characters.');
189
+ if (!/^[\p{L}\p{N} _.-]+$/u.test(label) || label.includes(':'))
190
+ throw new Error(
191
+ 'Agent label may contain only letters, numbers, spaces, _, -, and .; colons and control characters are not allowed.'
192
+ );
193
+ return label;
194
+ }
195
+
196
+ function formatAgentName(agent: string, label?: string): string {
197
+ const trimmed = label?.trim() ?? '';
198
+ return trimmed ? `${agent}: ${trimmed}` : agent;
199
+ }
200
+
201
+ function handleId(input: unknown, kind: 'AgentHandle' | 'TaskHandle'): string {
202
+ const normalized = normalizeHandleId(input, kind);
203
+ if (!normalized.ok) throw new HcRuntimeError('invalid_handle', normalized.message);
204
+ return normalized.id;
205
+ }
206
+
207
+ function toProcState(state: string | undefined): RuntimeProcState {
208
+ if (state === 'working') return 'working';
209
+ if (state === 'idle') return 'idle';
210
+ return 'unknown';
211
+ }
212
+
213
+ function toTaskState(state: InternalTaskState): RuntimeTaskState {
214
+ switch (state) {
215
+ case 'created':
216
+ case 'running':
217
+ return 'running';
218
+ case 'waiting':
219
+ return 'waiting';
220
+ case 'completed':
221
+ return 'done';
222
+ case 'blocked':
223
+ return 'blocked';
224
+ case 'failed':
225
+ case 'cancelled':
226
+ case 'timed_out':
227
+ return 'failed';
228
+ }
229
+ }
230
+
231
+ const TERMINAL_TASK_STATES: ReadonlySet<InternalTaskState> = new Set([
232
+ 'completed',
233
+ 'blocked',
234
+ 'failed',
235
+ 'cancelled',
236
+ 'timed_out',
237
+ ]);
238
+
239
+ // ── Module-singleton registries ─────────────────────────────────────────
240
+ // The adapter is stateless (one per action is enough): agents, tasks, and
241
+ // the parent mailbox live here, exactly like the pane backend's lifecycle
242
+ // registry. The owned-terminals file stays the cross-process source of
243
+ // truth for ownership (close/prune). `generationId` namespaces minted
244
+ // opaque ids for this process; there is no session rotation (unlike the
245
+ // pane backend's beginSession) because one extension process serves one
246
+ // parent session at a time here.
247
+ const generationId = randomUUID().slice(0, 8);
248
+ const agents = new Map<string, AgentRecord>();
249
+ const tasks = new Map<string, TaskRecord>();
250
+ let broker: ParentBroker | undefined;
251
+ let brokerOwnerKey: string | undefined;
252
+
253
+ function ownerSessionKey(sessionId?: string): string {
254
+ return (
255
+ sessionId?.trim() ||
256
+ process.env.PI_SHEPHERD_OWNER_SESSION?.trim() ||
257
+ `hc-parent-${generationId}`
258
+ );
259
+ }
260
+
261
+ function ensureBroker(sessionId?: string): ParentBroker {
262
+ const key = ownerSessionKey(sessionId);
263
+ if (broker && !broker.closed && brokerOwnerKey === key) return broker;
264
+ broker = createParentBroker(key);
265
+ brokerOwnerKey = key;
266
+ return broker;
267
+ }
268
+
269
+ /**
270
+ * OpenCode adapter hook: resolve (and create if needed) the hc parent
271
+ * broker for one parent session. Same singleton contract as the internal
272
+ * ensureBroker; exported so the adapter can re-register sheep after a
273
+ * broker rotation instead of failing sends with unknown child targets.
274
+ */
275
+ export function ensureHcBroker(sessionId?: string): ParentBroker {
276
+ return ensureBroker(sessionId);
277
+ }
278
+
279
+ function settleTask(record: TaskRecord, settlement: Omit<TaskResultInternal, 'taskId' | 'agentId' | 'completedAt'> & { completedAt?: number }, options: HcSettleTaskOptions = {}): TaskResultInternal {
280
+ if (record.result) return { ...record.result };
281
+ const completedAt = settlement.completedAt ?? Date.now();
282
+ const ok = settlement.status === 'completed' && settlement.ok !== false;
283
+ const defaultReturnCode =
284
+ settlement.status === 'cancelled'
285
+ ? 130
286
+ : settlement.status === 'timed_out'
287
+ ? 124
288
+ : settlement.status === 'blocked'
289
+ ? 2
290
+ : ok
291
+ ? 0
292
+ : 1;
293
+ const result: TaskResultInternal = {
294
+ taskId: record.taskId,
295
+ agentId: record.agentId,
296
+ status: settlement.status,
297
+ ok,
298
+ returnCode: settlement.returnCode ?? defaultReturnCode,
299
+ ...(settlement.text !== undefined ? { text: settlement.text } : {}),
300
+ ...(settlement.error !== undefined ? { error: settlement.error } : {}),
301
+ completedAt,
302
+ };
303
+ record.result = result;
304
+ record.state = settlement.status;
305
+ if (record.timeoutId) {
306
+ clearTimeout(record.timeoutId);
307
+ record.timeoutId = undefined;
308
+ }
309
+ record.pendingRequestIds.clear();
310
+ record.waitingSince = undefined;
311
+ record.staleNotifiedAt = undefined;
312
+ record.pendingReplyMessageId = undefined;
313
+ record.pendingReplyTargetAgentId = undefined;
314
+ record.pendingReplyDeadlineAt = undefined;
315
+ record.pendingReplyText = undefined;
316
+ try {
317
+ record.onSettled?.({ ...result });
318
+ } catch {
319
+ /* artifact persistence must not break task settlement */
320
+ }
321
+ const agent = agents.get(record.agentId);
322
+ if (agent?.activeTaskId === record.taskId) {
323
+ agent.activeTaskId = undefined;
324
+ if (agent.state !== 'closed') {
325
+ agent.state =
326
+ settlement.status === 'completed'
327
+ ? 'done'
328
+ : settlement.status === 'blocked'
329
+ ? 'blocked'
330
+ : 'failed';
331
+ }
332
+ }
333
+ try {
334
+ finalizeTaskArtifact(record, result);
335
+ } catch {
336
+ /* artifact persistence must not break task settlement */
337
+ }
338
+ // Non-blocking watcher delivery + observer feed (pane parity): the
339
+ // bridge owns the only ledger `record` call sites, so this path only
340
+ // notifies watchers and then observers. The bridge records the
341
+ // observation and schedules the idle wake, exactly like Herdr.
342
+ const hadWatchers = notifyHcTaskWatchers(result);
343
+ const agentHandle = agents.get(record.agentId)?.handle;
344
+ const settlementContext: HcTaskSettlementContext = {
345
+ hadWatchers,
346
+ ...(agentHandle ? { agent: agentHandle.agent, label: agentHandle.label } : {}),
347
+ ...(options.source !== undefined ? { source: options.source } : {}),
348
+ };
349
+ notifyHcTaskSettledObservers(result, settlementContext);
350
+ return { ...result };
351
+ }
352
+
353
+ function resolveReplyForTask(record: TaskRecord, replyTo: string): boolean {
354
+ if (record.result || replyTo !== record.pendingReplyMessageId) return false;
355
+ record.pendingRequestIds.delete(record.pendingReplyMessageId!);
356
+ record.pendingReplyMessageId = undefined;
357
+ record.pendingReplyTargetAgentId = undefined;
358
+ record.pendingReplyDeadlineAt = undefined;
359
+ record.pendingReplyText = undefined;
360
+ if (record.state === 'waiting') {
361
+ record.state = 'running';
362
+ record.waitingSince = undefined;
363
+ record.staleNotifiedAt = undefined;
364
+ }
365
+ return true;
366
+ }
367
+
368
+ function openPendingRequest(
369
+ record: TaskRecord,
370
+ request: { messageId: string; targetAgentId?: string; deadlineAt?: number; text?: string }
371
+ ): void {
372
+ if (record.result) {
373
+ throw new HcRuntimeError(
374
+ 'invalid_transition',
375
+ `Task "${record.taskId}" is already ${record.state}.`
376
+ );
377
+ }
378
+ if (record.pendingReplyMessageId !== undefined) {
379
+ throw new HcRuntimeError(
380
+ 'invalid_task',
381
+ `Task "${record.taskId}" already has an outstanding tracked reply (${record.pendingReplyMessageId}).`
382
+ );
383
+ }
384
+ if (record.state === 'created') record.state = 'running';
385
+ record.pendingReplyMessageId = request.messageId;
386
+ record.pendingReplyTargetAgentId = request.targetAgentId;
387
+ record.pendingReplyText = request.text;
388
+ if (request.deadlineAt !== undefined && Number.isFinite(request.deadlineAt)) {
389
+ record.pendingReplyDeadlineAt = request.deadlineAt;
390
+ }
391
+ record.pendingRequestIds.add(request.messageId);
392
+ record.state = 'waiting';
393
+ record.waitingSince ??= Date.now();
394
+ // One stale reminder per wait episode (information only); the reply
395
+ // deadline below stays the authoritative settlement.
396
+ try {
397
+ hcStaleWaitMonitor.kick();
398
+ } catch {
399
+ /* monitor is best effort */
400
+ }
401
+ }
402
+
403
+ /** Best-effort rejected-completion diagnostic beside the drain's own store. */
404
+ function writeTaskDoneDiagnostic(active: ParentBroker, kind: string, envelope: ShepherdMessageEnvelope, reason: string): void {
405
+ try {
406
+ const dir = path.join(active.rootDir, 'rejected');
407
+ fs.mkdirSync(dir, { recursive: true });
408
+ fs.writeFileSync(
409
+ path.join(dir, `task-done-${kind}-${Date.now()}.json`),
410
+ JSON.stringify({ at: Date.now(), reason, envelope }, null, 2),
411
+ 'utf8'
412
+ );
413
+ } catch {
414
+ /* diagnostics must never break broker polling */
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Apply one explicit child completion to the task registry. The envelope
420
+ * sender is broker-authenticated; a task id that does not resolve to the
421
+ * sender's own task is re-anchored on the sender's active task, and a
422
+ * completion with no resolvable task is dropped observably.
423
+ */
424
+ function applyTaskDoneEnvelope(active: ParentBroker, envelope: ShepherdMessageEnvelope): TaskResultInternal | undefined {
425
+ if (envelope.kind !== 'task_done' || !envelope.status) return undefined;
426
+ let record: TaskRecord | undefined;
427
+ if (envelope.taskId) record = tasks.get(envelope.taskId);
428
+ let senderAgentId: string | undefined;
429
+ for (const agent of agents.values()) {
430
+ if (agent.handle.id === envelope.senderId) {
431
+ senderAgentId = agent.handle.id;
432
+ break;
433
+ }
434
+ }
435
+ let senderActiveTask: TaskRecord | undefined;
436
+ if (senderAgentId !== undefined) {
437
+ const sender = agents.get(senderAgentId);
438
+ const candidate = sender?.activeTaskId ? tasks.get(sender.activeTaskId) : undefined;
439
+ if (candidate && !candidate.result) senderActiveTask = candidate;
440
+ }
441
+ if (record && record.result) return { ...record.result };
442
+ let effective = record;
443
+ if (record && senderAgentId !== undefined && record.agentId !== senderAgentId) {
444
+ effective = senderActiveTask;
445
+ }
446
+ if (!effective) effective = senderActiveTask;
447
+ if (!effective || senderAgentId === undefined) {
448
+ writeTaskDoneDiagnostic(active, 'dropped', envelope, 'no active task matches the sender');
449
+ return undefined;
450
+ }
451
+ if (envelope.status === 'completed' && effective.pendingRequestIds.size > 0) return undefined;
452
+ try {
453
+ if (effective.agentId !== senderAgentId) {
454
+ throw new HcRuntimeError(
455
+ 'task_agent_mismatch',
456
+ `Agent "${senderAgentId}" does not own task "${effective.taskId}".`
457
+ );
458
+ }
459
+ return settleTask(effective, {
460
+ status: envelope.status,
461
+ text: envelope.summary ?? envelope.content,
462
+ error: envelope.error,
463
+ });
464
+ } catch {
465
+ writeTaskDoneDiagnostic(active, 'dropped', envelope, `settlement of "${effective.taskId}" was rejected`);
466
+ return undefined;
467
+ }
468
+ }
469
+
470
+ // The drain's broker is threaded through: resolving a *separate* broker
471
+ // here (bare `ensureBroker()`) would mint a fallback-keyed store, orphan
472
+ // the session mailbox, and address reply relays to a store the child
473
+ // never polls.
474
+ function applyMessageEnvelope(active: ParentBroker, envelope: ShepherdMessageEnvelope): void {
475
+ switch (envelope.kind) {
476
+ case 'runtime': {
477
+ if (envelope.replyReceived === true && envelope.taskId && envelope.replyTo) {
478
+ const record = tasks.get(envelope.taskId);
479
+ if (record) resolveReplyForTask(record, envelope.replyTo);
480
+ return;
481
+ }
482
+ if (envelope.requestOpen === true && envelope.taskId && envelope.replyTo) {
483
+ const record = tasks.get(envelope.taskId);
484
+ if (record && !record.result && record.pendingReplyMessageId !== envelope.replyTo) {
485
+ try {
486
+ openPendingRequest(record, {
487
+ messageId: envelope.replyTo,
488
+ targetAgentId: envelope.requestTargetId,
489
+ text: envelope.summary ?? envelope.content,
490
+ });
491
+ } catch {
492
+ /* one outstanding request per task; keep the first */
493
+ }
494
+ }
495
+ }
496
+ return;
497
+ }
498
+ case 'reply': {
499
+ if (envelope.replyTo && envelope.taskId) {
500
+ const record = tasks.get(envelope.taskId);
501
+ if (record && resolveReplyForTask(record, envelope.replyTo)) {
502
+ if (record.agentId !== envelope.senderId) {
503
+ const owner = agents.get(record.agentId);
504
+ if (owner?.handle.terminalId) {
505
+ try {
506
+ const relayed = createEnvelope(
507
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.parentId },
508
+ {
509
+ kind: 'reply',
510
+ targetId: owner.handle.id,
511
+ messageId: mintMessageId(),
512
+ taskId: envelope.taskId,
513
+ threadId: envelope.threadId,
514
+ replyTo: envelope.replyTo,
515
+ originSenderId: envelope.senderId,
516
+ delivery: envelope.delivery,
517
+ content: envelope.content,
518
+ }
519
+ );
520
+ publishFromParent(active, relayed);
521
+ } catch {
522
+ /* relay is best effort; the requester task already resolved */
523
+ }
524
+ }
525
+ }
526
+ }
527
+ }
528
+ return;
529
+ }
530
+ default:
531
+ return;
532
+ }
533
+ }
534
+
535
+ /** Drain the parent mailbox; task completions settle the registry. */
536
+ function drainHcSessionInbox(sessionId?: string): void {
537
+ const active = ensureBroker(sessionId);
538
+ let envelopes: ShepherdMessageEnvelope[];
539
+ try {
540
+ envelopes = pollParentInbox(active);
541
+ } catch {
542
+ return;
543
+ }
544
+ for (const envelope of envelopes) {
545
+ try {
546
+ if (envelope.kind === 'task_done') applyTaskDoneEnvelope(active, envelope);
547
+ else applyMessageEnvelope(active, envelope);
548
+ } catch {
549
+ /* one bad envelope must not stop the drain */
550
+ }
551
+ }
552
+ settleDueReplyTimeouts();
553
+ }
554
+
555
+ /** Settle waiting tasks whose tracked-reply deadline has passed. */
556
+ function settleDueReplyTimeouts(now = Date.now()): void {
557
+ for (const record of tasks.values()) {
558
+ if (record.result) continue;
559
+ if (
560
+ record.state === 'waiting' &&
561
+ record.pendingReplyDeadlineAt !== undefined &&
562
+ now >= record.pendingReplyDeadlineAt
563
+ ) {
564
+ settleTask(record, {
565
+ status: 'blocked',
566
+ ok: false,
567
+ text: `Timed out waiting for a reply from ${record.pendingReplyTargetAgentId ?? 'the target agent'} (message ${record.pendingReplyMessageId ?? 'unknown'} never answered).`,
568
+ error: 'Tracked reply deadline reached.',
569
+ });
570
+ }
571
+ }
572
+ }
573
+
574
+ // ── 011: background inbox poll ──────────────────────────────────────────
575
+ // Herdr parity: the pane backend polls the parent inbox every 250 ms, so
576
+ // completions settle while the Shepherd is idle. hc drains only inside
577
+ // tool calls; this timer pumps the same session-keyed drain in the
578
+ // background. The tick never settles directly and never mints a broker:
579
+ // unresolvable sessions are skipped, never fallback-keyed.
580
+ const HC_DRAIN_POLL_MS = 250;
581
+ // Single session: the hc runtime is single-session-per-process (the module
582
+ // `generationId` is baked into every agent/task id), so the poller tracks
583
+ // one session key. A set would alternate `ensureBroker` keys and mint a
584
+ // fresh store on every drain instead of polling the live mailbox.
585
+ let hcPollSession: string | undefined;
586
+ let hcDrainTimer: ReturnType<typeof setInterval> | undefined;
587
+
588
+ function startHcInboxPoller(): void {
589
+ if (hcDrainTimer) return;
590
+ hcDrainTimer = setInterval(() => {
591
+ try {
592
+ pollHcInboxOnce();
593
+ } catch {
594
+ /* a tick must never break the host turn */
595
+ }
596
+ }, HC_DRAIN_POLL_MS);
597
+ (hcDrainTimer as any).unref?.();
598
+ }
599
+
600
+ export function stopHcInboxPoller(): void {
601
+ if (hcDrainTimer) clearInterval(hcDrainTimer);
602
+ hcDrainTimer = undefined;
603
+ }
604
+
605
+ export function isHcInboxPollerRunning(): boolean {
606
+ return hcDrainTimer !== undefined;
607
+ }
608
+
609
+ /**
610
+ * Register a session with possibly-open work; starts the poller. Resolves
611
+ * through `ownerSessionKey` exactly like the drains, so the tick always
612
+ * polls the same store the tool calls use (explicit id, env session, or
613
+ * the process fallback — never skipped, never a different key).
614
+ */
615
+ export function registerHcPollSession(sessionId?: string): void {
616
+ hcPollSession = ownerSessionKey(sessionId);
617
+ startHcInboxPoller();
618
+ }
619
+
620
+ /** One synchronous poll pass over the registered session, then stop at quiescence. */
621
+ export function pollHcInboxOnce(): void {
622
+ if (hcPollSession !== undefined) {
623
+ try {
624
+ drainHcSessionInbox(hcPollSession);
625
+ } catch {
626
+ /* a bad session drain must not stop the pass */
627
+ }
628
+ }
629
+ for (const record of tasks.values()) {
630
+ if (!record.result) return;
631
+ }
632
+ stopHcInboxPoller();
633
+ }
634
+
635
+ /**
636
+ * Drain-first entry for read paths (`watch` registration, `status` view):
637
+ * returns false without touching anything when no session resolves, so a
638
+ * read can never mint a fallback-keyed broker.
639
+ */
640
+ export function drainHcInboxForSession(sessionId?: string): boolean {
641
+ const id = sessionId?.trim();
642
+ if (!id) return false;
643
+ drainHcSessionInbox(id);
644
+ return true;
645
+ }
646
+
647
+ /** Test seam (011 suite): isolated agent/task fixtures for real-settlement ticks. */
648
+ export function hcInjectTestAgent(agent: AgentRecord): void {
649
+ agents.set(agent.handle.id, agent);
650
+ }
651
+ export function hcInjectTestTask(task: TaskRecord): void {
652
+ tasks.set(task.taskId, task);
653
+ }
654
+ export function hcRemoveTestAgent(agentId: string): void {
655
+ agents.delete(agentId);
656
+ }
657
+ export function hcRemoveTestTask(taskId: string): void {
658
+ tasks.delete(taskId);
659
+ }
660
+
661
+ /** Test seam: lifecycle + unref visibility without wall-clock waits. */
662
+ export function hcInboxPollerStateForTests(): {
663
+ running: boolean;
664
+ session: string | undefined;
665
+ unrefed: boolean | undefined;
666
+ } {
667
+ let unrefed: boolean | undefined;
668
+ try {
669
+ unrefed =
670
+ hcDrainTimer === undefined
671
+ ? undefined
672
+ : typeof (hcDrainTimer as any).hasRef === 'function'
673
+ ? !(hcDrainTimer as any).hasRef()
674
+ : undefined;
675
+ } catch {
676
+ unrefed = undefined;
677
+ }
678
+ return { running: hcDrainTimer !== undefined, session: hcPollSession, unrefed };
679
+ }
680
+
681
+ // ── Phase 2 parity: stale-wait monitor + non-blocking task watchers ──────
682
+ // Mirrors the pane-based backend's stale-wait monitor and task-watcher
683
+ // service over the module hc registries. The
684
+ // monitor is information only (never a settlement); reply deadlines remain
685
+ // the authoritative `blocked` settlement. Watchers are non-blocking: `watch`
686
+ // registers synchronously and later completions arrive via the notifier,
687
+ // exactly like the pane backend's task-watcher bridge.
688
+
689
+ export interface HcStaleWaitInfo {
690
+ taskId: string;
691
+ agentId: string;
692
+ agent?: string;
693
+ label?: string;
694
+ description: string;
695
+ waitingSince: number;
696
+ elapsedMs: number;
697
+ requestMessageId: string;
698
+ question: string;
699
+ recipientId?: string;
700
+ recipientName?: string;
701
+ recipientState?: string;
702
+ thresholdMinutes: number;
703
+ }
704
+
705
+ export type HcStaleWaitNotifier = (info: HcStaleWaitInfo) => void | Promise<void>;
706
+
707
+ class HcStaleWaitMonitor {
708
+ private timer?: ReturnType<typeof setInterval>;
709
+ private notifier?: HcStaleWaitNotifier;
710
+ private readonly intervalMs: number;
711
+
712
+ constructor(notifier?: HcStaleWaitNotifier, intervalMs = 1_000) {
713
+ this.notifier = notifier;
714
+ this.intervalMs = intervalMs;
715
+ }
716
+
717
+ kick(): void {
718
+ this.ensureStarted();
719
+ void this.poll();
720
+ }
721
+
722
+ shutdown(): void {
723
+ if (this.timer) clearInterval(this.timer);
724
+ this.timer = undefined;
725
+ }
726
+
727
+ setNotifier(notifier?: HcStaleWaitNotifier): void {
728
+ this.notifier = notifier;
729
+ }
730
+
731
+ private ensureStarted(): void {
732
+ if (this.timer) return;
733
+ this.timer = setInterval(() => void this.poll(), this.intervalMs);
734
+ (this.timer as any).unref?.();
735
+ }
736
+
737
+ private maybeStop(): void {
738
+ const waiting = [...tasks.values()].some(t => t.state === 'waiting' && !t.result);
739
+ if (!waiting && this.timer) {
740
+ clearInterval(this.timer);
741
+ this.timer = undefined;
742
+ }
743
+ }
744
+
745
+ async poll(): Promise<void> {
746
+ const now = Date.now();
747
+ const waiting = [...tasks.values()].filter(t => t.state === 'waiting' && !t.result);
748
+ if (waiting.length === 0) {
749
+ this.maybeStop();
750
+ return;
751
+ }
752
+ for (const task of waiting) {
753
+ const thresholdMinutes = (() => {
754
+ try {
755
+ const agent = agents.get(task.agentId);
756
+ return loadSettings(agent?.handle.cwd ?? process.cwd()).staleWaitThreshold;
757
+ } catch {
758
+ return DEFAULT_SETTINGS.staleWaitThreshold;
759
+ }
760
+ })();
761
+ if (thresholdMinutes < 1) continue;
762
+ if (now - (task.waitingSince ?? now) < thresholdMinutes * 60_000) continue;
763
+ if (task.staleNotifiedAt !== undefined) continue;
764
+ const elapsedMs = now - (task.waitingSince ?? now);
765
+ const owner = agents.get(task.agentId);
766
+ let recipientName: string | undefined;
767
+ let recipientState: string | undefined;
768
+ if (task.pendingReplyTargetAgentId) {
769
+ const recipient = agents.get(task.pendingReplyTargetAgentId);
770
+ if (recipient) {
771
+ recipientName = recipient.handle.label
772
+ ? `${recipient.handle.agent}: ${recipient.handle.label}`
773
+ : recipient.handle.agent;
774
+ recipientState = recipient.state;
775
+ }
776
+ }
777
+ const info: HcStaleWaitInfo = {
778
+ taskId: task.taskId,
779
+ agentId: task.agentId,
780
+ ...(owner ? { agent: owner.handle.agent, label: owner.handle.label } : {}),
781
+ description: task.description,
782
+ waitingSince: task.waitingSince ?? now,
783
+ elapsedMs,
784
+ requestMessageId: task.pendingReplyMessageId ?? '',
785
+ question: task.pendingReplyText ?? '',
786
+ ...(task.pendingReplyTargetAgentId ? { recipientId: task.pendingReplyTargetAgentId } : {}),
787
+ ...(recipientName ? { recipientName } : {}),
788
+ ...(recipientState ? { recipientState } : {}),
789
+ thresholdMinutes,
790
+ };
791
+ try {
792
+ task.staleNotifiedAt = Date.now();
793
+ const result = this.notifier?.(info);
794
+ if (result && typeof (result as Promise<void>).catch === 'function') {
795
+ (result as Promise<void>).catch(() => undefined);
796
+ }
797
+ } catch {
798
+ // Best effort; reply deadline stays authoritative.
799
+ }
800
+ }
801
+ this.maybeStop();
802
+ }
803
+ }
804
+
805
+ export const hcStaleWaitMonitor = new HcStaleWaitMonitor();
806
+
807
+ export function configureHcStaleWaitNotifications(notifier?: HcStaleWaitNotifier): void {
808
+ hcStaleWaitMonitor.setNotifier(notifier);
809
+ }
810
+
811
+ export function shutdownHcStaleWaitMonitor(): void {
812
+ hcStaleWaitMonitor.shutdown();
813
+ stopHcInboxPoller();
814
+ }
815
+
816
+ // ── Non-blocking hc task watchers (shepherd_watch parity) ─────────────────
817
+ // `HcRuntime.watch` blocks; the `shepherd_watch` tool must return at once
818
+ // and deliver later completions via notification. This registry mirrors
819
+ // `LifecycleRegistry.watchTasks` + `TaskWatcherService`: synchronous
820
+ // registration with already-settled sync delivery, exactly-once later
821
+ // delivery per task, and unseen-ledger feed for watcher-less settlements.
822
+
823
+ export interface HcTaskWatcherRegistration {
824
+ watcherId: string;
825
+ taskIds: string[];
826
+ pending: string[];
827
+ completed: TaskResultInternal[];
828
+ }
829
+
830
+ export type HcTaskWatcherCompletion = TaskResultInternal & { agent?: string; label?: string };
831
+ export type HcTaskWatcherCallback = (completion: HcTaskWatcherCompletion) => void;
832
+
833
+ const hcWatchers = new Map<
834
+ string,
835
+ {
836
+ kind: 'task';
837
+ taskIds: string[];
838
+ pending: Set<string>;
839
+ callback?: HcTaskWatcherCallback | HcTaskWatcherCallback[];
840
+ delivered: Set<string>;
841
+ }
842
+ >();
843
+ const hcTaskWatchers = new Map<string, Set<string>>();
844
+
845
+ function hcCompletionFor(taskId: string): HcTaskWatcherCompletion | undefined {
846
+ const record = tasks.get(taskId);
847
+ if (!record?.result) return undefined;
848
+ const agent = agents.get(record.agentId);
849
+ return {
850
+ ...record.result,
851
+ ...(agent ? { agent: agent.handle.agent, label: agent.handle.label } : {}),
852
+ };
853
+ }
854
+
855
+ /** Synchronous registration; already-settled tasks deliver immediately. */
856
+ export function watchHcTasks(
857
+ handles: string | string[],
858
+ callback?: HcTaskWatcherCallback | HcTaskWatcherCallback[]
859
+ ): HcTaskWatcherRegistration {
860
+ const values = Array.isArray(handles) ? handles : [handles];
861
+ if (values.length === 0) {
862
+ throw new HcRuntimeError('invalid_handle', 'Expected one or more opaque task ids to watch.');
863
+ }
864
+ const taskIds = values.map(value => {
865
+ const id = handleId(value, 'TaskHandle');
866
+ const record = tasks.get(id);
867
+ if (!record) {
868
+ throw new HcRuntimeError(
869
+ 'unknown_task',
870
+ `Unknown task id "${id}". Task ids are scoped to this parent session; use the id returned by shepherd_delegate, not an agent id or terminal address.`
871
+ );
872
+ }
873
+ return record.taskId;
874
+ });
875
+ if (new Set(taskIds).size !== taskIds.length) {
876
+ throw new HcRuntimeError('invalid_handle', 'A watcher cannot contain duplicate task ids.');
877
+ }
878
+ const watcherId = mintId('watch', generationId);
879
+ const pending = new Set<string>();
880
+ const completed: TaskResultInternal[] = [];
881
+ const deliver = (completion: HcTaskWatcherCompletion): void => {
882
+ if (Array.isArray(callback)) {
883
+ for (const one of callback) one(completion);
884
+ } else callback?.(completion);
885
+ };
886
+ for (const taskId of taskIds) {
887
+ const done = hcCompletionFor(taskId);
888
+ if (done) completed.push({ ...done });
889
+ else pending.add(taskId);
890
+ }
891
+ if (pending.size > 0) {
892
+ hcWatchers.set(watcherId, {
893
+ kind: 'task',
894
+ taskIds: [...taskIds],
895
+ pending,
896
+ callback,
897
+ delivered: new Set(),
898
+ });
899
+ for (const taskId of pending) {
900
+ let watchers = hcTaskWatchers.get(taskId);
901
+ if (!watchers) hcTaskWatchers.set(taskId, (watchers = new Set()));
902
+ watchers.add(watcherId);
903
+ }
904
+ // Synchronous already-settled delivery must still flow through the
905
+ // notifier path so `shepherd_watch` sees uniform completions.
906
+ for (const done of completed) {
907
+ try {
908
+ deliver({ ...done });
909
+ } catch {
910
+ /* delivery must not break registration */
911
+ }
912
+ }
913
+ }
914
+ return { watcherId, taskIds: [...taskIds], pending: [...pending], completed };
915
+ }
916
+
917
+ /** Deliver one settlement to watchers; returns whether anyone observed it. */
918
+ function notifyHcTaskWatchers(result: TaskResultInternal): boolean {
919
+ const watcherIds = [...(hcTaskWatchers.get(result.taskId) ?? [])];
920
+ hcTaskWatchers.delete(result.taskId);
921
+ const agent = agents.get(result.agentId);
922
+ let hadWatchers = false;
923
+ for (const watcherId of watcherIds) {
924
+ const watcher = hcWatchers.get(watcherId);
925
+ if (!watcher || watcher.delivered.has(result.taskId)) continue;
926
+ watcher.delivered.add(result.taskId);
927
+ watcher.pending.delete(result.taskId);
928
+ try {
929
+ const delivery: HcTaskWatcherCompletion = {
930
+ ...result,
931
+ ...(agent ? { agent: agent.handle.agent, label: agent.handle.label } : {}),
932
+ };
933
+ const cb = watcher.callback;
934
+ if (Array.isArray(cb)) {
935
+ for (const one of cb) one(delivery);
936
+ } else cb?.(delivery);
937
+ } catch {
938
+ /* notification delivery must not break settlement */
939
+ }
940
+ if (watcher.callback !== undefined) hadWatchers = true;
941
+ if (watcher.pending.size === 0) hcWatchers.delete(watcherId);
942
+ }
943
+ return hadWatchers;
944
+ }
945
+
946
+ /** Internal source tags for settlements that are not unseen-at-source. */
947
+ export type HcTaskSettlementSource = 'delegate-submission-failure';
948
+
949
+ /**
950
+ * Context attached to each hc settlement observation.
951
+ *
952
+ * `hadWatchers` is true only when at least one hc task-watcher callback was
953
+ * actually invoked for this settlement. `agent`/`label` come from the settled
954
+ * agent's handle. `source` marks settlements callers must not treat as unseen
955
+ * completions (a delegate submission failure is already reported in the
956
+ * `shepherd_delegate` tool result).
957
+ */
958
+ export interface HcTaskSettlementContext {
959
+ hadWatchers: boolean;
960
+ agent?: string;
961
+ label?: string;
962
+ source?: HcTaskSettlementSource;
963
+ }
964
+
965
+ /** One hc settlement observation; see {@link onTaskSettled}. */
966
+ export type HcTaskSettledListener = (result: TaskResultInternal, context: HcTaskSettlementContext) => void;
967
+
968
+ /** Internal settle options; only the delegate failure path passes `source`. */
969
+ export interface HcSettleTaskOptions {
970
+ source?: HcTaskSettlementSource;
971
+ }
972
+
973
+ const hcSettlementListeners = new Set<HcTaskSettledListener>();
974
+
975
+ /**
976
+ * Registry contract: observe hc settlements that reach a terminal task state.
977
+ *
978
+ * Mirrors the pane-backend registry `onTaskSettled` contract: the listener fires once per actual
979
+ * transition into a terminal task state, after the hc watcher fan-out, with
980
+ * a shallow copy of the result and a fresh context. Listener failures are
981
+ * swallowed and can never affect settlement; with no listener subscribed,
982
+ * `settleTask` behaves exactly as before. Prompt (legacy) settlements are not
983
+ * observed (the hc runtime has no prompt path).
984
+ */
985
+ export function onTaskSettled(listener: HcTaskSettledListener): () => void {
986
+ hcSettlementListeners.add(listener);
987
+ return () => {
988
+ hcSettlementListeners.delete(listener);
989
+ };
990
+ }
991
+
992
+ /**
993
+ * Deliver one terminal settlement to `onTaskSettled` subscribers, each with
994
+ * its own shallow copy of the result and context. Listener failures are
995
+ * swallowed and can never affect settlement. Called by the settle path after
996
+ * the hc watcher fan-out; exported so observer parity is unit-testable
997
+ * without a live terminal (mirrors the pane-backend settle listener loop).
998
+ */
999
+ export function notifyHcTaskSettledObservers(
1000
+ result: TaskResultInternal,
1001
+ context: HcTaskSettlementContext
1002
+ ): void {
1003
+ for (const listener of [...hcSettlementListeners]) {
1004
+ try {
1005
+ listener({ ...result }, { ...context });
1006
+ } catch {
1007
+ /* settlement observation must not break settlement */
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ export type HcTaskWatcherNotifier = (notification: {
1013
+ watcherId: string;
1014
+ completions: HcTaskWatcherCompletion[];
1015
+ }) => void | Promise<void>;
1016
+
1017
+ /** Coalescing non-blocking delivery bridge (mirrors TaskWatcherService). */
1018
+ class HcTaskWatcherService {
1019
+ private notifier?: HcTaskWatcherNotifier;
1020
+ private readonly coalesceMs: number;
1021
+ private readonly queued = new Map<string, HcTaskWatcherCompletion[]>();
1022
+ private readonly order = new Map<string, Map<string, number>>();
1023
+ private readonly remaining = new Map<string, number>();
1024
+ private readonly flushTimers = new Map<string, ReturnType<typeof setTimeout>>();
1025
+
1026
+ constructor(notifier?: HcTaskWatcherNotifier, coalesceMs = 25) {
1027
+ this.notifier = notifier;
1028
+ this.coalesceMs = coalesceMs;
1029
+ }
1030
+
1031
+ setNotifier(notifier?: HcTaskWatcherNotifier): void {
1032
+ this.notifier = notifier;
1033
+ }
1034
+
1035
+ watch(handles: string | string[]): HcTaskWatcherRegistration {
1036
+ let watcherId = '';
1037
+ const registration = watchHcTasks(handles, completion => {
1038
+ this.queue(watcherId, completion);
1039
+ });
1040
+ watcherId = registration.watcherId;
1041
+ if (registration.pending.length > 0) {
1042
+ this.order.set(
1043
+ watcherId,
1044
+ new Map(registration.taskIds.map((taskId, index) => [taskId, index]))
1045
+ );
1046
+ this.remaining.set(watcherId, registration.pending.length);
1047
+ }
1048
+ return registration;
1049
+ }
1050
+
1051
+ shutdown(): void {
1052
+ for (const timer of this.flushTimers.values()) clearTimeout(timer);
1053
+ this.flushTimers.clear();
1054
+ this.queued.clear();
1055
+ this.order.clear();
1056
+ this.remaining.clear();
1057
+ hcWatchers.clear();
1058
+ hcTaskWatchers.clear();
1059
+ }
1060
+
1061
+ private queue(watcherId: string, completion: HcTaskWatcherCompletion): void {
1062
+ if (!watcherId) return;
1063
+ const list = this.queued.get(watcherId) ?? [];
1064
+ list.push({ ...completion });
1065
+ this.queued.set(watcherId, list);
1066
+ const remaining = this.remaining.get(watcherId);
1067
+ if (remaining !== undefined) this.remaining.set(watcherId, Math.max(0, remaining - 1));
1068
+ if (!this.flushTimers.has(watcherId)) {
1069
+ const timer = setTimeout(() => this.flush(watcherId), this.coalesceMs);
1070
+ (timer as any).unref?.();
1071
+ this.flushTimers.set(watcherId, timer);
1072
+ }
1073
+ }
1074
+
1075
+ private flush(watcherId: string): void {
1076
+ this.flushTimers.delete(watcherId);
1077
+ const completions = this.queued.get(watcherId);
1078
+ this.queued.delete(watcherId);
1079
+ if (!completions || completions.length === 0) return;
1080
+ const order = this.order.get(watcherId);
1081
+ if (order) {
1082
+ completions.sort(
1083
+ (left, right) =>
1084
+ (order.get(left.taskId) ?? Number.MAX_SAFE_INTEGER) -
1085
+ (order.get(right.taskId) ?? Number.MAX_SAFE_INTEGER)
1086
+ );
1087
+ }
1088
+ if (this.remaining.get(watcherId) === 0) {
1089
+ this.order.delete(watcherId);
1090
+ this.remaining.delete(watcherId);
1091
+ }
1092
+ try {
1093
+ const result = this.notifier?.({ watcherId, completions });
1094
+ if (result && typeof (result as Promise<void>).catch === 'function') {
1095
+ (result as Promise<void>).catch(() => undefined);
1096
+ }
1097
+ } catch {
1098
+ // Durable result; missing bridge must not corrupt settlement.
1099
+ }
1100
+ }
1101
+ }
1102
+
1103
+ export const hcTaskWatcherService = new HcTaskWatcherService();
1104
+
1105
+ export function configureHcTaskWatcherNotifications(notifier?: HcTaskWatcherNotifier): void {
1106
+ hcTaskWatcherService.setNotifier(notifier);
1107
+ }
1108
+
1109
+ export function shutdownHcTaskWatchers(): void {
1110
+ hcTaskWatcherService.shutdown();
1111
+ stopHcInboxPoller();
1112
+ }
1113
+
1114
+ /** True when the id names a known hc task (tool routing, not a contract). */
1115
+ export function isHcTaskId(id: unknown): boolean {
1116
+ if (typeof id !== 'string' || !id) return false;
1117
+ return tasks.has(id);
1118
+ }
1119
+
1120
+ /**
1121
+ * Non-contract introspection for the OpenCode adapter: mailbox handles for
1122
+ * publishing child envelopes (message/done) as a sheep. Returns undefined
1123
+ * when no broker or record exists (single-active-parent backend: the
1124
+ * current broker wins).
1125
+ */
1126
+ export function describeHcSheepMailbox(agentId: string):
1127
+ | {
1128
+ childCapability: ChildCapability;
1129
+ rootDir: string;
1130
+ sessionId: string;
1131
+ brokerId: string;
1132
+ parentId: string;
1133
+ }
1134
+ | undefined {
1135
+ const normalized = normalizeHandleId(agentId, 'AgentHandle');
1136
+ if (!normalized.ok) return undefined;
1137
+ const record = agents.get(normalized.id);
1138
+ if (!record?.childCapability || !broker || broker.closed) return undefined;
1139
+ return {
1140
+ childCapability: record.childCapability,
1141
+ rootDir: broker.rootDir,
1142
+ sessionId: broker.sessionId,
1143
+ brokerId: broker.brokerId,
1144
+ parentId: broker.parentId,
1145
+ };
1146
+ }
1147
+
1148
+ /**
1149
+ * Non-contract introspection for the OpenCode adapter: task ownership for
1150
+ * routing child calls (done/message) without a bound session. Returns
1151
+ * undefined for unknown task ids.
1152
+ */
1153
+ export function describeHcTask(
1154
+ taskId: string
1155
+ ): { taskId: string; agentId: string; state: string; description: string } | undefined {
1156
+ const record = tasks.get(taskId);
1157
+ if (!record) return undefined;
1158
+ return {
1159
+ taskId: record.taskId,
1160
+ agentId: record.agentId,
1161
+ state: record.state,
1162
+ description: record.description,
1163
+ };
1164
+ }
1165
+
1166
+ /**
1167
+ * Non-contract introspection for the OpenCode adapter: resolve an owned hc
1168
+ * sheep to its terminal address for input delivery (`hc send`). Returns
1169
+ * undefined for unknown ids or sheep without a terminal (the caller
1170
+ * surfaces the backend's not-found error).
1171
+ */
1172
+ export function resolveHcTerminalId(agentId: string): string | undefined {
1173
+ const normalized = normalizeHandleId(agentId, 'AgentHandle');
1174
+ if (!normalized.ok) return undefined;
1175
+ return agents.get(normalized.id)?.handle.terminalId;
1176
+ }
1177
+
1178
+ /**
1179
+ * Tool-facing status view for an hc sheep: lifecycle state plus the active
1180
+ * tracked task with the same fields the pane-backend tool reports (waiting
1181
+ * age, pending request, waiting recipient, stale flag). Returns undefined
1182
+ * task when no open task exists.
1183
+ */
1184
+ export function describeHcStatusView(agentId: string): {
1185
+ handle: { id: string; agent: string; label: string };
1186
+ state: AgentState;
1187
+ task?: {
1188
+ id: string;
1189
+ state: InternalTaskState;
1190
+ description: string;
1191
+ waitingSince?: number;
1192
+ waitingMs?: number;
1193
+ pendingRequestMessageId?: string;
1194
+ waitingRecipient?: string;
1195
+ stale?: boolean;
1196
+ };
1197
+ } {
1198
+ const id = handleId(agentId, 'AgentHandle');
1199
+ const record = agents.get(id);
1200
+ if (!record) {
1201
+ throw new HcRuntimeError(
1202
+ 'unknown_handle',
1203
+ `Unknown agent id "${id}". Lifecycle ids are scoped to this parent session; use the id from the latest spawn result.`
1204
+ );
1205
+ }
1206
+ let taskView: ReturnType<typeof describeHcStatusView>['task'];
1207
+ const open = record.activeTaskId ? tasks.get(record.activeTaskId) : undefined;
1208
+ if (open && !open.result) {
1209
+ let waitingRecipient: string | undefined;
1210
+ if (open.pendingReplyTargetAgentId) {
1211
+ const recipient = agents.get(open.pendingReplyTargetAgentId);
1212
+ waitingRecipient = recipient
1213
+ ? recipient.handle.label
1214
+ ? `${recipient.handle.agent}: ${recipient.handle.label}`
1215
+ : recipient.handle.agent
1216
+ : open.pendingReplyTargetAgentId;
1217
+ }
1218
+ taskView = {
1219
+ id: open.taskId,
1220
+ state: open.state,
1221
+ description: open.description,
1222
+ ...(open.waitingSince !== undefined
1223
+ ? { waitingSince: open.waitingSince, waitingMs: Math.max(0, Date.now() - open.waitingSince) }
1224
+ : {}),
1225
+ ...(open.pendingReplyMessageId ? { pendingRequestMessageId: open.pendingReplyMessageId } : {}),
1226
+ ...(waitingRecipient ? { waitingRecipient } : {}),
1227
+ ...(open.staleNotifiedAt !== undefined ? { stale: true as const } : {}),
1228
+ };
1229
+ }
1230
+ return {
1231
+ handle: { id: record.handle.id, agent: record.handle.agent, label: record.handle.label },
1232
+ state: record.state,
1233
+ ...(taskView ? { task: taskView } : {}),
1234
+ };
1235
+ }
1236
+
1237
+ /**
1238
+ * Non-contract introspection for the resolver seam: display identity for a
1239
+ * known hc agent. Unknown ids throw, exactly like the registry lookups
1240
+ * behind every other method. Records are retained after close so a closed
1241
+ * sheep still describes itself (mirrors the pane-backend registry).
1242
+ */
1243
+ export function describeHcAgent(agentId: string): {
1244
+ id: string;
1245
+ agent: string;
1246
+ label: string;
1247
+ model?: string;
1248
+ } {
1249
+ const id = handleId(agentId, 'AgentHandle');
1250
+ const record = agents.get(id);
1251
+ if (!record) {
1252
+ throw new HcRuntimeError(
1253
+ 'unknown_handle',
1254
+ `Unknown agent id "${id}". Lifecycle ids are scoped to this parent session; use the id from the latest spawn result. A terminal address is not an agent id.`
1255
+ );
1256
+ }
1257
+ return {
1258
+ id: record.handle.id,
1259
+ agent: record.handle.agent,
1260
+ label: record.handle.label,
1261
+ ...(record.handle.model ? { model: record.handle.model } : {}),
1262
+ };
1263
+ }
1264
+
1265
+ /**
1266
+ * Resolve a diagnostic read target to an opaque hc agent id: exact id first,
1267
+ * then display identity (`agent`, `agent: label`, label), then owned
1268
+ * terminal name/address. Returns undefined when nothing matches (the caller
1269
+ * surfaces the backend's useful not-found error).
1270
+ */
1271
+ export function resolveHcAgentId(target: string): string | undefined {
1272
+ if (agents.has(target)) return target;
1273
+ for (const record of agents.values()) {
1274
+ const display = record.handle.label
1275
+ ? `${record.handle.agent}: ${record.handle.label}`
1276
+ : record.handle.agent;
1277
+ if (
1278
+ record.handle.agent === target ||
1279
+ record.handle.label === target ||
1280
+ display === target
1281
+ ) {
1282
+ return record.handle.id;
1283
+ }
1284
+ }
1285
+ try {
1286
+ const match = loadCreatedTerminals().find(t => t.terminalId === target || t.name === target);
1287
+ if (match) {
1288
+ for (const record of agents.values()) {
1289
+ if (record.handle.terminalId === match.terminalId) return record.handle.id;
1290
+ }
1291
+ }
1292
+ } catch {
1293
+ /* registry read is best effort */
1294
+ }
1295
+ return undefined;
1296
+ }
1297
+
1298
+ /**
1299
+ * Build the hc runtime adapter for one parent session context. Stateless:
1300
+ * registries live at module scope so per-action instances share sheep.
1301
+ */
1302
+ export function createHcRuntime(context: HcRuntimeContext = {}): ShepherdRuntime {
1303
+ const cwd = context.cwd ?? process.cwd();
1304
+ const sessionId = context.sessionId;
1305
+
1306
+ function canonicalAgent(input: unknown): AgentRecord {
1307
+ const id = handleId(input, 'AgentHandle');
1308
+ const record = agents.get(id);
1309
+ if (!record)
1310
+ throw new HcRuntimeError(
1311
+ 'unknown_handle',
1312
+ `Unknown agent id "${id}". Lifecycle ids are scoped to this parent session; use the id from the latest spawn result. A terminal address is not an agent id.`
1313
+ );
1314
+ return record;
1315
+ }
1316
+
1317
+ function taskRecord(input: unknown): TaskRecord {
1318
+ const id = handleId(input, 'TaskHandle');
1319
+ const record = tasks.get(id);
1320
+ if (!record) {
1321
+ throw new HcRuntimeError(
1322
+ 'unknown_task',
1323
+ `Unknown task id "${id}". Task ids are scoped to this parent session; use the id returned by shepherd_delegate, not an agent id or terminal address.`
1324
+ );
1325
+ }
1326
+ return record;
1327
+ }
1328
+
1329
+ function toCompletion(result: TaskResultInternal): Completion {
1330
+ const agent = agents.get(result.agentId);
1331
+ return {
1332
+ taskId: result.taskId,
1333
+ agentId: result.agentId,
1334
+ status: result.status,
1335
+ ok: result.ok,
1336
+ returnCode: result.returnCode,
1337
+ ...(result.text !== undefined ? { text: result.text } : {}),
1338
+ ...(result.error !== undefined ? { error: result.error } : {}),
1339
+ completedAt: result.completedAt,
1340
+ ...(agent ? { agent: agent.handle.agent } : {}),
1341
+ ...(agent && agent.handle.label ? { label: agent.handle.label } : {}),
1342
+ };
1343
+ }
1344
+
1345
+ function finalizeTaskArtifact(record: TaskRecord, result: TaskResultInternal): void {
1346
+ const { artifactSession, artifact } = record;
1347
+ if (!artifactSession || !artifact) return;
1348
+ const status =
1349
+ result.status === 'timed_out'
1350
+ ? 'timed-out'
1351
+ : result.status === 'cancelled'
1352
+ ? 'cancelled'
1353
+ : result.status === 'completed'
1354
+ ? 'completed'
1355
+ : 'failed';
1356
+ finalizeArtifact(artifactSession, artifact, { status, output: result.text, error: result.error });
1357
+ }
1358
+
1359
+ /** Closure thin wrapper: tool-call drains keep their exact behavior. */
1360
+ function drainBrokerInbox(): void {
1361
+ drainHcSessionInbox(sessionId);
1362
+ }
1363
+
1364
+ async function terminalState(terminalId: string): Promise<{ live: boolean; agentState?: string }> {
1365
+ try {
1366
+ const rec = (await hcExec(['get', terminalId, '--json'])) as any;
1367
+ const agentState =
1368
+ typeof rec?.status?.state === 'string' ? (rec.status.state as string) : undefined;
1369
+ return { live: rec?.state === 'live', agentState };
1370
+ } catch (error) {
1371
+ if (error instanceof HcError && error.kind === 'not_found') return { live: false };
1372
+ return { live: true };
1373
+ }
1374
+ }
1375
+
1376
+ async function settleFromSignal(record: TaskRecord): Promise<TaskResultInternal | undefined> {
1377
+ const agent = agents.get(record.agentId);
1378
+ const signalPath = agent?.completionSignalPath;
1379
+ if (!signalPath) return undefined;
1380
+ const signal: any = readCompletionSignal(signalPath);
1381
+ if (!signal?.signalId) return undefined;
1382
+ if (signal.taskId !== undefined && signal.taskId !== record.taskId) return undefined;
1383
+ if (signal.taskId === undefined && signal.signalId === agent?.baselineCompletionSignalId) {
1384
+ return undefined;
1385
+ }
1386
+ const status = signal.type === 'error' ? 'failed' : 'completed';
1387
+ let text: string | undefined =
1388
+ typeof signal.summary === 'string' && signal.summary ? signal.summary : undefined;
1389
+ if (!text && agent?.completionResultPath) {
1390
+ const last = readLastAssistantText(agent.completionResultPath).trim();
1391
+ if (last) text = last;
1392
+ }
1393
+ if (!text && agent?.handle.terminalId) {
1394
+ const tail = (await readHcTerminalTail(agent.handle.terminalId)).trim();
1395
+ if (tail) text = tail;
1396
+ }
1397
+ return settleTask(record, {
1398
+ status: status as 'completed' | 'failed',
1399
+ ...(text !== undefined ? { text } : {}),
1400
+ ...(signal.errorMessage !== undefined ? { error: String(signal.errorMessage) } : {}),
1401
+ });
1402
+ }
1403
+
1404
+ return {
1405
+ async spawn(def, opts) {
1406
+ const label = validateAgentLabel(opts.label);
1407
+ const spawnCwd = opts.cwd ?? cwd;
1408
+ const settings = loadSettings(spawnCwd);
1409
+ // Placement is accepted and ignored: hc terminals have no panes/tabs;
1410
+ // the sheep always starts as a background terminal in the cwd.
1411
+ const _placement: SpawnPlacement | undefined = opts.placement;
1412
+ void _placement;
1413
+ const discovered = discoverAgents(spawnCwd, settings.agentScope, {
1414
+ includeBundled: settings.includeBundledAgents,
1415
+ }).agents;
1416
+ const found = discovered.find(a => a.name === def.name);
1417
+ if (!found) {
1418
+ const available = discovered.map(a => a.name).join(', ');
1419
+ const suggestion = discovered.find(
1420
+ a => a.name.toLowerCase() === def.name.trim().toLowerCase()
1421
+ );
1422
+ throw new Error(
1423
+ `Unknown agent "${def.name}" in ${settings.agentScope} scope.` +
1424
+ (suggestion ? ` Did you mean "${suggestion.name}"?` : '') +
1425
+ (available ? ` Available agents: ${available}.` : ' No agents are available.') +
1426
+ ' Call shepherd with action "agents" to list exact names.'
1427
+ );
1428
+ }
1429
+ if (found.source === 'project' && settings.confirmProjectAgents && context.hasUI) {
1430
+ const ok = await context.ui.confirm(
1431
+ 'Run project-local agent?',
1432
+ `Agent: ${def.name}\nSource: ${found.filePath}`
1433
+ );
1434
+ if (!ok) throw new Error('Project-local agent was not approved.');
1435
+ }
1436
+ const display = formatAgentName(found.name, label);
1437
+ if (
1438
+ label &&
1439
+ [...agents.values()].some(
1440
+ a => formatAgentName(a.handle.agent, a.handle.label) === display
1441
+ )
1442
+ ) {
1443
+ throw new Error(`Duplicate agent label "${display}".`);
1444
+ }
1445
+ const active = ensureBroker(sessionId);
1446
+ const reservedAgentId = mintId('agent', generationId);
1447
+ const childCapability = registerChild(active, reservedAgentId);
1448
+ const delegatedModel = resolveDelegatedModel(found.model, context.model);
1449
+ const delegatedThinking = resolveDelegatedThinking(found.thinking, context.thinkingLevel);
1450
+ let launched: { terminalId: string; dir: string; sessionFile: string; scriptFile: string } | undefined;
1451
+ try {
1452
+ launched = launchPiInHcTerminal(found.name, {
1453
+ name: found.name,
1454
+ label,
1455
+ cwd: spawnCwd,
1456
+ persistent: true,
1457
+ childBroker: { rootDir: active.rootDir, ...childCapability },
1458
+ systemPrompt: found.systemPrompt,
1459
+ omitSystemPrompt: found.omitSystemPrompt,
1460
+ omitPiDocumentation: found.omitPiDocumentation === true,
1461
+ omitContextFiles: found.omitContextFiles === true,
1462
+ model: delegatedModel,
1463
+ thinking: delegatedThinking,
1464
+ tools: found.tools,
1465
+ // Host launch overrides (other hosts boot their own CLI); Pi omits.
1466
+ ...(context.launch?.binary !== undefined ? { binary: context.launch.binary } : {}),
1467
+ ...(context.launch?.extensionEntry !== undefined
1468
+ ? { extensionEntry: context.launch.extensionEntry }
1469
+ : {}),
1470
+ ...(context.launch?.envPrefix !== undefined
1471
+ ? { envPrefix: context.launch.envPrefix }
1472
+ : {}),
1473
+ ...(context.launch?.command !== undefined ? { command: context.launch.command } : {}),
1474
+ });
1475
+ const ready = await waitForHcAgentDetected(launched.terminalId, { timeoutMs: 20_000 });
1476
+ if (!ready.detected) {
1477
+ const output = (await readHcTerminalTail(launched.terminalId)).trim();
1478
+ const suffix = ready.exitCode === undefined ? '' : ` (return code ${ready.exitCode})`;
1479
+ throw Object.assign(
1480
+ new Error(`Agent "${found.name}" did not become ready${suffix}.${output ? `\n${output}` : ''}`),
1481
+ { returnCode: ready.exitCode ?? 1, code: 'agent_not_ready' }
1482
+ );
1483
+ }
1484
+ } catch (error) {
1485
+ if (launched) {
1486
+ try {
1487
+ killHcTerminal(launched.terminalId);
1488
+ } catch {}
1489
+ removeCreatedTerminalDir(launched.terminalId);
1490
+ forgetCreatedTerminal(launched.terminalId);
1491
+ }
1492
+ try {
1493
+ unregisterChild(active, reservedAgentId);
1494
+ } catch {}
1495
+ throw error;
1496
+ }
1497
+ const id = reservedAgentId;
1498
+ const signalPath = `${launched!.sessionFile}.exit`;
1499
+ const baseline = readCompletionSignal(signalPath)?.signalId;
1500
+ agents.set(id, {
1501
+ handle: {
1502
+ id,
1503
+ agent: found.name,
1504
+ label,
1505
+ ...(delegatedModel ? { model: delegatedModel } : {}),
1506
+ terminalId: launched.terminalId,
1507
+ cwd: spawnCwd,
1508
+ },
1509
+ state: 'idle',
1510
+ completionSignalPath: signalPath,
1511
+ completionResultPath: launched.sessionFile,
1512
+ artifactSession: context.artifactSession,
1513
+ childCapability,
1514
+ baselineCompletionSignalId: baseline,
1515
+ });
1516
+ return id;
1517
+ },
1518
+
1519
+ async delegate(agentId, task, opts) {
1520
+ if (typeof task !== 'string' || !task.trim())
1521
+ throw new HcRuntimeError('invalid_task', 'Delegated task description must not be empty.');
1522
+ const agent = canonicalAgent(agentId);
1523
+ if (agent.state === 'closed') {
1524
+ throw new HcRuntimeError('closed_handle', `Agent "${agent.handle.id}" is closed.`);
1525
+ }
1526
+ if (!agent.handle.terminalId) throw new Error('Agent handle has no terminal.');
1527
+ const detected = await waitForHcAgentDetected(agent.handle.terminalId, { timeoutMs: 15_000 });
1528
+ if (!detected.detected) throw new Error(`Agent "${agent.handle.id}" is not detected.`);
1529
+ if (agent.activeTaskId) {
1530
+ throw new HcRuntimeError(
1531
+ 'active_task',
1532
+ `Agent "${agent.handle.id}" already has an active tracked task (${agent.activeTaskId}).`
1533
+ );
1534
+ }
1535
+ const active = ensureBroker(sessionId);
1536
+ if (!agent.childCapability) {
1537
+ agent.childCapability = registerChild(active, agent.handle.id);
1538
+ }
1539
+ const createdAt = Date.now();
1540
+ const id = mintId('task', generationId);
1541
+ const deadlineAt =
1542
+ opts.timeoutMin !== undefined ? createdAt + opts.timeoutMin * 60_000 : undefined;
1543
+ if (deadlineAt !== undefined && !Number.isFinite(deadlineAt)) {
1544
+ throw new HcRuntimeError('invalid_task', 'Task timeout must be a finite number.');
1545
+ }
1546
+ // `requestId` has no mailbox dedup equivalent: a retried submit is a
1547
+ // second call by design here.
1548
+ void opts.requestId;
1549
+ const record: TaskRecord = {
1550
+ taskId: id,
1551
+ agentId: agent.handle.id,
1552
+ description: task.trim(),
1553
+ state: 'created',
1554
+ createdAt,
1555
+ ...(deadlineAt !== undefined ? { deadlineAt } : {}),
1556
+ pendingRequestIds: new Set(),
1557
+ artifactSession: context.artifactSession ?? agent.artifactSession,
1558
+ };
1559
+ tasks.set(id, record);
1560
+ // 011: the background poll covers this session while work is open.
1561
+ registerHcPollSession(sessionId);
1562
+ agent.activeTaskId = id;
1563
+ agent.baselineCompletionSignalId = agent.completionSignalPath
1564
+ ? (readCompletionSignal(agent.completionSignalPath)?.signalId ??
1565
+ agent.baselineCompletionSignalId)
1566
+ : undefined;
1567
+ if (deadlineAt !== undefined) {
1568
+ const delay = Math.max(0, deadlineAt - Date.now());
1569
+ record.timeoutId = setTimeout(() => {
1570
+ // Drain-first: a `task_done` already queued in the parent inbox
1571
+ // wins over the bare deadline (mirrors the `watch`-loop
1572
+ // drain-then-check order; 010 §3). A genuinely late done still
1573
+ // loses: `settleTask` on an already-terminal record is a no-op.
1574
+ drainBrokerInbox();
1575
+ if (!record.result) {
1576
+ settleTask(record, { status: 'timed_out', error: 'Tracked task deadline reached.' });
1577
+ }
1578
+ }, delay);
1579
+ (record.timeoutId as any).unref?.();
1580
+ }
1581
+ const session = record.artifactSession;
1582
+ try {
1583
+ if (session) {
1584
+ const artifact = reserveArtifacts(session, [
1585
+ { agent: agent.handle.agent, mode: 'single', task },
1586
+ ])[0];
1587
+ markArtifactStarted(session, artifact, { taskId: id, agentId: agent.handle.id });
1588
+ record.artifactSession = session;
1589
+ record.artifact = artifact;
1590
+ record.onSettled = result => finalizeTaskArtifact(record, result);
1591
+ }
1592
+ const envelope = createEnvelope(
1593
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.parentId },
1594
+ {
1595
+ kind: 'task',
1596
+ targetId: agent.handle.id,
1597
+ taskId: id,
1598
+ delivery: 'followUp',
1599
+ content: task,
1600
+ }
1601
+ );
1602
+ publishFromParent(active, envelope);
1603
+ record.state = 'running';
1604
+ return id;
1605
+ } catch (error) {
1606
+ settleTask(
1607
+ record,
1608
+ {
1609
+ status: 'failed',
1610
+ error: String((error as any)?.message ?? error),
1611
+ },
1612
+ { source: 'delegate-submission-failure' }
1613
+ );
1614
+ throw new Error(`Task submission failed: ${String((error as any)?.message ?? error)}`);
1615
+ }
1616
+ },
1617
+
1618
+ async message(target, msg, opts): Promise<MessageId> {
1619
+ if (typeof msg !== 'string' || !msg.trim()) {
1620
+ throw new HcRuntimeError('invalid_task', 'Message content must not be empty.');
1621
+ }
1622
+ if (target === 'parent') {
1623
+ throw new HcRuntimeError(
1624
+ 'invalid_handle',
1625
+ 'hc runtime adapter cannot address "parent": child-to-parent messages use the child broker surface.'
1626
+ );
1627
+ }
1628
+ const active = ensureBroker(sessionId);
1629
+ let agent: AgentRecord;
1630
+ try {
1631
+ agent = canonicalAgent(target);
1632
+ } catch (error) {
1633
+ if (error instanceof HcRuntimeError && error.code === 'unknown_handle') {
1634
+ throw new HcRuntimeError(
1635
+ 'invalid_target',
1636
+ `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 terminal address, or a placeholder such as "<planner agent ID>".`
1637
+ );
1638
+ }
1639
+ throw error;
1640
+ }
1641
+ if (agent.state === 'closed') {
1642
+ throw new HcRuntimeError('closed_handle', `Agent "${agent.handle.id}" is closed.`);
1643
+ }
1644
+ // Fresh correlation before routing: a reply that already landed
1645
+ // resolves the wait here instead of leaving `status` stale.
1646
+ drainBrokerInbox();
1647
+ settleDueReplyTimeouts();
1648
+ // Correlated traffic goes through the mailbox so request/task state
1649
+ // matches the pane-based backend exactly.
1650
+ if (opts.taskId) {
1651
+ const record = taskRecord(opts.taskId);
1652
+ if (record.agentId !== agent.handle.id) {
1653
+ throw new HcRuntimeError(
1654
+ 'task_agent_mismatch',
1655
+ `Task "${opts.taskId}" is owned by another agent than the message target.`
1656
+ );
1657
+ }
1658
+ if (opts.expectsReply) {
1659
+ const replyDeadline =
1660
+ Date.now() + loadSettings(agent.handle.cwd ?? cwd).timeout * 60_000;
1661
+ const provisional = createEnvelope(
1662
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.parentId },
1663
+ {
1664
+ kind: 'message',
1665
+ targetId: agent.handle.id,
1666
+ messageId: mintMessageId(),
1667
+ taskId: opts.taskId,
1668
+ threadId: opts.threadId,
1669
+ replyTo: opts.replyTo,
1670
+ expectsReply: true,
1671
+ delivery: opts.delivery === 'followUp' ? 'followUp' : 'steer',
1672
+ content: msg,
1673
+ createdAt: Date.now(),
1674
+ }
1675
+ );
1676
+ openPendingRequest(record, {
1677
+ messageId: provisional.messageId,
1678
+ targetAgentId: agent.handle.id,
1679
+ deadlineAt: replyDeadline,
1680
+ text: msg,
1681
+ });
1682
+ try {
1683
+ const accepted = publishFromParent(active, provisional);
1684
+ return accepted.messageId;
1685
+ } catch (error) {
1686
+ try {
1687
+ resolveReplyForTask(record, provisional.messageId);
1688
+ } catch {}
1689
+ throw error;
1690
+ }
1691
+ }
1692
+ const envelope = createEnvelope(
1693
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.parentId },
1694
+ {
1695
+ kind: opts.replyTo ? 'reply' : 'message',
1696
+ targetId: agent.handle.id,
1697
+ messageId: mintMessageId(),
1698
+ taskId: opts.taskId,
1699
+ threadId: opts.threadId,
1700
+ replyTo: opts.replyTo,
1701
+ delivery: opts.delivery === 'followUp' ? 'followUp' : 'steer',
1702
+ content: msg,
1703
+ }
1704
+ );
1705
+ const accepted = publishFromParent(active, envelope);
1706
+ if (opts.replyTo) {
1707
+ try {
1708
+ resolveReplyForTask(record, opts.replyTo);
1709
+ } catch {
1710
+ /* non-tracked replies stay deliverable as ordinary correlation */
1711
+ }
1712
+ }
1713
+ return accepted.messageId;
1714
+ }
1715
+ if (opts.replyTo) {
1716
+ const envelope = createEnvelope(
1717
+ { sessionId: active.sessionId, brokerId: active.brokerId, senderId: active.parentId },
1718
+ {
1719
+ kind: 'reply',
1720
+ targetId: agent.handle.id,
1721
+ messageId: mintMessageId(),
1722
+ threadId: opts.threadId,
1723
+ replyTo: opts.replyTo,
1724
+ delivery: opts.delivery === 'followUp' ? 'followUp' : 'steer',
1725
+ content: msg,
1726
+ }
1727
+ );
1728
+ const accepted = publishFromParent(active, envelope);
1729
+ return accepted.messageId;
1730
+ }
1731
+ // Untracked text goes straight to the terminal (paste + Enter), the
1732
+ // analogue of a native prompt poke. A fresh id is minted for the
1733
+ // receipt; there is no mailbox correlation to resolve later.
1734
+ if (!agent.handle.terminalId) throw new Error('Agent handle has no terminal.');
1735
+ const messageId = mintMessageId();
1736
+ try {
1737
+ await hcExec(
1738
+ opts.delivery === 'followUp'
1739
+ ? ['send', agent.handle.terminalId, msg, '--json']
1740
+ : ['send', agent.handle.terminalId, msg, '--force', '--json']
1741
+ );
1742
+ } catch (error) {
1743
+ throw new Error(
1744
+ `Message send failed: ${error instanceof HcError ? `${error.kind}: ${error.message}` : String((error as any)?.message ?? error)}`
1745
+ );
1746
+ }
1747
+ return messageId;
1748
+ },
1749
+
1750
+ async watch(taskIds) {
1751
+ const values = Array.isArray(taskIds) ? taskIds : [taskIds];
1752
+ if (values.length === 0)
1753
+ throw new HcRuntimeError('invalid_handle', 'Expected one or more opaque task ids to watch.');
1754
+ const ids = values.map(value => taskRecord(value).taskId);
1755
+ if (new Set(ids).size !== ids.length) {
1756
+ throw new HcRuntimeError('invalid_handle', 'A wait cannot contain duplicate task ids.');
1757
+ }
1758
+ const overallTimeoutMs = 1_200_000;
1759
+ const deadline = Date.now() + overallTimeoutMs;
1760
+ for (;;) {
1761
+ drainBrokerInbox();
1762
+ const now = Date.now();
1763
+ for (const id of ids) {
1764
+ const record = tasks.get(id)!;
1765
+ if (record.result) continue;
1766
+ if (record.deadlineAt !== undefined && now >= record.deadlineAt) {
1767
+ settleTask(record, { status: 'timed_out', error: 'Tracked task deadline reached.' });
1768
+ continue;
1769
+ }
1770
+ if (
1771
+ record.state === 'waiting' &&
1772
+ record.pendingReplyDeadlineAt !== undefined &&
1773
+ now >= record.pendingReplyDeadlineAt
1774
+ ) {
1775
+ settleTask(record, {
1776
+ status: 'blocked',
1777
+ ok: false,
1778
+ text: `Timed out waiting for a reply from ${record.pendingReplyTargetAgentId ?? 'the target agent'} (message ${record.pendingReplyMessageId ?? 'unknown'} never answered).`,
1779
+ error: 'Tracked reply deadline reached.',
1780
+ });
1781
+ continue;
1782
+ }
1783
+ const settled = await settleFromSignal(record);
1784
+ if (settled) continue;
1785
+ const agent = agents.get(record.agentId);
1786
+ if (agent?.handle.terminalId) {
1787
+ const { live } = await terminalState(agent.handle.terminalId);
1788
+ if (!live) {
1789
+ const retry = await settleFromSignal(record);
1790
+ if (!retry) {
1791
+ settleTask(record, {
1792
+ status: 'failed',
1793
+ error: 'Agent terminal ended before the task completed.',
1794
+ });
1795
+ }
1796
+ }
1797
+ }
1798
+ }
1799
+ if (ids.every(id => tasks.get(id)?.result)) break;
1800
+ if (Date.now() >= deadline) {
1801
+ const pending = ids.filter(id => !tasks.get(id)?.result);
1802
+ throw new HcRuntimeError(
1803
+ 'timeout',
1804
+ `Timed out after 20 minutes waiting for ${pending.length} unsettled task${pending.length === 1 ? '' : 's'}. The tasks keep running; watch them later with shepherd_watch.`
1805
+ );
1806
+ }
1807
+ // Idle efficiently on the first unsettled terminal; a check-in (or a
1808
+ // finished terminal, which returns at once) simply re-runs the drain.
1809
+ const firstOpen = ids.map(id => tasks.get(id)!).find(r => !r.result);
1810
+ const terminalId = firstOpen ? agents.get(firstOpen.agentId)?.handle.terminalId : undefined;
1811
+ if (terminalId) {
1812
+ try {
1813
+ await hcExec(['wait', terminalId, '--timeout', '3', '--json']);
1814
+ } catch {
1815
+ await new Promise(r => setTimeout(r, 1000));
1816
+ }
1817
+ } else {
1818
+ await new Promise(r => setTimeout(r, 500));
1819
+ }
1820
+ }
1821
+ return ids.map(id => toCompletion(tasks.get(id)!.result!));
1822
+ },
1823
+
1824
+ async status(agentId) {
1825
+ const agent = canonicalAgent(agentId);
1826
+ drainBrokerInbox();
1827
+ settleDueReplyTimeouts();
1828
+ let proc: RuntimeProcState = 'unknown';
1829
+ if (agent.state === 'closed') {
1830
+ proc = 'unknown';
1831
+ } else if (agent.handle.terminalId) {
1832
+ proc = toProcState((await terminalState(agent.handle.terminalId)).agentState);
1833
+ }
1834
+ const record = agent.activeTaskId ? tasks.get(agent.activeTaskId) : undefined;
1835
+ const open = record && !record.result ? record : undefined;
1836
+ return {
1837
+ proc,
1838
+ task: open ? toTaskState(open.state) : 'done',
1839
+ ...(open?.pendingReplyMessageId ? { waitingOn: open.pendingReplyMessageId } : {}),
1840
+ ...(open?.staleNotifiedAt !== undefined ? { stale: true } : {}),
1841
+ } as RuntimeStatus;
1842
+ },
1843
+
1844
+ async close(agentId) {
1845
+ const agent = canonicalAgent(agentId);
1846
+ const record = agents.get(agent.handle.id)!;
1847
+ if (
1848
+ !record.handle.terminalId ||
1849
+ !loadCreatedTerminals().some(t => t.terminalId === record.handle.terminalId)
1850
+ )
1851
+ throw new Error('Refusing to close an unowned terminal.');
1852
+ const terminalId = record.handle.terminalId;
1853
+ if (record.activeTaskId) {
1854
+ const task = tasks.get(record.activeTaskId);
1855
+ if (task && !task.result) {
1856
+ settleTask(task, { status: 'cancelled', error: 'Agent was closed.' });
1857
+ }
1858
+ record.activeTaskId = undefined;
1859
+ }
1860
+ record.state = 'closed';
1861
+ const active = ensureBroker(sessionId);
1862
+ try {
1863
+ unregisterChild(active, record.handle.id);
1864
+ } catch {
1865
+ /* best effort */
1866
+ }
1867
+ try {
1868
+ killHcTerminal(terminalId);
1869
+ } catch {
1870
+ throw new Error('Could not close agent terminal.');
1871
+ }
1872
+ removeCreatedTerminalDir(terminalId);
1873
+ forgetCreatedTerminal(terminalId);
1874
+ },
1875
+
1876
+ async read(agentId, opts) {
1877
+ const agent = canonicalAgent(agentId);
1878
+ if (!agent.handle.terminalId) {
1879
+ throw new HcRuntimeError(
1880
+ 'unknown_handle',
1881
+ `Agent "${agent.handle.id}" has no terminal to read.`
1882
+ );
1883
+ }
1884
+ const tail = await readHcTerminalTail(agent.handle.terminalId);
1885
+ const limit = opts?.lines;
1886
+ if (limit === undefined || !Number.isFinite(limit) || limit <= 0) return tail;
1887
+ const count = Math.trunc(limit);
1888
+ if (count <= 0) return '';
1889
+ const lines = tail.split('\n');
1890
+ while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
1891
+ return lines.slice(-count).join('\n');
1892
+ },
1893
+ };
1894
+ }
1895
+
1896
+ // Re-export the context type for resolver wiring (Phase 1.2) without
1897
+ // reaching into this module's closure.
1898
+ export type { AgentHandle, TaskId };