@luminascale/shepherd 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/.agents/agents/README.md +12 -0
  2. package/.agents/agents/planner.md +38 -0
  3. package/.agents/agents/reviewer.md +38 -0
  4. package/.agents/agents/scout.md +43 -0
  5. package/.agents/agents/worker.md +33 -0
  6. package/.agents/skills/smoke-test/SKILL.md +155 -0
  7. package/.agents/skills/smoke-test/references/forensics.md +46 -0
  8. package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
  9. package/.github/workflows/publish.yml +77 -0
  10. package/.pi/prompts/release.md +21 -0
  11. package/.prettierrc +10 -0
  12. package/AGENTS.md +88 -0
  13. package/CONTRIBUTING.md +177 -0
  14. package/LICENSE +201 -0
  15. package/README.md +424 -2
  16. package/docs/README.md +25 -0
  17. package/docs/guides/agent-definitions.md +42 -0
  18. package/docs/guides/diagnostics.md +199 -0
  19. package/docs/guides/tool-reference.md +55 -0
  20. package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
  21. package/docs/plans/agent-labels.md +257 -0
  22. package/docs/plans/architecture.md +110 -0
  23. package/docs/plans/settings-scope.md +163 -0
  24. package/docs/plans/tool-surface-split.md +278 -0
  25. package/docs/reference/dictionary +26 -0
  26. package/docs/releasing.md +47 -0
  27. package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
  28. package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
  29. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
  30. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
  31. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
  32. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
  33. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
  34. package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
  35. package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
  36. package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
  37. package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
  38. package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
  39. package/index.ts +599 -0
  40. package/package.json +112 -4
  41. package/scripts/capture-system-prompt.mjs +45 -0
  42. package/scripts/extract-pi-system-prompt.mjs +277 -0
  43. package/scripts/host-impact.mjs +74 -0
  44. package/scripts/resolve-agent.mjs +43 -0
  45. package/scripts/show-shepherd-orchestrator.mjs +58 -0
  46. package/scripts/show-shepherd-prompt.mjs +96 -0
  47. package/scripts/verify-suites.mjs +67 -0
  48. package/specs/001-artifacts/spec.md +436 -0
  49. package/specs/002-simplify-agent-orchestration/plan.md +287 -0
  50. package/specs/002-simplify-agent-orchestration/spec.md +323 -0
  51. package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
  52. package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
  53. package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
  54. package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
  55. package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
  56. package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
  57. package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
  58. package/specs/005-per-workspace-settings/plan.md +230 -0
  59. package/specs/005-per-workspace-settings/spec.md +368 -0
  60. package/specs/005-per-workspace-settings/tasks.md +178 -0
  61. package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
  62. package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
  63. package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
  64. package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
  65. package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
  66. package/specs/007-unwatched-completion-notice/journal.md +145 -0
  67. package/specs/007-unwatched-completion-notice/plan.md +186 -0
  68. package/specs/007-unwatched-completion-notice/spec.md +284 -0
  69. package/specs/007-unwatched-completion-notice/tasks.md +147 -0
  70. package/specs/008-remote-machine-sheep/intent.md +174 -0
  71. package/specs/008-remote-machine-sheep/journal.md +57 -0
  72. package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
  73. package/specs/009-hc-runtime/intent.md +44 -0
  74. package/specs/009-hc-runtime/plan.md +49 -0
  75. package/specs/009-hc-runtime/spec.md +118 -0
  76. package/specs/009-hc-runtime/tasks.md +62 -0
  77. package/specs/010-unseen-watch-parity/intent.md +57 -0
  78. package/specs/010-unseen-watch-parity/journal.md +172 -0
  79. package/specs/010-unseen-watch-parity/plan.md +74 -0
  80. package/specs/010-unseen-watch-parity/spec.md +191 -0
  81. package/specs/010-unseen-watch-parity/tasks.md +119 -0
  82. package/specs/011-hc-background-poll/intent.md +57 -0
  83. package/specs/011-hc-background-poll/journal.md +95 -0
  84. package/specs/011-hc-background-poll/plan.md +87 -0
  85. package/specs/011-hc-background-poll/spec.md +141 -0
  86. package/specs/011-hc-background-poll/tasks.md +83 -0
  87. package/specs/012-steer-default/intent.md +12 -0
  88. package/specs/012-steer-default/journal.md +40 -0
  89. package/specs/012-steer-default/plan.md +7 -0
  90. package/specs/012-steer-default/spec.md +42 -0
  91. package/specs/012-steer-default/tasks.md +6 -0
  92. package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
  93. package/specs/013-opencode-shepherd/intent.md +59 -0
  94. package/specs/013-opencode-shepherd/plan.md +204 -0
  95. package/specs/013-opencode-shepherd/spec.md +258 -0
  96. package/specs/013-opencode-shepherd/tasks.md +259 -0
  97. package/src/core/artifact-sessions.ts +835 -0
  98. package/src/core/config.ts +329 -0
  99. package/src/core/discovery.ts +342 -0
  100. package/src/core/herdr.ts +1 -0
  101. package/src/core/host.ts +77 -0
  102. package/src/core/ids.ts +78 -0
  103. package/src/core/lifecycle.ts +1 -0
  104. package/src/core/messaging.ts +1 -0
  105. package/src/core/migration.ts +55 -0
  106. package/src/core/orchestration.ts +1 -0
  107. package/src/core/types.ts +143 -0
  108. package/src/core/unseen-completions.ts +114 -0
  109. package/src/extension/cli.ts +417 -0
  110. package/src/extension/config.ts +1 -0
  111. package/src/extension/settings-ui.ts +296 -0
  112. package/src/extension/shepherd-done.ts +768 -0
  113. package/src/extension/shepherd.ts +2548 -0
  114. package/src/extension/system-prompt.ts +38 -0
  115. package/src/extension/unseen-completions.ts +237 -0
  116. package/src/opencode/actions.ts +794 -0
  117. package/src/opencode/bridge.ts +777 -0
  118. package/src/opencode/display.ts +36 -0
  119. package/src/opencode/fieldnotes.ts +60 -0
  120. package/src/opencode/host.ts +62 -0
  121. package/src/opencode/orphans.ts +162 -0
  122. package/src/opencode/server.ts +458 -0
  123. package/src/runtimes/backend.ts +119 -0
  124. package/src/runtimes/detect.ts +102 -0
  125. package/src/runtimes/hc/hc.ts +527 -0
  126. package/src/runtimes/hc/runtime.ts +1898 -0
  127. package/src/runtimes/herdr/herdr.ts +912 -0
  128. package/src/runtimes/herdr/lifecycle.ts +1712 -0
  129. package/src/runtimes/herdr/messaging.ts +703 -0
  130. package/src/runtimes/herdr/orchestration.ts +1583 -0
  131. package/src/runtimes/herdr/runtime.ts +224 -0
  132. package/src/runtimes/runtime.ts +133 -0
  133. package/src/runtimes/settle-observations.ts +114 -0
  134. package/test/fixtures/context-project/AGENTS.md +2 -0
  135. package/test/fixtures/home/.agents/agents/same.md +6 -0
  136. package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
  137. package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
  138. package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
  139. package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
  140. package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
  141. package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
  142. package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
  143. package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
  144. package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
  145. package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
  146. package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
  147. package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
  148. package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
  149. package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
  150. package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
  151. package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
  152. package/test/fixtures/proj/.pi/agents/same.md +6 -0
  153. package/test/helpers/fake-clock.mjs +39 -0
  154. package/test/helpers/feature-contracts.mjs +44 -0
  155. package/test/helpers/test-utils.mjs +44 -0
  156. package/test/verify-artifact-sessions.mjs +258 -0
  157. package/test/verify-backend.mjs +297 -0
  158. package/test/verify-child-mislabel.mjs +135 -0
  159. package/test/verify-child-surface.mjs +321 -0
  160. package/test/verify-cli.mjs +197 -0
  161. package/test/verify-command-ux.mjs +100 -0
  162. package/test/verify-compat.mjs +32 -0
  163. package/test/verify-cross-host-notes.mjs +128 -0
  164. package/test/verify-delegate.mjs +161 -0
  165. package/test/verify-detect.mjs +151 -0
  166. package/test/verify-discovery.mjs +239 -0
  167. package/test/verify-done-nudge.mjs +238 -0
  168. package/test/verify-effective-prompt.mjs +98 -0
  169. package/test/verify-hc-matrix.mjs +246 -0
  170. package/test/verify-hc-poll.mjs +260 -0
  171. package/test/verify-host-docs.mjs +35 -0
  172. package/test/verify-host-impact.mjs +49 -0
  173. package/test/verify-ids.mjs +141 -0
  174. package/test/verify-launch.mjs +183 -0
  175. package/test/verify-message-routing.mjs +560 -0
  176. package/test/verify-messaging.mjs +303 -0
  177. package/test/verify-migration-notice.mjs +69 -0
  178. package/test/verify-multi-wait.mjs +42 -0
  179. package/test/verify-opencode-display.mjs +47 -0
  180. package/test/verify-opencode-fieldnotes.mjs +121 -0
  181. package/test/verify-opencode-notice.mjs +77 -0
  182. package/test/verify-opencode-nudge.mjs +116 -0
  183. package/test/verify-opencode-orphans.mjs +160 -0
  184. package/test/verify-opencode-surface.mjs +107 -0
  185. package/test/verify-packaging.mjs +82 -0
  186. package/test/verify-parent-surface.mjs +118 -0
  187. package/test/verify-phase0.mjs +95 -0
  188. package/test/verify-registry.mjs +124 -0
  189. package/test/verify-rename-migration.mjs +111 -0
  190. package/test/verify-rendering.mjs +379 -0
  191. package/test/verify-session-boundary.mjs +146 -0
  192. package/test/verify-settings.mjs +260 -0
  193. package/test/verify-stale-wait.mjs +339 -0
  194. package/test/verify-status-widget.mjs +377 -0
  195. package/test/verify-status.mjs +172 -0
  196. package/test/verify-task-completion.mjs +156 -0
  197. package/test/verify-task-failures.mjs +201 -0
  198. package/test/verify-task-mislabel.mjs +143 -0
  199. package/test/verify-task-registry.mjs +194 -0
  200. package/test/verify-task-watchers.mjs +217 -0
  201. package/test/verify-tool-schemas.mjs +120 -0
  202. package/test/verify-unseen-completions.mjs +1211 -0
  203. package/test/verify-watchers.mjs +181 -0
