@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.
- package/.agents/agents/README.md +12 -0
- package/.agents/agents/planner.md +38 -0
- package/.agents/agents/reviewer.md +38 -0
- package/.agents/agents/scout.md +43 -0
- package/.agents/agents/worker.md +33 -0
- package/.agents/skills/smoke-test/SKILL.md +155 -0
- package/.agents/skills/smoke-test/references/forensics.md +46 -0
- package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
- package/.github/workflows/publish.yml +77 -0
- package/.pi/prompts/release.md +21 -0
- package/.prettierrc +10 -0
- package/AGENTS.md +88 -0
- package/CONTRIBUTING.md +177 -0
- package/LICENSE +201 -0
- package/README.md +424 -2
- package/docs/README.md +25 -0
- package/docs/guides/agent-definitions.md +42 -0
- package/docs/guides/diagnostics.md +199 -0
- package/docs/guides/tool-reference.md +55 -0
- package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
- package/docs/plans/agent-labels.md +257 -0
- package/docs/plans/architecture.md +110 -0
- package/docs/plans/settings-scope.md +163 -0
- package/docs/plans/tool-surface-split.md +278 -0
- package/docs/reference/dictionary +26 -0
- package/docs/releasing.md +47 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
- package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
- package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
- package/index.ts +599 -0
- package/package.json +112 -4
- package/scripts/capture-system-prompt.mjs +45 -0
- package/scripts/extract-pi-system-prompt.mjs +277 -0
- package/scripts/host-impact.mjs +74 -0
- package/scripts/resolve-agent.mjs +43 -0
- package/scripts/show-shepherd-orchestrator.mjs +58 -0
- package/scripts/show-shepherd-prompt.mjs +96 -0
- package/scripts/verify-suites.mjs +67 -0
- package/specs/001-artifacts/spec.md +436 -0
- package/specs/002-simplify-agent-orchestration/plan.md +287 -0
- package/specs/002-simplify-agent-orchestration/spec.md +323 -0
- package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
- package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
- package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
- package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
- package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
- package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
- package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
- package/specs/005-per-workspace-settings/plan.md +230 -0
- package/specs/005-per-workspace-settings/spec.md +368 -0
- package/specs/005-per-workspace-settings/tasks.md +178 -0
- package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
- package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
- package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
- package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
- package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
- package/specs/007-unwatched-completion-notice/journal.md +145 -0
- package/specs/007-unwatched-completion-notice/plan.md +186 -0
- package/specs/007-unwatched-completion-notice/spec.md +284 -0
- package/specs/007-unwatched-completion-notice/tasks.md +147 -0
- package/specs/008-remote-machine-sheep/intent.md +174 -0
- package/specs/008-remote-machine-sheep/journal.md +57 -0
- package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
- package/specs/009-hc-runtime/intent.md +44 -0
- package/specs/009-hc-runtime/plan.md +49 -0
- package/specs/009-hc-runtime/spec.md +118 -0
- package/specs/009-hc-runtime/tasks.md +62 -0
- package/specs/010-unseen-watch-parity/intent.md +57 -0
- package/specs/010-unseen-watch-parity/journal.md +172 -0
- package/specs/010-unseen-watch-parity/plan.md +74 -0
- package/specs/010-unseen-watch-parity/spec.md +191 -0
- package/specs/010-unseen-watch-parity/tasks.md +119 -0
- package/specs/011-hc-background-poll/intent.md +57 -0
- package/specs/011-hc-background-poll/journal.md +95 -0
- package/specs/011-hc-background-poll/plan.md +87 -0
- package/specs/011-hc-background-poll/spec.md +141 -0
- package/specs/011-hc-background-poll/tasks.md +83 -0
- package/specs/012-steer-default/intent.md +12 -0
- package/specs/012-steer-default/journal.md +40 -0
- package/specs/012-steer-default/plan.md +7 -0
- package/specs/012-steer-default/spec.md +42 -0
- package/specs/012-steer-default/tasks.md +6 -0
- package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
- package/specs/013-opencode-shepherd/intent.md +59 -0
- package/specs/013-opencode-shepherd/plan.md +204 -0
- package/specs/013-opencode-shepherd/spec.md +258 -0
- package/specs/013-opencode-shepherd/tasks.md +259 -0
- package/src/core/artifact-sessions.ts +835 -0
- package/src/core/config.ts +329 -0
- package/src/core/discovery.ts +342 -0
- package/src/core/herdr.ts +1 -0
- package/src/core/host.ts +77 -0
- package/src/core/ids.ts +78 -0
- package/src/core/lifecycle.ts +1 -0
- package/src/core/messaging.ts +1 -0
- package/src/core/migration.ts +55 -0
- package/src/core/orchestration.ts +1 -0
- package/src/core/types.ts +143 -0
- package/src/core/unseen-completions.ts +114 -0
- package/src/extension/cli.ts +417 -0
- package/src/extension/config.ts +1 -0
- package/src/extension/settings-ui.ts +296 -0
- package/src/extension/shepherd-done.ts +768 -0
- package/src/extension/shepherd.ts +2548 -0
- package/src/extension/system-prompt.ts +38 -0
- package/src/extension/unseen-completions.ts +237 -0
- package/src/opencode/actions.ts +794 -0
- package/src/opencode/bridge.ts +777 -0
- package/src/opencode/display.ts +36 -0
- package/src/opencode/fieldnotes.ts +60 -0
- package/src/opencode/host.ts +62 -0
- package/src/opencode/orphans.ts +162 -0
- package/src/opencode/server.ts +458 -0
- package/src/runtimes/backend.ts +119 -0
- package/src/runtimes/detect.ts +102 -0
- package/src/runtimes/hc/hc.ts +527 -0
- package/src/runtimes/hc/runtime.ts +1898 -0
- package/src/runtimes/herdr/herdr.ts +912 -0
- package/src/runtimes/herdr/lifecycle.ts +1712 -0
- package/src/runtimes/herdr/messaging.ts +703 -0
- package/src/runtimes/herdr/orchestration.ts +1583 -0
- package/src/runtimes/herdr/runtime.ts +224 -0
- package/src/runtimes/runtime.ts +133 -0
- package/src/runtimes/settle-observations.ts +114 -0
- package/test/fixtures/context-project/AGENTS.md +2 -0
- package/test/fixtures/home/.agents/agents/same.md +6 -0
- package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
- package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
- package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
- package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
- package/test/fixtures/proj/.pi/agents/same.md +6 -0
- package/test/helpers/fake-clock.mjs +39 -0
- package/test/helpers/feature-contracts.mjs +44 -0
- package/test/helpers/test-utils.mjs +44 -0
- package/test/verify-artifact-sessions.mjs +258 -0
- package/test/verify-backend.mjs +297 -0
- package/test/verify-child-mislabel.mjs +135 -0
- package/test/verify-child-surface.mjs +321 -0
- package/test/verify-cli.mjs +197 -0
- package/test/verify-command-ux.mjs +100 -0
- package/test/verify-compat.mjs +32 -0
- package/test/verify-cross-host-notes.mjs +128 -0
- package/test/verify-delegate.mjs +161 -0
- package/test/verify-detect.mjs +151 -0
- package/test/verify-discovery.mjs +239 -0
- package/test/verify-done-nudge.mjs +238 -0
- package/test/verify-effective-prompt.mjs +98 -0
- package/test/verify-hc-matrix.mjs +246 -0
- package/test/verify-hc-poll.mjs +260 -0
- package/test/verify-host-docs.mjs +35 -0
- package/test/verify-host-impact.mjs +49 -0
- package/test/verify-ids.mjs +141 -0
- package/test/verify-launch.mjs +183 -0
- package/test/verify-message-routing.mjs +560 -0
- package/test/verify-messaging.mjs +303 -0
- package/test/verify-migration-notice.mjs +69 -0
- package/test/verify-multi-wait.mjs +42 -0
- package/test/verify-opencode-display.mjs +47 -0
- package/test/verify-opencode-fieldnotes.mjs +121 -0
- package/test/verify-opencode-notice.mjs +77 -0
- package/test/verify-opencode-nudge.mjs +116 -0
- package/test/verify-opencode-orphans.mjs +160 -0
- package/test/verify-opencode-surface.mjs +107 -0
- package/test/verify-packaging.mjs +82 -0
- package/test/verify-parent-surface.mjs +118 -0
- package/test/verify-phase0.mjs +95 -0
- package/test/verify-registry.mjs +124 -0
- package/test/verify-rename-migration.mjs +111 -0
- package/test/verify-rendering.mjs +379 -0
- package/test/verify-session-boundary.mjs +146 -0
- package/test/verify-settings.mjs +260 -0
- package/test/verify-stale-wait.mjs +339 -0
- package/test/verify-status-widget.mjs +377 -0
- package/test/verify-status.mjs +172 -0
- package/test/verify-task-completion.mjs +156 -0
- package/test/verify-task-failures.mjs +201 -0
- package/test/verify-task-mislabel.mjs +143 -0
- package/test/verify-task-registry.mjs +194 -0
- package/test/verify-task-watchers.mjs +217 -0
- package/test/verify-tool-schemas.mjs +120 -0
- package/test/verify-unseen-completions.mjs +1211 -0
- package/test/verify-watchers.mjs +181 -0
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode bridge (spec 013, Phase 3): routing, delivery, and notifications.
|
|
3
|
+
*
|
|
4
|
+
* Pi-owned surface for OpenCode. The engine registries are the source of
|
|
5
|
+
* truth for task/message state; this module adds what the OpenCode host
|
|
6
|
+
* needs around them:
|
|
7
|
+
*
|
|
8
|
+
* - Sheep records + task→parent routing maps (server-process scope).
|
|
9
|
+
* - Parent→sheep delivery via terminal input (Herdr `agent prompt` with a
|
|
10
|
+
* `pane send-text` fallback; `hc send` on hc). The opencode TUI ignores
|
|
11
|
+
* `--session` attach, so terminal input is the exact, session-free
|
|
12
|
+
* transport. `session.prompt` is used only for parent-session notices,
|
|
13
|
+
* where the session id is exactly known.
|
|
14
|
+
* - Child envelope publishing (message/done) through the shared file broker
|
|
15
|
+
* with the sheep as sender, followed by the backend drain — mirroring
|
|
16
|
+
* what the Pi child surface does, so registry semantics (reply
|
|
17
|
+
* correlation, waiting states, completion settlement) are identical.
|
|
18
|
+
* - Exactly-once completion prompts via the backend `onTaskSettled`
|
|
19
|
+
* observers (delegate-submission failures excluded: already reported).
|
|
20
|
+
* - Stale-wait prompts via the engine monitors.
|
|
21
|
+
* - Done-nudge on child run completion via `session.execution.*` events
|
|
22
|
+
* (`session.idle` is never emitted in v2), delivered as terminal input
|
|
23
|
+
* to the sheep's pane; bounded per task, then escalated to the parent.
|
|
24
|
+
*
|
|
25
|
+
* Capability model: task ids are unguessable opaque ids and act as the
|
|
26
|
+
* bearer credential (same as Pi's broker tokens). A session may act for a
|
|
27
|
+
* task it can name; sender display resolves through the task owner or the
|
|
28
|
+
* bound sheep session.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { herdrExecSync } from '../runtimes/herdr/herdr.ts';
|
|
32
|
+
import { hcExecSync } from '../runtimes/hc/hc.ts';
|
|
33
|
+
import {
|
|
34
|
+
bindSessionOwner,
|
|
35
|
+
lifecycleRegistry,
|
|
36
|
+
} from '../runtimes/herdr/orchestration.ts';
|
|
37
|
+
import {
|
|
38
|
+
configureStaleWaitNotifications,
|
|
39
|
+
ensureParentBroker,
|
|
40
|
+
processParentBrokerMessages,
|
|
41
|
+
} from '../runtimes/herdr/lifecycle.ts';
|
|
42
|
+
import {
|
|
43
|
+
configureHcStaleWaitNotifications,
|
|
44
|
+
describeHcAgent,
|
|
45
|
+
drainHcInboxForSession,
|
|
46
|
+
ensureHcBroker,
|
|
47
|
+
onTaskSettled as onHcTaskSettled,
|
|
48
|
+
resolveHcTerminalId,
|
|
49
|
+
} from '../runtimes/hc/runtime.ts';
|
|
50
|
+
import {
|
|
51
|
+
createChildBroker,
|
|
52
|
+
createEnvelope,
|
|
53
|
+
publishFromChild,
|
|
54
|
+
registerChild,
|
|
55
|
+
type ChildCapability,
|
|
56
|
+
} from '../runtimes/herdr/messaging.ts';
|
|
57
|
+
import { unseenCompletionLedger } from '../core/unseen-completions.ts';
|
|
58
|
+
import { statusAgent } from '../runtimes/herdr/lifecycle.ts';
|
|
59
|
+
import { describeHcStatusView } from '../runtimes/hc/runtime.ts';
|
|
60
|
+
|
|
61
|
+
export type SheepBackend = 'herdr' | 'hc';
|
|
62
|
+
|
|
63
|
+
export interface SheepRecord {
|
|
64
|
+
agentId: string;
|
|
65
|
+
backend: SheepBackend;
|
|
66
|
+
paneId?: string;
|
|
67
|
+
terminalId?: string;
|
|
68
|
+
cwd: string;
|
|
69
|
+
parentSessionId: string;
|
|
70
|
+
childCapability: ChildCapability;
|
|
71
|
+
brokerRootDir: string;
|
|
72
|
+
brokerSessionId: string;
|
|
73
|
+
brokerId: string;
|
|
74
|
+
parentBrokerId: string;
|
|
75
|
+
/** Wall-clock ms when the sheep was spawned (discovery-bind baseline). */
|
|
76
|
+
spawnedAt: number;
|
|
77
|
+
/** Best-effort bound OpenCode child session (discovery or first call). */
|
|
78
|
+
boundChildSessionId?: string;
|
|
79
|
+
/** Message ids relayed to this sheep, for replyTo→task inference. */
|
|
80
|
+
receivedMessages: Map<string, string | undefined>;
|
|
81
|
+
/** Outstanding expectsReply requests published by this sheep. */
|
|
82
|
+
outstandingRequests: Set<string>;
|
|
83
|
+
/** Done-nudges sent per task id (bounded, then escalated). */
|
|
84
|
+
nudgeCounts: Map<string, number>;
|
|
85
|
+
/** Tasks whose stall was already escalated to the parent. */
|
|
86
|
+
escalatedTasks: Set<string>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const sheepByAgent = new Map<string, SheepRecord>();
|
|
90
|
+
const childSessionToAgent = new Map<string, string>();
|
|
91
|
+
const taskToParent = new Map<string, Map<string, string>>();
|
|
92
|
+
/** Sessions that used parent tools: sheep-only tools refuse them. */
|
|
93
|
+
const parentSessions = new Set<string>();
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Mark a session as a parent (orchestrator) session.
|
|
97
|
+
* A sheep that touched a parent-only tool before its session was bound must
|
|
98
|
+
* not keep a stale parent mark: sheep binding wins (see isParentSession).
|
|
99
|
+
*/
|
|
100
|
+
export function markParentSession(sessionId: string): void {
|
|
101
|
+
if (!sessionId) return;
|
|
102
|
+
if (isSheepSession(sessionId)) {
|
|
103
|
+
parentSessions.delete(sessionId);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
parentSessions.add(sessionId);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* True when the session was seen driving the parent surface.
|
|
111
|
+
* Known sheep sessions are never parents, even if an early parent-tool call
|
|
112
|
+
* marked them before binding — otherwise `sheepMessage` rejects the reply.
|
|
113
|
+
*/
|
|
114
|
+
export function isParentSession(sessionId: string): boolean {
|
|
115
|
+
return parentSessions.has(sessionId) && !isSheepSession(sessionId);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function parentMapFor(taskId: string): Map<string, string> {
|
|
119
|
+
let map = taskToParent.get(taskId);
|
|
120
|
+
if (!map) taskToParent.set(taskId, (map = new Map()));
|
|
121
|
+
return map;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Remember which parent session owns a task (delegate/watch time).
|
|
126
|
+
* Sheep sessions are never notice recipients: a child that learns a task id
|
|
127
|
+
* (e.g. from a relayed question) must not become a "parent" and receive the
|
|
128
|
+
* completion notice. This also keeps a stray peer-process observation from
|
|
129
|
+
* prompting a sheep pane.
|
|
130
|
+
*/
|
|
131
|
+
export function noteTaskParent(taskId: string, parentSessionId: string): void {
|
|
132
|
+
if (!parentSessionId || isSheepSession(parentSessionId)) return;
|
|
133
|
+
parentMapFor(taskId).set('parent', parentSessionId);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** All parent sessions waiting on a task (delegate + watchers). */
|
|
137
|
+
function parentsFor(taskId: string): string[] {
|
|
138
|
+
const map = taskToParent.get(taskId);
|
|
139
|
+
if (!map) return [];
|
|
140
|
+
return [...map.values()];
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function recordSheepSpawn(record: Omit<SheepRecord, 'receivedMessages' | 'outstandingRequests' | 'nudgeCounts' | 'escalatedTasks' | 'spawnedAt'>): void {
|
|
144
|
+
sheepByAgent.set(record.agentId, {
|
|
145
|
+
...record,
|
|
146
|
+
spawnedAt: Date.now(),
|
|
147
|
+
receivedMessages: new Map(),
|
|
148
|
+
outstandingRequests: new Set(),
|
|
149
|
+
nudgeCounts: new Map(),
|
|
150
|
+
escalatedTasks: new Set(),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function forgetSheep(agentId: string): void {
|
|
155
|
+
const record = sheepByAgent.get(agentId);
|
|
156
|
+
if (!record) return;
|
|
157
|
+
sheepByAgent.delete(agentId);
|
|
158
|
+
if (record.boundChildSessionId) childSessionToAgent.delete(record.boundChildSessionId);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Re-resolve a sheep into the CURRENT parent broker, re-registering it
|
|
163
|
+
* when a broker rotation (reload, multi-session server) dropped its entry.
|
|
164
|
+
* Without this, sends fail with "unknown child target" and child
|
|
165
|
+
* envelopes land in a directory no drain reads. Idempotent: a registered
|
|
166
|
+
* sheep is returned untouched.
|
|
167
|
+
*/
|
|
168
|
+
export function ensureSheepBroker(record: SheepRecord): void {
|
|
169
|
+
const key = record.parentSessionId || undefined;
|
|
170
|
+
if (record.backend === 'hc') {
|
|
171
|
+
const active = ensureHcBroker(key);
|
|
172
|
+
if (!active.children.has(record.agentId)) {
|
|
173
|
+
const cap = registerChild(active, record.agentId);
|
|
174
|
+
record.childCapability = cap;
|
|
175
|
+
record.brokerRootDir = active.rootDir;
|
|
176
|
+
record.brokerSessionId = active.sessionId;
|
|
177
|
+
record.brokerId = active.brokerId;
|
|
178
|
+
record.parentBrokerId = active.parentId;
|
|
179
|
+
}
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const active = ensureParentBroker(key);
|
|
183
|
+
if (!active.children.has(record.agentId)) {
|
|
184
|
+
const cap = registerChild(active, record.agentId);
|
|
185
|
+
record.childCapability = cap;
|
|
186
|
+
record.brokerRootDir = active.rootDir;
|
|
187
|
+
record.brokerSessionId = active.sessionId;
|
|
188
|
+
record.brokerId = active.brokerId;
|
|
189
|
+
record.parentBrokerId = active.parentId;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Clear routing state once a task settles (prevents unbounded growth). */
|
|
194
|
+
export function forgetTaskParent(taskId: string): void {
|
|
195
|
+
taskToParent.delete(taskId);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
type SessionLister = (directory: string) => Promise<unknown>;
|
|
199
|
+
let listSessions: SessionLister | undefined;
|
|
200
|
+
|
|
201
|
+
/** Session lister for best-effort sheep-session discovery (set at setup). */
|
|
202
|
+
export function setSessionLister(lister: SessionLister): void {
|
|
203
|
+
listSessions = lister;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
interface ListedSession {
|
|
207
|
+
id: string;
|
|
208
|
+
created: number;
|
|
209
|
+
directory: string;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function normalizeSessionList(raw: unknown): ListedSession[] {
|
|
213
|
+
const arr = Array.isArray(raw)
|
|
214
|
+
? raw
|
|
215
|
+
: ((raw as any)?.data ?? (raw as any)?.sessions ?? (raw as any)?.items ?? []);
|
|
216
|
+
if (!Array.isArray(arr)) return [];
|
|
217
|
+
return arr.flatMap((s: any) => {
|
|
218
|
+
const id = s?.id ?? s?.sessionID;
|
|
219
|
+
if (typeof id !== 'string' || !id) return [];
|
|
220
|
+
const created =
|
|
221
|
+
Number(s?.time?.created ?? s?.created ?? s?.time?.updated ?? 0) || 0;
|
|
222
|
+
const directory = s?.location?.directory ?? s?.directory ?? '';
|
|
223
|
+
return [{ id, created, directory }];
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Best-effort bind of a sheep to its OpenCode child session. The TUI
|
|
229
|
+
* creates its server session lazily on first input, so right after spawn
|
|
230
|
+
* there is nothing to bind. The first terminal-input delivery creates it;
|
|
231
|
+
* this background poll then binds the newest session in the sheep's cwd.
|
|
232
|
+
* The delegating parent session is always excluded, so it can never be
|
|
233
|
+
* mistaken for its own sheep. Never used for auth or delivery (those are
|
|
234
|
+
* task-id and pane-exact); it only powers the done-nudge trigger.
|
|
235
|
+
*/
|
|
236
|
+
export function kickoffSheepBind(record: SheepRecord, excludeSessionId?: string): void {
|
|
237
|
+
if (record.boundChildSessionId || !listSessions) return;
|
|
238
|
+
const lister = listSessions;
|
|
239
|
+
const baseline = Date.now();
|
|
240
|
+
void (async () => {
|
|
241
|
+
for (let i = 0; i < 30; i++) {
|
|
242
|
+
await new Promise(r => setTimeout(r, 2000));
|
|
243
|
+
try {
|
|
244
|
+
if (sheepByAgent.get(record.agentId)?.boundChildSessionId) return;
|
|
245
|
+
const sessions = normalizeSessionList(await lister(record.cwd));
|
|
246
|
+
const candidate = sessions
|
|
247
|
+
.filter(
|
|
248
|
+
s =>
|
|
249
|
+
s.id !== excludeSessionId &&
|
|
250
|
+
s.created >= baseline - 5000 &&
|
|
251
|
+
(!s.directory || s.directory === record.cwd)
|
|
252
|
+
)
|
|
253
|
+
.sort((a, b) => b.created - a.created)[0];
|
|
254
|
+
if (candidate) {
|
|
255
|
+
bindChildSession(record.agentId, candidate.id);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
} catch {
|
|
259
|
+
/* keep polling; discovery is best effort */
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
})();
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function sheepRecord(agentId: string): SheepRecord | undefined {
|
|
266
|
+
return sheepByAgent.get(agentId);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function isSheepSession(sessionId: string): boolean {
|
|
270
|
+
return childSessionToAgent.has(sessionId);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function agentForChildSession(sessionId: string): string | undefined {
|
|
274
|
+
return childSessionToAgent.get(sessionId);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Find the sheep a relayed message was delivered to (by relayed message
|
|
279
|
+
* id). Exact attribution for peer replies from not-yet-bound sessions:
|
|
280
|
+
* only the terminal that received the message can know its id.
|
|
281
|
+
*/
|
|
282
|
+
export function recipientOfRelayedMessage(messageId: string): SheepRecord | undefined {
|
|
283
|
+
for (const record of sheepByAgent.values()) {
|
|
284
|
+
if (record.receivedMessages.has(messageId)) return record;
|
|
285
|
+
}
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function bindChildSession(agentId: string, childSessionId: string): void {
|
|
290
|
+
const record = sheepByAgent.get(agentId);
|
|
291
|
+
if (!record) return;
|
|
292
|
+
if (record.boundChildSessionId) childSessionToAgent.delete(record.boundChildSessionId);
|
|
293
|
+
record.boundChildSessionId = childSessionId;
|
|
294
|
+
childSessionToAgent.set(childSessionId, agentId);
|
|
295
|
+
// A pre-binding parent-tool call may have marked this session as a parent;
|
|
296
|
+
// binding as a sheep must win so `sheepMessage` accepts its replies.
|
|
297
|
+
parentSessions.delete(childSessionId);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** True when a pane/terminal transport belongs to a currently managed sheep. */
|
|
301
|
+
export function isManagedTransport(id: string): boolean {
|
|
302
|
+
for (const record of sheepByAgent.values()) {
|
|
303
|
+
if (record.paneId === id || record.terminalId === id) return true;
|
|
304
|
+
}
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Resolve a sheep's agent from its bound session, if any. */
|
|
309
|
+
function agentForSession(sessionId: string): SheepRecord | undefined {
|
|
310
|
+
const agentId = childSessionToAgent.get(sessionId);
|
|
311
|
+
return agentId ? sheepByAgent.get(agentId) : undefined;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function displayName(agent: string, label: string): string {
|
|
315
|
+
return label ? `${agent}: ${label}` : agent;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Best-effort display identity for prompts (never throws). */
|
|
319
|
+
export function sheepDisplay(agentId: string): string {
|
|
320
|
+
const record = sheepByAgent.get(agentId);
|
|
321
|
+
if (record) {
|
|
322
|
+
try {
|
|
323
|
+
const handle =
|
|
324
|
+
record.backend === 'hc'
|
|
325
|
+
? describeHcAgent(agentId)
|
|
326
|
+
: lifecycleRegistry.getAgent(agentId).handle;
|
|
327
|
+
return displayName(handle.agent, handle.label);
|
|
328
|
+
} catch {
|
|
329
|
+
/* fall through */
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return agentId;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ── Terminal-input delivery ─────────────────────────────────────────────
|
|
336
|
+
|
|
337
|
+
function deliverToHerdrPane(paneId: string, text: string): void {
|
|
338
|
+
// Prefer the agent-aware prompt (rejects when the agent is blocked);
|
|
339
|
+
// fall back to raw pane input when the agent is not yet detected.
|
|
340
|
+
try {
|
|
341
|
+
herdrExecSync(['agent', 'prompt', paneId, text]);
|
|
342
|
+
return;
|
|
343
|
+
} catch {
|
|
344
|
+
/* fall through to raw input */
|
|
345
|
+
}
|
|
346
|
+
herdrExecSync(['pane', 'send-text', paneId, text]);
|
|
347
|
+
herdrExecSync(['pane', 'send-keys', paneId, 'Enter']);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function deliverToHcTerminal(terminalId: string, text: string): void {
|
|
351
|
+
hcExecSync(['send', terminalId, text]);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Deliver text to a sheep's terminal (throws with the backend error). */
|
|
355
|
+
export async function deliverToSheep(record: SheepRecord, text: string): Promise<void> {
|
|
356
|
+
// The child TUI may still be booting when the first delivery lands.
|
|
357
|
+
// Retry briefly: terminal input buffers until the agent reads it.
|
|
358
|
+
let lastError: unknown;
|
|
359
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
360
|
+
try {
|
|
361
|
+
deliverToSheepOnce(record, text);
|
|
362
|
+
return;
|
|
363
|
+
} catch (error) {
|
|
364
|
+
lastError = error;
|
|
365
|
+
if (attempt < 2) await new Promise(r => setTimeout(r, 4000));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function deliverToSheepOnce(record: SheepRecord, text: string): void {
|
|
372
|
+
if (record.backend === 'hc') {
|
|
373
|
+
const terminalId = record.terminalId ?? resolveHcTerminalId(record.agentId);
|
|
374
|
+
if (!terminalId) throw new Error(`Sheep "${record.agentId}" has no terminal to deliver to.`);
|
|
375
|
+
record.terminalId = terminalId;
|
|
376
|
+
deliverToHcTerminal(terminalId, text);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
const paneId = record.paneId;
|
|
380
|
+
if (!paneId) throw new Error(`Sheep "${record.agentId}" has no pane to deliver to.`);
|
|
381
|
+
deliverToHerdrPane(paneId, text);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ── Injected text formats ───────────────────────────────────────────────
|
|
385
|
+
|
|
386
|
+
export function taskTextForSheep(task: string, taskId: string): string {
|
|
387
|
+
return (
|
|
388
|
+
`${task}\n\nTask ID: ${taskId}\n\n` +
|
|
389
|
+
'[Autonomous agent]\n' +
|
|
390
|
+
'Complete this task autonomously. A delegated task may span multiple runs: ending the current run or becoming idle does not complete the task. ' +
|
|
391
|
+
'Use shepherd_message when you need information from another participant. When you ask another participant a question, set taskId to your delegated Task ID, set expectsReply to true, and remember the returned Message ID. ' +
|
|
392
|
+
'When you later have the answer to a request, send a shepherd_message TO THE SHEPHERD (target "shepherd") with taskId set and replyTo set to the original request\'s Message ID, so the Shepherd can correlate the reply and resume the waiting task. ' +
|
|
393
|
+
'Do not reply directly to another participant\'s address for a tracked request; route it through the Shepherd. ' +
|
|
394
|
+
'If the task cannot proceed, call shepherd_done with status blocked and explain why. ' +
|
|
395
|
+
'Call shepherd_done with your Task ID only when the whole task is complete or explicitly blocked/failed. ' +
|
|
396
|
+
'When finished, make your FINAL assistant message a concise summary of what you did and found; it is reported back to the caller.'
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
export function messageTextForSheep(opts: {
|
|
401
|
+
sender: string;
|
|
402
|
+
senderId?: string;
|
|
403
|
+
messageId: string;
|
|
404
|
+
taskId?: string;
|
|
405
|
+
threadId?: string;
|
|
406
|
+
replyTo?: string;
|
|
407
|
+
content: string;
|
|
408
|
+
}): string {
|
|
409
|
+
const lines = [
|
|
410
|
+
`[Shepherd message from ${opts.sender}]`,
|
|
411
|
+
`Message ID: ${opts.messageId}`,
|
|
412
|
+
];
|
|
413
|
+
if (opts.senderId) lines.push(`From: ${opts.senderId}`);
|
|
414
|
+
if (opts.taskId) lines.push(`Task ID: ${opts.taskId}`);
|
|
415
|
+
if (opts.threadId) lines.push(`Thread ID: ${opts.threadId}`);
|
|
416
|
+
if (opts.replyTo) lines.push(`Reply to: ${opts.replyTo}`);
|
|
417
|
+
lines.push('', opts.content);
|
|
418
|
+
if (opts.replyTo) {
|
|
419
|
+
lines.push(
|
|
420
|
+
'',
|
|
421
|
+
'You are a Shepherd sheep and this message IS your task traffic: act on it with tools, not prose.',
|
|
422
|
+
'Ignore any terminal from-label (e.g. hc from=...); the true sender is the From id above. Do not use shell workarounds.',
|
|
423
|
+
`Answer by calling shepherd_message addressed to the From id above (never to the parent), setting replyTo to ${opts.replyTo} and taskId to the Task ID above. Text answers alone never unblock the questioner.`
|
|
424
|
+
);
|
|
425
|
+
} else if (opts.taskId) {
|
|
426
|
+
lines.push(
|
|
427
|
+
'',
|
|
428
|
+
'You are a Shepherd sheep and this message IS your task traffic: act on it with tools, not prose.',
|
|
429
|
+
'Ignore any terminal from-label (e.g. hc from=...); the true sender is the From id above. Do not use shell workarounds.',
|
|
430
|
+
'If this message asks you a question, answer by calling shepherd_message addressed to the From id above, with replyTo set to the Message ID above and taskId to the Task ID above.'
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
return lines.join('\n');
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export function nudgeTextForSheep(taskId: string, attempt: number, limit: number): string {
|
|
437
|
+
const remaining = Math.max(0, limit - attempt);
|
|
438
|
+
return [
|
|
439
|
+
'[Shepherd completion check]',
|
|
440
|
+
`You ended a run without calling shepherd_done, so delegated task ${taskId} is still open and the Shepherd is waiting for its result. Nothing was reported.`,
|
|
441
|
+
'',
|
|
442
|
+
'Do not start new work in this run. Finish the task now and report exactly one terminal outcome with shepherd_done (include your Task ID):',
|
|
443
|
+
'- status "completed" — the task is finished; summarize what you did.',
|
|
444
|
+
'- status "blocked" — you cannot proceed; state what blocks you.',
|
|
445
|
+
'- status "failed" — the task cannot be completed; give the reason.',
|
|
446
|
+
'',
|
|
447
|
+
'If you are instead waiting for an answer from the Shepherd or a peer, end this run without shepherd_done and reply when the answer arrives.',
|
|
448
|
+
remaining > 0
|
|
449
|
+
? `Reminder ${attempt} of ${limit}.`
|
|
450
|
+
: `Final reminder ${attempt} of ${limit}; if this task is still open after this run, the Shepherd is told it stalled.`,
|
|
451
|
+
].join('\n');
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ── Child envelope publishing ───────────────────────────────────────────
|
|
455
|
+
|
|
456
|
+
function childBrokerFor(record: SheepRecord) {
|
|
457
|
+
return createChildBroker({ rootDir: record.brokerRootDir, ...record.childCapability });
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function drainBackend(record: SheepRecord): void {
|
|
461
|
+
try {
|
|
462
|
+
if (record.backend === 'hc') drainHcInboxForSession(record.parentSessionId);
|
|
463
|
+
else void processParentBrokerMessages();
|
|
464
|
+
} catch {
|
|
465
|
+
/* drains stay best-effort; registry state is already updated */
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
export interface SheepPublishResult {
|
|
470
|
+
messageId: string;
|
|
471
|
+
delivery: string;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Publish a task_done envelope as the sheep, then drain. */
|
|
475
|
+
export function publishSheepDone(
|
|
476
|
+
record: SheepRecord,
|
|
477
|
+
opts: { taskId: string; status: 'completed' | 'blocked' | 'failed'; summary?: string }
|
|
478
|
+
): SheepPublishResult {
|
|
479
|
+
const broker = childBrokerFor(record);
|
|
480
|
+
const completion = createEnvelope(
|
|
481
|
+
{ sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: record.agentId },
|
|
482
|
+
{
|
|
483
|
+
kind: 'task_done',
|
|
484
|
+
targetId: broker.parentId,
|
|
485
|
+
taskId: opts.taskId,
|
|
486
|
+
status: opts.status,
|
|
487
|
+
summary: opts.summary,
|
|
488
|
+
content: opts.summary,
|
|
489
|
+
delivery: 'followUp',
|
|
490
|
+
}
|
|
491
|
+
);
|
|
492
|
+
const accepted = publishFromChild(broker, completion);
|
|
493
|
+
drainBackend(record);
|
|
494
|
+
return { messageId: completion.messageId, delivery: accepted.delivery };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
export interface SheepMessageInput {
|
|
498
|
+
target: string;
|
|
499
|
+
message: string;
|
|
500
|
+
taskId?: string;
|
|
501
|
+
threadId?: string;
|
|
502
|
+
replyTo?: string;
|
|
503
|
+
expectsReply?: boolean;
|
|
504
|
+
delivery?: 'followUp' | 'steer';
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Publish a sheep message/reply as the sheep, mirroring the Pi child
|
|
509
|
+
* surface: peer replies go direct with a correlation mirror to the parent;
|
|
510
|
+
* expectsReply opens a tracked request with its own mirror. Then drain.
|
|
511
|
+
*/
|
|
512
|
+
export function publishSheepMessage(
|
|
513
|
+
record: SheepRecord,
|
|
514
|
+
input: SheepMessageInput
|
|
515
|
+
): SheepPublishResult & { mirrorDelivered?: boolean } {
|
|
516
|
+
const broker = childBrokerFor(record);
|
|
517
|
+
const message = createEnvelope(
|
|
518
|
+
{ sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: record.agentId },
|
|
519
|
+
{
|
|
520
|
+
kind: input.replyTo ? 'reply' : 'message',
|
|
521
|
+
targetId: input.target,
|
|
522
|
+
taskId: input.taskId,
|
|
523
|
+
threadId: input.threadId,
|
|
524
|
+
replyTo: input.replyTo,
|
|
525
|
+
expectsReply: input.expectsReply,
|
|
526
|
+
delivery: input.delivery === 'followUp' ? 'followUp' : 'steer',
|
|
527
|
+
content: input.message,
|
|
528
|
+
}
|
|
529
|
+
);
|
|
530
|
+
const accepted = publishFromChild(broker, message);
|
|
531
|
+
let mirrorDelivered = true;
|
|
532
|
+
const isPeerReply =
|
|
533
|
+
accepted.delivery === 'queued' &&
|
|
534
|
+
input.replyTo &&
|
|
535
|
+
!['shepherd', 'parent', broker.parentId].includes(input.target);
|
|
536
|
+
const isTrackedRequest = accepted.delivery === 'queued' && input.expectsReply === true;
|
|
537
|
+
try {
|
|
538
|
+
if (isPeerReply) {
|
|
539
|
+
const mirror = createEnvelope(
|
|
540
|
+
{ sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: record.agentId },
|
|
541
|
+
{
|
|
542
|
+
kind: 'runtime',
|
|
543
|
+
targetId: broker.parentId,
|
|
544
|
+
taskId: input.taskId,
|
|
545
|
+
replyTo: input.replyTo,
|
|
546
|
+
replyReceived: true,
|
|
547
|
+
summary: input.message,
|
|
548
|
+
delivery: 'followUp',
|
|
549
|
+
}
|
|
550
|
+
);
|
|
551
|
+
publishFromChild(broker, mirror);
|
|
552
|
+
}
|
|
553
|
+
if (isTrackedRequest) {
|
|
554
|
+
const mirrored = createEnvelope(
|
|
555
|
+
{ sessionId: broker.sessionId, brokerId: broker.brokerId, senderId: record.agentId },
|
|
556
|
+
{
|
|
557
|
+
kind: 'runtime',
|
|
558
|
+
targetId: broker.parentId,
|
|
559
|
+
taskId: input.taskId,
|
|
560
|
+
threadId: input.threadId,
|
|
561
|
+
replyTo: message.messageId,
|
|
562
|
+
requestOpen: true,
|
|
563
|
+
requestTargetId: ['shepherd', 'parent'].includes(input.target)
|
|
564
|
+
? broker.parentId
|
|
565
|
+
: input.target,
|
|
566
|
+
summary: input.message,
|
|
567
|
+
delivery: 'followUp',
|
|
568
|
+
}
|
|
569
|
+
);
|
|
570
|
+
publishFromChild(broker, mirrored);
|
|
571
|
+
}
|
|
572
|
+
} catch {
|
|
573
|
+
mirrorDelivered = false;
|
|
574
|
+
}
|
|
575
|
+
if (input.expectsReply === true) record.outstandingRequests.add(message.messageId);
|
|
576
|
+
drainBackend(record);
|
|
577
|
+
return { messageId: message.messageId, delivery: accepted.delivery, mirrorDelivered };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// ── Parent-session prompting ────────────────────────────────────────────
|
|
581
|
+
|
|
582
|
+
const PARENT_NOTICE_RETRIES = 3;
|
|
583
|
+
const parentNoticeDelay = (attempt: number) => 250 * (attempt + 1);
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Deliver a notice to a human parent session. Sheep sessions are never
|
|
587
|
+
* notified, and a transient failure (the parent is generating a reply, so
|
|
588
|
+
* `session.prompt` rejects) is retried instead of silently dropped. Results
|
|
589
|
+
* stay retrievable via status/watch even if every attempt fails.
|
|
590
|
+
*/
|
|
591
|
+
async function promptParent(
|
|
592
|
+
ctx: any,
|
|
593
|
+
parentSessionId: string | undefined,
|
|
594
|
+
content: string
|
|
595
|
+
): Promise<void> {
|
|
596
|
+
if (!parentSessionId || isSheepSession(parentSessionId)) return;
|
|
597
|
+
for (let attempt = 0; attempt < PARENT_NOTICE_RETRIES; attempt++) {
|
|
598
|
+
try {
|
|
599
|
+
await ctx.session.prompt({ sessionID: parentSessionId, text: content });
|
|
600
|
+
return;
|
|
601
|
+
} catch (error) {
|
|
602
|
+
if (attempt === PARENT_NOTICE_RETRIES - 1) {
|
|
603
|
+
console.error(`shepherd: parent notice delivery failed after ${PARENT_NOTICE_RETRIES} attempts: ${String(error)}`);
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
await new Promise(resolve => setTimeout(resolve, parentNoticeDelay(attempt)));
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function completionText(result: {
|
|
612
|
+
taskId: string;
|
|
613
|
+
agentId: string;
|
|
614
|
+
status: string;
|
|
615
|
+
ok: boolean;
|
|
616
|
+
returnCode: number;
|
|
617
|
+
text?: string;
|
|
618
|
+
error?: string;
|
|
619
|
+
agent?: string;
|
|
620
|
+
label?: string;
|
|
621
|
+
}): string {
|
|
622
|
+
const identity = result.label ? `${result.agent ?? result.agentId}: ${result.label}` : (result.agent ?? result.agentId);
|
|
623
|
+
const lines = [`shepherd_watcher completion: ${identity} ${result.status}`, `task id: ${result.taskId}`];
|
|
624
|
+
if (result.text) lines.push('', result.text);
|
|
625
|
+
if (result.error) lines.push('', `error: ${result.error}`);
|
|
626
|
+
return lines.join('\n');
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ── Bridge installation ─────────────────────────────────────────────────
|
|
630
|
+
|
|
631
|
+
function doneNudgeLimit(): number {
|
|
632
|
+
const raw = process.env.SHEPHERD_DONE_NUDGES ?? process.env.PI_SHEPHERD_DONE_NUDGES;
|
|
633
|
+
if (raw === undefined) return 1;
|
|
634
|
+
const parsed = Number.parseInt(raw, 10);
|
|
635
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 1;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
export function installOpencodeBridges(ctx: any): void {
|
|
639
|
+
try {
|
|
640
|
+
setSessionLister(async (directory: string) => ctx.session.list({ directory, limit: 20 }));
|
|
641
|
+
} catch {
|
|
642
|
+
/* discovery bind stays disabled without a lister */
|
|
643
|
+
}
|
|
644
|
+
const onSettled = (result: any, context: { hadWatchers?: boolean; source?: string }) => {
|
|
645
|
+
try {
|
|
646
|
+
// A delegate submission failure is already reported in the delegate
|
|
647
|
+
// tool result; never prompt it again here.
|
|
648
|
+
if (context?.source === 'delegate-submission-failure') return;
|
|
649
|
+
const parents = parentsFor(result.taskId);
|
|
650
|
+
if (parents.length === 0) return;
|
|
651
|
+
const content = completionText(result);
|
|
652
|
+
for (const parent of parents) void promptParent(ctx, parent, content);
|
|
653
|
+
// Exactly-once: routing served, drop it so re-settles (retries) cannot
|
|
654
|
+
// prompt twice and the map cannot grow without bound.
|
|
655
|
+
forgetTaskParent(result.taskId);
|
|
656
|
+
} catch {
|
|
657
|
+
/* observation must not break settlement */
|
|
658
|
+
}
|
|
659
|
+
};
|
|
660
|
+
try {
|
|
661
|
+
lifecycleRegistry.onTaskSettled(onSettled);
|
|
662
|
+
} catch {
|
|
663
|
+
/* bridge is best effort */
|
|
664
|
+
}
|
|
665
|
+
try {
|
|
666
|
+
onHcTaskSettled(onSettled);
|
|
667
|
+
} catch {
|
|
668
|
+
/* bridge is best effort */
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const onStale = (info: any) => {
|
|
672
|
+
try {
|
|
673
|
+
const parents = parentsFor(info.taskId);
|
|
674
|
+
if (parents.length === 0) return;
|
|
675
|
+
const owner = info.label
|
|
676
|
+
? `${info.agent ?? info.agentId}: ${info.label}`
|
|
677
|
+
: (info.agent ?? info.agentId);
|
|
678
|
+
const lines = [
|
|
679
|
+
'Shepherd stale wait',
|
|
680
|
+
`Waiting on a reply for task ${info.taskId} (owner: ${owner}).`,
|
|
681
|
+
`Question: ${info.question ?? ''}`,
|
|
682
|
+
`Pending request: ${info.requestMessageId ?? 'unknown'}`,
|
|
683
|
+
];
|
|
684
|
+
for (const parent of parents) void promptParent(ctx, parent, lines.join('\n'));
|
|
685
|
+
} catch {
|
|
686
|
+
/* information only */
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
try {
|
|
690
|
+
configureStaleWaitNotifications(onStale);
|
|
691
|
+
} catch {
|
|
692
|
+
/* bridge is best effort */
|
|
693
|
+
}
|
|
694
|
+
try {
|
|
695
|
+
configureHcStaleWaitNotifications(onStale);
|
|
696
|
+
} catch {
|
|
697
|
+
/* bridge is best effort */
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// Done-nudge on child run completion. `session.idle` is never emitted in
|
|
701
|
+
// v2; the execution outcomes are the documented replacement. Only bound
|
|
702
|
+
// sheep sessions with an open, non-waiting task are nudged, bounded per
|
|
703
|
+
// task, then escalated to the parent instead of looping.
|
|
704
|
+
try {
|
|
705
|
+
const stream = ctx.event.subscribe({
|
|
706
|
+
types: ['session.execution.succeeded', 'session.execution.failed'],
|
|
707
|
+
});
|
|
708
|
+
void (async () => {
|
|
709
|
+
for await (const event of stream) {
|
|
710
|
+
try {
|
|
711
|
+
const sessionId: string | undefined =
|
|
712
|
+
event?.properties?.sessionID ??
|
|
713
|
+
event?.properties?.sessionId ??
|
|
714
|
+
event?.sessionID ??
|
|
715
|
+
event?.sessionId;
|
|
716
|
+
if (!sessionId) continue;
|
|
717
|
+
const agent = agentForSession(sessionId);
|
|
718
|
+
if (!agent) continue;
|
|
719
|
+
// Find the sheep's open running task (waiting tasks expect a
|
|
720
|
+
// reply; ending the run is how the sheep waits for it).
|
|
721
|
+
let openTaskId: string | undefined;
|
|
722
|
+
try {
|
|
723
|
+
if (agent.backend === 'hc') {
|
|
724
|
+
const task = describeHcStatusView(agent.agentId).task;
|
|
725
|
+
if (task && task.state !== 'waiting') openTaskId = task.id;
|
|
726
|
+
} else {
|
|
727
|
+
const task = statusAgent(agent.agentId).task;
|
|
728
|
+
if (task && (task.state === 'running' || task.state === 'created')) {
|
|
729
|
+
openTaskId = task.id;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
} catch {
|
|
733
|
+
/* status is best effort */
|
|
734
|
+
}
|
|
735
|
+
if (!openTaskId || agent.outstandingRequests.size > 0) continue;
|
|
736
|
+
const limit = doneNudgeLimit();
|
|
737
|
+
if (limit <= 0) continue;
|
|
738
|
+
const sent = agent.nudgeCounts.get(openTaskId) ?? 0;
|
|
739
|
+
if (sent >= limit) {
|
|
740
|
+
if (!agent.escalatedTasks.has(openTaskId)) {
|
|
741
|
+
agent.escalatedTasks.add(openTaskId);
|
|
742
|
+
await promptParent(
|
|
743
|
+
ctx,
|
|
744
|
+
agent.parentSessionId,
|
|
745
|
+
`Shepherd completion stalled: task ${openTaskId} is still open after ${limit} reminder(s).`
|
|
746
|
+
);
|
|
747
|
+
}
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
agent.nudgeCounts.set(openTaskId, sent + 1);
|
|
751
|
+
try {
|
|
752
|
+
await deliverToSheep(agent, nudgeTextForSheep(openTaskId, sent + 1, limit));
|
|
753
|
+
} catch {
|
|
754
|
+
await promptParent(
|
|
755
|
+
ctx,
|
|
756
|
+
agent.parentSessionId,
|
|
757
|
+
`Shepherd completion stalled: task ${openTaskId} is still open (nudge delivery failed).`
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
} catch {
|
|
761
|
+
/* one bad event must not stop the stream */
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
})();
|
|
765
|
+
} catch {
|
|
766
|
+
/* nudge is best effort; deadlines stay authoritative */
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** Clear unseen notices for watched tasks (an explicit watch pulls them). */
|
|
771
|
+
export function clearUnseenForWatch(taskIds: string[]): void {
|
|
772
|
+
try {
|
|
773
|
+
unseenCompletionLedger.clear(taskIds);
|
|
774
|
+
} catch {
|
|
775
|
+
/* ledger is best effort */
|
|
776
|
+
}
|
|
777
|
+
}
|