@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,77 @@
1
+ /**
2
+ * Host capability seam (spec 013, Phase 1).
3
+ *
4
+ * The shared engine must not statically import any host SDK: a static
5
+ * `@earendil-works/pi-*` import in the engine module graph would fail to
6
+ * load on the OpenCode path, where those packages are not installed.
7
+ * Host-specific values (agent directory, project config dir name, registry
8
+ * subdir, frontmatter parser) therefore arrive through this module.
9
+ *
10
+ * Resolution order: an explicitly installed capability wins (each adapter
11
+ * installs its own at load); otherwise Pi's implementations are resolved
12
+ * once via dynamic import. A missing Pi package (the OpenCode path) is
13
+ * detected precisely by `ERR_MODULE_NOT_FOUND` and means the host must
14
+ * install its own capabilities; any other import failure is rethrown so a
15
+ * broken Pi install is never masked. Existing tests keep passing untouched
16
+ * because the Pi defaults honor the same `HOME` / `PI_CODING_AGENT_DIR`
17
+ * env vars.
18
+ */
19
+
20
+ // The Pi SDK is ESM-only (no `require` condition), so the fallback must be
21
+ // a dynamic import. Top-level await keeps every call site synchronous.
22
+
23
+ export interface FrontmatterResult<T> {
24
+ frontmatter: T;
25
+ body: string;
26
+ }
27
+
28
+ export interface HostCapabilities {
29
+ /** Active agent dir (Pi: `getAgentDir()`; honors `PI_CODING_AGENT_DIR`). */
30
+ getAgentDir(): string;
31
+ /** Project config dir name (Pi: `CONFIG_DIR_NAME`, i.e. `.pi`). */
32
+ projectConfigDirName: string;
33
+ /** Data subdir under the agent dir (frozen: `pi-shepherd`, see FR-013). */
34
+ dataDirName: string;
35
+ /** YAML-frontmatter parser for agent definition files. */
36
+ parseFrontmatter<T>(content: string): FrontmatterResult<T>;
37
+ }
38
+
39
+ let explicit: HostCapabilities | undefined;
40
+ let piFallback: HostCapabilities | undefined;
41
+ let piUnavailable = false;
42
+
43
+ /** Install the calling host's capabilities. Each adapter calls this at load. */
44
+ export function setHostCapabilities(caps: HostCapabilities): void {
45
+ explicit = caps;
46
+ }
47
+
48
+ try {
49
+ const pi = (await import('@earendil-works/pi-coding-agent')) as {
50
+ getAgentDir(): string;
51
+ CONFIG_DIR_NAME: string;
52
+ parseFrontmatter<T>(content: string): FrontmatterResult<T>;
53
+ };
54
+ piFallback = {
55
+ getAgentDir: pi.getAgentDir,
56
+ projectConfigDirName: pi.CONFIG_DIR_NAME,
57
+ dataDirName: 'pi-shepherd',
58
+ parseFrontmatter: pi.parseFrontmatter,
59
+ };
60
+ } catch (error) {
61
+ // Only a missing package means "different host"; anything else (a
62
+ // broken Pi install) must surface, not silently degrade.
63
+ if ((error as { code?: string })?.code !== 'ERR_MODULE_NOT_FOUND') throw error;
64
+ piUnavailable = true;
65
+ }
66
+
67
+ /** Active capabilities: explicit install wins, Pi fallback otherwise. */
68
+ export function hostCapabilities(): HostCapabilities {
69
+ if (explicit) return explicit;
70
+ if (piFallback) return piFallback;
71
+ throw new Error(
72
+ 'No Shepherd host capabilities installed. ' +
73
+ (piUnavailable
74
+ ? 'The Pi SDK is not installed; the host adapter must call setHostCapabilities() at load.'
75
+ : 'The Pi SDK failed to load and no host capabilities were installed.')
76
+ );
77
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Opaque id codec shared by every Shepherd runtime.
3
+ *
4
+ * Pure helpers only: no registry state, no runtime imports, and no
5
+ * `LifecycleError` dependency. Callers own their error type and translate a
6
+ * failed normalization into it. Public formats are part of the model-facing
7
+ * contract and must stay stable:
8
+ *
9
+ * mintId('agent', sessionId) -> shepherd-agent-<session>-<uuid>
10
+ * mintId('prompt', sessionId) -> shepherd-prompt-<session>-<uuid>
11
+ * mintId('task', sessionId) -> shepherd-task-<session>-<uuid>
12
+ * mintId('watch', sessionId) -> shepherd-watch-<session>-<uuid>
13
+ * mintMessageId() -> shepherd-message-<uuid>
14
+ *
15
+ * Handles are opaque: callers pass the id string itself or `{ id: "..." }`,
16
+ * and the value is never parsed for pane/conversation identity.
17
+ */
18
+
19
+ import { randomUUID } from 'node:crypto';
20
+
21
+ /** Kind segment of a registry-minted handle id. */
22
+ export type IdKind = 'agent' | 'prompt' | 'task' | 'watch';
23
+
24
+ /** Handle kinds accepted by `normalizeHandleId`. */
25
+ export type HandleKind = 'AgentHandle' | 'PromptHandle' | 'TaskHandle';
26
+
27
+ /** Normalization outcome: the id, or the byte-stable error message to expose. */
28
+ export type HandleNormalization =
29
+ | { readonly ok: true; readonly id: string }
30
+ | { readonly ok: false; readonly message: string };
31
+
32
+ /**
33
+ * Invalid-handle messages are literal and byte-stable: public tools surface
34
+ * them verbatim, so nothing may reword, trim, or re-punctuate them.
35
+ */
36
+ const INVALID_HANDLE_MESSAGES: Record<HandleKind, string> = {
37
+ AgentHandle:
38
+ 'Expected the opaque agent id as a string. Do not pass a quoted JSON object, array, or Herdr pane id. Correct syntax: { id: "shepherd-agent-..." }.',
39
+ PromptHandle:
40
+ 'Expected the opaque prompt id as a string. Do not pass a quoted JSON object, array, or Herdr pane id. Correct syntax: { id: "shepherd-prompt-..." } (or { id: ["prompt-a", "prompt-b"] } for parallel wait).',
41
+ TaskHandle:
42
+ 'Expected the opaque TaskHandle id as a string. Do not pass a quoted JSON object, array, agent id, or Herdr pane id. Correct syntax: { id: "shepherd-task-..." }. ',
43
+ };
44
+
45
+ /** Mint the opaque id format `shepherd-<kind>-<session>-<uuid>`. */
46
+ export function mintId(kind: IdKind, sessionId: string): string {
47
+ return `shepherd-${kind}-${sessionId}-${randomUUID()}`;
48
+ }
49
+
50
+ /** Mint the broker envelope format `shepherd-message-<uuid>`. */
51
+ export function mintMessageId(): string {
52
+ return `shepherd-message-${randomUUID()}`;
53
+ }
54
+
55
+ /**
56
+ * Extract an opaque handle id from its two accepted inputs: a non-blank
57
+ * string, or an object with a string `id` property. On rejection it returns
58
+ * the exact per-kind error message instead of throwing.
59
+ *
60
+ * Behavior is intentionally identical to the historical inline
61
+ * `handleId` / `taskHandleId` validators in `LifecycleRegistry`: strings are
62
+ * returned unchanged (not trimmed), and object `id` values are accepted as-is.
63
+ */
64
+ export function normalizeHandleId(input: unknown, kind: HandleKind): HandleNormalization {
65
+ if (typeof input === 'string') {
66
+ if (input.trim().length === 0) return { ok: false, message: INVALID_HANDLE_MESSAGES[kind] };
67
+ return { ok: true, id: input };
68
+ }
69
+ if (
70
+ input !== null &&
71
+ typeof input === 'object' &&
72
+ !Array.isArray(input) &&
73
+ typeof (input as { id?: unknown }).id === 'string'
74
+ ) {
75
+ return { ok: true, id: (input as { id: string }).id };
76
+ }
77
+ return { ok: false, message: INVALID_HANDLE_MESSAGES[kind] };
78
+ }
@@ -0,0 +1 @@
1
+ export * from '../runtimes/herdr/lifecycle.ts';
@@ -0,0 +1 @@
1
+ export * from '../runtimes/herdr/messaging.ts';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * One-time farewell notice for the `@luminascale/pi-shepherd` package name.
3
+ *
4
+ * Host-neutral: the marker lives in the active host's user data directory, so
5
+ * Pi and OpenCode each show the notice once. Child sheep processes never see
6
+ * it — they load the same package but must not receive human-facing release
7
+ * messaging.
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { hostCapabilities } from './host.ts';
13
+
14
+ export const NEW_PACKAGE_NAME = '@luminascale/shepherd';
15
+
16
+ export const MIGRATION_NOTICE =
17
+ `Shepherd is moving to ${NEW_PACKAGE_NAME}. ` +
18
+ 'This is the last release under @luminascale/pi-shepherd. ' +
19
+ 'When you are ready, install @luminascale/shepherd: settings, agent definitions, ' +
20
+ 'registrations, and fieldnotes carry over automatically.';
21
+
22
+ const MARKER_FILE = 'migration-notice.json';
23
+
24
+ /** True inside a launched child (Pi or OpenCode capability prefix). */
25
+ export function isChildShepherdProcess(): boolean {
26
+ return Boolean(process.env.PI_SHEPHERD_SESSION || process.env.SHEPHERD_TASK_ID);
27
+ }
28
+
29
+ export function migrationMarkerFile(): string {
30
+ const host = hostCapabilities();
31
+ return path.join(host.getAgentDir(), host.dataDirName, MARKER_FILE);
32
+ }
33
+
34
+ /**
35
+ * Return the notice exactly once per host user, never in a child process.
36
+ * The marker is created with an exclusive write so concurrent sessions race
37
+ * safely: only one of them receives the text.
38
+ */
39
+ export function migrationNoticeOnce(): string | undefined {
40
+ if (isChildShepherdProcess()) return undefined;
41
+ const file = migrationMarkerFile();
42
+ try {
43
+ fs.mkdirSync(path.dirname(file), { recursive: true });
44
+ fs.writeFileSync(
45
+ file,
46
+ JSON.stringify({ shownAt: new Date().toISOString(), newName: NEW_PACKAGE_NAME }, null, 2),
47
+ { flag: 'wx' }
48
+ );
49
+ } catch (error: any) {
50
+ if (error?.code === 'EEXIST') return undefined;
51
+ // A read-only or full disk must not break the host session.
52
+ return undefined;
53
+ }
54
+ return MIGRATION_NOTICE;
55
+ }
@@ -0,0 +1 @@
1
+ export * from '../runtimes/herdr/orchestration.ts';
@@ -0,0 +1,143 @@
1
+ import { Type, type TUnsafe } from 'typebox';
2
+
3
+ /**
4
+ * String-enum schema helper (spec 013: vendored into the engine so shared
5
+ * code needs no host SDK). Identical output to the Pi helper: a plain
6
+ * `{ type: 'string', enum }` schema, compatible with providers that do not
7
+ * support anyOf/const patterns.
8
+ */
9
+ function StringEnum<T extends readonly string[]>(
10
+ values: T,
11
+ options?: { description?: string; default?: T[number] }
12
+ ): TUnsafe<T[number]> {
13
+ return Type.Unsafe<T[number]>({
14
+ type: 'string',
15
+ enum: values,
16
+ ...(options?.description && { description: options.description }),
17
+ ...(options?.default && { default: options.default }),
18
+ });
19
+ }
20
+
21
+ export const AgentScopeSchema = StringEnum(['user', 'project', 'both'] as const, {
22
+ description:
23
+ 'Which agent-definition directories to use. Defaults to the persisted Shepherd setting; an explicit value overrides it.',
24
+ });
25
+
26
+ export const SpawnPlacementSchema = StringEnum(
27
+ ['pane_right', 'pane_down', 'tab', 'workspace'] as const,
28
+ {
29
+ description:
30
+ '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.',
31
+ }
32
+ );
33
+
34
+ export const SpawnParams = Type.Object({
35
+ action: Type.Literal('spawn', {
36
+ description: 'Spawn an idle persistent agent; does not submit work.',
37
+ }),
38
+ agent: Type.String({
39
+ description:
40
+ 'Exact discovered agent name (case-sensitive). If unsure, call shepherd with action "agents" first.',
41
+ }),
42
+ label: Type.String({
43
+ description:
44
+ 'Short task-specific human label for this spawned instance. Letters, numbers, spaces, _, -, and . only; max 64 characters.',
45
+ }),
46
+ placement: Type.Optional(SpawnPlacementSchema),
47
+ cwd: Type.Optional(Type.String()),
48
+ });
49
+ export const AgentIdSchema = Type.String({
50
+ description:
51
+ 'Exact opaque agent id returned by shepherd_spawn. Copy it verbatim; do not use an agent name (such as "planner"), display label, Herdr pane id, or placeholder such as "<planner agent ID>".',
52
+ });
53
+ export const PromptIdSchema = Type.String({
54
+ description:
55
+ 'Opaque prompt id returned by shepherd_prompt. Do not use an agent id or Herdr pane id.',
56
+ });
57
+ export const TaskIdSchema = Type.String({
58
+ description:
59
+ 'Opaque task id returned by shepherd_delegate. Do not use an agent id or Herdr pane id.',
60
+ });
61
+
62
+ export const LifecycleDelegateParams = Type.Object({
63
+ action: Type.Literal('delegate', {
64
+ description:
65
+ 'Start tracked asynchronous work on a spawned agent and return a task id without waiting.',
66
+ }),
67
+ target: AgentIdSchema,
68
+ task: Type.String({ description: 'Non-empty delegated task description.' }),
69
+ timeout: Type.Optional(
70
+ Type.Integer({ default: 60, description: 'Optional task deadline in minutes.' })
71
+ ),
72
+ });
73
+
74
+ export const LifecyclePromptParams = Type.Object({
75
+ action: Type.Literal('prompt', {
76
+ description:
77
+ 'Deprecated compatibility path: submits one message to an agent and returns a prompt id without waiting. For tracked work, prefer shepherd_delegate (task) + shepherd_watch; shepherd_prompt ties completion to one child turn, so it cannot carry work that must survive peer replies.',
78
+ }),
79
+ id: AgentIdSchema,
80
+ message: Type.String({
81
+ description:
82
+ 'Task or question to submit to the spawned agent. Submission returns immediately; use shepherd_watch for the result.',
83
+ }),
84
+ timeout: Type.Optional(
85
+ Type.Integer({
86
+ default: 60,
87
+ description:
88
+ 'Optional readiness wait before submission; normally omit. It is capped at 15 seconds internally. Completion is reported asynchronously by shepherd_watch.',
89
+ })
90
+ ),
91
+ });
92
+ export const WatchParams = Type.Object({
93
+ action: Type.Literal('watch', {
94
+ description:
95
+ 'Register a non-blocking one-shot watcher for task completions (legacy prompt ids are also accepted).',
96
+ }),
97
+ id: Type.Union(
98
+ [
99
+ TaskIdSchema,
100
+ PromptIdSchema,
101
+ Type.Array(Type.Union([TaskIdSchema, PromptIdSchema]), {
102
+ minItems: 1,
103
+ description:
104
+ 'Array of opaque task (or legacy prompt) ids; completions are reported as each settles.',
105
+ }),
106
+ ],
107
+ {
108
+ description:
109
+ 'One opaque task id (preferred) or legacy prompt id, or a non-empty array of such ids returned by shepherd_delegate (or shepherd_prompt).',
110
+ }
111
+ ),
112
+ });
113
+ export const LifecycleMessageParams = Type.Object({
114
+ action: Type.Literal('message', {
115
+ description:
116
+ 'Send one asynchronous message to an agent and return a message id without waiting.',
117
+ }),
118
+ target: AgentIdSchema,
119
+ message: Type.String({ description: 'Non-empty message content.' }),
120
+ taskId: Type.Optional(TaskIdSchema),
121
+ threadId: Type.Optional(Type.String({ description: 'Conversation/thread correlation id.' })),
122
+ replyTo: Type.Optional(Type.String({ description: 'Message id of the request being answered.' })),
123
+ expectsReply: Type.Optional(
124
+ Type.Boolean({ description: 'Track this message as a request that expects a reply.' })
125
+ ),
126
+ delivery: Type.Optional(
127
+ Type.Union([Type.Literal('followUp'), Type.Literal('steer')], {
128
+ description: 'Delivery mode; followUp is the default, steer is for urgent input.',
129
+ })
130
+ ),
131
+ });
132
+ export const LifecycleStatusParams = Type.Object({
133
+ action: Type.Literal('status', {
134
+ description: 'Inspect an agent without focusing or mutating its Herdr pane.',
135
+ }),
136
+ id: AgentIdSchema,
137
+ });
138
+ export const LifecycleCloseParams = Type.Object({
139
+ action: Type.Literal('close', {
140
+ description: 'Close an owned agent and cancel any unresolved prompt.',
141
+ }),
142
+ id: AgentIdSchema,
143
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Session-scoped ledger of tracked-task settlements that have not yet been
3
+ * noticed by the parent session.
4
+ *
5
+ * The registry settlement observer feeds this ledger whenever a task settles
6
+ * without an attached watcher. The parent extension bridge
7
+ * (`src/extension/unseen-completions.ts`) drains entries after delivering one
8
+ * notice; explicit `shepherd_watch` retrieval and `shepherd_close` clear
9
+ * entries directly.
10
+ *
11
+ * Pure by design: this module must not import `@earendil-works/*`,
12
+ * `src/runtimes/`, or `src/extension/`, so any runtime implementation can feed
13
+ * the same ledger (spec 007).
14
+ */
15
+
16
+ export interface UnseenSettlement {
17
+ taskId: string;
18
+ agentId: string;
19
+ agent?: string;
20
+ label?: string;
21
+ status: 'completed' | 'blocked' | 'failed' | 'timed_out';
22
+ ok: boolean;
23
+ returnCode: number;
24
+ text?: string;
25
+ error?: string;
26
+ }
27
+
28
+ /** Structural settlement input; independent of the runtime's `TaskResult`. */
29
+ export interface UnseenSettlementResult {
30
+ taskId: string;
31
+ agentId: string;
32
+ status: UnseenSettlement['status'] | 'cancelled';
33
+ ok: boolean;
34
+ returnCode: number;
35
+ text?: string;
36
+ error?: string;
37
+ }
38
+
39
+ /** Observer context attached to one settlement. */
40
+ export interface UnseenSettlementContext {
41
+ hadWatchers: boolean;
42
+ agent?: string;
43
+ label?: string;
44
+ source?: 'delegate-submission-failure';
45
+ }
46
+
47
+ /**
48
+ * Map keyed by task id, in insertion order. Entries exist only while
49
+ * un-noticed; notifying (boundary or idle) drains them.
50
+ */
51
+ export class UnseenCompletionLedger {
52
+ private readonly settlements = new Map<string, UnseenSettlement>();
53
+
54
+ /**
55
+ * Add one settlement unless it had watchers, is a parent-initiated
56
+ * cancellation, came from the delegate submission failure path, or is
57
+ * already recorded. Returns whether a new entry was added.
58
+ */
59
+ record(result: UnseenSettlementResult, context: UnseenSettlementContext): boolean {
60
+ if (context.hadWatchers) return false;
61
+ if (context.source === 'delegate-submission-failure') return false;
62
+ if (result.status === 'cancelled') return false;
63
+ if (this.settlements.has(result.taskId)) return false;
64
+ this.settlements.set(result.taskId, {
65
+ taskId: result.taskId,
66
+ agentId: result.agentId,
67
+ ...(context.agent !== undefined ? { agent: context.agent } : {}),
68
+ ...(context.label !== undefined ? { label: context.label } : {}),
69
+ status: result.status,
70
+ ok: result.ok,
71
+ returnCode: result.returnCode,
72
+ ...(result.text !== undefined ? { text: result.text } : {}),
73
+ ...(result.error !== undefined ? { error: result.error } : {}),
74
+ });
75
+ return true;
76
+ }
77
+
78
+ /** Un-noticed entries in insertion order. */
79
+ pending(): ReadonlyArray<UnseenSettlement> {
80
+ return [...this.settlements.values()].map(settlement => ({ ...settlement }));
81
+ }
82
+
83
+ /** Drop entries after a notice was successfully handed to pi. */
84
+ drain(taskIds: string[]): void {
85
+ for (const taskId of taskIds) this.settlements.delete(taskId);
86
+ }
87
+
88
+ /** Retrieval clear (for example `shepherd_watch`); returns removed ids. */
89
+ clear(taskIds: string[]): string[] {
90
+ const cleared: string[] = [];
91
+ for (const taskId of taskIds) {
92
+ if (this.settlements.delete(taskId)) cleared.push(taskId);
93
+ }
94
+ return cleared;
95
+ }
96
+
97
+ /** Close clear (for example `shepherd_close`); returns removed ids. */
98
+ clearForAgent(agentId: string): string[] {
99
+ const cleared: string[] = [];
100
+ for (const [taskId, settlement] of this.settlements) {
101
+ if (settlement.agentId !== agentId) continue;
102
+ this.settlements.delete(taskId);
103
+ cleared.push(taskId);
104
+ }
105
+ return cleared;
106
+ }
107
+
108
+ /** Session lifecycle clear. */
109
+ clearAll(): void {
110
+ this.settlements.clear();
111
+ }
112
+ }
113
+
114
+ export const unseenCompletionLedger = new UnseenCompletionLedger();