@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,1583 @@
1
+ /** Low-level agent lifecycle handles and session-scoped registries. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import type { ArtifactReservation, ShepherdSession } from '../../core/artifact-sessions.ts';
4
+ import { mintId, normalizeHandleId, type IdKind } from '../../core/ids.ts';
5
+ import type { ChildCapability } from './messaging.ts';
6
+
7
+ export type AgentLifecycleState =
8
+ 'idle' | 'working' | 'blocked' | 'done' | 'unknown' | 'failed' | 'closed';
9
+
10
+ export type PromptResultStatus = 'idle' | 'done' | 'blocked' | 'failed' | 'timeout' | 'cancelled';
11
+
12
+ export interface AgentHandle {
13
+ id: string;
14
+ agent: string;
15
+ label: string;
16
+ /** Provider-qualified model actually selected for the child, when known. */
17
+ model?: string;
18
+ paneId?: string;
19
+ tabId?: string;
20
+ workspaceId?: string;
21
+ /** Workspace cwd owning this agent; used for settings resolution. */
22
+ cwd?: string;
23
+ }
24
+
25
+ /**
26
+ * The model-facing tools use opaque ids. The registry still accepts full
27
+ * internal handles for implementation callers and maintains the complete
28
+ * object behind each id.
29
+ */
30
+ /** Public lifecycle calls use the opaque id; internal callers may still hold the full handle. */
31
+ export type AgentHandleInput = AgentHandle | string;
32
+
33
+ export function formatAgentName(agent: string, label?: string): string {
34
+ const trimmed = label?.trim() ?? '';
35
+ return trimmed ? `${agent}: ${trimmed}` : agent;
36
+ }
37
+
38
+ export function validateAgentLabel(value: unknown): string {
39
+ if (value == null) return '';
40
+ if (typeof value !== 'string') throw new Error('Agent label must be a string.');
41
+ const label = value.trim();
42
+ if (!label) return '';
43
+ if (label.length > 64) throw new Error('Agent label must be at most 64 characters.');
44
+ if (!/^[\p{L}\p{N} _.-]+$/u.test(label) || label.includes(':'))
45
+ throw new Error(
46
+ 'Agent label may contain only letters, numbers, spaces, _, -, and .; colons and control characters are not allowed.'
47
+ );
48
+ return label;
49
+ }
50
+
51
+ export interface PromptHandle {
52
+ id: string;
53
+ agentId: string;
54
+ createdAt: number;
55
+ }
56
+
57
+ /** Public lifecycle calls use the opaque id; internal callers may still hold the full handle. */
58
+ export type PromptHandleInput = PromptHandle | string;
59
+
60
+ export type TaskState =
61
+ | 'created'
62
+ | 'running'
63
+ | 'waiting'
64
+ | 'completed'
65
+ | 'blocked'
66
+ | 'failed'
67
+ | 'cancelled'
68
+ | 'timed_out';
69
+
70
+ export type TaskResultStatus = 'completed' | 'blocked' | 'failed' | 'cancelled' | 'timed_out';
71
+
72
+ export interface TaskHandle {
73
+ id: string;
74
+ agentId: string;
75
+ createdAt: number;
76
+ }
77
+
78
+ /** Public lifecycle calls use the opaque task id; internal callers may hold the handle. */
79
+ export type TaskHandleInput = TaskHandle | string;
80
+
81
+ export interface TaskResult {
82
+ taskId: string;
83
+ agentId: string;
84
+ status: TaskResultStatus;
85
+ ok: boolean;
86
+ /** Stable process-style outcome: 0 success, 1 failure, 2 blocked, 124 timeout, 130 cancelled. */
87
+ returnCode: number;
88
+ text?: string;
89
+ error?: string;
90
+ completedAt: number;
91
+ artifact?: ArtifactReservation;
92
+ artifactSession?: ShepherdSession;
93
+ }
94
+
95
+ export interface TaskRecord {
96
+ taskId: string;
97
+ agentId: string;
98
+ description: string;
99
+ state: TaskState;
100
+ createdAt: number;
101
+ startedAt?: number;
102
+ waitingSince?: number;
103
+ deadlineAt?: number;
104
+ /**
105
+ * Correlation state for the task's single outstanding tracked reply.
106
+ *
107
+ * The Phase 6 initial policy allows exactly one outstanding request per task
108
+ * (the spec permits restricting a task to one outstanding request). This
109
+ * keeps reply correlation deterministic: the reply's `replyTo` must match
110
+ * `pendingReplyMessageId`. The request opens when the child (or parent,
111
+ * for a parent-originated question) sends an `expectsReply` message and is
112
+ * resolved on a matching reply, an explicit cancellation, close, or timeout.
113
+ */
114
+ pendingReplyMessageId?: string;
115
+ pendingReplyTargetAgentId?: string;
116
+ pendingReplyDeadlineAt?: number;
117
+ pendingReplyText?: string;
118
+ pendingRequestIds: string[];
119
+ staleNotifiedAt?: number;
120
+ artifactSession?: ShepherdSession;
121
+ /** Workspace cwd owning this task. */
122
+ cwd?: string;
123
+ artifact?: ArtifactReservation;
124
+ result?: TaskResult;
125
+ }
126
+
127
+ export interface TaskSettlement {
128
+ status: TaskResultStatus;
129
+ ok?: boolean;
130
+ returnCode?: number;
131
+ text?: string;
132
+ error?: string;
133
+ completedAt?: number;
134
+ }
135
+
136
+ /** Internal source tags for settlements that are not unseen-at-source. */
137
+ export type TaskSettlementSource = 'delegate-submission-failure';
138
+
139
+ /**
140
+ * Context attached to each registry settlement observation.
141
+ *
142
+ * `hadWatchers` is true only when at least one task-watcher callback was
143
+ * actually invoked for this settlement. `agent`/`label` come from the settled
144
+ * agent's handle. `source` marks settlements callers must not treat as unseen
145
+ * completions (a delegate submission failure is already reported in the
146
+ * `shepherd_delegate` tool result).
147
+ */
148
+ export interface TaskSettlementContext {
149
+ hadWatchers: boolean;
150
+ agent?: string;
151
+ label?: string;
152
+ source?: TaskSettlementSource;
153
+ }
154
+
155
+ /** One registry settlement observation; see {@link LifecycleRegistry.onTaskSettled}. */
156
+ export type TaskSettledListener = (result: TaskResult, context: TaskSettlementContext) => void;
157
+
158
+ /** Internal settle options; only the delegate failure path passes `source`. */
159
+ export interface SettleTaskOptions {
160
+ source?: TaskSettlementSource;
161
+ }
162
+
163
+ export interface CreateTaskOptions {
164
+ timeoutMs?: number;
165
+ deadlineAt?: number;
166
+ artifactSession?: ShepherdSession;
167
+ }
168
+
169
+ /** Public, task-scoped view of an agent's active tracked task. */
170
+ export interface AgentTaskStatus {
171
+ id: string;
172
+ state: TaskState;
173
+ description: string;
174
+ /** Milliseconds the task has been waiting on its required reply. */
175
+ waitingMs?: number;
176
+ waitingSince?: number;
177
+ /** Id of the pending request (message) the task is waiting on. */
178
+ pendingRequestMessageId?: string;
179
+ /** Display name of the agent the reply is expected from. */
180
+ waitingRecipient?: string;
181
+ /** True when the stale-wait monitor has already reminded for this episode. */
182
+ stale?: boolean;
183
+ }
184
+
185
+ export interface AgentStatus {
186
+ handle: AgentHandle;
187
+ /** The owning process/agent's lifecycle state (idle/working/blocked/done/failed/closed). */
188
+ state: AgentLifecycleState;
189
+ /** The agent's active tracked task, if one is still open. Independent of `state`. */
190
+ task?: AgentTaskStatus;
191
+ paneId?: string;
192
+ tabId?: string;
193
+ workspaceId?: string;
194
+ error?: string;
195
+ }
196
+
197
+ export interface PromptResult {
198
+ promptId: string;
199
+ agentId: string;
200
+ status: PromptResultStatus;
201
+ ok: boolean;
202
+ /** Stable process-style outcome: 0 success, 1 failure, 2 blocked, 124 timeout, 130 cancelled. */
203
+ returnCode?: number;
204
+ text?: string;
205
+ error?: string;
206
+ artifact?: ArtifactReservation;
207
+ artifactSession?: ShepherdSession;
208
+ }
209
+
210
+ /** A prompt completion enriched with the persistent agent's display identity. */
211
+ export interface WatcherCompletion extends PromptResult {
212
+ agent?: string;
213
+ label?: string;
214
+ }
215
+
216
+ /** A task completion enriched with the owning agent's display identity. */
217
+ export interface TaskWatcherCompletion extends TaskResult {
218
+ agent?: string;
219
+ label?: string;
220
+ }
221
+
222
+ export interface TaskWatcherRegistration {
223
+ watcherId: string;
224
+ taskIds: string[];
225
+ pending: string[];
226
+ completed: TaskResult[];
227
+ }
228
+
229
+ /**
230
+ * A watcher notification payload. Completions are heterogeneous: task
231
+ * completions (Phase 7 and later) and legacy prompt completions (watchers that
232
+ * were registered with prompt ids) are not mixed in a single notification.
233
+ */
234
+ export interface TaskWatcherNotification {
235
+ watcherId: string;
236
+ completions: TaskResult[];
237
+ }
238
+
239
+ export type TaskWatcherCallback = (completion: TaskWatcherCompletion) => void;
240
+
241
+ export interface WatcherRegistration {
242
+ watcherId: string;
243
+ /** Task ids in this watcher; empty for purely prompt-based watchers. */
244
+ taskIds: string[];
245
+ promptIds: string[];
246
+ pending: string[];
247
+ completed: PromptResult[];
248
+ }
249
+
250
+ export interface WatcherNotification {
251
+ watcherId: string;
252
+ completions: WatcherCompletion[];
253
+ }
254
+
255
+ export type PromptWatcherCallback = (completion: WatcherCompletion) => void;
256
+
257
+ export class LifecycleError extends Error {
258
+ readonly code:
259
+ | 'unknown_handle'
260
+ | 'closed_handle'
261
+ | 'active_prompt'
262
+ | 'active_task'
263
+ | 'unknown_task'
264
+ | 'task_agent_mismatch'
265
+ | 'invalid_handle'
266
+ | 'invalid_task'
267
+ | 'invalid_transition'
268
+ | 'timeout';
269
+ constructor(code: LifecycleError['code'], message: string) {
270
+ super(message);
271
+ this.name = 'LifecycleError';
272
+ this.code = code;
273
+ }
274
+ }
275
+
276
+ interface AgentRecord {
277
+ /** Internal registry generation; records from another pi session are stale. */
278
+ lifecycleSessionId: string;
279
+ handle: AgentHandle;
280
+ /** Completion sidecar emitted by the child for each completed prompt. */
281
+ completionSignalPath?: string;
282
+ /** Child JSONL session file; the full last answer is read from it on completion. */
283
+ completionResultPath?: string;
284
+ /** Durable fieldnotes session owned by the parent pi session. */
285
+ artifactSession?: ShepherdSession;
286
+ state: AgentLifecycleState;
287
+ activePromptId?: string;
288
+ /** One active tracked task is reserved independently of prompt records. */
289
+ activeTaskId?: string;
290
+ /** Parent broker capability used to launch and route this child. */
291
+ childCapability?: ChildCapability;
292
+ error?: string;
293
+ }
294
+
295
+ interface TaskRecordInternal extends Omit<TaskRecord, 'pendingRequestIds'> {
296
+ /** Internal registry generation; records from another pi session are stale. */
297
+ lifecycleSessionId: string;
298
+ pendingRequestIds: Set<string>;
299
+ settled: boolean;
300
+ onSettled?: (result: TaskResult) => void;
301
+ timeoutId?: ReturnType<typeof setTimeout>;
302
+ }
303
+
304
+ interface PromptRecord {
305
+ /** Internal registry generation; records from another pi session are stale. */
306
+ lifecycleSessionId: string;
307
+ handle: PromptHandle;
308
+ artifactSession?: ShepherdSession;
309
+ artifact?: ArtifactReservation;
310
+ onSettled?: (result: PromptResult) => void;
311
+ /** Herdr state sequence before submission; prevents matching pre-submit idle. */
312
+ baselineStateChangeSeq?: number;
313
+ /** Completion sidecar signal before submission; detects fast completions. */
314
+ baselineCompletionSignalId?: string;
315
+ observedWorking: boolean;
316
+ result?: PromptResult;
317
+ settled: boolean;
318
+ resolve: (result: PromptResult) => void;
319
+ promise: Promise<PromptResult>;
320
+ /** Active timeout handle from waitPrompts; cleared on settle. */
321
+ timeoutId?: ReturnType<typeof setTimeout>;
322
+ }
323
+
324
+ /**
325
+ * In-memory registry for the extension process. Public ids are opaque and
326
+ * include a random component; records are additionally scoped to the active
327
+ * parent pi session so callers never need to know Herdr pane ids.
328
+ */
329
+ function handleId(input: unknown, kind: 'AgentHandle' | 'PromptHandle'): string {
330
+ const normalized = normalizeHandleId(input, kind);
331
+ if (!normalized.ok) throw new LifecycleError('invalid_handle', normalized.message);
332
+ return normalized.id;
333
+ }
334
+
335
+ function taskHandleId(input: unknown): string {
336
+ const normalized = normalizeHandleId(input, 'TaskHandle');
337
+ if (!normalized.ok) throw new LifecycleError('invalid_handle', normalized.message);
338
+ return normalized.id;
339
+ }
340
+
341
+ export class LifecycleRegistry {
342
+ /** Opaque id namespace for the currently active parent pi session. */
343
+ private sessionId = randomUUID().slice(0, 8);
344
+ /** Real pi session identity used to make repeated session_start idempotent. */
345
+ private parentSessionId?: string;
346
+ private readonly agents = new Map<string, AgentRecord>();
347
+ /** Reserved spawn ids are tied to the generation that allocated them. */
348
+ private readonly allocatedAgentSessions = new Map<string, string>();
349
+ private readonly prompts = new Map<string, PromptRecord>();
350
+ private readonly tasks = new Map<string, TaskRecordInternal>();
351
+ private readonly watchers = new Map<
352
+ string,
353
+ {
354
+ kind: 'prompt' | 'task';
355
+ promptIds: string[];
356
+ taskIds: string[];
357
+ pending: Set<string>;
358
+ callback?: PromptWatcherCallback;
359
+ delivered: Set<string>;
360
+ }
361
+ >();
362
+ private readonly promptWatchers = new Map<string, Set<string>>();
363
+ private readonly taskWatchers = new Map<string, Set<string>>();
364
+ private readonly settlementListeners = new Set<TaskSettledListener>();
365
+
366
+ private id(kind: IdKind): string {
367
+ return mintId(kind, this.sessionId);
368
+ }
369
+
370
+ /**
371
+ * Registry contract: observe settlements that reach a terminal task state.
372
+ *
373
+ * The listener fires once per actual transition, after the task-watcher
374
+ * fan-out, with a shallow copy of the result and a fresh context. Listener
375
+ * failures are swallowed and can never affect settlement; with no listener
376
+ * subscribed, `settleTask` behaves exactly as before. Legacy prompt
377
+ * settlements are not observed. Any replacement runtime (spec 006,
378
+ * Phase 1+) must expose this hook with the same semantics.
379
+ */
380
+ onTaskSettled(listener: TaskSettledListener): () => void {
381
+ this.settlementListeners.add(listener);
382
+ return () => {
383
+ this.settlementListeners.delete(listener);
384
+ };
385
+ }
386
+
387
+ /**
388
+ * Start (or re-enter) a parent pi session.
389
+ *
390
+ * The extension module can remain loaded while pi switches sessions, so the
391
+ * in-memory registry must advance its opaque-id namespace explicitly. Old
392
+ * records remain in memory so late callbacks can be recognized and ignored,
393
+ * but all public lookups and projections treat them as retired.
394
+ *
395
+ * A missing identity is deliberately a no-op: without a session id we
396
+ * cannot distinguish a repeated event for the same session from a switch.
397
+ */
398
+ beginSession(parentSessionId?: string): void {
399
+ const normalized = parentSessionId?.trim();
400
+ if (!normalized || normalized === this.parentSessionId) return;
401
+ this.parentSessionId = normalized;
402
+ this.sessionId = randomUUID().slice(0, 8);
403
+ this.clearWatchers();
404
+ }
405
+
406
+ private isCurrent(record: { lifecycleSessionId: string }): boolean {
407
+ return record.lifecycleSessionId === this.sessionId;
408
+ }
409
+
410
+ /** Reserve an opaque agent id before a child process is launched. */
411
+ allocateAgentId(): string {
412
+ const id = this.id('agent');
413
+ this.allocatedAgentSessions.set(id, this.sessionId);
414
+ return id;
415
+ }
416
+
417
+ registerAgent(
418
+ input: Omit<AgentHandle, 'id'> & { id?: string },
419
+ metadata: {
420
+ completionSignalPath?: string;
421
+ completionResultPath?: string;
422
+ artifactSession?: ShepherdSession;
423
+ childCapability?: ChildCapability;
424
+ } = {}
425
+ ): AgentHandle {
426
+ const label = validateAgentLabel(input.label);
427
+ const display = formatAgentName(input.agent, label);
428
+ if (
429
+ label &&
430
+ [...this.agents.values()].some(
431
+ a => this.isCurrent(a) && formatAgentName(a.handle.agent, a.handle.label) === display
432
+ )
433
+ )
434
+ throw new Error(`Duplicate agent label "${display}".`);
435
+ const requestedId = input.id;
436
+ if (requestedId !== undefined && (typeof requestedId !== 'string' || !requestedId.trim())) {
437
+ throw new LifecycleError(
438
+ 'invalid_handle',
439
+ 'Agent id must be a non-empty opaque string when supplied internally.'
440
+ );
441
+ }
442
+ if (requestedId) {
443
+ const allocatedSession = this.allocatedAgentSessions.get(requestedId);
444
+ if (allocatedSession && allocatedSession !== this.sessionId) {
445
+ throw new LifecycleError(
446
+ 'invalid_handle',
447
+ `Agent id "${requestedId}" belongs to a retired parent session.`
448
+ );
449
+ }
450
+ }
451
+ if (requestedId && this.agents.has(requestedId)) {
452
+ throw new LifecycleError(
453
+ 'invalid_handle',
454
+ `Agent id "${requestedId}" is already registered.`
455
+ );
456
+ }
457
+ const handle = { ...input, label, id: requestedId ?? this.id('agent') };
458
+ if (requestedId) this.allocatedAgentSessions.delete(requestedId);
459
+ this.agents.set(handle.id, {
460
+ lifecycleSessionId: this.sessionId,
461
+ handle,
462
+ completionSignalPath: metadata.completionSignalPath,
463
+ completionResultPath: metadata.completionResultPath,
464
+ artifactSession: metadata.artifactSession,
465
+ childCapability: metadata.childCapability,
466
+ state: 'idle',
467
+ });
468
+ return { ...handle };
469
+ }
470
+
471
+ getAgent(input: AgentHandleInput | unknown): AgentRecord {
472
+ const id = handleId(input, 'AgentHandle');
473
+ const record = this.agents.get(id);
474
+ if (!record || !this.isCurrent(record))
475
+ throw new LifecycleError(
476
+ 'unknown_handle',
477
+ `Unknown agent id "${id}". Lifecycle ids are scoped to this parent session; use the id from the latest spawn result. A Herdr pane id is not an agent id.`
478
+ );
479
+ return record;
480
+ }
481
+
482
+ canonicalAgentHandle(input: AgentHandleInput | unknown): AgentHandle {
483
+ return { ...this.getAgent(input).handle };
484
+ }
485
+
486
+ attachAgentChildCapability(handle: AgentHandleInput, capability: ChildCapability): void {
487
+ this.getAgent(handle).childCapability = { ...capability };
488
+ }
489
+
490
+ agentChildCapability(handle: AgentHandleInput): ChildCapability | undefined {
491
+ const capability = this.getAgent(handle).childCapability;
492
+ return capability ? { ...capability } : undefined;
493
+ }
494
+
495
+ status(handle: AgentHandleInput, state?: AgentLifecycleState, error?: string): AgentStatus {
496
+ const record = this.getAgent(handle);
497
+ if (state) record.state = state;
498
+ if (error) record.error = error;
499
+ const task = this.taskStatusForAgent(record);
500
+ return {
501
+ handle: { ...record.handle },
502
+ state: record.state,
503
+ ...(task ? { task } : {}),
504
+ ...(record.error ? { error: record.error } : {}),
505
+ };
506
+ }
507
+
508
+ /**
509
+ * The agent's active tracked task as a public status view, or undefined when
510
+ * the agent owns no open task. Independent of the process/agent state: an
511
+ * idle process can own a `waiting` task and a working process a `running` one.
512
+ */
513
+ taskStatusForAgent(record: AgentRecord): AgentTaskStatus | undefined {
514
+ if (!record.activeTaskId) return undefined;
515
+ const task = this.tasks.get(record.activeTaskId);
516
+ if (!task || !this.isCurrent(task) || task.settled) return undefined;
517
+ const waiting = task.state === 'waiting' ? task.waitingSince : undefined;
518
+ let waitingRecipient: string | undefined;
519
+ if (task.pendingReplyTargetAgentId) {
520
+ try {
521
+ const recipient = this.agents.get(task.pendingReplyTargetAgentId);
522
+ waitingRecipient =
523
+ recipient && this.isCurrent(recipient)
524
+ ? formatAgentName(recipient.handle.agent, recipient.handle.label)
525
+ : task.pendingReplyTargetAgentId;
526
+ } catch {
527
+ waitingRecipient = task.pendingReplyTargetAgentId;
528
+ }
529
+ }
530
+ return {
531
+ id: task.taskId,
532
+ state: task.state,
533
+ description: task.description,
534
+ ...(waiting !== undefined
535
+ ? { waitingSince: waiting, waitingMs: Math.max(0, Date.now() - waiting) }
536
+ : {}),
537
+ ...(task.pendingReplyMessageId
538
+ ? { pendingRequestMessageId: task.pendingReplyMessageId }
539
+ : {}),
540
+ ...(waitingRecipient ? { waitingRecipient } : {}),
541
+ ...(task.staleNotifiedAt !== undefined ? { stale: true } : {}),
542
+ };
543
+ }
544
+
545
+ /**
546
+ * Update the observed process/agent state without settling an open prompt.
547
+ *
548
+ * This separation is a guardrail for the tracked-task protocol: a child can
549
+ * become idle between turns while a delegated task is waiting for a reply.
550
+ * Future task records must settle only through explicit completion or an
551
+ * explicit failure, cancellation, or timeout path.
552
+ */
553
+ setAgentState(handle: AgentHandleInput, state: AgentLifecycleState, error?: string): void {
554
+ const record = this.getAgent(handle);
555
+ record.state = state;
556
+ record.error = error;
557
+ }
558
+
559
+ /**
560
+ * Reserve a tracked task slot without assuming that the child has started
561
+ * running yet. The caller can publish the task and then call
562
+ * setTaskRunning(); reserving first closes the concurrent-delegation race.
563
+ */
564
+ createTask(
565
+ handle: AgentHandleInput,
566
+ description: string,
567
+ options: CreateTaskOptions = {}
568
+ ): TaskHandle {
569
+ const agent = this.getAgent(handle);
570
+ const agentId = agent.handle.id;
571
+ if (agent.state === 'closed') {
572
+ throw new LifecycleError('closed_handle', `Agent "${agentId}" is closed.`);
573
+ }
574
+ if (agent.activeTaskId) {
575
+ throw new LifecycleError(
576
+ 'active_task',
577
+ `Agent "${agentId}" already has an active tracked task (${agent.activeTaskId}).`
578
+ );
579
+ }
580
+ if (typeof description !== 'string' || !description.trim()) {
581
+ throw new LifecycleError('invalid_task', 'Task description must not be empty.');
582
+ }
583
+ if (description.length > 100_000) {
584
+ throw new LifecycleError(
585
+ 'invalid_task',
586
+ 'Task description must be at most 100000 characters.'
587
+ );
588
+ }
589
+ if (
590
+ options.timeoutMs !== undefined &&
591
+ (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 0)
592
+ ) {
593
+ throw new LifecycleError(
594
+ 'invalid_task',
595
+ 'Task timeout must be a non-negative finite number.'
596
+ );
597
+ }
598
+ if (options.deadlineAt !== undefined && !Number.isFinite(options.deadlineAt)) {
599
+ throw new LifecycleError('invalid_task', 'Task deadline must be a finite timestamp.');
600
+ }
601
+ if (options.timeoutMs !== undefined && options.deadlineAt !== undefined) {
602
+ throw new LifecycleError('invalid_task', 'Specify either timeoutMs or deadlineAt, not both.');
603
+ }
604
+ const createdAt = Date.now();
605
+ const task: TaskHandle = { id: this.id('task'), agentId, createdAt };
606
+ const deadlineAt =
607
+ options.deadlineAt ??
608
+ (options.timeoutMs !== undefined ? createdAt + options.timeoutMs : undefined);
609
+ this.tasks.set(task.id, {
610
+ lifecycleSessionId: this.sessionId,
611
+ taskId: task.id,
612
+ agentId,
613
+ description: description.trim(),
614
+ state: 'created',
615
+ createdAt,
616
+ deadlineAt,
617
+ cwd: agent.handle.cwd,
618
+ pendingRequestIds: new Set(),
619
+ artifactSession: options.artifactSession,
620
+ settled: false,
621
+ });
622
+ agent.activeTaskId = task.id;
623
+ const record = this.tasks.get(task.id)!;
624
+ if (record.deadlineAt !== undefined) {
625
+ const delay = Math.max(0, record.deadlineAt - Date.now());
626
+ record.timeoutId = setTimeout(() => {
627
+ if (!record.settled && this.isCurrent(record)) {
628
+ this.settleTask(task.id, {
629
+ status: 'timed_out',
630
+ error: 'Tracked task deadline reached.',
631
+ });
632
+ }
633
+ }, delay);
634
+ (record.timeoutId as any).unref?.();
635
+ }
636
+ return { ...task };
637
+ }
638
+
639
+ /**
640
+ * Block until every given task has settled, resolved in input order.
641
+ * Completion is delivered exactly once per task by the task-watcher registry
642
+ * hook, never by polling; a timeout rejects with a descriptive error
643
+ * without touching the tasks themselves (their own deadlines remain
644
+ * authoritative).
645
+ */
646
+ waitForTasks(
647
+ handles: TaskHandleInput | TaskHandleInput[],
648
+ timeoutMs = 1_200_000
649
+ ): Promise<TaskResult[]> {
650
+ const values = Array.isArray(handles) ? handles : [handles];
651
+ if (values.length === 0)
652
+ throw new LifecycleError(
653
+ 'invalid_handle',
654
+ 'Expected one or more opaque task ids to wait for.'
655
+ );
656
+ const taskIds = values.map(value => this.taskRecord(value).taskId);
657
+ if (new Set(taskIds).size !== taskIds.length) {
658
+ throw new LifecycleError('invalid_handle', 'A wait cannot contain duplicate task ids.');
659
+ }
660
+ return new Promise<TaskResult[]>((resolve, reject) => {
661
+ const results = new Set<TaskResult>();
662
+ let timer: ReturnType<typeof setTimeout> | undefined;
663
+ const settle = (): void => {
664
+ if (timer) clearTimeout(timer);
665
+ resolve(taskIds.map(taskId => [...results.values()].find(r => r.taskId === taskId)!));
666
+ };
667
+ // watchTasks delivers already-settled tasks synchronously (in input
668
+ // order) through the Set callback, and registers the watch for the rest.
669
+ const registration = this.watchTasks(taskIds, [
670
+ completion => {
671
+ results.add(completion);
672
+ if (results.size >= taskIds.length) settle();
673
+ },
674
+ ]);
675
+ if (results.size >= taskIds.length) {
676
+ settle();
677
+ return;
678
+ }
679
+ const minutes = Math.round(timeoutMs / 60000);
680
+ const seconds = Math.round(timeoutMs / 1000);
681
+ const span =
682
+ minutes >= 1
683
+ ? `${minutes} minute${minutes === 1 ? '' : 's'}`
684
+ : `${seconds} second${seconds === 1 ? '' : 's'}`;
685
+ timer = setTimeout(() => {
686
+ this.removeWatcher(registration.watcherId);
687
+ reject(
688
+ new LifecycleError(
689
+ 'timeout',
690
+ `Timed out after ${span} waiting for ${registration.pending.length} unsettled task${registration.pending.length === 1 ? '' : 's'}. The tasks keep running; watch them later with shepherd_watch.`
691
+ )
692
+ );
693
+ }, timeoutMs);
694
+ (timer as any).unref?.();
695
+ });
696
+ }
697
+
698
+ private taskRecord(input: TaskHandleInput | unknown): TaskRecordInternal {
699
+ const id = taskHandleId(input);
700
+ const record = this.tasks.get(id);
701
+ if (!record || !this.isCurrent(record)) {
702
+ throw new LifecycleError(
703
+ 'unknown_task',
704
+ `Unknown task id "${id}". Task ids are scoped to this parent session; use the id returned by shepherd_delegate, not an agent id or Herdr pane id.`
705
+ );
706
+ }
707
+ return record;
708
+ }
709
+
710
+ private taskSnapshot(record: TaskRecordInternal): TaskRecord {
711
+ return {
712
+ taskId: record.taskId,
713
+ agentId: record.agentId,
714
+ description: record.description,
715
+ state: record.state,
716
+ createdAt: record.createdAt,
717
+ ...(record.cwd !== undefined ? { cwd: record.cwd } : {}),
718
+ ...(record.startedAt !== undefined ? { startedAt: record.startedAt } : {}),
719
+ ...(record.waitingSince !== undefined ? { waitingSince: record.waitingSince } : {}),
720
+ ...(record.deadlineAt !== undefined ? { deadlineAt: record.deadlineAt } : {}),
721
+ ...(record.pendingReplyMessageId !== undefined
722
+ ? { pendingReplyMessageId: record.pendingReplyMessageId }
723
+ : {}),
724
+ ...(record.pendingReplyTargetAgentId !== undefined
725
+ ? { pendingReplyTargetAgentId: record.pendingReplyTargetAgentId }
726
+ : {}),
727
+ ...(record.pendingReplyDeadlineAt !== undefined
728
+ ? { pendingReplyDeadlineAt: record.pendingReplyDeadlineAt }
729
+ : {}),
730
+ ...(record.pendingReplyText !== undefined
731
+ ? { pendingReplyText: record.pendingReplyText }
732
+ : {}),
733
+ pendingRequestIds: [...record.pendingRequestIds],
734
+ ...(record.staleNotifiedAt !== undefined ? { staleNotifiedAt: record.staleNotifiedAt } : {}),
735
+ ...(record.artifactSession ? { artifactSession: record.artifactSession } : {}),
736
+ ...(record.artifact ? { artifact: record.artifact } : {}),
737
+ ...(record.result ? { result: { ...record.result } } : {}),
738
+ };
739
+ }
740
+
741
+ canonicalTaskHandle(input: TaskHandleInput | unknown): TaskHandle {
742
+ const record = this.taskRecord(input);
743
+ return { id: record.taskId, agentId: record.agentId, createdAt: record.createdAt };
744
+ }
745
+
746
+ getTask(input: TaskHandleInput | unknown): TaskRecord {
747
+ return this.taskSnapshot(this.taskRecord(input));
748
+ }
749
+
750
+ taskResult(input: TaskHandleInput | unknown): TaskResult | undefined {
751
+ const result = this.taskRecord(input).result;
752
+ return result ? { ...result } : undefined;
753
+ }
754
+
755
+ /**
756
+ * Verify the child identity before accepting a task lifecycle event. The
757
+ * mailbox will perform the same check at its transport boundary; keeping
758
+ * this assertion in the registry prevents internal callers from bypassing
759
+ * ownership accidentally.
760
+ */
761
+ assertTaskOwner(
762
+ taskInput: TaskHandleInput | unknown,
763
+ agentInput: AgentHandleInput | unknown
764
+ ): TaskRecord {
765
+ const task = this.taskRecord(taskInput);
766
+ const agent = this.getAgent(agentInput);
767
+ if (task.agentId !== agent.handle.id) {
768
+ throw new LifecycleError(
769
+ 'task_agent_mismatch',
770
+ `Agent "${agent.handle.id}" does not own task "${task.taskId}".`
771
+ );
772
+ }
773
+ return this.taskSnapshot(task);
774
+ }
775
+
776
+ settleTaskForAgent(
777
+ taskInput: TaskHandleInput | unknown,
778
+ agentInput: AgentHandleInput | unknown,
779
+ settlement: TaskSettlement
780
+ ): TaskResult {
781
+ this.assertTaskOwner(taskInput, agentInput);
782
+ return this.settleTask(taskInput, settlement);
783
+ }
784
+
785
+ allTasks(): TaskRecord[] {
786
+ return [...this.tasks.values()]
787
+ .filter(record => this.isCurrent(record))
788
+ .map(record => this.taskSnapshot(record));
789
+ }
790
+
791
+ activeTaskForAgent(handle: AgentHandleInput): TaskRecord | undefined {
792
+ const agent = this.getAgent(handle);
793
+ return agent.activeTaskId ? this.taskSnapshot(this.taskRecord(agent.activeTaskId)) : undefined;
794
+ }
795
+
796
+ setTaskRunning(input: TaskHandleInput | unknown): TaskRecord {
797
+ const record = this.taskRecord(input);
798
+ if (record.settled) {
799
+ throw new LifecycleError(
800
+ 'invalid_transition',
801
+ `Task "${record.taskId}" is already ${record.state}.`
802
+ );
803
+ }
804
+ if (record.state !== 'created' && record.state !== 'waiting' && record.state !== 'running') {
805
+ throw new LifecycleError(
806
+ 'invalid_transition',
807
+ `Task "${record.taskId}" cannot become running from ${record.state}.`
808
+ );
809
+ }
810
+ if (record.state === 'waiting' && record.pendingRequestIds.size > 0) {
811
+ throw new LifecycleError(
812
+ 'invalid_transition',
813
+ `Task "${record.taskId}" cannot resume while requests are pending.`
814
+ );
815
+ }
816
+ record.state = 'running';
817
+ record.startedAt ??= Date.now();
818
+ record.waitingSince = undefined;
819
+ record.staleNotifiedAt = undefined;
820
+ return this.taskSnapshot(record);
821
+ }
822
+
823
+ setTaskWaiting(input: TaskHandleInput | unknown): TaskRecord {
824
+ const record = this.taskRecord(input);
825
+ if (record.settled) {
826
+ throw new LifecycleError(
827
+ 'invalid_transition',
828
+ `Task "${record.taskId}" is already ${record.state}.`
829
+ );
830
+ }
831
+ if (record.state !== 'running' && record.state !== 'waiting') {
832
+ throw new LifecycleError(
833
+ 'invalid_transition',
834
+ `Task "${record.taskId}" cannot become waiting from ${record.state}.`
835
+ );
836
+ }
837
+ if (record.pendingRequestIds.size === 0) {
838
+ throw new LifecycleError(
839
+ 'invalid_transition',
840
+ `Task "${record.taskId}" cannot become waiting without a pending request.`
841
+ );
842
+ }
843
+ record.state = 'waiting';
844
+ record.waitingSince ??= Date.now();
845
+ return this.taskSnapshot(record);
846
+ }
847
+
848
+ /**
849
+ * Record that a stale-wait reminder for this task was just surfaced to the
850
+ * parent, so the monitor does not repeat it while the task is still waiting.
851
+ * Cleared automatically by a reply (resolvePendingRequest), a resume
852
+ * (setTaskRunning), or any settlement.
853
+ */
854
+ markStaleNotified(input: TaskHandleInput | unknown): TaskRecord {
855
+ const record = this.taskRecord(input);
856
+ record.staleNotifiedAt = Date.now();
857
+ return this.taskSnapshot(record);
858
+ }
859
+
860
+ addPendingRequest(input: TaskHandleInput | unknown, requestId: string): TaskRecord {
861
+ const record = this.taskRecord(input);
862
+ if (record.settled) {
863
+ throw new LifecycleError(
864
+ 'invalid_transition',
865
+ `Task "${record.taskId}" is already ${record.state}.`
866
+ );
867
+ }
868
+ if (typeof requestId !== 'string' || !requestId.trim()) {
869
+ throw new LifecycleError('invalid_task', 'Pending request id must not be empty.');
870
+ }
871
+ record.pendingRequestIds.add(requestId);
872
+ return this.taskSnapshot(record);
873
+ }
874
+
875
+ resolvePendingRequest(input: TaskHandleInput | unknown, requestId: string): TaskRecord {
876
+ const record = this.taskRecord(input);
877
+ if (record.settled) return this.taskSnapshot(record);
878
+ record.pendingRequestIds.delete(requestId);
879
+ if (record.state === 'waiting' && record.pendingRequestIds.size === 0) {
880
+ record.state = 'running';
881
+ record.waitingSince = undefined;
882
+ record.staleNotifiedAt = undefined;
883
+ record.startedAt ??= Date.now();
884
+ }
885
+ return this.taskSnapshot(record);
886
+ }
887
+
888
+ cancelPendingRequest(input: TaskHandleInput | unknown, requestId: string): TaskRecord {
889
+ return this.resolvePendingRequest(input, requestId);
890
+ }
891
+
892
+ /**
893
+ * Open the task's single outstanding tracked reply. Opens the pending set and
894
+ * moves the task to `waiting`. If a reply is already outstanding the task is
895
+ * kept waiting for the earlier one (the initial policy allows one outstanding
896
+ * request per task) and the existing reply id is returned so the caller can
897
+ * correlate.
898
+ */
899
+ openPendingRequest(
900
+ input: TaskHandleInput | unknown,
901
+ request: {
902
+ messageId: string;
903
+ targetAgentId?: string;
904
+ deadlineAt?: number;
905
+ text?: string;
906
+ }
907
+ ): TaskRecord {
908
+ const record = this.taskRecord(input);
909
+ if (record.settled) {
910
+ throw new LifecycleError(
911
+ 'invalid_transition',
912
+ `Task "${record.taskId}" is already ${record.state}.`
913
+ );
914
+ }
915
+ if (record.pendingReplyMessageId !== undefined) {
916
+ throw new LifecycleError(
917
+ 'invalid_task',
918
+ `Task "${record.taskId}" already has an outstanding tracked reply (${record.pendingReplyMessageId}).`
919
+ );
920
+ }
921
+ if (record.state === 'created') {
922
+ this.setTaskRunning(input);
923
+ }
924
+ record.pendingReplyMessageId = request.messageId;
925
+ record.pendingReplyTargetAgentId = request.targetAgentId;
926
+ record.pendingReplyText = request.text;
927
+ if (request.deadlineAt !== undefined && Number.isFinite(request.deadlineAt)) {
928
+ record.pendingReplyDeadlineAt = request.deadlineAt;
929
+ }
930
+ this.addPendingRequest(input, request.messageId);
931
+ this.setTaskWaiting(input);
932
+ return this.taskSnapshot(record);
933
+ }
934
+
935
+ /**
936
+ * Resolve the task's outstanding tracked reply when the matching reply
937
+ * arrives. The reply's `replyTo` must equal the pending message id; anything
938
+ * else (wrong task, unknown message) leaves the request pending so the owner
939
+ * can still block/cancel it explicitly. Returns correlation metadata so the
940
+ * parent can relay the reply to the asker.
941
+ */
942
+ resolveReplyForTask(
943
+ input: TaskHandleInput | unknown,
944
+ replyTo: string
945
+ ): {
946
+ resolved: boolean;
947
+ taskId: string;
948
+ agentId: string;
949
+ pendingReplyMessageId?: string;
950
+ targetAgentId?: string;
951
+ } {
952
+ const record = this.taskRecord(input);
953
+ const taskId = record.taskId;
954
+ const agentId = record.agentId;
955
+ if (replyTo !== record.pendingReplyMessageId) {
956
+ return {
957
+ resolved: false,
958
+ taskId,
959
+ agentId,
960
+ pendingReplyMessageId: record.pendingReplyMessageId,
961
+ targetAgentId: record.pendingReplyTargetAgentId,
962
+ };
963
+ }
964
+ this.resolvePendingRequest(input, record.pendingReplyMessageId);
965
+ const repliedTo = record.pendingReplyMessageId;
966
+ const targetAgentId = record.pendingReplyTargetAgentId;
967
+ record.pendingReplyMessageId = undefined;
968
+ record.pendingReplyTargetAgentId = undefined;
969
+ record.pendingReplyDeadlineAt = undefined;
970
+ record.pendingReplyText = undefined;
971
+ return { resolved: true, taskId, agentId, pendingReplyMessageId: repliedTo, targetAgentId };
972
+ }
973
+
974
+ /**
975
+ * Clear a task's outstanding tracked reply without delivering it (close,
976
+ * explicit timeout, or an invalid reply). Returns when a request was cleared.
977
+ */
978
+ clearPendingReply(input: TaskHandleInput | unknown): TaskRecord {
979
+ const record = this.taskRecord(input);
980
+ if (record.pendingReplyMessageId !== undefined && !record.settled) {
981
+ this.resolvePendingRequest(input, record.pendingReplyMessageId);
982
+ }
983
+ record.pendingReplyMessageId = undefined;
984
+ record.pendingReplyTargetAgentId = undefined;
985
+ record.pendingReplyDeadlineAt = undefined;
986
+ record.pendingReplyText = undefined;
987
+ return this.taskSnapshot(record);
988
+ }
989
+
990
+ markTaskStaleNotified(input: TaskHandleInput | unknown, at = Date.now()): TaskRecord {
991
+ const record = this.taskRecord(input);
992
+ if (record.state !== 'waiting') {
993
+ throw new LifecycleError('invalid_transition', `Task "${record.taskId}" is not waiting.`);
994
+ }
995
+ if (!Number.isFinite(at))
996
+ throw new LifecycleError('invalid_task', 'Stale notification time must be finite.');
997
+ record.staleNotifiedAt = at;
998
+ return this.taskSnapshot(record);
999
+ }
1000
+
1001
+ clearTaskStaleNotification(input: TaskHandleInput | unknown): TaskRecord {
1002
+ const record = this.taskRecord(input);
1003
+ record.staleNotifiedAt = undefined;
1004
+ return this.taskSnapshot(record);
1005
+ }
1006
+
1007
+ attachTaskArtifact(
1008
+ input: TaskHandleInput | unknown,
1009
+ session: ShepherdSession,
1010
+ artifact: ArtifactReservation,
1011
+ onSettled?: (result: TaskResult) => void
1012
+ ): void {
1013
+ const record = this.taskRecord(input);
1014
+ record.artifactSession = session;
1015
+ record.artifact = artifact;
1016
+ record.onSettled = onSettled;
1017
+ }
1018
+
1019
+ taskArtifact(input: TaskHandleInput | unknown): {
1020
+ session?: ShepherdSession;
1021
+ artifact?: ArtifactReservation;
1022
+ } {
1023
+ const record = this.taskRecord(input);
1024
+ return { session: record.artifactSession, artifact: record.artifact };
1025
+ }
1026
+
1027
+ settleTask(
1028
+ input: TaskHandleInput | unknown,
1029
+ settlement: TaskSettlement,
1030
+ options: SettleTaskOptions = {}
1031
+ ): TaskResult {
1032
+ const record = this.taskRecord(input);
1033
+ if (record.settled) return { ...record.result! };
1034
+ if (!['completed', 'blocked', 'failed', 'cancelled', 'timed_out'].includes(settlement.status)) {
1035
+ throw new LifecycleError(
1036
+ 'invalid_task',
1037
+ `Unknown task result status "${settlement.status}".`
1038
+ );
1039
+ }
1040
+ const completedAt = settlement.completedAt ?? Date.now();
1041
+ if (!Number.isFinite(completedAt)) {
1042
+ throw new LifecycleError('invalid_task', 'Task completion time must be finite.');
1043
+ }
1044
+ const ok = settlement.status === 'completed' && settlement.ok !== false;
1045
+ const defaultReturnCode =
1046
+ settlement.status === 'cancelled'
1047
+ ? 130
1048
+ : settlement.status === 'timed_out'
1049
+ ? 124
1050
+ : settlement.status === 'blocked'
1051
+ ? 2
1052
+ : ok
1053
+ ? 0
1054
+ : 1;
1055
+ const result: TaskResult = {
1056
+ taskId: record.taskId,
1057
+ agentId: record.agentId,
1058
+ status: settlement.status,
1059
+ ok,
1060
+ returnCode: settlement.returnCode ?? defaultReturnCode,
1061
+ ...(settlement.text !== undefined ? { text: settlement.text } : {}),
1062
+ ...(settlement.error !== undefined ? { error: settlement.error } : {}),
1063
+ completedAt,
1064
+ ...(record.artifact ? { artifact: record.artifact } : {}),
1065
+ ...(record.artifactSession ? { artifactSession: record.artifactSession } : {}),
1066
+ };
1067
+ record.result = result;
1068
+ record.state = settlement.status;
1069
+ record.settled = true;
1070
+ if (record.timeoutId) {
1071
+ clearTimeout(record.timeoutId);
1072
+ record.timeoutId = undefined;
1073
+ }
1074
+ record.pendingRequestIds.clear();
1075
+ record.waitingSince = undefined;
1076
+ record.staleNotifiedAt = undefined;
1077
+ record.pendingReplyMessageId = undefined;
1078
+ record.pendingReplyTargetAgentId = undefined;
1079
+ record.pendingReplyDeadlineAt = undefined;
1080
+ record.pendingReplyText = undefined;
1081
+ try {
1082
+ record.onSettled?.({ ...result });
1083
+ } catch {
1084
+ /* artifact persistence must not break task settlement */
1085
+ }
1086
+ const agent = this.agents.get(record.agentId);
1087
+ if (agent?.activeTaskId === record.taskId) {
1088
+ agent.activeTaskId = undefined;
1089
+ if (agent.state !== 'closed') {
1090
+ agent.state =
1091
+ settlement.status === 'completed'
1092
+ ? 'done'
1093
+ : settlement.status === 'blocked'
1094
+ ? 'blocked'
1095
+ : 'failed';
1096
+ }
1097
+ }
1098
+ // Notify each task watcher exactly once, using the task id as the primary
1099
+ // correlation key. Settlement is authoritative in the task record; a
1100
+ // callback failure must never affect waiters or artifacts. This is the
1101
+ // only signal that drives task watcher completion — entering `waiting`,
1102
+ // `idle`, or `agent_settled` is intentionally not a settlement here.
1103
+ const watcherIds = [...(this.taskWatchers.get(record.taskId) ?? [])];
1104
+ this.taskWatchers.delete(record.taskId);
1105
+ const agentHandle = this.agents.get(record.agentId)?.handle;
1106
+ const notifyTaskWatcher = (
1107
+ watcher: WatcherRegistration,
1108
+ result: TaskResult,
1109
+ agentHandle: AgentHandle | undefined
1110
+ ): void => {
1111
+ const cb = watcher.callback as TaskWatcherCallback | TaskWatcherCallback[] | undefined;
1112
+ const delivery = {
1113
+ ...result,
1114
+ ...(agentHandle ? { agent: agentHandle.agent, label: agentHandle.label } : {}),
1115
+ };
1116
+ try {
1117
+ if (Array.isArray(cb)) {
1118
+ for (const one of cb) one(delivery);
1119
+ } else cb?.(delivery);
1120
+ } catch {
1121
+ /* notification delivery must not break lifecycle settlement */
1122
+ }
1123
+ };
1124
+ let hadWatchers = false;
1125
+ for (const watcherId of watcherIds) {
1126
+ const watcher = this.watchers.get(watcherId);
1127
+ if (!watcher || watcher.delivered.has(record.taskId)) continue;
1128
+ watcher.delivered.add(record.taskId);
1129
+ watcher.pending.delete(record.taskId);
1130
+ notifyTaskWatcher(watcher, result, agentHandle);
1131
+ // Only a watcher that actually registered a callback counts as observed;
1132
+ // a callback-less registration (internal API) must not suppress the
1133
+ // unseen-completion notice.
1134
+ if (watcher.callback !== undefined) hadWatchers = true;
1135
+ if (watcher.pending.size === 0) this.watchers.delete(watcherId);
1136
+ }
1137
+ const settlementContext: TaskSettlementContext = {
1138
+ hadWatchers,
1139
+ ...(agentHandle ? { agent: agentHandle.agent, label: agentHandle.label } : {}),
1140
+ ...(options.source !== undefined ? { source: options.source } : {}),
1141
+ };
1142
+ for (const listener of [...this.settlementListeners]) {
1143
+ try {
1144
+ listener({ ...result }, { ...settlementContext });
1145
+ } catch {
1146
+ /* settlement observation must not break lifecycle settlement */
1147
+ }
1148
+ }
1149
+ return { ...result };
1150
+ }
1151
+
1152
+ cancelTask(handle: AgentHandleInput, reason = 'Agent was closed.'): TaskResult | undefined {
1153
+ const agent = this.getAgent(handle);
1154
+ if (!agent.activeTaskId) return undefined;
1155
+ return this.settleTask(agent.activeTaskId, {
1156
+ status: 'cancelled',
1157
+ ok: false,
1158
+ returnCode: 130,
1159
+ error: reason,
1160
+ });
1161
+ }
1162
+
1163
+ createPrompt(
1164
+ handle: AgentHandleInput,
1165
+ timeoutMs?: number,
1166
+ baselineStateChangeSeq?: number,
1167
+ baselineCompletionSignalId?: string
1168
+ ): PromptHandle {
1169
+ const agent = this.getAgent(handle);
1170
+ const agentId = agent.handle.id;
1171
+ if (agent.state === 'closed')
1172
+ throw new LifecycleError('closed_handle', `Agent "${agentId}" is closed.`);
1173
+ if (agent.activePromptId) {
1174
+ throw new LifecycleError(
1175
+ 'active_prompt',
1176
+ `Agent "${agentId}" already has an unresolved prompt.`
1177
+ );
1178
+ }
1179
+ let resolve!: (result: PromptResult) => void;
1180
+ const promise = new Promise<PromptResult>(r => (resolve = r));
1181
+ const prompt: PromptHandle = { id: this.id('prompt'), agentId, createdAt: Date.now() };
1182
+ this.prompts.set(prompt.id, {
1183
+ lifecycleSessionId: this.sessionId,
1184
+ handle: prompt,
1185
+ baselineStateChangeSeq,
1186
+ baselineCompletionSignalId,
1187
+ observedWorking: false,
1188
+ settled: false,
1189
+ resolve,
1190
+ promise,
1191
+ });
1192
+ agent.activePromptId = prompt.id;
1193
+ agent.state = 'working';
1194
+ // Do not arm a timeout here; waitPrompts owns the timeout and will set/extend it.
1195
+ // A very long safety net (1h) is set only if wait is never called.
1196
+ const safetyTimeoutId = setTimeout(() => {
1197
+ const record = this.prompts.get(prompt.id);
1198
+ if (!record || !this.isCurrent(record)) return;
1199
+ this.settlePrompt(prompt, {
1200
+ promptId: prompt.id,
1201
+ agentId: prompt.agentId,
1202
+ status: 'timeout',
1203
+ ok: false,
1204
+ error: 'Prompt timed out (safety net: wait never called).',
1205
+ });
1206
+ }, 3_600_000);
1207
+ this.prompts.get(prompt.id)!.timeoutId = safetyTimeoutId;
1208
+ return { ...prompt };
1209
+ }
1210
+
1211
+ getPrompt(input: PromptHandleInput | unknown): PromptRecord {
1212
+ const id = handleId(input, 'PromptHandle');
1213
+ const record = this.prompts.get(id);
1214
+ if (!record || !this.isCurrent(record))
1215
+ throw new LifecycleError(
1216
+ 'unknown_handle',
1217
+ `Unknown prompt id "${id}". Lifecycle ids are scoped to this parent session; use the id from the latest prompt result, not an agent id or Herdr pane id.`
1218
+ );
1219
+ return record;
1220
+ }
1221
+
1222
+ canonicalPromptHandle(input: PromptHandleInput | unknown): PromptHandle {
1223
+ return { ...this.getPrompt(input).handle };
1224
+ }
1225
+
1226
+ /** Return the terminal result when one is already available. */
1227
+ promptResult(input: PromptHandleInput | unknown): PromptResult | undefined {
1228
+ return this.getPrompt(input).settled ? { ...this.getPrompt(input).result! } : undefined;
1229
+ }
1230
+
1231
+ /**
1232
+ * Register a one-shot observer for specific prompt invocations. This method
1233
+ * is deliberately synchronous: callers receive settled results that already
1234
+ * exist and pending ids without waiting for the child.
1235
+ */
1236
+ watchPrompts(
1237
+ handles: PromptHandleInput | PromptHandleInput[],
1238
+ callback?: PromptWatcherCallback
1239
+ ): WatcherRegistration {
1240
+ const values = Array.isArray(handles) ? handles : [handles];
1241
+ if (values.length === 0) {
1242
+ throw new LifecycleError(
1243
+ 'invalid_handle',
1244
+ 'Expected one or more opaque prompt ids to watch.'
1245
+ );
1246
+ }
1247
+ const promptIds = values.map(value => this.canonicalPromptHandle(value).id);
1248
+ if (new Set(promptIds).size !== promptIds.length) {
1249
+ throw new LifecycleError('invalid_handle', 'A watcher cannot contain duplicate prompt ids.');
1250
+ }
1251
+ const watcherId = this.id('watch');
1252
+ const pending = new Set<string>();
1253
+ const completed: PromptResult[] = [];
1254
+ for (const promptId of promptIds) {
1255
+ const prompt = this.prompts.get(promptId)!;
1256
+ if (prompt.settled) completed.push({ ...prompt.result! });
1257
+ else pending.add(promptId);
1258
+ }
1259
+ if (pending.size > 0) {
1260
+ this.watchers.set(watcherId, {
1261
+ kind: 'prompt',
1262
+ promptIds: [...promptIds],
1263
+ taskIds: [],
1264
+ pending,
1265
+ callback,
1266
+ delivered: new Set(),
1267
+ });
1268
+ for (const promptId of pending) {
1269
+ let watchers = this.promptWatchers.get(promptId);
1270
+ if (!watchers) this.promptWatchers.set(promptId, (watchers = new Set()));
1271
+ watchers.add(watcherId);
1272
+ }
1273
+ }
1274
+ return { watcherId, taskIds: [], promptIds, pending: [...pending], completed };
1275
+ }
1276
+
1277
+ /** Prompt ids that still have at least one active watcher. */
1278
+ watchedPromptIds(): string[] {
1279
+ return [...this.promptWatchers.keys()];
1280
+ }
1281
+
1282
+ /** True when an opaque handle string is a tracked task id for this session. */
1283
+ isTaskId(id: string): boolean {
1284
+ const record = this.tasks.get(id);
1285
+ return !!record && this.isCurrent(record);
1286
+ }
1287
+
1288
+ /** Task ids that still have at least one active watcher. */
1289
+ watchedTaskIds(): string[] {
1290
+ return [...this.taskWatchers.keys()];
1291
+ }
1292
+
1293
+ /**
1294
+ * Register a one-shot observer for specific tracked tasks. Synchronous, like
1295
+ * {@link watchPrompts}: already-settled tasks are returned immediately and
1296
+ * pending tasks are reported exactly once when they reach a terminal state.
1297
+ * A watcher never observes a child entering `waiting`, `idle`, or
1298
+ * `agent_settled`; only settlement (shepherd_done or an explicit
1299
+ * failure/cancellation/timeout) fires the callback.
1300
+ */
1301
+ watchTasks(
1302
+ handles: TaskHandleInput | TaskHandleInput[],
1303
+ callback?: TaskWatcherCallback
1304
+ ): TaskWatcherRegistration {
1305
+ const values = Array.isArray(handles) ? handles : [handles];
1306
+ if (values.length === 0) {
1307
+ throw new LifecycleError('invalid_handle', 'Expected one or more opaque task ids to watch.');
1308
+ }
1309
+ const taskIds = values.map(value => {
1310
+ const record = this.taskRecord(value);
1311
+ return record.taskId;
1312
+ });
1313
+ if (new Set(taskIds).size !== taskIds.length) {
1314
+ throw new LifecycleError('invalid_handle', 'A watcher cannot contain duplicate task ids.');
1315
+ }
1316
+ const watcherId = this.id('watch');
1317
+ const pending = new Set<string>();
1318
+ const completed: TaskResult[] = [];
1319
+ const invoker =
1320
+ callback === undefined
1321
+ ? () => undefined
1322
+ : Array.isArray(callback)
1323
+ ? cb => {
1324
+ for (const one of callback) one(cb);
1325
+ }
1326
+ : (cb: TaskWatcherCompletion) => {
1327
+ callback(cb);
1328
+ };
1329
+ const agentHandleOf = (agentId: string) => {
1330
+ const agent = this.agents.get(agentId);
1331
+ return agent && this.isCurrent(agent) ? agent.handle : undefined;
1332
+ };
1333
+ const notify = (record: TaskRecordInternal, settledNow: boolean): void => {
1334
+ const result = record.result!;
1335
+ const completedAt = result.completedAt;
1336
+ try {
1337
+ invoker({
1338
+ ...result,
1339
+ ...(agentHandleOf(record.agentId)
1340
+ ? {
1341
+ agent: agentHandleOf(record.agentId)!.agent,
1342
+ label: agentHandleOf(record.agentId)!.label,
1343
+ }
1344
+ : {}),
1345
+ });
1346
+ } catch {
1347
+ /* notification delivery must not break lifecycle settlement */
1348
+ }
1349
+ if (settledNow) completed.push({ ...record.result });
1350
+ else pending.add(record.taskId);
1351
+ };
1352
+ for (const taskId of taskIds) {
1353
+ const record = this.tasks.get(taskId)!;
1354
+ if (record.settled && record.result) {
1355
+ // Synchronous, in-order delivery for tasks that are already done.
1356
+ notify(record, true);
1357
+ } else {
1358
+ pending.add(taskId);
1359
+ }
1360
+ }
1361
+ if (pending.size > 0) {
1362
+ this.watchers.set(watcherId, {
1363
+ kind: 'task',
1364
+ promptIds: [],
1365
+ taskIds: [...taskIds],
1366
+ pending,
1367
+ callback,
1368
+ delivered: new Set(),
1369
+ });
1370
+ for (const taskId of pending) {
1371
+ let watchers = this.taskWatchers.get(taskId);
1372
+ if (!watchers) this.taskWatchers.set(taskId, (watchers = new Set()));
1373
+ watchers.add(watcherId);
1374
+ }
1375
+ }
1376
+ return { watcherId, taskIds: [...taskIds], pending: [...pending], completed };
1377
+ }
1378
+
1379
+ /** Remove all watchers during parent session teardown. */
1380
+ clearWatchers(): void {
1381
+ for (const [watcherId, watcher] of this.watchers)
1382
+ this.removeWatcherInternal(watcherId, watcher);
1383
+ this.watchers.clear();
1384
+ this.promptWatchers.clear();
1385
+ this.taskWatchers.clear();
1386
+ }
1387
+
1388
+ /** Detach one watcher so its remaining tasks no longer notify it. */
1389
+ removeWatcher(watcherId: string): void {
1390
+ const watcher = this.watchers.get(watcherId);
1391
+ if (watcher) this.removeWatcherInternal(watcherId, watcher);
1392
+ }
1393
+
1394
+ private removeWatcherInternal(
1395
+ watcherId: string,
1396
+ watcher: { kind: 'prompt' | 'task'; pending: Set<string> }
1397
+ ): void {
1398
+ const index = watcher.kind === 'task' ? this.taskWatchers : this.promptWatchers;
1399
+ for (const id of watcher.pending) {
1400
+ const watchers = index.get(id);
1401
+ watchers?.delete(watcherId);
1402
+ if (watchers && watchers.size === 0) index.delete(id);
1403
+ }
1404
+ this.watchers.delete(watcherId);
1405
+ }
1406
+
1407
+ wait(handle: PromptHandleInput | unknown): Promise<PromptResult> {
1408
+ return this.getPrompt(handle).promise;
1409
+ }
1410
+
1411
+ completionSignalPath(handle: AgentHandleInput): string | undefined {
1412
+ return this.getAgent(handle).completionSignalPath;
1413
+ }
1414
+
1415
+ completionResultPath(handle: AgentHandleInput): string | undefined {
1416
+ return this.getAgent(handle).completionResultPath;
1417
+ }
1418
+
1419
+ artifactSession(handle: AgentHandleInput): ShepherdSession | undefined {
1420
+ return this.getAgent(handle).artifactSession;
1421
+ }
1422
+
1423
+ attachPromptArtifact(
1424
+ handle: PromptHandleInput,
1425
+ session: ShepherdSession,
1426
+ artifact: ArtifactReservation,
1427
+ onSettled?: (result: PromptResult) => void
1428
+ ): void {
1429
+ const prompt = this.getPrompt(handle);
1430
+ prompt.artifactSession = session;
1431
+ prompt.artifact = artifact;
1432
+ prompt.onSettled = onSettled;
1433
+ }
1434
+
1435
+ promptArtifact(handle: PromptHandleInput): {
1436
+ session?: ShepherdSession;
1437
+ artifact?: ArtifactReservation;
1438
+ } {
1439
+ const prompt = this.getPrompt(handle);
1440
+ return { session: prompt.artifactSession, artifact: prompt.artifact };
1441
+ }
1442
+
1443
+ promptTracking(handle: PromptHandle): {
1444
+ baselineStateChangeSeq?: number;
1445
+ baselineCompletionSignalId?: string;
1446
+ observedWorking: boolean;
1447
+ } {
1448
+ const record = this.getPrompt(handle);
1449
+ return {
1450
+ baselineStateChangeSeq: record.baselineStateChangeSeq,
1451
+ baselineCompletionSignalId: record.baselineCompletionSignalId,
1452
+ observedWorking: record.observedWorking,
1453
+ };
1454
+ }
1455
+
1456
+ observeWorking(handle: PromptHandle): void {
1457
+ this.getPrompt(handle).observedWorking = true;
1458
+ }
1459
+
1460
+ settlePrompt(handle: PromptHandle, result: PromptResult): PromptResult {
1461
+ const prompt = this.getPrompt(handle);
1462
+ if (prompt.settled) return { ...prompt.result! };
1463
+ const returnCode =
1464
+ result.returnCode ??
1465
+ (result.status === 'cancelled'
1466
+ ? 130
1467
+ : result.status === 'timeout'
1468
+ ? 124
1469
+ : result.status === 'blocked'
1470
+ ? 2
1471
+ : result.ok
1472
+ ? 0
1473
+ : 1);
1474
+ prompt.result = {
1475
+ ...result,
1476
+ returnCode,
1477
+ promptId: prompt.handle.id,
1478
+ agentId: prompt.handle.agentId,
1479
+ ...(prompt.artifact ? { artifact: prompt.artifact } : {}),
1480
+ ...(prompt.artifactSession ? { artifactSession: prompt.artifactSession } : {}),
1481
+ };
1482
+ prompt.settled = true;
1483
+ // Clear any active timeout (safety net from createPrompt or waitPrompts).
1484
+ if (prompt.timeoutId) {
1485
+ clearTimeout(prompt.timeoutId);
1486
+ prompt.timeoutId = undefined;
1487
+ }
1488
+ try {
1489
+ prompt.onSettled?.({ ...prompt.result });
1490
+ } catch {
1491
+ /* persistence must not break lifecycle settlement */
1492
+ }
1493
+ // Notify each watcher exactly once, using the prompt id as the primary
1494
+ // correlation key. Settlement is still authoritative in the prompt
1495
+ // record; a callback failure must never affect waiters or artifacts.
1496
+ const watcherIds = [...(this.promptWatchers.get(prompt.handle.id) ?? [])];
1497
+ this.promptWatchers.delete(prompt.handle.id);
1498
+ const agentForWatcher = this.agents.get(prompt.handle.agentId)?.handle;
1499
+ for (const watcherId of watcherIds) {
1500
+ const watcher = this.watchers.get(watcherId);
1501
+ if (!watcher || watcher.delivered.has(prompt.handle.id)) continue;
1502
+ watcher.delivered.add(prompt.handle.id);
1503
+ watcher.pending.delete(prompt.handle.id);
1504
+ try {
1505
+ watcher.callback?.({
1506
+ ...prompt.result,
1507
+ ...(agentForWatcher
1508
+ ? { agent: agentForWatcher.agent, label: agentForWatcher.label }
1509
+ : {}),
1510
+ });
1511
+ } catch {
1512
+ /* notification delivery must not break lifecycle settlement */
1513
+ }
1514
+ if (watcher.pending.size === 0) this.watchers.delete(watcherId);
1515
+ }
1516
+ const agent = this.agents.get(prompt.handle.agentId);
1517
+ if (agent?.activePromptId === prompt.handle.id) {
1518
+ agent.activePromptId = undefined;
1519
+ if (agent.state !== 'closed') agent.state = result.ok ? 'done' : 'failed';
1520
+ }
1521
+ prompt.resolve({ ...prompt.result });
1522
+ return { ...prompt.result };
1523
+ }
1524
+
1525
+ cancelPrompts(handle: AgentHandle, reason = 'Agent was closed.'): void {
1526
+ const agent = this.getAgent(handle);
1527
+ this.cancelTask(handle, reason);
1528
+ if (agent.activePromptId) {
1529
+ const prompt = this.prompts.get(agent.activePromptId);
1530
+ if (prompt)
1531
+ this.settlePrompt(prompt.handle, {
1532
+ promptId: prompt.handle.id,
1533
+ agentId: handle.id,
1534
+ status: 'cancelled',
1535
+ ok: false,
1536
+ returnCode: 130,
1537
+ error: reason,
1538
+ });
1539
+ }
1540
+ agent.state = 'closed';
1541
+ }
1542
+
1543
+ close(handle: AgentHandle): void {
1544
+ const agent = this.getAgent(handle);
1545
+ if (agent.state === 'closed') return;
1546
+ this.cancelPrompts(handle);
1547
+ }
1548
+
1549
+ allAgents(): AgentHandle[] {
1550
+ return [...this.agents.values()]
1551
+ .filter(record => this.isCurrent(record))
1552
+ .map(r => ({ ...r.handle }));
1553
+ }
1554
+ }
1555
+
1556
+ export const lifecycleRegistry = new LifecycleRegistry();
1557
+
1558
+ // ── Session owner identity ──────────────────────────────────────────────
1559
+ // The created-panes registry is shared across all pi-shepherd processes (it
1560
+ // lives in the user agent dir), so pane creation must be tagged with the
1561
+ // owning parent session and session-facing views must filter by it. The owner
1562
+ // id is the parent pi session's session id, bound once by the extension at
1563
+ // session_start; a test/override env var wins when set.
1564
+
1565
+ let boundSessionOwner: string | undefined;
1566
+
1567
+ /**
1568
+ * Stable identity of this parent pi session for tagging owned panes.
1569
+ * Undefined when not yet bound (and no override is set).
1570
+ */
1571
+ export function sessionOwner(): string | undefined {
1572
+ const override = process.env.PI_SHEPHERD_OWNER_SESSION?.trim();
1573
+ return override || boundSessionOwner;
1574
+ }
1575
+
1576
+ /**
1577
+ * Bind (or clear) the parent session identity. Called from session_start /
1578
+ * session_shutdown; binding is idempotent so re-fire is safe.
1579
+ */
1580
+ export function bindSessionOwner(id: string | undefined): void {
1581
+ if (id?.trim()) boundSessionOwner = id.trim();
1582
+ else boundSessionOwner = undefined;
1583
+ }