@@ -0,0 +1,458 @@
1
+ /**
2
+ * OpenCode server plugin entry (spec 013, Phase 3).
3
+ *
4
+ * Registers the Shepherd tool family and the `/shepherd` command against
5
+ * the shared engine: spawn/delegate/message/watch/status/read/close plus
6
+ * the herd/agents/prune umbrella, with the child shepherd_message and
7
+ * shepherd_done tools served from the same surface (sheep sessions are
8
+ * gated out of the parent tools, parent sessions out of shepherd_done).
9
+ * Parent fieldnotes sessions resolve onto the shared `.shepherd/sessions`
10
+ * layout (Phase 4); settings are file-based for now (see the carried-forward
11
+ * spec question).
12
+ */
13
+
14
+ import { Plugin } from "@opencode/plugin"
15
+ import { installOpencodeHost } from "./host.ts"
16
+ import {
17
+ closeSheep,
18
+ delegateSheep,
19
+ listAgents,
20
+ listHerd,
21
+ messageSheep,
22
+ pruneRegistrations,
23
+ readSheep,
24
+ sheepDone,
25
+ sheepMessage,
26
+ spawnSheep,
27
+ statusSheep,
28
+ watchSheep,
29
+ type OpencodeActionContext,
30
+ } from "./actions.ts"
31
+ import { installOpencodeBridges, isSheepSession, markParentSession } from "./bridge.ts"
32
+ import { parseShepherdCli, tokenizeCli } from "../extension/cli.ts"
33
+ import { displayCommandOutput } from "./display.ts"
34
+ import { migrationNoticeOnce } from "../core/migration.ts"
35
+ import { noticeNewOrphans, reapOrphans } from "./orphans.ts"
36
+
37
+ installOpencodeHost()
38
+
39
+ /** Resolve the OpenCode session's working directory for engine calls. */
40
+ async function actionContext(ctx: any, sessionID: string): Promise<OpencodeActionContext> {
41
+ try {
42
+ const session = await ctx.session.get({ sessionID })
43
+ const directory = (session as any)?.directory
44
+ if (typeof directory === "string" && directory.length > 0) return { cwd: directory, sessionId: sessionID }
45
+ } catch {
46
+ // Fall through to the plugin location, then the process cwd.
47
+ }
48
+ return { cwd: ctx.location?.directory ?? process.cwd(), sessionId: sessionID }
49
+ }
50
+
51
+ function errorText(error: unknown): string {
52
+ return error instanceof Error ? error.message : String(error ?? "unknown error")
53
+ }
54
+
55
+ /** Display a human-facing command result without starting an assistant turn. */
56
+ async function showCommandOutput(ctx: any, sessionID: string, text: string): Promise<void> {
57
+ // Farewell notice for the old package name: human sessions only, once per
58
+ // host user, and display-only like the rest of the command output.
59
+ if (!isSheepSession(sessionID)) {
60
+ const notice = migrationNoticeOnce()
61
+ if (notice) text = `${notice}\n\n${text}`
62
+ }
63
+ try {
64
+ await displayCommandOutput(ctx, sessionID, text)
65
+ } catch (error) {
66
+ // Never fall back to session.prompt here: that would reintroduce the turn.
67
+ console.error(`shepherd: command display failed: ${errorText(error)}`)
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Gate a parent-only tool: sheep sessions cannot orchestrate. Marks every
73
+ * other caller as a parent session (sheep-only tools refuse those).
74
+ */
75
+ function parentOnly(sessionID: string, tool: string): void {
76
+ if (isSheepSession(sessionID)) {
77
+ throw new Error(`${tool} is not available in sheep sessions; sheep use shepherd_message and shepherd_done.`)
78
+ }
79
+ markParentSession(sessionID)
80
+ }
81
+
82
+ const PLACEMENT_DESC =
83
+ "Optional placement: pane_right or pane_down splits the current pane, tab creates a new tab, and workspace creates a new workspace. If omitted, uses a background tab."
84
+
85
+ export default Plugin.define({
86
+ id: "shepherd",
87
+ async setup(ctx) {
88
+ installOpencodeBridges(ctx)
89
+ // A reload loses in-memory sheep state but not the owned panes/terminals.
90
+ // Surface them once per orphan set; never block tool registration on it.
91
+ void noticeNewOrphans(ctx)
92
+ await ctx.tool.transform((editor) => {
93
+ editor.add({
94
+ name: "shepherd",
95
+ description:
96
+ "Shepherd control plane: list the live herd (agents in Herdr panes), list available agent definitions, prune stale registrations, or reap sheep orphaned by a server restart. Lifecycle operations are separate tools: shepherd_spawn, shepherd_status, shepherd_read, shepherd_close.",
97
+ input: {
98
+ type: "object",
99
+ properties: {
100
+ action: {
101
+ type: "string",
102
+ enum: ["herd", "agents", "prune", "reap"],
103
+ description:
104
+ "herd: live agents. agents: definitions. prune: drop stale registrations. reap: close sheep orphaned by a server restart.",
105
+ },
106
+ agentScope: {
107
+ type: "string",
108
+ enum: ["user", "project", "both"],
109
+ description: "Which agent-definition directories to use (agents action only).",
110
+ },
111
+ },
112
+ required: ["action"],
113
+ additionalProperties: false,
114
+ },
115
+ execute: async (input: any, context: any) => {
116
+ parentOnly(context.sessionID, "shepherd")
117
+ const actx = await actionContext(ctx, context.sessionID)
118
+ const action = (input as any).action
119
+ if (action === "herd") return { content: await listHerd(actx) }
120
+ if (action === "agents")
121
+ return { content: await listAgents(actx, { agentScope: (input as any).agentScope }) }
122
+ if (action === "reap") return { content: reapOrphans(context.sessionID) }
123
+ return { content: await pruneRegistrations(actx) }
124
+ },
125
+ })
126
+
127
+ editor.add({
128
+ name: "shepherd_spawn",
129
+ description:
130
+ "Spawn an idle, persistent agent in a Herdr pane (no task submitted). Provide a short task-specific label (for example: code review). Use shepherd with action agents first if you do not know an exact agent name. The result prints an opaque agent id; pass it to shepherd_status, shepherd_read, or shepherd_close. Never use a pane id where an agent id is expected.",
131
+ input: {
132
+ type: "object",
133
+ properties: {
134
+ agent: {
135
+ type: "string",
136
+ description: "Exact discovered agent name (case-sensitive).",
137
+ },
138
+ label: {
139
+ type: "string",
140
+ description: "Short task-specific label (max 64 characters).",
141
+ },
142
+ placement: { type: "string", description: PLACEMENT_DESC },
143
+ cwd: {
144
+ type: "string",
145
+ description: "Working directory for the child; defaults to the session cwd.",
146
+ },
147
+ },
148
+ required: ["agent"],
149
+ additionalProperties: false,
150
+ },
151
+ execute: async (input: any, context: any) => {
152
+ parentOnly(context.sessionID, "shepherd_spawn")
153
+ const actx = await actionContext(ctx, context.sessionID)
154
+ return {
155
+ content: await spawnSheep(actx, {
156
+ agent: String((input as any).agent ?? ""),
157
+ label: String((input as any).label ?? ""),
158
+ placement: (input as any).placement,
159
+ cwd: (input as any).cwd,
160
+ }),
161
+ }
162
+ },
163
+ })
164
+
165
+ editor.add({
166
+ name: "shepherd_status",
167
+ description:
168
+ "Inspect a spawned agent without focusing or mutating its pane. Reports process state plus the state of its active task (an idle process can own a waiting task).",
169
+ input: {
170
+ type: "object",
171
+ properties: {
172
+ id: {
173
+ type: "string",
174
+ description: "Exact opaque agent id returned by shepherd_spawn. Never a pane id.",
175
+ },
176
+ },
177
+ required: ["id"],
178
+ additionalProperties: false,
179
+ },
180
+ execute: async (input: any, context: any) => {
181
+ parentOnly(context.sessionID, "shepherd_status")
182
+ const actx = await actionContext(ctx, context.sessionID)
183
+ return { content: await statusSheep(actx, { id: String((input as any).id ?? "") }) }
184
+ },
185
+ })
186
+
187
+ editor.add({
188
+ name: "shepherd_read",
189
+ description:
190
+ "Read recent terminal output from a spawned agent for diagnostics. Accepts an agent name, pane id, or opaque agent id.",
191
+ input: {
192
+ type: "object",
193
+ properties: {
194
+ name: {
195
+ type: "string",
196
+ description: "Agent name, pane id, or opaque agent id of the target.",
197
+ },
198
+ lines: {
199
+ type: "number",
200
+ description: "Number of recent lines for read (default 40).",
201
+ },
202
+ },
203
+ required: ["name"],
204
+ additionalProperties: false,
205
+ },
206
+ execute: async (input: any, context: any) => {
207
+ parentOnly(context.sessionID, "shepherd_read")
208
+ const actx = await actionContext(ctx, context.sessionID)
209
+ return {
210
+ content: await readSheep(actx, {
211
+ target: String((input as any).name ?? ""),
212
+ lines: (input as any).lines,
213
+ }),
214
+ }
215
+ },
216
+ })
217
+
218
+ editor.add({
219
+ name: "shepherd_close",
220
+ description:
221
+ "Close an owned agent and cancel its active task. Only shepherd-created work is closed.",
222
+ input: {
223
+ type: "object",
224
+ properties: {
225
+ id: {
226
+ type: "string",
227
+ description: "Exact opaque agent id returned by shepherd_spawn. Never a pane id.",
228
+ },
229
+ },
230
+ required: ["id"],
231
+ additionalProperties: false,
232
+ },
233
+ execute: async (input: any, context: any) => {
234
+ parentOnly(context.sessionID, "shepherd_close")
235
+ const actx = await actionContext(ctx, context.sessionID)
236
+ return { content: await closeSheep(actx, { id: String((input as any).id ?? "") }) }
237
+ },
238
+ })
239
+
240
+ editor.add({
241
+ name: "shepherd_delegate",
242
+ description:
243
+ "Start tracked asynchronous work on a spawned agent and return a task id immediately. The task can span runs; use shepherd_watch to observe terminal completion. Nothing settles until the sheep calls shepherd_done (or the task fails, is cancelled, or times out).",
244
+ input: {
245
+ type: "object",
246
+ properties: {
247
+ target: {
248
+ type: "string",
249
+ description: "Exact opaque agent id returned by shepherd_spawn. Never a pane id.",
250
+ },
251
+ task: { type: "string", description: "Non-empty delegated task description." },
252
+ timeout: {
253
+ type: "number",
254
+ description: "Optional task deadline in minutes (default 60).",
255
+ },
256
+ },
257
+ required: ["target", "task"],
258
+ additionalProperties: false,
259
+ },
260
+ execute: async (input: any, context: any) => {
261
+ parentOnly(context.sessionID, "shepherd_delegate")
262
+ const actx = await actionContext(ctx, context.sessionID)
263
+ return {
264
+ content: await delegateSheep(actx, {
265
+ target: String((input as any).target ?? ""),
266
+ task: String((input as any).task ?? ""),
267
+ timeout: (input as any).timeout,
268
+ }),
269
+ }
270
+ },
271
+ })
272
+
273
+ editor.add({
274
+ name: "shepherd_watch",
275
+ description:
276
+ "Register a non-blocking one-shot watcher for task completions. Returns immediately; already-settled tasks are reported inline and pending completions arrive automatically. Accepts one task id or a non-empty array.",
277
+ input: {
278
+ type: "object",
279
+ properties: {
280
+ id: {
281
+ anyOf: [
282
+ { type: "string", description: "Opaque task id returned by shepherd_delegate." },
283
+ {
284
+ type: "array",
285
+ items: { type: "string" },
286
+ minItems: 1,
287
+ description: "Non-empty array of opaque task ids.",
288
+ },
289
+ ],
290
+ },
291
+ },
292
+ required: ["id"],
293
+ additionalProperties: false,
294
+ },
295
+ execute: async (input: any, context: any) => {
296
+ parentOnly(context.sessionID, "shepherd_watch")
297
+ const actx = await actionContext(ctx, context.sessionID)
298
+ return { content: await watchSheep(actx, { id: (input as any).id }) }
299
+ },
300
+ })
301
+
302
+ editor.add({
303
+ name: "shepherd_message",
304
+ description:
305
+ "Send one asynchronous message and return immediately. Parent form: target MUST be the exact opaque sheep agent id from shepherd_spawn; use expectsReply with a taskId to park the task until the reply arrives. Sheep form (delegated sheep sessions only): target parent/shepherd or a peer agent id; set taskId/replyTo from the delivered task text.",
306
+ input: {
307
+ type: "object",
308
+ properties: {
309
+ target: {
310
+ type: "string",
311
+ description:
312
+ "Parent form: exact opaque sheep agent id. Sheep form: parent, shepherd, or a peer agent id.",
313
+ },
314
+ message: { type: "string", description: "Non-empty message content." },
315
+ taskId: { type: "string", description: "Active delegated task id, when this message belongs to a task." },
316
+ threadId: { type: "string", description: "Conversation/thread correlation id." },
317
+ replyTo: { type: "string", description: "Message id of the request being answered." },
318
+ expectsReply: {
319
+ type: "boolean",
320
+ description: "Track this message as a request that expects a reply.",
321
+ },
322
+ delivery: {
323
+ type: "string",
324
+ enum: ["followUp", "steer"],
325
+ description: "Delivery mode; followUp queues passively, steer is for urgent input.",
326
+ },
327
+ },
328
+ required: ["target", "message"],
329
+ additionalProperties: false,
330
+ },
331
+ execute: async (input: any, context: any) => {
332
+ const actx = await actionContext(ctx, context.sessionID)
333
+ const args = {
334
+ target: String((input as any).target ?? ""),
335
+ message: String((input as any).message ?? ""),
336
+ taskId: (input as any).taskId,
337
+ threadId: (input as any).threadId,
338
+ replyTo: (input as any).replyTo,
339
+ expectsReply: (input as any).expectsReply,
340
+ delivery: (input as any).delivery,
341
+ }
342
+ if (isSheepSession(context.sessionID)) {
343
+ const result = await sheepMessage(actx, args, context.sessionID)
344
+ if (result.parentPrompt && result.parentSessionId) {
345
+ try {
346
+ await ctx.session.prompt({ sessionID: result.parentSessionId, text: result.parentPrompt })
347
+ } catch {
348
+ result.text += " (parent notice delivery failed; the message itself was accepted)"
349
+ }
350
+ }
351
+ return { content: result.text }
352
+ }
353
+ markParentSession(context.sessionID)
354
+ return { content: await messageSheep(actx, args) }
355
+ },
356
+ })
357
+
358
+ editor.add({
359
+ name: "shepherd_done",
360
+ description:
361
+ "Sheep-only: explicitly complete, block, or fail the current delegated task. This is the only signal that tells the parent a tracked task has finished. Include the Task ID from the delegated task text.",
362
+ input: {
363
+ type: "object",
364
+ properties: {
365
+ taskId: {
366
+ type: "string",
367
+ description: "Exact Task ID from the delegated task text (omit only to complete the sheep's open task).",
368
+ },
369
+ status: {
370
+ type: "string",
371
+ enum: ["completed", "blocked", "failed"],
372
+ description: "Terminal status for the delegated task.",
373
+ },
374
+ summary: {
375
+ type: "string",
376
+ description: "Concise completion, blocked, or failure summary.",
377
+ },
378
+ },
379
+ required: ["status"],
380
+ additionalProperties: false,
381
+ },
382
+ execute: async (input: any, context: any) => {
383
+ const actx = await actionContext(ctx, context.sessionID)
384
+ const result = await sheepDone(
385
+ actx,
386
+ {
387
+ taskId: (input as any).taskId,
388
+ status: String((input as any).status ?? ""),
389
+ summary: (input as any).summary,
390
+ },
391
+ context.sessionID
392
+ )
393
+ return { content: result.text }
394
+ },
395
+ })
396
+ })
397
+
398
+ await ctx.command.transform((editor) => {
399
+ editor.add({
400
+ name: "shepherd",
401
+ description: "Shepherd: agents | herd | spawn <agent> | status <target> | read <target>",
402
+ execute: async ({ sessionID, prompt }: any) => {
403
+ markParentSession(sessionID)
404
+ const actx = await actionContext(ctx, sessionID)
405
+ const raw = String(prompt?.text ?? "").trim()
406
+ if (!raw) {
407
+ await showCommandOutput(
408
+ ctx,
409
+ sessionID,
410
+ [
411
+ "Shepherd settings are file-based in Phase 2: edit the user config or the",
412
+ "project `.shepherd/config.json` directly. For herd operations use one of:",
413
+ "agents, herd, spawn <agent>, status <target>, read <target>.",
414
+ ].join("\n")
415
+ )
416
+ return
417
+ }
418
+ const parsed = parseShepherdCli(tokenizeCli(raw))
419
+ if ("error" in parsed) {
420
+ await showCommandOutput(ctx, sessionID, `Shepherd: ${parsed.error}`)
421
+ return
422
+ }
423
+ try {
424
+ const args = parsed.args as any
425
+ let result: string
426
+ switch (parsed.action) {
427
+ case "herd":
428
+ result = await listHerd(actx)
429
+ break
430
+ case "agents":
431
+ result = await listAgents(actx, { agentScope: args.agentScope })
432
+ break
433
+ case "spawn":
434
+ result = await spawnSheep(actx, {
435
+ agent: args.agent,
436
+ label: args.label ?? "",
437
+ placement: args.placement,
438
+ cwd: args.cwd,
439
+ })
440
+ break
441
+ case "status":
442
+ result = await statusSheep(actx, { id: args.id })
443
+ break
444
+ case "read":
445
+ result = await readSheep(actx, { target: args.name, lines: args.lines })
446
+ break
447
+ default:
448
+ result = `Shepherd: action "${parsed.action}" is not available from the command yet; use the shepherd_* tools.`
449
+ }
450
+ await showCommandOutput(ctx, sessionID, `[shepherd ${parsed.action}]\n${result}`)
451
+ } catch (error) {
452
+ await showCommandOutput(ctx, sessionID, `Shepherd command failed: ${errorText(error)}`)
453
+ }
454
+ },
455
+ })
456
+ })
457
+ },
458
+ })
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Backend resolver (009 Phase 0.2) — which runtime should this command use?
3
+ *
4
+ * App-side only. The model never decides: no `shepherd_*` tool schema,
5
+ * prompt snippet, or result mentions `backend`. The pin lives in
6
+ * `src/core/config.ts` (`backend: auto|herdr|hc`, default `auto`,
7
+ * user-owned precedence — a project file can never force it) plus one row
8
+ * in `/shepherd settings`.
9
+ *
10
+ * `resolveBackend(pin, caller)`:
11
+ * - pin `herdr|hc` wins outright; when that runtime is unreachable it throws
12
+ * with a setup hint and no fallback (never cross-spawns).
13
+ * - pin `auto` (default) maps the caller: `herdr-tui->herdr`,
14
+ * `hc-app->hc`, `plain->reachable-or-error` (prefer `herdr` server when
15
+ * up, else `hc`, else throw naming both hints).
16
+ *
17
+ * Pure given injected probes; defaults hit the local machine synchronously
18
+ * with a short timeout. Never returns `auto`, never leaks pane/terminal ids
19
+ * or socket paths — callers surface only the setup hint.
20
+ */
21
+
22
+ import { execFileSync } from 'node:child_process';
23
+ import type { BackendSetting, ResolvedBackend } from '../core/config.ts';
24
+ import type { CallerKind } from './detect.ts';
25
+
26
+ export type { BackendSetting, ResolvedBackend };
27
+
28
+ export const HC_SETUP_HINT =
29
+ 'Run from an `hc` terminal (HC_TERMINAL_ID and HC_TERMINAL_SOCKET set) with `hc` on PATH.';
30
+
31
+ export const HERDR_SETUP_HINT_FALLBACK =
32
+ 'Run `herdr` to start/attach Herdr (or ensure the headless server is up), and keep `herdr` on PATH.';
33
+
34
+ const PROBE_TIMEOUT_MS = 3_000;
35
+
36
+ function defaultIsHerdrReachable(): boolean {
37
+ try {
38
+ execFileSync('herdr', ['--version'], { stdio: 'ignore', timeout: PROBE_TIMEOUT_MS });
39
+ } catch {
40
+ return false;
41
+ }
42
+ if (process.env.HERDR_ENV === '1') return true;
43
+ try {
44
+ const out = execFileSync('herdr', ['status', 'server'], {
45
+ encoding: 'utf8',
46
+ timeout: PROBE_TIMEOUT_MS,
47
+ });
48
+ return /status:\s*running/i.test(String(out));
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ function defaultIsHcReachable(): boolean {
55
+ try {
56
+ execFileSync('hc', ['ls'], { stdio: 'ignore', timeout: PROBE_TIMEOUT_MS });
57
+ return true;
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
62
+
63
+ export interface ResolveBackendDeps {
64
+ isHerdrReachable?: () => boolean;
65
+ isHcReachable?: () => boolean;
66
+ }
67
+
68
+ function safeProbe(probe: () => boolean): boolean {
69
+ try {
70
+ return probe() === true;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Pick the concrete runtime for one command. Throws with a setup hint when
78
+ * the pinned (or plain-auto) runtime is unreachable — callers convert this
79
+ * to the standard Shepherd error shape, never a fallback spawn.
80
+ */
81
+ export function resolveBackend(
82
+ pin: BackendSetting,
83
+ caller: CallerKind,
84
+ deps: ResolveBackendDeps = {}
85
+ ): ResolvedBackend {
86
+ const isHerdrReachable = deps.isHerdrReachable ?? defaultIsHerdrReachable;
87
+ const isHcReachable = deps.isHcReachable ?? defaultIsHcReachable;
88
+
89
+ if (pin === 'herdr') {
90
+ if (!safeProbe(isHerdrReachable)) {
91
+ throw new Error(
92
+ `backend "herdr" is pinned but unreachable. ${HERDR_SETUP_HINT_FALLBACK} ` +
93
+ `No fallback was attempted: set backend to "auto" to run where called from.`
94
+ );
95
+ }
96
+ return 'herdr';
97
+ }
98
+
99
+ if (pin === 'hc') {
100
+ if (!safeProbe(isHcReachable)) {
101
+ throw new Error(
102
+ `backend "hc" is pinned but unreachable. ${HC_SETUP_HINT} ` +
103
+ `No fallback was attempted: set backend to "auto" to run where called from.`
104
+ );
105
+ }
106
+ return 'hc';
107
+ }
108
+
109
+ // auto: run where called from.
110
+ if (caller === 'herdr-tui') return 'herdr';
111
+ if (caller === 'hc-app') return 'hc';
112
+
113
+ // plain caller: prefer a reachable herdr server, else hc, else clean error.
114
+ if (safeProbe(isHerdrReachable)) return 'herdr';
115
+ if (safeProbe(isHcReachable)) return 'hc';
116
+ throw new Error(
117
+ `No reachable backend (plain caller, backend "auto"). ${HERDR_SETUP_HINT_FALLBACK} ${HC_SETUP_HINT}`
118
+ );
119
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Caller detection (009 Phase 0.1) — where is this Shepherd command running?
3
+ *
4
+ * Pure `detectCaller()`: `herdr-tui | hc-app | plain` from env + binary +
5
+ * socket only. No tool/result/README surface, no behavior change; the Phase
6
+ * 0.2 resolver will consume this per command.
7
+ *
8
+ * Authoritative signals only (never labels/titles):
9
+ * - `herdr-tui` iff `HERDR_ENV == "1"` AND `HERDR_PANE_ID` set AND
10
+ * `herdr --version` exits 0.
11
+ * - `hc-app` iff `HC_TERMINAL_ID` set AND `HC_TERMINAL_SOCKET` exists AND
12
+ * `hc ls` exits 0.
13
+ * - `plain` otherwise.
14
+ *
15
+ * Nested tiebreak (innermost wins): when both env groups are present — e.g.
16
+ * a TUI pane that ran `hc run`, whose child inherits `HERDR_*` and gains
17
+ * fresh `HC_*` — the `hc-app` check runs first. Rationale: `HC_TERMINAL_ID`
18
+ * is minted per `hc` invocation (the direct caller), while `HERDR_ENV=1` is
19
+ * broadly inherited down the process tree, so `HC_*` presence is the
20
+ * stronger direct-caller signal. A half-signal (env present but binary or
21
+ * socket missing) never masks a fully-validated other runtime; it falls
22
+ * through to `plain`.
23
+ *
24
+ * Unit-testable: pass `{ env, execOk, fileExists }` to inject fakes.
25
+ * Defaults read `process.env`, probe synchronously with a short timeout,
26
+ * and check the socket with `fs.existsSync`. Env is checked first, so a
27
+ * `plain` process never spawns a subprocess.
28
+ */
29
+
30
+ import { execFileSync } from 'node:child_process';
31
+ import { existsSync } from 'node:fs';
32
+
33
+ /** Where the current Shepherd command was invoked from. Internal only. */
34
+ export type CallerKind = 'herdr-tui' | 'hc-app' | 'plain';
35
+
36
+ /** String-valued environment mapping (`process.env` shape). */
37
+ export type EnvLike = { [key: string]: string | undefined };
38
+
39
+ /**
40
+ * Synchronous binary probe: true iff `cmd args...` exits 0.
41
+ * Injected fakes may record calls to assert the env-first short-circuit.
42
+ */
43
+ export type ExecProbe = (cmd: string, args: string[]) => boolean;
44
+
45
+ /** Synchronous path-existence check (socket probe). Defaults to `existsSync`. */
46
+ export type ExistsProbe = (path: string) => boolean;
47
+
48
+ export interface DetectDeps {
49
+ env?: EnvLike;
50
+ execOk?: ExecProbe;
51
+ fileExists?: ExistsProbe;
52
+ }
53
+
54
+ /** Short subprocess cap so per-command detection stays cheap. */
55
+ const PROBE_TIMEOUT_MS = 3_000;
56
+
57
+ function defaultExecOk(cmd: string, args: string[]): boolean {
58
+ try {
59
+ execFileSync(cmd, args, { stdio: 'ignore', timeout: PROBE_TIMEOUT_MS });
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ function hasText(value: string | undefined): value is string {
67
+ return typeof value === 'string' && value.length > 0;
68
+ }
69
+
70
+ /**
71
+ * Classify the current caller. Pure given `deps`; reads `process.env` and
72
+ * probes the local machine by default. Never throws — probe failures fall
73
+ * through to the next candidate, then `plain`.
74
+ */
75
+ export function detectCaller(deps: DetectDeps = {}): CallerKind {
76
+ const env = deps.env ?? (process.env as EnvLike);
77
+ const execOk = deps.execOk ?? defaultExecOk;
78
+ const fileExists = deps.fileExists ?? existsSync;
79
+
80
+ // hc-app first: innermost wins when both env groups are present.
81
+ if (hasText(env.HC_TERMINAL_ID) && hasText(env.HC_TERMINAL_SOCKET)) {
82
+ try {
83
+ if (fileExists(env.HC_TERMINAL_SOCKET) && execOk('hc', ['ls'])) {
84
+ return 'hc-app';
85
+ }
86
+ } catch {
87
+ // Probe threw synchronously (fake or fs error) — try herdr, then plain.
88
+ }
89
+ }
90
+
91
+ if (env.HERDR_ENV === '1' && hasText(env.HERDR_PANE_ID)) {
92
+ try {
93
+ if (execOk('herdr', ['--version'])) {
94
+ return 'herdr-tui';
95
+ }
96
+ } catch {
97
+ // Probe threw synchronously — fall through to plain.
98
+ }
99
+ }
100
+
101
+ return 'plain';
102
+ }