@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,2548 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shepherd tool — the model-facing `shepherd` tool for the parent pi session.
|
|
3
|
+
*
|
|
4
|
+
* One tool surface:
|
|
5
|
+
* - spawn/prompt/watch/status/read/close/prune — manage pi agents living in
|
|
6
|
+
* Herdr panes (machinery in herdr.ts).
|
|
7
|
+
*
|
|
8
|
+
* Registered by index.ts in the parent session only. Launched agents get the
|
|
9
|
+
* in-tab completion extension from shepherd-done.ts instead.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { execFile } from 'node:child_process';
|
|
13
|
+
import { promisify } from 'node:util';
|
|
14
|
+
import type { AgentToolResult } from '@earendil-works/pi-agent-core';
|
|
15
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
16
|
+
import { StringEnum } from '@earendil-works/pi-ai';
|
|
17
|
+
import { Box, Text } from '@earendil-works/pi-tui';
|
|
18
|
+
import { Type, type Static } from 'typebox';
|
|
19
|
+
import {
|
|
20
|
+
AgentScopeSchema,
|
|
21
|
+
SpawnParams,
|
|
22
|
+
LifecycleDelegateParams,
|
|
23
|
+
LifecycleMessageParams,
|
|
24
|
+
LifecyclePromptParams,
|
|
25
|
+
WatchParams,
|
|
26
|
+
LifecycleStatusParams,
|
|
27
|
+
LifecycleCloseParams,
|
|
28
|
+
TaskIdSchema,
|
|
29
|
+
PromptIdSchema,
|
|
30
|
+
} from '../core/types.ts';
|
|
31
|
+
import {
|
|
32
|
+
startAgent,
|
|
33
|
+
promptAgent,
|
|
34
|
+
statusAgent,
|
|
35
|
+
promptWatcherService,
|
|
36
|
+
configurePromptWatcherNotifications,
|
|
37
|
+
taskWatcherService,
|
|
38
|
+
configureTaskWatcherNotifications,
|
|
39
|
+
configureStaleWaitNotifications,
|
|
40
|
+
type StaleWaitInfo,
|
|
41
|
+
sendParentMessage,
|
|
42
|
+
configureParentMessageNotifications,
|
|
43
|
+
} from '../runtimes/herdr/lifecycle.ts';
|
|
44
|
+
import { fieldnotesEnabled, loadSettings } from '../core/config.ts';
|
|
45
|
+
import { detectCaller } from '../runtimes/detect.ts';
|
|
46
|
+
import {
|
|
47
|
+
HC_SETUP_HINT,
|
|
48
|
+
resolveBackend,
|
|
49
|
+
type ResolvedBackend,
|
|
50
|
+
} from '../runtimes/backend.ts';
|
|
51
|
+
import { unseenCompletionLedger } from '../core/unseen-completions.ts';
|
|
52
|
+
import { lifecycleRegistry, LifecycleError } from '../runtimes/herdr/orchestration.ts';
|
|
53
|
+
import { createHerdrRuntime } from '../runtimes/herdr/runtime.ts';
|
|
54
|
+
import {
|
|
55
|
+
configureHcStaleWaitNotifications,
|
|
56
|
+
configureHcTaskWatcherNotifications,
|
|
57
|
+
createHcRuntime,
|
|
58
|
+
describeHcAgent,
|
|
59
|
+
describeHcStatusView,
|
|
60
|
+
drainHcInboxForSession,
|
|
61
|
+
hcTaskWatcherService,
|
|
62
|
+
isHcTaskId,
|
|
63
|
+
resolveHcAgentId,
|
|
64
|
+
} from '../runtimes/hc/runtime.ts';
|
|
65
|
+
import { formatShepherdCommand, omitMaterializedDefaults } from './cli.ts';
|
|
66
|
+
import { isHcAvailable } from '../runtimes/hc/hc.ts';
|
|
67
|
+
import {
|
|
68
|
+
resolveOrCreateParentArtifactSession,
|
|
69
|
+
type ShepherdSession,
|
|
70
|
+
} from '../core/artifact-sessions.ts';
|
|
71
|
+
import type { AgentThinkingLevel, DelegatorModel } from '../core/discovery.ts';
|
|
72
|
+
import { discoverAgents, formatAgentList } from '../core/discovery.ts';
|
|
73
|
+
import {
|
|
74
|
+
HERDR_SETUP_HINT,
|
|
75
|
+
agentSummaries,
|
|
76
|
+
createHerdrTab,
|
|
77
|
+
formatSummary,
|
|
78
|
+
getHerdrWorkspaceId,
|
|
79
|
+
herdrExec,
|
|
80
|
+
herdrExecSync,
|
|
81
|
+
isHerdrAvailable,
|
|
82
|
+
launchPiInPane,
|
|
83
|
+
loadCreatedPanes,
|
|
84
|
+
paneExists,
|
|
85
|
+
paneIdOf,
|
|
86
|
+
pruneStaleCreatedPanes,
|
|
87
|
+
readPaneTail,
|
|
88
|
+
recordCreatedPane,
|
|
89
|
+
removeCreatedPaneDir,
|
|
90
|
+
setCreatedPaneDir,
|
|
91
|
+
waitForHerdrAgentDetected,
|
|
92
|
+
waitForHerdrShellReady,
|
|
93
|
+
} from '../runtimes/herdr/herdr.ts';
|
|
94
|
+
|
|
95
|
+
const execFileAsync = promisify(execFile);
|
|
96
|
+
export const SourceSchema = StringEnum(
|
|
97
|
+
['visible', 'recent', 'recent-unwrapped', 'detection'] as const,
|
|
98
|
+
{
|
|
99
|
+
description: 'Terminal snapshot source for read',
|
|
100
|
+
default: 'recent-unwrapped',
|
|
101
|
+
}
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
const HerdParams = Type.Object({
|
|
105
|
+
action: Type.Literal('herd', {
|
|
106
|
+
description: 'List the live herd: agents detected in Herdr panes.',
|
|
107
|
+
}),
|
|
108
|
+
});
|
|
109
|
+
const AgentsParams = Type.Object({
|
|
110
|
+
action: Type.Literal('agents', {
|
|
111
|
+
description: 'List all available agents (also called sheep) and their source metadata.',
|
|
112
|
+
}),
|
|
113
|
+
agentScope: Type.Optional(AgentScopeSchema),
|
|
114
|
+
});
|
|
115
|
+
const ReadParams = Type.Object({
|
|
116
|
+
action: Type.Literal('read', {
|
|
117
|
+
description: 'Read recent terminal output from an agent or pane.',
|
|
118
|
+
}),
|
|
119
|
+
name: Type.String({
|
|
120
|
+
description: 'Agent name, Herdr pane id, or opaque agent id of the target.',
|
|
121
|
+
}),
|
|
122
|
+
lines: Type.Optional(
|
|
123
|
+
Type.Integer({ description: 'Number of recent lines for read (default 40)', default: 40 })
|
|
124
|
+
),
|
|
125
|
+
source: Type.Optional(SourceSchema),
|
|
126
|
+
});
|
|
127
|
+
const PruneParams = Type.Object({
|
|
128
|
+
action: Type.Literal('prune', { description: 'Remove stale pi-shepherd pane registrations.' }),
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
/** Parameters for the umbrella control-plane tool. Lifecycle operations have
|
|
132
|
+
* separate flat schemas and registered tools below. */
|
|
133
|
+
const AnyShepherdUnion = Type.Union(
|
|
134
|
+
[
|
|
135
|
+
HerdParams,
|
|
136
|
+
AgentsParams,
|
|
137
|
+
SpawnParams,
|
|
138
|
+
LifecycleDelegateParams,
|
|
139
|
+
LifecycleMessageParams,
|
|
140
|
+
LifecyclePromptParams,
|
|
141
|
+
WatchParams,
|
|
142
|
+
LifecycleStatusParams,
|
|
143
|
+
LifecycleCloseParams,
|
|
144
|
+
ReadParams,
|
|
145
|
+
PruneParams,
|
|
146
|
+
],
|
|
147
|
+
{
|
|
148
|
+
description:
|
|
149
|
+
'Action-discriminated shepherd commands for managing specialized agents (also called sheep), their fieldnotes (artifacts), and their Herdr panes.',
|
|
150
|
+
}
|
|
151
|
+
);
|
|
152
|
+
export type ShepherdArgs = Static<typeof AnyShepherdUnion>;
|
|
153
|
+
|
|
154
|
+
function prepareForSchema<T>(input: unknown): T {
|
|
155
|
+
return prepareShepherdArguments(input) as unknown as T;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Some model/provider tool-call transports encode nested JSON values as
|
|
160
|
+
* strings. Pi validates arguments after this hook, so normalize only known
|
|
161
|
+
* transport-serialization details here. The public lifecycle protocol uses
|
|
162
|
+
* opaque id strings; the legacy `handle` form is accepted here temporarily so
|
|
163
|
+
* existing callers fail soft while migrating.
|
|
164
|
+
*/
|
|
165
|
+
export function prepareShepherdArguments(input: unknown): ShepherdArgs {
|
|
166
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) return input as ShepherdArgs;
|
|
167
|
+
const args = { ...(input as Record<string, unknown>) };
|
|
168
|
+
// Compatibility for transcripts produced before lifecycle calls switched to
|
|
169
|
+
// scalar ids. Convert `{ handle: { id: ... } }` (or its JSON encoding) into
|
|
170
|
+
// the current `{ id: ... }` form before schema validation.
|
|
171
|
+
if (!('id' in args) && 'handle' in args) {
|
|
172
|
+
let legacy: unknown = args.handle;
|
|
173
|
+
if (typeof legacy === 'string') {
|
|
174
|
+
try {
|
|
175
|
+
legacy = JSON.parse(legacy);
|
|
176
|
+
} catch {
|
|
177
|
+
// A plain string is already a usable legacy id.
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (Array.isArray(legacy)) {
|
|
181
|
+
args.id = legacy.map(item =>
|
|
182
|
+
item && typeof item === 'object' && typeof (item as any).id === 'string'
|
|
183
|
+
? (item as any).id
|
|
184
|
+
: item
|
|
185
|
+
);
|
|
186
|
+
} else if (legacy && typeof legacy === 'object' && typeof (legacy as any).id === 'string') {
|
|
187
|
+
args.id = (legacy as any).id;
|
|
188
|
+
} else {
|
|
189
|
+
args.id = legacy;
|
|
190
|
+
}
|
|
191
|
+
delete args.handle;
|
|
192
|
+
}
|
|
193
|
+
// These values are deliberately not part of the spawn protocol. Settings
|
|
194
|
+
// and the discovered agent definition own them; silently discard legacy
|
|
195
|
+
// callers' copies so they cannot override those sources before validation.
|
|
196
|
+
for (const name of ['agentScope', 'confirmProjectAgents', 'omitSystemPrompt', 'direction']) {
|
|
197
|
+
delete args[name];
|
|
198
|
+
}
|
|
199
|
+
if (typeof args.id === 'string' && args.id.trim().startsWith('[')) {
|
|
200
|
+
try {
|
|
201
|
+
const parsed = JSON.parse(args.id);
|
|
202
|
+
if (Array.isArray(parsed)) args.id = parsed;
|
|
203
|
+
} catch {
|
|
204
|
+
// Leave malformed values untouched for normal schema validation.
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
for (const name of ['timeout', 'lines']) {
|
|
208
|
+
const value = args[name];
|
|
209
|
+
if (typeof value === 'string' && /^[-+]?\d+$/.test(value.trim())) {
|
|
210
|
+
args[name] = Number(value.trim());
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return args as ShepherdArgs;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function unavailableResult(
|
|
217
|
+
action?: string,
|
|
218
|
+
args?: ShepherdArgs
|
|
219
|
+
): AgentToolResult<Record<string, unknown>> {
|
|
220
|
+
return {
|
|
221
|
+
content: [
|
|
222
|
+
{ type: 'text', text: `Herd requires a running Herdr session.\n${HERDR_SETUP_HINT}` },
|
|
223
|
+
],
|
|
224
|
+
details: {
|
|
225
|
+
...(action && args ? { call: publicToolCall(action, args) } : {}),
|
|
226
|
+
code: 'herdr_unavailable',
|
|
227
|
+
returnCode: 1,
|
|
228
|
+
returnValue: { code: 'herdr_unavailable', error: 'herdr not available', returnCode: 1 },
|
|
229
|
+
error: 'herdr not available',
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function textResult(
|
|
235
|
+
text: string,
|
|
236
|
+
details: Record<string, unknown>
|
|
237
|
+
): AgentToolResult<Record<string, unknown>> {
|
|
238
|
+
return {
|
|
239
|
+
content: [{ type: 'text' as const, text }],
|
|
240
|
+
// Every completed Shepherd operation exposes its return value and a
|
|
241
|
+
// process-style return code. Individual operations can override these for
|
|
242
|
+
// a structured/failed/partial result.
|
|
243
|
+
details: { returnValue: text, returnCode: 0, ...details },
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Keep the opaque lifecycle id easy to copy from model-visible tool text. */
|
|
248
|
+
export function formatIdForModel(id: string): string {
|
|
249
|
+
return id;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Keep the exact public tool invocation visible alongside its result. */
|
|
253
|
+
function publicToolCall(
|
|
254
|
+
action: string,
|
|
255
|
+
args: ShepherdArgs,
|
|
256
|
+
defaultCwd = process.cwd()
|
|
257
|
+
): Record<string, unknown> {
|
|
258
|
+
const { action: _action, artifactSession: _artifactSession, ...parameters } = args as any;
|
|
259
|
+
const name = ['herd', 'agents', 'prune'].includes(action) ? 'shepherd' : `shepherd_${action}`;
|
|
260
|
+
return { name, arguments: omitMaterializedDefaults(action, parameters, defaultCwd) };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function displayAgentName(agentId: string): string {
|
|
264
|
+
try {
|
|
265
|
+
const handle = lifecycleRegistry.getAgent({ id: agentId }).handle;
|
|
266
|
+
return handle.label ? `${handle.agent}: ${handle.label}` : handle.agent;
|
|
267
|
+
} catch {
|
|
268
|
+
return agentId;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Resolver seam (spec 009): per-command resolve, Phase 2 routes spawn/
|
|
274
|
+
* delegate/message/status/read/watch/close through the resolved runtime
|
|
275
|
+
* (legacy prompt stays pane-only: deprecated compat, hc callers use delegate).
|
|
276
|
+
* Per-command resolve: the explicit `backend` pin wins, otherwise run where
|
|
277
|
+
* called from. Native ids never cross backends: each runtime only honors
|
|
278
|
+
* ids from its own registry, so a pane id is junk to hc and a terminal
|
|
279
|
+
* address is junk to panes.
|
|
280
|
+
*/
|
|
281
|
+
function commandBackend(ctx: ShepherdContext): ResolvedBackend {
|
|
282
|
+
return resolveBackend(loadSettings(ctx.cwd).backend, detectCaller());
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Display identity for an hc sheep; falls back to the raw id like displayAgentName. */
|
|
286
|
+
function hcAgentIdentity(id: string): { id: string; agent: string; label: string; model?: string } {
|
|
287
|
+
try {
|
|
288
|
+
return describeHcAgent(id);
|
|
289
|
+
} catch {
|
|
290
|
+
return { id, agent: id, label: '' };
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function lifecycleHandleForPane(paneId: unknown): any | undefined {
|
|
295
|
+
if (typeof paneId !== 'string' || !paneId) return undefined;
|
|
296
|
+
return lifecycleRegistry.allAgents().find(handle => handle.paneId === paneId);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function shepherdHerdAgents(agents: unknown[]): any[] {
|
|
300
|
+
return agents
|
|
301
|
+
.filter(agent => agent && typeof agent === 'object' && (agent as any).shepherd === true)
|
|
302
|
+
.map(agent => {
|
|
303
|
+
const record = agent as Record<string, unknown>;
|
|
304
|
+
const handle = lifecycleHandleForPane(record.paneId);
|
|
305
|
+
const visible: Record<string, unknown> = handle
|
|
306
|
+
? {
|
|
307
|
+
agentId: handle.id,
|
|
308
|
+
agent: handle.agent,
|
|
309
|
+
...(handle.label ? { label: handle.label } : {}),
|
|
310
|
+
}
|
|
311
|
+
: { agentId: record.focused === true ? 'shepherd' : record.name };
|
|
312
|
+
return {
|
|
313
|
+
...visible,
|
|
314
|
+
state: record.state,
|
|
315
|
+
...(record.focused === true ? { focused: true } : {}),
|
|
316
|
+
};
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function formatHerdAgentList(agents: unknown[], indent = ' '): string[] {
|
|
321
|
+
return agents.flatMap((agent, index) => {
|
|
322
|
+
if (!agent || typeof agent !== 'object' || Array.isArray(agent)) {
|
|
323
|
+
return [`${indent}${formatHumanScalar(agent)}`];
|
|
324
|
+
}
|
|
325
|
+
const entries = Object.entries(agent);
|
|
326
|
+
if (entries.length === 0) return [`${indent}agent id: unknown`];
|
|
327
|
+
const [[firstKey, firstValue], ...rest] = entries;
|
|
328
|
+
const firstLines = formatHumanField(humanizeKey(firstKey), firstValue, indent);
|
|
329
|
+
return [
|
|
330
|
+
...(index > 0 ? [''] : []),
|
|
331
|
+
...firstLines,
|
|
332
|
+
...rest.flatMap(([key, value]) => formatHumanField(humanizeKey(key), value, `${indent} `)),
|
|
333
|
+
];
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function formatToolResultText(result: any): string | undefined {
|
|
338
|
+
const body = result?.content?.[0]?.type === 'text' ? (result.content[0].text ?? '') : undefined;
|
|
339
|
+
const details = result?.details && typeof result.details === 'object' ? result.details : {};
|
|
340
|
+
const call = details.call;
|
|
341
|
+
if (!call?.name) return body;
|
|
342
|
+
// executeShepherd embeds the structured text for non-TUI/API callers. Do
|
|
343
|
+
// not append a second call/return/details block when the renderer sees it.
|
|
344
|
+
if (typeof body === 'string' && body.includes('\ncall:\n')) return body;
|
|
345
|
+
|
|
346
|
+
const returnValue = details.returnValue ?? details.result;
|
|
347
|
+
const visibleDetails = Object.entries(details)
|
|
348
|
+
.filter(
|
|
349
|
+
([key]) =>
|
|
350
|
+
![
|
|
351
|
+
'call',
|
|
352
|
+
'agent',
|
|
353
|
+
'label',
|
|
354
|
+
'model',
|
|
355
|
+
'status',
|
|
356
|
+
'artifactSession',
|
|
357
|
+
'returnValue',
|
|
358
|
+
'result',
|
|
359
|
+
].includes(key)
|
|
360
|
+
)
|
|
361
|
+
.sort(([left], [right]) => Number(left === 'returnCode') - Number(right === 'returnCode'))
|
|
362
|
+
.map(([key, value]) => {
|
|
363
|
+
let displayKey = key.replace(/[A-Z]/g, letter => ` ${letter.toLowerCase()}`);
|
|
364
|
+
if (key === 'id' && call.name === 'shepherd_spawn') displayKey = 'agent id';
|
|
365
|
+
if (key === 'fieldnote' && call.name === 'shepherd_spawn') displayKey = 'agent fieldnote';
|
|
366
|
+
const displayValue =
|
|
367
|
+
value === null && key === 'fieldnote'
|
|
368
|
+
? 'none'
|
|
369
|
+
: typeof value === 'string'
|
|
370
|
+
? value
|
|
371
|
+
: JSON.stringify(value);
|
|
372
|
+
return ` ${displayKey}: ${displayValue ?? 'null'}`;
|
|
373
|
+
});
|
|
374
|
+
const callText = `${call.name} ${JSON.stringify(call.arguments ?? {})}`;
|
|
375
|
+
const renderedReturn = formatReturnValue(returnValue);
|
|
376
|
+
return [
|
|
377
|
+
body ?? '(no output)',
|
|
378
|
+
'',
|
|
379
|
+
'call:',
|
|
380
|
+
` ${callText}`,
|
|
381
|
+
'',
|
|
382
|
+
'return:',
|
|
383
|
+
` ${renderedReturn}`,
|
|
384
|
+
...(visibleDetails.length ? ['', 'details:', ...visibleDetails] : []),
|
|
385
|
+
].join('\n');
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function formatReturnValue(value: unknown): string {
|
|
389
|
+
if (typeof value === 'string') return value;
|
|
390
|
+
if (Array.isArray(value)) {
|
|
391
|
+
const items = value.map(item => JSON.stringify(item));
|
|
392
|
+
return `[${items.join(',\n ')}]`;
|
|
393
|
+
}
|
|
394
|
+
return JSON.stringify(value ?? null);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function withToolResultText(
|
|
398
|
+
result: AgentToolResult<Record<string, unknown>>
|
|
399
|
+
): AgentToolResult<Record<string, unknown>> {
|
|
400
|
+
const text = formatToolResultText(result);
|
|
401
|
+
return text === undefined ? result : { ...result, content: [{ type: 'text', text }] };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function reusableText(lastComponent: unknown): Text {
|
|
405
|
+
return lastComponent instanceof Text ? lastComponent : new Text('', 0, 0);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Render custom Shepherd notifications from their structured `details` payload.
|
|
410
|
+
* The message content intentionally remains the detailed protocol text for the
|
|
411
|
+
* model/API; this formatter is only used by the human-facing message renderer.
|
|
412
|
+
*/
|
|
413
|
+
export function renderShepherdNotification(
|
|
414
|
+
message: any,
|
|
415
|
+
options: { expanded?: boolean; outputPad?: number },
|
|
416
|
+
theme: any,
|
|
417
|
+
formatted?: string
|
|
418
|
+
): Box {
|
|
419
|
+
const content = formatted ?? notificationFallbackText(message);
|
|
420
|
+
const collapsed = options.expanded !== true;
|
|
421
|
+
const renderedContent = collapsed ? formatCollapsedNotification(message, content) : content;
|
|
422
|
+
const lines = renderedContent.split('\n');
|
|
423
|
+
const title = lines.shift() ?? 'Shepherd notification';
|
|
424
|
+
const renderedRemainder = collapsed
|
|
425
|
+
? lines
|
|
426
|
+
.map(line => {
|
|
427
|
+
if (/^✓/.test(line)) return theme.fg('success', line);
|
|
428
|
+
if (/^✗/.test(line)) return theme.fg('error', line);
|
|
429
|
+
if (/^⚠/.test(line)) return theme.fg('warning', line);
|
|
430
|
+
return theme.fg('toolOutput', line);
|
|
431
|
+
})
|
|
432
|
+
.join('\n')
|
|
433
|
+
: styleExpandedToolResult(
|
|
434
|
+
lines.join('\n'),
|
|
435
|
+
theme,
|
|
436
|
+
message?.details?.messageId ? { boldFields: ['message'] } : undefined
|
|
437
|
+
);
|
|
438
|
+
const titleParts = title.split(/\s+/);
|
|
439
|
+
const titleVerb = titleParts.shift() ?? 'Shepherd';
|
|
440
|
+
const titleArgs = titleParts.join(' ');
|
|
441
|
+
const renderedTitle =
|
|
442
|
+
theme.fg('toolTitle', theme.bold(titleVerb)) +
|
|
443
|
+
(titleArgs ? ` ${theme.fg('accent', titleArgs)}` : '');
|
|
444
|
+
const rendered = renderedTitle + (lines.length ? `\n${renderedRemainder}` : '');
|
|
445
|
+
const box = new Box(options.outputPad ?? 0, 1, (text: string) =>
|
|
446
|
+
theme.bg('customMessageBg', text)
|
|
447
|
+
);
|
|
448
|
+
box.addChild(new Text(rendered, 0, 0));
|
|
449
|
+
return box;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Compact custom notifications the same way collapsed tool results show only
|
|
453
|
+
* their useful summary. Ctrl+O still exposes the structured notification. */
|
|
454
|
+
function compactNotificationText(value: unknown, maxLength = 160): string {
|
|
455
|
+
const text = String(value ?? '')
|
|
456
|
+
.replace(/\s+/g, ' ')
|
|
457
|
+
.trim();
|
|
458
|
+
if (text.length <= maxLength) return text;
|
|
459
|
+
return `${text.slice(0, maxLength - 1).trimEnd()}…`;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export function formatCollapsedNotification(message: any, formatted: string): string {
|
|
463
|
+
const lines = formatted.split('\n');
|
|
464
|
+
const title = lines[0] ?? 'Shepherd notification';
|
|
465
|
+
const details = message?.details;
|
|
466
|
+
if (details?.messageId) {
|
|
467
|
+
const text = compactNotificationText(details.content);
|
|
468
|
+
return text ? `${title}\n${text}` : title;
|
|
469
|
+
}
|
|
470
|
+
if (Array.isArray(details?.completions)) {
|
|
471
|
+
const ids =
|
|
472
|
+
details.taskIds ??
|
|
473
|
+
details.promptIds ??
|
|
474
|
+
details.completions
|
|
475
|
+
.map((completion: any) => completion.taskId ?? completion.promptId)
|
|
476
|
+
.filter((id: unknown): id is string => typeof id === 'string');
|
|
477
|
+
const target = Array.isArray(ids) && ids.length > 0 ? ids.join(', ') : 'completion';
|
|
478
|
+
const failed = details.completions.some(
|
|
479
|
+
(completion: any) =>
|
|
480
|
+
!['completed', 'done'].includes(completion.status) ||
|
|
481
|
+
(completion.returnCode !== undefined && completion.returnCode !== 0)
|
|
482
|
+
);
|
|
483
|
+
return [`shepherd_watch ${target}`, `${failed ? '✗ failed' : '✓ success'}`].join('\n');
|
|
484
|
+
}
|
|
485
|
+
if (details?.taskId) return `${title}: ${details.taskId}`;
|
|
486
|
+
return title;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function notificationFallbackText(message: any): string {
|
|
490
|
+
const content = typeof message?.content === 'string' ? message.content : '';
|
|
491
|
+
const marker = content.indexOf('\n\ncall:\n');
|
|
492
|
+
return marker >= 0 ? content.slice(0, marker) : content;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export function formatParentMessageNotification(
|
|
496
|
+
envelope: any,
|
|
497
|
+
customType?: string
|
|
498
|
+
): string | undefined {
|
|
499
|
+
if (!envelope || typeof envelope !== 'object' || !envelope.messageId) return undefined;
|
|
500
|
+
const isReply = envelope.kind === 'reply' || customType === 'shepherd.message.reply';
|
|
501
|
+
const isWarning = customType === 'shepherd.message.warning';
|
|
502
|
+
const sender = displayAgentName(String(envelope.senderId ?? envelope.from ?? 'unknown'));
|
|
503
|
+
const lines = [`Shepherd ${isWarning ? 'warning' : isReply ? 'reply' : 'message'} from ${sender}`];
|
|
504
|
+
const metadata: string[] = [];
|
|
505
|
+
for (const [label, value] of [
|
|
506
|
+
['message id', envelope.messageId],
|
|
507
|
+
['task id', envelope.taskId],
|
|
508
|
+
['thread id', envelope.threadId],
|
|
509
|
+
['reply to', envelope.replyTo],
|
|
510
|
+
] as const) {
|
|
511
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
512
|
+
metadata.push(...formatHumanField(label, value, ''));
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
if (isWarning && envelope.reason) {
|
|
516
|
+
metadata.push(...formatHumanField('reason', String(envelope.reason), ''));
|
|
517
|
+
}
|
|
518
|
+
if (metadata.length) lines.push('', ...metadata);
|
|
519
|
+
lines.push('', ...formatHumanField('message', String(envelope.content ?? ''), ''));
|
|
520
|
+
return lines.join('\n');
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function compactWatcherCompletion(completion: any): Record<string, unknown> {
|
|
524
|
+
if (!completion || typeof completion !== 'object') return { value: completion };
|
|
525
|
+
const keys = [
|
|
526
|
+
'taskId',
|
|
527
|
+
'promptId',
|
|
528
|
+
'agentId',
|
|
529
|
+
'agent',
|
|
530
|
+
'label',
|
|
531
|
+
'status',
|
|
532
|
+
'ok',
|
|
533
|
+
'returnCode',
|
|
534
|
+
'text',
|
|
535
|
+
'error',
|
|
536
|
+
'completedAt',
|
|
537
|
+
];
|
|
538
|
+
return Object.fromEntries(
|
|
539
|
+
keys
|
|
540
|
+
.filter(
|
|
541
|
+
key => completion[key] !== undefined && completion[key] !== null && completion[key] !== ''
|
|
542
|
+
)
|
|
543
|
+
.map(key => [key, completion[key]])
|
|
544
|
+
);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
export function formatWatcherNotification(
|
|
548
|
+
details: any,
|
|
549
|
+
kind: 'task' | 'prompt'
|
|
550
|
+
): string | undefined {
|
|
551
|
+
if (!details || typeof details !== 'object' || !Array.isArray(details.completions))
|
|
552
|
+
return undefined;
|
|
553
|
+
const lines = ['Shepherd watcher'];
|
|
554
|
+
const idLabel = kind === 'task' ? 'task ids' : 'prompt ids';
|
|
555
|
+
const ids = kind === 'task' ? details.taskIds : details.promptIds;
|
|
556
|
+
if (details.watcherId) lines.push(...formatHumanField('watcher id', details.watcherId, ''));
|
|
557
|
+
if (Array.isArray(ids)) lines.push(...formatHumanField(idLabel, ids, ''));
|
|
558
|
+
// Completion artifacts are durable storage metadata, not watcher output.
|
|
559
|
+
// Keep the expanded notification focused on operational fields.
|
|
560
|
+
lines.push(
|
|
561
|
+
...formatHumanField('completions', details.completions.map(compactWatcherCompletion), '')
|
|
562
|
+
);
|
|
563
|
+
return lines.join('\n');
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
export function formatStaleWaitNotification(info: any): string | undefined {
|
|
567
|
+
if (!info || typeof info !== 'object' || !info.taskId) return undefined;
|
|
568
|
+
const owner = info.label
|
|
569
|
+
? `${info.agent ?? info.agentId}: ${info.label}`
|
|
570
|
+
: (info.agent ?? info.agentId);
|
|
571
|
+
const recipient = info.recipientName
|
|
572
|
+
? `${info.recipientName}${info.recipientState ? ` (${info.recipientState})` : ''}`
|
|
573
|
+
: undefined;
|
|
574
|
+
const lines = ['Shepherd stale wait'];
|
|
575
|
+
if (info.elapsedMs !== undefined) {
|
|
576
|
+
lines.push(
|
|
577
|
+
...formatHumanField(
|
|
578
|
+
'waiting',
|
|
579
|
+
`${formatElapsedMs(info.elapsedMs)} (stale after ${info.thresholdMinutes} min)`,
|
|
580
|
+
''
|
|
581
|
+
)
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
lines.push(...formatHumanField('task id', info.taskId, ''));
|
|
585
|
+
if (owner) lines.push(...formatHumanField('owner', owner, ''));
|
|
586
|
+
if (info.description) lines.push(...formatHumanField('description', info.description, ''));
|
|
587
|
+
if (info.question) lines.push(...formatHumanField('question', info.question, ''));
|
|
588
|
+
if (info.requestMessageId) {
|
|
589
|
+
const pending = recipient
|
|
590
|
+
? `${info.requestMessageId} (waiting on ${recipient})`
|
|
591
|
+
: info.requestMessageId;
|
|
592
|
+
lines.push(...formatHumanField('pending request', pending, ''));
|
|
593
|
+
}
|
|
594
|
+
lines.push(
|
|
595
|
+
...formatHumanField(
|
|
596
|
+
'actions',
|
|
597
|
+
[
|
|
598
|
+
"Reply to the recipient on the owner's behalf via shepherd_message (set replyTo to the pending request).",
|
|
599
|
+
`Or nudge ${recipient ?? 'the target agent'} with shepherd_message (targetId = recipient).`,
|
|
600
|
+
"Or let the task's reply deadline settle it as blocked (shepherd_delegate timeout).",
|
|
601
|
+
].join('\n'),
|
|
602
|
+
''
|
|
603
|
+
)
|
|
604
|
+
);
|
|
605
|
+
return lines.join('\n');
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
let watcherParentSessionActive = true;
|
|
609
|
+
|
|
610
|
+
/** Enable/disable delivery without changing the core watcher's state model. */
|
|
611
|
+
export function setPromptWatcherSessionActive(active: boolean): void {
|
|
612
|
+
watcherParentSessionActive = active;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
let messageParentSessionActive = true;
|
|
616
|
+
|
|
617
|
+
/** Enable/disable message delivery without changing the core service. */
|
|
618
|
+
export function setShepherdMessageSessionActive(active: boolean): void {
|
|
619
|
+
messageParentSessionActive = active;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function registerPromptCompletionRenderer(pi: ExtensionAPI): void {
|
|
623
|
+
pi.registerMessageRenderer('shepherd.prompt.completion', (message, options, theme) =>
|
|
624
|
+
renderShepherdNotification(
|
|
625
|
+
message,
|
|
626
|
+
options,
|
|
627
|
+
theme,
|
|
628
|
+
formatWatcherNotification(message?.details, 'prompt')
|
|
629
|
+
)
|
|
630
|
+
);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** Enable/disable task-watcher delivery without changing the core service's state model. */
|
|
634
|
+
let taskWatcherParentSessionActive = false;
|
|
635
|
+
export function setTaskWatcherSessionActive(active: boolean): void {
|
|
636
|
+
taskWatcherParentSessionActive = active;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** Enable/disable stale-wait delivery without changing the core monitor's state model. */
|
|
640
|
+
let staleWaitParentSessionActive = false;
|
|
641
|
+
export function setStaleWaitSessionActive(active: boolean): void {
|
|
642
|
+
staleWaitParentSessionActive = active;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function formatElapsedMs(ms: number): string {
|
|
646
|
+
const s = Math.max(0, Math.floor(ms / 1000));
|
|
647
|
+
const m = Math.floor(s / 60);
|
|
648
|
+
const r = s % 60;
|
|
649
|
+
return m > 0 ? `${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}` : `${s}s`;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function registerStaleWaitRenderer(pi: ExtensionAPI): void {
|
|
653
|
+
pi.registerMessageRenderer('shepherd.stale.wait', (message, options, theme) =>
|
|
654
|
+
renderShepherdNotification(
|
|
655
|
+
message,
|
|
656
|
+
options,
|
|
657
|
+
theme,
|
|
658
|
+
formatStaleWaitNotification(message?.details)
|
|
659
|
+
)
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function configureStaleWaitBridge(pi: ExtensionAPI): void {
|
|
664
|
+
registerStaleWaitRenderer(pi);
|
|
665
|
+
configureStaleWaitNotifications(info => {
|
|
666
|
+
if (!staleWaitParentSessionActive) return;
|
|
667
|
+
const owner = info.label
|
|
668
|
+
? `${info.agent ?? info.agentId}: ${info.label}`
|
|
669
|
+
: (info.agent ?? info.agentId);
|
|
670
|
+
const recipient = info.recipientName
|
|
671
|
+
? `${info.recipientName}${info.recipientState ? ` (${info.recipientState})` : ''}`
|
|
672
|
+
: 'the target agent';
|
|
673
|
+
const body = [
|
|
674
|
+
`Waiting ${formatElapsedMs(info.elapsedMs)} for a reply (stale after ${info.thresholdMinutes} min).`,
|
|
675
|
+
`Task: ${info.taskId}`,
|
|
676
|
+
`Owner: ${owner} - ${info.description}`,
|
|
677
|
+
`Question: ${info.question}`,
|
|
678
|
+
`Pending request: ${info.requestMessageId} (waiting on ${recipient})`,
|
|
679
|
+
]
|
|
680
|
+
.filter(Boolean)
|
|
681
|
+
.join('\n');
|
|
682
|
+
const actions = [
|
|
683
|
+
"Reply to the recipient on the owner's behalf via shepherd_message (set replyTo to the pending request).",
|
|
684
|
+
`Or nudge ${recipient} with shepherd_message (targetId = recipient).`,
|
|
685
|
+
"Or let the task's reply deadline settle it as blocked (shepherd_delegate timeout).",
|
|
686
|
+
].join('\n');
|
|
687
|
+
const content = formatToolResultText({
|
|
688
|
+
content: [{ type: 'text' as const, text: body }],
|
|
689
|
+
details: {
|
|
690
|
+
call: {
|
|
691
|
+
name: 'shepherd_message (possible follow-up)',
|
|
692
|
+
arguments: { taskId: info.taskId, replyTo: info.requestMessageId },
|
|
693
|
+
},
|
|
694
|
+
taskId: info.taskId,
|
|
695
|
+
agentId: info.agentId,
|
|
696
|
+
elapsedMs: info.elapsedMs,
|
|
697
|
+
requestMessageId: info.requestMessageId,
|
|
698
|
+
action: actions,
|
|
699
|
+
returnValue: info,
|
|
700
|
+
},
|
|
701
|
+
});
|
|
702
|
+
try {
|
|
703
|
+
const sendResult: any = pi.sendMessage(
|
|
704
|
+
{
|
|
705
|
+
customType: 'shepherd.stale.wait',
|
|
706
|
+
content,
|
|
707
|
+
display: true,
|
|
708
|
+
details: info,
|
|
709
|
+
},
|
|
710
|
+
{ deliverAs: 'followUp', triggerTurn: false }
|
|
711
|
+
);
|
|
712
|
+
if (sendResult && typeof sendResult.catch === 'function') {
|
|
713
|
+
sendResult.catch(() => undefined);
|
|
714
|
+
}
|
|
715
|
+
} catch {
|
|
716
|
+
// Delivery is best effort; the reply deadline is the authoritative outcome.
|
|
717
|
+
}
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function registerTaskCompletionRenderer(pi: ExtensionAPI): void {
|
|
722
|
+
pi.registerMessageRenderer('shepherd.task.completion', (message, options, theme) =>
|
|
723
|
+
renderShepherdNotification(
|
|
724
|
+
message,
|
|
725
|
+
options,
|
|
726
|
+
theme,
|
|
727
|
+
formatWatcherNotification(message?.details, 'task')
|
|
728
|
+
)
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Bridge from core TASK watcher completions to the parent Pi session. A task
|
|
734
|
+
* completion is a terminal outcome (shepherd_done or an explicit
|
|
735
|
+
* failure/cancellation/timeout), so it always triggers a parent turn to process
|
|
736
|
+
* the result — matching the prompt bridge's delivery policy.
|
|
737
|
+
*
|
|
738
|
+
* Delivery uses `steer` rather than `followUp`: pi only delivers queued
|
|
739
|
+
* followUp messages when the parent run has no more tool calls at all, so a
|
|
740
|
+
* completion observed while the Shepherd is mid-turn (the normal async-watch
|
|
741
|
+
* flow) would otherwise sit queued until the whole turn ends — after cleanup
|
|
742
|
+
* tool calls such as shepherd_close. Steer surfaces the completion between
|
|
743
|
+
* tool rounds, and `triggerTurn` still fires immediately when the parent is
|
|
744
|
+
* idle.
|
|
745
|
+
*/
|
|
746
|
+
function configureTaskWatcherBridge(pi: ExtensionAPI): void {
|
|
747
|
+
registerTaskCompletionRenderer(pi);
|
|
748
|
+
configureTaskWatcherNotifications(notification => {
|
|
749
|
+
if (!taskWatcherParentSessionActive) return;
|
|
750
|
+
const summary = notification.completions
|
|
751
|
+
.map(completion => {
|
|
752
|
+
const identity = completion.label
|
|
753
|
+
? `${completion.agent ?? completion.agentId}: ${completion.label}`
|
|
754
|
+
: (completion.agent ?? completion.agentId);
|
|
755
|
+
return `${identity} ${completion.status}`;
|
|
756
|
+
})
|
|
757
|
+
.join(', ');
|
|
758
|
+
const returnCode =
|
|
759
|
+
notification.completions.find(completion => completion.returnCode !== 0)?.returnCode ?? 0;
|
|
760
|
+
// Keep the model-visible notification compact. The structured payload is
|
|
761
|
+
// retained in `details` for the expanded custom renderer and consumers.
|
|
762
|
+
const content = `shepherd_watcher completion${notification.completions.length === 1 ? '' : 's'}: ${summary}`;
|
|
763
|
+
try {
|
|
764
|
+
const sendResult: any = pi.sendMessage(
|
|
765
|
+
{
|
|
766
|
+
customType: 'shepherd.task.completion',
|
|
767
|
+
content,
|
|
768
|
+
display: true,
|
|
769
|
+
details: notification,
|
|
770
|
+
},
|
|
771
|
+
{ deliverAs: 'steer', triggerTurn: true }
|
|
772
|
+
);
|
|
773
|
+
if (sendResult && typeof sendResult.catch === 'function') {
|
|
774
|
+
sendResult.catch(() => undefined);
|
|
775
|
+
}
|
|
776
|
+
} catch {
|
|
777
|
+
// Delivery is best effort. The completion is already durable in the task
|
|
778
|
+
// registry and can be retrieved via shepherd_status.
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/**
|
|
784
|
+
* Hc task-watcher bridge (Phase 2 parity): same customType, summary shape,
|
|
785
|
+
* and steer/triggerTurn delivery as the pane-backend task bridge. Hc
|
|
786
|
+
* completions already carry display identity from the hc watcher registry.
|
|
787
|
+
*/
|
|
788
|
+
function configureHcTaskWatcherBridge(pi: ExtensionAPI): void {
|
|
789
|
+
registerTaskCompletionRenderer(pi);
|
|
790
|
+
configureHcTaskWatcherNotifications(notification => {
|
|
791
|
+
if (!taskWatcherParentSessionActive) return;
|
|
792
|
+
const summary = notification.completions
|
|
793
|
+
.map(completion => {
|
|
794
|
+
const identity = completion.label
|
|
795
|
+
? `${completion.agent ?? completion.agentId}: ${completion.label}`
|
|
796
|
+
: (completion.agent ?? completion.agentId);
|
|
797
|
+
return `${identity} ${completion.status}`;
|
|
798
|
+
})
|
|
799
|
+
.join(', ');
|
|
800
|
+
const content = `shepherd_watcher completion${notification.completions.length === 1 ? '' : 's'}: ${summary}`;
|
|
801
|
+
try {
|
|
802
|
+
const sendResult: any = pi.sendMessage(
|
|
803
|
+
{
|
|
804
|
+
customType: 'shepherd.task.completion',
|
|
805
|
+
content,
|
|
806
|
+
display: true,
|
|
807
|
+
details: notification,
|
|
808
|
+
},
|
|
809
|
+
{ deliverAs: 'steer', triggerTurn: true }
|
|
810
|
+
);
|
|
811
|
+
if (sendResult && typeof sendResult.catch === 'function') {
|
|
812
|
+
sendResult.catch(() => undefined);
|
|
813
|
+
}
|
|
814
|
+
} catch {
|
|
815
|
+
// Delivery is best effort; the completion stays retrievable via status.
|
|
816
|
+
}
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Hc stale-wait bridge (Phase 2 parity): same customType, body, and
|
|
822
|
+
* followUp/no-wake delivery as the pane-backend stale bridge. The reminder
|
|
823
|
+
* is information only; the reply deadline stays authoritative.
|
|
824
|
+
*/
|
|
825
|
+
function configureHcStaleWaitBridge(pi: ExtensionAPI): void {
|
|
826
|
+
registerStaleWaitRenderer(pi);
|
|
827
|
+
configureHcStaleWaitNotifications(info => {
|
|
828
|
+
if (!staleWaitParentSessionActive) return;
|
|
829
|
+
const owner = info.label
|
|
830
|
+
? `${info.agent ?? info.agentId}: ${info.label}`
|
|
831
|
+
: (info.agent ?? info.agentId);
|
|
832
|
+
const recipient = info.recipientName
|
|
833
|
+
? `${info.recipientName}${info.recipientState ? ` (${info.recipientState})` : ''}`
|
|
834
|
+
: 'the target agent';
|
|
835
|
+
const body = [
|
|
836
|
+
`Waiting ${formatElapsedMs(info.elapsedMs)} for a reply (stale after ${info.thresholdMinutes} min).`,
|
|
837
|
+
`Task: ${info.taskId}`,
|
|
838
|
+
`Owner: ${owner} - ${info.description}`,
|
|
839
|
+
`Question: ${info.question}`,
|
|
840
|
+
`Pending request: ${info.requestMessageId} (waiting on ${recipient})`,
|
|
841
|
+
]
|
|
842
|
+
.filter(Boolean)
|
|
843
|
+
.join('\n');
|
|
844
|
+
const actions = [
|
|
845
|
+
"Reply to the recipient on the owner's behalf via shepherd_message (set replyTo to the pending request).",
|
|
846
|
+
`Or nudge ${recipient} with shepherd_message (targetId = recipient).`,
|
|
847
|
+
"Or let the task's reply deadline settle it as blocked (shepherd_delegate timeout).",
|
|
848
|
+
].join('\n');
|
|
849
|
+
const content = formatToolResultText({
|
|
850
|
+
content: [{ type: 'text' as const, text: body }],
|
|
851
|
+
details: {
|
|
852
|
+
call: {
|
|
853
|
+
name: 'shepherd_message (possible follow-up)',
|
|
854
|
+
arguments: { taskId: info.taskId, replyTo: info.requestMessageId },
|
|
855
|
+
},
|
|
856
|
+
taskId: info.taskId,
|
|
857
|
+
agentId: info.agentId,
|
|
858
|
+
elapsedMs: info.elapsedMs,
|
|
859
|
+
requestMessageId: info.requestMessageId,
|
|
860
|
+
action: actions,
|
|
861
|
+
returnValue: info,
|
|
862
|
+
},
|
|
863
|
+
});
|
|
864
|
+
try {
|
|
865
|
+
const sendResult: any = pi.sendMessage(
|
|
866
|
+
{
|
|
867
|
+
customType: 'shepherd.stale.wait',
|
|
868
|
+
content,
|
|
869
|
+
display: true,
|
|
870
|
+
details: info,
|
|
871
|
+
},
|
|
872
|
+
{ deliverAs: 'followUp', triggerTurn: false }
|
|
873
|
+
);
|
|
874
|
+
if (sendResult && typeof sendResult.catch === 'function') {
|
|
875
|
+
sendResult.catch(() => undefined);
|
|
876
|
+
}
|
|
877
|
+
} catch {
|
|
878
|
+
// Delivery is best effort; the reply deadline is the authoritative outcome.
|
|
879
|
+
}
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** Narrow extension-owned bridge from core watcher completions to pi.
|
|
884
|
+
* Also wires child-originated messages (Phase 6) into the parent session.
|
|
885
|
+
*/
|
|
886
|
+
export function parentMessageDeliveryOptions(message: { kind: string; expectsReply?: boolean }): {
|
|
887
|
+
deliverAs: 'followUp' | 'steer';
|
|
888
|
+
triggerTurn: boolean;
|
|
889
|
+
} {
|
|
890
|
+
// Ordinary child notifications remain passive, but a request or reply is a
|
|
891
|
+
// decision point: the parent must get a turn to answer or resume waiting
|
|
892
|
+
// work. Wake-ups use `steer` so pi surfaces them between tool rounds while
|
|
893
|
+
// the Shepherd is mid-turn (followUp would queue until the whole run ends,
|
|
894
|
+
// after cleanup calls such as shepherd_close); when the parent is idle,
|
|
895
|
+
// `triggerTurn` still starts a turn immediately.
|
|
896
|
+
const wake = message.kind === 'reply' || message.expectsReply === true;
|
|
897
|
+
return {
|
|
898
|
+
deliverAs: wake ? 'steer' : 'followUp',
|
|
899
|
+
triggerTurn: wake,
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
function configurePromptWatcherBridge(pi: ExtensionAPI): void {
|
|
904
|
+
registerPromptCompletionRenderer(pi);
|
|
905
|
+
registerShepherdMessageRenderer(pi);
|
|
906
|
+
configurePromptWatcherNotifications(notification => {
|
|
907
|
+
if (!watcherParentSessionActive) return;
|
|
908
|
+
const summary = notification.completions
|
|
909
|
+
.map(completion => {
|
|
910
|
+
const identity = completion.label
|
|
911
|
+
? `${completion.agent ?? completion.agentId}: ${completion.label}`
|
|
912
|
+
: (completion.agent ?? completion.agentId);
|
|
913
|
+
return `${identity} ${completion.status}`;
|
|
914
|
+
})
|
|
915
|
+
.join(', ');
|
|
916
|
+
const returnCode =
|
|
917
|
+
notification.completions.find(completion => completion.returnCode !== 0)?.returnCode ?? 0;
|
|
918
|
+
// Keep the model-visible notification compact. The structured payload is
|
|
919
|
+
// retained in `details` for the expanded custom renderer and consumers.
|
|
920
|
+
const content = `shepherd_watcher completion${notification.completions.length === 1 ? '' : 's'}: ${summary}`;
|
|
921
|
+
try {
|
|
922
|
+
const sendResult: any = pi.sendMessage(
|
|
923
|
+
{
|
|
924
|
+
customType: 'shepherd.prompt.completion',
|
|
925
|
+
content,
|
|
926
|
+
display: true,
|
|
927
|
+
details: notification,
|
|
928
|
+
},
|
|
929
|
+
{ deliverAs: 'steer', triggerTurn: true }
|
|
930
|
+
);
|
|
931
|
+
if (sendResult && typeof sendResult.catch === 'function') {
|
|
932
|
+
sendResult.catch(() => undefined);
|
|
933
|
+
}
|
|
934
|
+
} catch {
|
|
935
|
+
// Delivery is best effort. The completion remains in the lifecycle
|
|
936
|
+
// prompt registry and can still be retrieved by shepherd_watch.
|
|
937
|
+
}
|
|
938
|
+
});
|
|
939
|
+
configureParentMessageNotifications(notification => {
|
|
940
|
+
if (!messageParentSessionActive) return;
|
|
941
|
+
const { envelope, reason } = notification;
|
|
942
|
+
if (envelope.kind === 'runtime') return; // task-state mirror only; never a user-facing message
|
|
943
|
+
const sender = displayAgentName(envelope.senderId);
|
|
944
|
+
if (notification.kind === 'task_done_dropped') {
|
|
945
|
+
// A child completion the registry could not apply: surface it so a lost
|
|
946
|
+
// completion is visible to the parent instead of resurfacing later as a
|
|
947
|
+
// misleading deadline timeout.
|
|
948
|
+
const content =
|
|
949
|
+
`Shepherd warning from ${sender}\n` +
|
|
950
|
+
`Task completion was not applied: ${reason ?? 'the reported task id matched no active task.'}` +
|
|
951
|
+
(envelope.summary ? `\nCompletion: ${envelope.summary}` : '');
|
|
952
|
+
try {
|
|
953
|
+
const sendResult: any = pi.sendMessage(
|
|
954
|
+
{
|
|
955
|
+
customType: 'shepherd.message.warning',
|
|
956
|
+
content,
|
|
957
|
+
display: true,
|
|
958
|
+
details: { ...envelope, reason: reason ?? undefined },
|
|
959
|
+
},
|
|
960
|
+
{ deliverAs: 'steer', triggerTurn: true }
|
|
961
|
+
);
|
|
962
|
+
if (sendResult && typeof sendResult.catch === 'function') {
|
|
963
|
+
sendResult.catch(() => undefined);
|
|
964
|
+
}
|
|
965
|
+
} catch {
|
|
966
|
+
// Delivery is best effort; the diagnostic file remains in the
|
|
967
|
+
// broker's rejected store.
|
|
968
|
+
}
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
const title = envelope.kind === 'reply' ? 'Shepherd reply' : 'Shepherd message';
|
|
972
|
+
// Keep the notification fallback readable too: the custom renderer uses
|
|
973
|
+
// `details` for collapsed/expanded views, while the message content keeps
|
|
974
|
+
// the sender heading and full message on separate lines for other clients.
|
|
975
|
+
const content = `${title} from ${sender}\n${String(envelope.content ?? '')}`;
|
|
976
|
+
try {
|
|
977
|
+
const sendResult: any = pi.sendMessage(
|
|
978
|
+
{
|
|
979
|
+
customType:
|
|
980
|
+
envelope.kind === 'reply' ? 'shepherd.message.reply' : 'shepherd.message.incoming',
|
|
981
|
+
content,
|
|
982
|
+
display: true,
|
|
983
|
+
details: envelope,
|
|
984
|
+
},
|
|
985
|
+
parentMessageDeliveryOptions(envelope)
|
|
986
|
+
);
|
|
987
|
+
if (sendResult && typeof sendResult.catch === 'function') {
|
|
988
|
+
sendResult.catch(() => undefined);
|
|
989
|
+
}
|
|
990
|
+
} catch {
|
|
991
|
+
// Delivery is best effort; the envelope remains in the parent's
|
|
992
|
+
// processed storage and the task state is already reconciled.
|
|
993
|
+
}
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
function registerShepherdMessageRenderer(pi: ExtensionAPI): void {
|
|
998
|
+
const render = (message: any, options: any, theme: any) =>
|
|
999
|
+
renderShepherdNotification(
|
|
1000
|
+
message,
|
|
1001
|
+
options,
|
|
1002
|
+
theme,
|
|
1003
|
+
formatParentMessageNotification(message?.details, message?.customType)
|
|
1004
|
+
);
|
|
1005
|
+
pi.registerMessageRenderer('shepherd.message.incoming', render);
|
|
1006
|
+
pi.registerMessageRenderer('shepherd.message.reply', render);
|
|
1007
|
+
pi.registerMessageRenderer('shepherd.message.warning', render);
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
type ShepherdContext = {
|
|
1011
|
+
cwd: string;
|
|
1012
|
+
model?: DelegatorModel;
|
|
1013
|
+
thinkingLevel?: AgentThinkingLevel;
|
|
1014
|
+
hasUI?: boolean;
|
|
1015
|
+
ui?: any;
|
|
1016
|
+
sessionManager?: { getSessionId(): string; getSessionFile?(): string | undefined };
|
|
1017
|
+
};
|
|
1018
|
+
|
|
1019
|
+
function parentArtifactSession(ctx: ShepherdContext): ShepherdSession | undefined {
|
|
1020
|
+
// The setting is snapshotted when the parent pi session starts. This means
|
|
1021
|
+
// disabling fieldnotes does not change the contract of agents already
|
|
1022
|
+
// running in this session; start a new pi session to stop using them.
|
|
1023
|
+
if (!fieldnotesEnabled()) return undefined;
|
|
1024
|
+
const parentPiSessionId = ctx.sessionManager?.getSessionId();
|
|
1025
|
+
if (!parentPiSessionId) throw new Error('Unable to resolve the parent pi session identity.');
|
|
1026
|
+
return resolveOrCreateParentArtifactSession({
|
|
1027
|
+
parentPiSessionId,
|
|
1028
|
+
parentSessionFile: ctx.sessionManager?.getSessionFile?.(),
|
|
1029
|
+
projectRoot: ctx.cwd,
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
export async function doAction(
|
|
1034
|
+
args: ShepherdArgs,
|
|
1035
|
+
ctx: ShepherdContext,
|
|
1036
|
+
signal?: AbortSignal,
|
|
1037
|
+
onUpdate?: (partial: AgentToolResult<Record<string, unknown>>) => void
|
|
1038
|
+
): Promise<AgentToolResult<Record<string, unknown>>> {
|
|
1039
|
+
// Phase 2 (spec 009): all lifecycle calls go through the resolved
|
|
1040
|
+
// runtime. `delegate`/`close` were routed first (Phase 1.2); `spawn`,
|
|
1041
|
+
// `message`, `status`, `read`, and `watch` join them now that parity is
|
|
1042
|
+
// proven (expectsReply/stale/blocked/read-tail/done-nudge, fieldnotes
|
|
1043
|
+
// bridge). Per-command resolve: the explicit `backend` pin wins, otherwise
|
|
1044
|
+
// run where called from. Native ids never cross backends: each runtime
|
|
1045
|
+
// only honors ids from its own registry, so a pane id is junk to hc and
|
|
1046
|
+
// a terminal address is junk to panes. Adapters are stateless, so one per
|
|
1047
|
+
// action is enough.
|
|
1048
|
+
const runtime = createHerdrRuntime({
|
|
1049
|
+
cwd: ctx.cwd,
|
|
1050
|
+
model: ctx.model,
|
|
1051
|
+
thinkingLevel: ctx.thinkingLevel,
|
|
1052
|
+
hasUI: ctx.hasUI,
|
|
1053
|
+
ui: ctx.ui,
|
|
1054
|
+
sessionId: ctx.sessionManager?.getSessionId(),
|
|
1055
|
+
});
|
|
1056
|
+
const backend = commandBackend(ctx);
|
|
1057
|
+
const resolvedRuntime =
|
|
1058
|
+
backend === 'hc'
|
|
1059
|
+
? createHcRuntime({
|
|
1060
|
+
cwd: ctx.cwd,
|
|
1061
|
+
model: ctx.model,
|
|
1062
|
+
thinkingLevel: ctx.thinkingLevel,
|
|
1063
|
+
hasUI: ctx.hasUI,
|
|
1064
|
+
ui: ctx.ui,
|
|
1065
|
+
sessionId: ctx.sessionManager?.getSessionId(),
|
|
1066
|
+
})
|
|
1067
|
+
: runtime;
|
|
1068
|
+
switch (args.action) {
|
|
1069
|
+
case 'spawn': {
|
|
1070
|
+
const a: any = args;
|
|
1071
|
+
// Explicit artifactSession wins (the command adapter pre-resolves it
|
|
1072
|
+
// tolerantly); otherwise resolve/require the parent artifact session.
|
|
1073
|
+
const artifactSession =
|
|
1074
|
+
'artifactSession' in a ? a.artifactSession : parentArtifactSession(ctx);
|
|
1075
|
+
// Startup readiness has its own fixed internal grace periods; timeout
|
|
1076
|
+
// settings apply only to submitted prompts and their waits. Emit a
|
|
1077
|
+
// partial result so the TUI can show progress while Herdr starts the
|
|
1078
|
+
// child pane.
|
|
1079
|
+
onUpdate?.({
|
|
1080
|
+
content: [{ type: 'text', text: `Spawning ${a.agent}…` }],
|
|
1081
|
+
details: {
|
|
1082
|
+
agent: a.agent,
|
|
1083
|
+
label: a.label,
|
|
1084
|
+
placement: a.placement,
|
|
1085
|
+
},
|
|
1086
|
+
});
|
|
1087
|
+
if (backend === 'hc') {
|
|
1088
|
+
const hcRuntime = createHcRuntime({
|
|
1089
|
+
cwd: ctx.cwd,
|
|
1090
|
+
model: ctx.model,
|
|
1091
|
+
thinkingLevel: ctx.thinkingLevel,
|
|
1092
|
+
hasUI: ctx.hasUI,
|
|
1093
|
+
ui: ctx.ui,
|
|
1094
|
+
sessionId: ctx.sessionManager?.getSessionId(),
|
|
1095
|
+
artifactSession,
|
|
1096
|
+
});
|
|
1097
|
+
const id = await hcRuntime.spawn(
|
|
1098
|
+
{ name: a.agent } as any,
|
|
1099
|
+
{ cwd: a.cwd, label: a.label, placement: a.placement }
|
|
1100
|
+
);
|
|
1101
|
+
const hcHandle = hcAgentIdentity(id);
|
|
1102
|
+
return textResult(
|
|
1103
|
+
`shepherd_spawn spawned ${hcHandle.label ? `${hcHandle.agent}: ${hcHandle.label}` : hcHandle.agent}`,
|
|
1104
|
+
{
|
|
1105
|
+
id,
|
|
1106
|
+
agent: hcHandle.agent,
|
|
1107
|
+
label: hcHandle.label,
|
|
1108
|
+
model: hcHandle.model ?? null,
|
|
1109
|
+
returnValue: {
|
|
1110
|
+
id,
|
|
1111
|
+
agent: hcHandle.agent,
|
|
1112
|
+
label: hcHandle.label,
|
|
1113
|
+
model: hcHandle.model ?? null,
|
|
1114
|
+
},
|
|
1115
|
+
fieldnote: artifactSession?.sessionRelativePath ?? null,
|
|
1116
|
+
...(artifactSession ? { artifactSession } : {}),
|
|
1117
|
+
}
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
const handle = await startAgent(
|
|
1121
|
+
a.agent,
|
|
1122
|
+
{
|
|
1123
|
+
label: a.label,
|
|
1124
|
+
placement: a.placement,
|
|
1125
|
+
cwd: a.cwd,
|
|
1126
|
+
artifactSession,
|
|
1127
|
+
},
|
|
1128
|
+
{ ...ctx, sessionId: ctx.sessionManager?.getSessionId() }
|
|
1129
|
+
);
|
|
1130
|
+
return textResult(
|
|
1131
|
+
`shepherd_spawn spawned ${handle.label ? `${handle.agent}: ${handle.label}` : handle.agent}`,
|
|
1132
|
+
{
|
|
1133
|
+
id: handle.id,
|
|
1134
|
+
agent: handle.agent,
|
|
1135
|
+
label: handle.label,
|
|
1136
|
+
model: handle.model ?? null,
|
|
1137
|
+
returnValue: {
|
|
1138
|
+
id: handle.id,
|
|
1139
|
+
agent: handle.agent,
|
|
1140
|
+
label: handle.label,
|
|
1141
|
+
model: handle.model ?? null,
|
|
1142
|
+
},
|
|
1143
|
+
fieldnote: artifactSession?.sessionRelativePath ?? null,
|
|
1144
|
+
...(artifactSession ? { artifactSession } : {}),
|
|
1145
|
+
}
|
|
1146
|
+
);
|
|
1147
|
+
}
|
|
1148
|
+
case 'delegate': {
|
|
1149
|
+
const a: any = args;
|
|
1150
|
+
const timeoutMinutes = a.timeout ?? loadSettings(ctx.cwd).timeout;
|
|
1151
|
+
if (!Number.isFinite(timeoutMinutes) || timeoutMinutes <= 0) {
|
|
1152
|
+
throw new Error('Delegated task timeout must be a positive number of minutes.');
|
|
1153
|
+
}
|
|
1154
|
+
const taskId = await resolvedRuntime.delegate(a.target, a.task, {
|
|
1155
|
+
timeoutMin: timeoutMinutes,
|
|
1156
|
+
});
|
|
1157
|
+
const agent =
|
|
1158
|
+
backend === 'hc' ? hcAgentIdentity(a.target) : lifecycleRegistry.getAgent(a.target).handle;
|
|
1159
|
+
return textResult(
|
|
1160
|
+
`Delegated task to ${agent.agent}${agent.label ? `: ${agent.label}` : ''}`,
|
|
1161
|
+
{
|
|
1162
|
+
id: taskId,
|
|
1163
|
+
taskId,
|
|
1164
|
+
agentId: agent.id,
|
|
1165
|
+
state: 'running',
|
|
1166
|
+
returnValue: {
|
|
1167
|
+
taskId,
|
|
1168
|
+
agentId: agent.id,
|
|
1169
|
+
state: 'running',
|
|
1170
|
+
},
|
|
1171
|
+
}
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
case 'message': {
|
|
1175
|
+
const a: any = args;
|
|
1176
|
+
if (backend === 'hc') {
|
|
1177
|
+
const messageId = await resolvedRuntime.message(a.target, a.message, {
|
|
1178
|
+
taskId: a.taskId ?? a.id,
|
|
1179
|
+
threadId: a.threadId,
|
|
1180
|
+
replyTo: a.replyTo,
|
|
1181
|
+
expectsReply: a.expectsReply,
|
|
1182
|
+
delivery: a.delivery,
|
|
1183
|
+
});
|
|
1184
|
+
const hcHandle = hcAgentIdentity(a.target);
|
|
1185
|
+
const display = hcHandle.label ? `${hcHandle.agent}: ${hcHandle.label}` : hcHandle.agent;
|
|
1186
|
+
// Task correlation mirrors the pane path: an expectsReply request
|
|
1187
|
+
// parks the task in `waiting`; a plain correlated message reports
|
|
1188
|
+
// the task's current state.
|
|
1189
|
+
let targetTaskState: string | undefined;
|
|
1190
|
+
const correlatedId = a.taskId ?? a.id;
|
|
1191
|
+
if (correlatedId) {
|
|
1192
|
+
try {
|
|
1193
|
+
const view = describeHcStatusView(a.target);
|
|
1194
|
+
if (view.task && view.task.id === correlatedId) targetTaskState = view.task.state;
|
|
1195
|
+
} catch {
|
|
1196
|
+
/* display hint is best effort */
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
if (!targetTaskState && a.expectsReply && correlatedId) targetTaskState = 'waiting';
|
|
1200
|
+
return textResult(
|
|
1201
|
+
`Message queued to ${display}` +
|
|
1202
|
+
(targetTaskState ? ` (task ${targetTaskState})` : ''),
|
|
1203
|
+
{
|
|
1204
|
+
id: messageId,
|
|
1205
|
+
messageId,
|
|
1206
|
+
returnValue: {
|
|
1207
|
+
messageId,
|
|
1208
|
+
accepted: true,
|
|
1209
|
+
delivery: a.delivery ?? 'steer',
|
|
1210
|
+
...(a.expectsReply && correlatedId ? { requestId: messageId } : {}),
|
|
1211
|
+
targetId: hcHandle.id,
|
|
1212
|
+
},
|
|
1213
|
+
...(a.expectsReply && correlatedId ? { requestId: messageId } : {}),
|
|
1214
|
+
...(targetTaskState ? { targetTaskState } : {}),
|
|
1215
|
+
}
|
|
1216
|
+
);
|
|
1217
|
+
}
|
|
1218
|
+
const result = sendParentMessage({
|
|
1219
|
+
target: a.target,
|
|
1220
|
+
message: a.message,
|
|
1221
|
+
taskId: a.taskId ?? a.id,
|
|
1222
|
+
threadId: a.threadId,
|
|
1223
|
+
replyTo: a.replyTo,
|
|
1224
|
+
expectsReply: a.expectsReply,
|
|
1225
|
+
delivery: a.delivery,
|
|
1226
|
+
});
|
|
1227
|
+
return textResult(
|
|
1228
|
+
`Message queued to ${displayAgentName(result.targetId)}` +
|
|
1229
|
+
(result.targetTaskState ? ` (task ${result.targetTaskState})` : ''),
|
|
1230
|
+
{
|
|
1231
|
+
id: result.messageId,
|
|
1232
|
+
messageId: result.messageId,
|
|
1233
|
+
returnValue: {
|
|
1234
|
+
messageId: result.messageId,
|
|
1235
|
+
accepted: result.accepted,
|
|
1236
|
+
delivery: result.delivery,
|
|
1237
|
+
...(result.requestId ? { requestId: result.requestId } : {}),
|
|
1238
|
+
targetId: result.targetId,
|
|
1239
|
+
},
|
|
1240
|
+
...(result.requestId ? { requestId: result.requestId } : {}),
|
|
1241
|
+
...(result.targetTaskState ? { targetTaskState: result.targetTaskState } : {}),
|
|
1242
|
+
}
|
|
1243
|
+
);
|
|
1244
|
+
}
|
|
1245
|
+
case 'prompt': {
|
|
1246
|
+
const a: any = args;
|
|
1247
|
+
// Convert timeout from minutes to milliseconds for internal use.
|
|
1248
|
+
// Default: the settings timeout.
|
|
1249
|
+
const defaultTimeout = loadSettings(ctx.cwd).timeout;
|
|
1250
|
+
const timeoutMinutes = a.timeout ?? defaultTimeout;
|
|
1251
|
+
const timeoutMs = timeoutMinutes * 60_000;
|
|
1252
|
+
const handle = await promptAgent(a.id ?? a.handle, a.message, { timeout: timeoutMs });
|
|
1253
|
+
const agent = lifecycleRegistry.getAgent(handle.agentId).handle;
|
|
1254
|
+
const artifact = lifecycleRegistry.promptArtifact(handle);
|
|
1255
|
+
return textResult(`Prompted ${agent.agent}${agent.label ? `: ${agent.label}` : ''}`, {
|
|
1256
|
+
id: handle.id,
|
|
1257
|
+
returnValue: {
|
|
1258
|
+
id: handle.id,
|
|
1259
|
+
...(artifact.artifact ? { artifact: artifact.artifact } : {}),
|
|
1260
|
+
},
|
|
1261
|
+
...(artifact.artifact ? { artifact: artifact.artifact } : {}),
|
|
1262
|
+
...(artifact.session ? { artifactSession: artifact.session } : {}),
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
case 'watch': {
|
|
1266
|
+
const a: any = args;
|
|
1267
|
+
const ids: string[] = Array.isArray(a.id) ? a.id : [a.id];
|
|
1268
|
+
if (ids.length === 0) {
|
|
1269
|
+
throw new LifecycleError(
|
|
1270
|
+
'invalid_handle',
|
|
1271
|
+
'Expected one or more task (or legacy prompt) ids to watch.'
|
|
1272
|
+
);
|
|
1273
|
+
}
|
|
1274
|
+
if (backend === 'hc') {
|
|
1275
|
+
// Hc tasks never mix with legacy prompt ids; every id must name a
|
|
1276
|
+
// known hc task (opaque ids never cross backends).
|
|
1277
|
+
for (const id of ids) {
|
|
1278
|
+
if (!isHcTaskId(id)) {
|
|
1279
|
+
throw new LifecycleError(
|
|
1280
|
+
'invalid_handle',
|
|
1281
|
+
`Unknown watcher target "${id}". Pass a task id from shepherd_delegate; agent ids and terminal addresses are not valid watcher targets.`
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
if (new Set(ids).size !== ids.length) {
|
|
1286
|
+
throw new LifecycleError(
|
|
1287
|
+
'invalid_handle',
|
|
1288
|
+
'A watcher cannot contain duplicate task ids.'
|
|
1289
|
+
);
|
|
1290
|
+
}
|
|
1291
|
+
// 011 drain-first: settle anything already queued so an
|
|
1292
|
+
// already-settled task reports `completed`, never stale `pending`.
|
|
1293
|
+
// Never throws, never mints a broker: unresolvable sessions skip.
|
|
1294
|
+
try {
|
|
1295
|
+
drainHcInboxForSession(ctx.sessionManager?.getSessionId());
|
|
1296
|
+
} catch {
|
|
1297
|
+
/* reads stay best-effort */
|
|
1298
|
+
}
|
|
1299
|
+
const registration = hcTaskWatcherService.watch(ids);
|
|
1300
|
+
unseenCompletionLedger.clear(registration.taskIds);
|
|
1301
|
+
const summary =
|
|
1302
|
+
registration.pending.length > 0
|
|
1303
|
+
? `watching ${registration.pending.length} task${registration.pending.length === 1 ? '' : 's'} asynchronously`
|
|
1304
|
+
: 'watch registered; all tasks were already settled';
|
|
1305
|
+
return textResult(summary, {
|
|
1306
|
+
watcherId: registration.watcherId,
|
|
1307
|
+
taskIds: registration.taskIds,
|
|
1308
|
+
pending: registration.pending,
|
|
1309
|
+
completed: registration.completed,
|
|
1310
|
+
returnValue: registration,
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
// A tracker id is a task first; anything else must be a known prompt id.
|
|
1314
|
+
// Agent ids and Herdr pane ids are rejected with a clear error here so
|
|
1315
|
+
// the model is never silently pointing a watcher at the wrong scope.
|
|
1316
|
+
const taskIds = ids.filter(id => lifecycleRegistry.isTaskId(id));
|
|
1317
|
+
const promptIds: string[] = [];
|
|
1318
|
+
for (const id of ids) {
|
|
1319
|
+
if (taskIds.includes(id)) continue;
|
|
1320
|
+
try {
|
|
1321
|
+
lifecycleRegistry.getPrompt(id);
|
|
1322
|
+
} catch {
|
|
1323
|
+
throw new LifecycleError(
|
|
1324
|
+
'invalid_handle',
|
|
1325
|
+
`Unknown watcher target "${id}". Pass a task id from shepherd_delegate or a legacy prompt id from shepherd_prompt; agent ids and Herdr pane ids are not valid watcher targets.`
|
|
1326
|
+
);
|
|
1327
|
+
}
|
|
1328
|
+
promptIds.push(id);
|
|
1329
|
+
}
|
|
1330
|
+
if (taskIds.length > 0 && promptIds.length > 0) {
|
|
1331
|
+
throw new LifecycleError(
|
|
1332
|
+
'invalid_handle',
|
|
1333
|
+
'A single shepherd_watch call cannot mix task ids and legacy prompt ids; watch tasks in one call and prompts in another.'
|
|
1334
|
+
);
|
|
1335
|
+
}
|
|
1336
|
+
if (taskIds.length > 0) {
|
|
1337
|
+
const registration = taskWatcherService.watch(taskIds);
|
|
1338
|
+
// Retrieval clear: an explicit watch is the authoritative way to pull
|
|
1339
|
+
// already-settled task results, so their pending unseen notices must
|
|
1340
|
+
// not fire later (the late delivery never reaches the watcher
|
|
1341
|
+
// notifier; see spec 007 section 5).
|
|
1342
|
+
unseenCompletionLedger.clear(registration.taskIds);
|
|
1343
|
+
const summary =
|
|
1344
|
+
registration.pending.length > 0
|
|
1345
|
+
? `watching ${registration.pending.length} task${registration.pending.length === 1 ? '' : 's'} asynchronously`
|
|
1346
|
+
: 'watch registered; all tasks were already settled';
|
|
1347
|
+
return textResult(summary, {
|
|
1348
|
+
watcherId: registration.watcherId,
|
|
1349
|
+
taskIds: registration.taskIds,
|
|
1350
|
+
pending: registration.pending,
|
|
1351
|
+
completed: registration.completed,
|
|
1352
|
+
returnValue: registration,
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
const registration = promptWatcherService.watch(promptIds);
|
|
1356
|
+
const summary =
|
|
1357
|
+
registration.pending.length > 0
|
|
1358
|
+
? `watching ${registration.pending.length} prompt${registration.pending.length === 1 ? '' : 's'} asynchronously`
|
|
1359
|
+
: 'watch registered; all prompts were already settled';
|
|
1360
|
+
return textResult(summary, {
|
|
1361
|
+
watcherId: registration.watcherId,
|
|
1362
|
+
promptIds: registration.promptIds,
|
|
1363
|
+
pending: registration.pending,
|
|
1364
|
+
completed: registration.completed,
|
|
1365
|
+
returnValue: registration,
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
case 'status': {
|
|
1369
|
+
const a: any = args;
|
|
1370
|
+
if (backend === 'hc') {
|
|
1371
|
+
// 011 drain-first: same freshness guarantee as `watch` above.
|
|
1372
|
+
try {
|
|
1373
|
+
drainHcInboxForSession(ctx.sessionManager?.getSessionId());
|
|
1374
|
+
} catch {
|
|
1375
|
+
/* reads stay best-effort */
|
|
1376
|
+
}
|
|
1377
|
+
const view = describeHcStatusView(a.id ?? a.handle);
|
|
1378
|
+
const publicResult = {
|
|
1379
|
+
id: view.handle.id,
|
|
1380
|
+
state: view.state,
|
|
1381
|
+
...(view.task
|
|
1382
|
+
? {
|
|
1383
|
+
task: {
|
|
1384
|
+
id: view.task.id,
|
|
1385
|
+
state: view.task.state,
|
|
1386
|
+
...(view.task.waitingMs !== undefined
|
|
1387
|
+
? { waitingMs: view.task.waitingMs }
|
|
1388
|
+
: {}),
|
|
1389
|
+
...(view.task.pendingRequestMessageId
|
|
1390
|
+
? { pendingRequest: view.task.pendingRequestMessageId }
|
|
1391
|
+
: {}),
|
|
1392
|
+
...(view.task.waitingRecipient
|
|
1393
|
+
? { waitingOn: view.task.waitingRecipient }
|
|
1394
|
+
: {}),
|
|
1395
|
+
...(view.task.stale ? { stale: true } : {}),
|
|
1396
|
+
},
|
|
1397
|
+
}
|
|
1398
|
+
: {}),
|
|
1399
|
+
};
|
|
1400
|
+
const taskNote = view.task ? `; task ${view.task.id} ${view.task.state}` : '';
|
|
1401
|
+
return textResult(`agent ${view.state}${taskNote}.`, {
|
|
1402
|
+
status: publicResult,
|
|
1403
|
+
returnValue: publicResult,
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
const result = statusAgent(a.id ?? a.handle);
|
|
1407
|
+
const publicResult = {
|
|
1408
|
+
id: result.handle.id,
|
|
1409
|
+
state: result.state,
|
|
1410
|
+
...(result.task
|
|
1411
|
+
? {
|
|
1412
|
+
task: {
|
|
1413
|
+
id: result.task.id,
|
|
1414
|
+
state: result.task.state,
|
|
1415
|
+
...(result.task.waitingMs !== undefined
|
|
1416
|
+
? { waitingMs: result.task.waitingMs }
|
|
1417
|
+
: {}),
|
|
1418
|
+
...(result.task.pendingRequestMessageId
|
|
1419
|
+
? { pendingRequest: result.task.pendingRequestMessageId }
|
|
1420
|
+
: {}),
|
|
1421
|
+
...(result.task.waitingRecipient
|
|
1422
|
+
? { waitingOn: result.task.waitingRecipient }
|
|
1423
|
+
: {}),
|
|
1424
|
+
...(result.task.stale ? { stale: true } : {}),
|
|
1425
|
+
},
|
|
1426
|
+
}
|
|
1427
|
+
: {}),
|
|
1428
|
+
...(result.error ? { error: result.error } : {}),
|
|
1429
|
+
};
|
|
1430
|
+
const taskNote = result.task ? `; task ${result.task.id} ${result.task.state}` : '';
|
|
1431
|
+
return textResult(`agent ${result.state}${taskNote}.`, {
|
|
1432
|
+
status: publicResult,
|
|
1433
|
+
returnValue: publicResult,
|
|
1434
|
+
});
|
|
1435
|
+
}
|
|
1436
|
+
case 'close': {
|
|
1437
|
+
const a: any = args;
|
|
1438
|
+
const id = a.id ?? a.handle;
|
|
1439
|
+
await resolvedRuntime.close(id);
|
|
1440
|
+
if (backend === 'hc') {
|
|
1441
|
+
const hcHandle = hcAgentIdentity(id);
|
|
1442
|
+
const cleared = unseenCompletionLedger.clearForAgent(hcHandle.id);
|
|
1443
|
+
const clearedNote =
|
|
1444
|
+
cleared.length > 0
|
|
1445
|
+
? `; cleared ${cleared.length} unseen completion(s): ${cleared.join(', ')}`
|
|
1446
|
+
: '';
|
|
1447
|
+
return textResult(
|
|
1448
|
+
`closed ${hcHandle.label ? `${hcHandle.agent}: ${hcHandle.label}` : hcHandle.agent}${clearedNote}`,
|
|
1449
|
+
{
|
|
1450
|
+
id: hcHandle.id,
|
|
1451
|
+
...(cleared.length > 0 ? { clearedUnseenCompletions: cleared } : {}),
|
|
1452
|
+
returnValue: {
|
|
1453
|
+
id: hcHandle.id,
|
|
1454
|
+
...(cleared.length > 0 ? { clearedUnseenCompletions: cleared } : {}),
|
|
1455
|
+
},
|
|
1456
|
+
}
|
|
1457
|
+
);
|
|
1458
|
+
}
|
|
1459
|
+
const handle = lifecycleRegistry.getAgent(id).handle;
|
|
1460
|
+
const cleared = unseenCompletionLedger.clearForAgent(handle.id);
|
|
1461
|
+
const clearedNote =
|
|
1462
|
+
cleared.length > 0
|
|
1463
|
+
? `; cleared ${cleared.length} unseen completion(s): ${cleared.join(', ')}`
|
|
1464
|
+
: '';
|
|
1465
|
+
return textResult(
|
|
1466
|
+
`closed ${handle.label ? `${handle.agent}: ${handle.label}` : handle.agent}${clearedNote}`,
|
|
1467
|
+
{
|
|
1468
|
+
id: handle.id,
|
|
1469
|
+
...(cleared.length > 0 ? { clearedUnseenCompletions: cleared } : {}),
|
|
1470
|
+
returnValue: {
|
|
1471
|
+
id: handle.id,
|
|
1472
|
+
...(cleared.length > 0 ? { clearedUnseenCompletions: cleared } : {}),
|
|
1473
|
+
},
|
|
1474
|
+
}
|
|
1475
|
+
);
|
|
1476
|
+
}
|
|
1477
|
+
case 'agents': {
|
|
1478
|
+
// List available agent definitions for the shepherd's herd.
|
|
1479
|
+
const scope = args.agentScope ?? loadSettings(ctx.cwd).agentScope;
|
|
1480
|
+
const { agents, projectDirs } = discoverAgents(ctx.cwd, scope, {
|
|
1481
|
+
includeBundled: loadSettings(ctx.cwd).includeBundledAgents,
|
|
1482
|
+
});
|
|
1483
|
+
if (agents.length === 0)
|
|
1484
|
+
return textResult(
|
|
1485
|
+
`No agent definitions found in ${scope} scope. Do not guess an agent name; add a definition or choose another scope.`,
|
|
1486
|
+
{ agents: [], projectDirs, scope }
|
|
1487
|
+
);
|
|
1488
|
+
const lines = agents.map(a => `${a.name} (${a.source}): ${a.description}`);
|
|
1489
|
+
return textResult(
|
|
1490
|
+
`Available agent names (copy the name exactly; names are case-sensitive):\n${lines.join('\n')}`,
|
|
1491
|
+
{ agents, projectDirs, scope }
|
|
1492
|
+
);
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
case 'herd': {
|
|
1496
|
+
// Silently drop registrations for panes that no longer exist so a
|
|
1497
|
+
// long-lived session doesn't accumulate stale entries.
|
|
1498
|
+
pruneStaleCreatedPanes();
|
|
1499
|
+
const out = herdrExecSync(['agent', 'list']);
|
|
1500
|
+
const agents = agentSummaries(out);
|
|
1501
|
+
if (agents.length === 0) return textResult('No agents detected in Herdr.', { agents });
|
|
1502
|
+
return textResult(agents.map(formatSummary).join('\n'), { agents });
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
case 'read': {
|
|
1506
|
+
const target = args.name?.trim();
|
|
1507
|
+
if (!target) return textResult('Provide a name/pane target (action=read).', {});
|
|
1508
|
+
const lines = args.lines ?? 40;
|
|
1509
|
+
if (backend === 'hc') {
|
|
1510
|
+
// Hc terminals have no pane sources; `lines` tails the terminal.
|
|
1511
|
+
// Accept an opaque agent id, a display identity, or an owned
|
|
1512
|
+
// terminal name. Raw terminal addresses never resolve here: they
|
|
1513
|
+
// are not opaque ids (see the resolver seam).
|
|
1514
|
+
const agentId = resolveHcAgentId(target);
|
|
1515
|
+
if (!agentId) {
|
|
1516
|
+
return {
|
|
1517
|
+
content: [
|
|
1518
|
+
{
|
|
1519
|
+
type: 'text',
|
|
1520
|
+
text: `Could not read "${target}": unknown hc agent, terminal, or name.`,
|
|
1521
|
+
},
|
|
1522
|
+
],
|
|
1523
|
+
details: { target, error: 'unknown hc read target' },
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
try {
|
|
1527
|
+
const tail = await resolvedRuntime.read(agentId, { lines });
|
|
1528
|
+
return textResult((tail as string).trim() || '(no terminal output)', {
|
|
1529
|
+
target,
|
|
1530
|
+
lines,
|
|
1531
|
+
});
|
|
1532
|
+
} catch (error: any) {
|
|
1533
|
+
return {
|
|
1534
|
+
content: [
|
|
1535
|
+
{
|
|
1536
|
+
type: 'text',
|
|
1537
|
+
text: `Could not read "${target}": ${error?.message ?? String(error)}`,
|
|
1538
|
+
},
|
|
1539
|
+
],
|
|
1540
|
+
details: { target, error: String(error?.message ?? error) },
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
const source = args.source ?? 'recent-unwrapped';
|
|
1545
|
+
// Resolve a shepherd pane by its recorded paneId or label (same as
|
|
1546
|
+
// prompt/close) so `read scout` works after a lifecycle start.
|
|
1547
|
+
const created = loadCreatedPanes();
|
|
1548
|
+
const match = created.find(p => p.paneId === target || p.name === target);
|
|
1549
|
+
let resolved = match?.paneId ?? target;
|
|
1550
|
+
// Diagnostics are often invoked from the lifecycle result, where the
|
|
1551
|
+
// caller has the opaque agent id rather than the Herdr pane id.
|
|
1552
|
+
// Resolve that id only through our in-memory registry; never guess a
|
|
1553
|
+
// pane from an arbitrary id.
|
|
1554
|
+
if (!match) {
|
|
1555
|
+
try {
|
|
1556
|
+
resolved = lifecycleRegistry.getAgent({ id: target }).handle.paneId ?? target;
|
|
1557
|
+
} catch {
|
|
1558
|
+
// Keep the original target so Herdr returns the useful not-found
|
|
1559
|
+
// error for unknown names/panes.
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
try {
|
|
1563
|
+
const { stdout } = await execFileAsync(
|
|
1564
|
+
'herdr',
|
|
1565
|
+
[
|
|
1566
|
+
'agent',
|
|
1567
|
+
'read',
|
|
1568
|
+
resolved,
|
|
1569
|
+
'--source',
|
|
1570
|
+
source,
|
|
1571
|
+
'--lines',
|
|
1572
|
+
String(lines),
|
|
1573
|
+
'--format',
|
|
1574
|
+
'text',
|
|
1575
|
+
],
|
|
1576
|
+
{ encoding: 'utf8' }
|
|
1577
|
+
);
|
|
1578
|
+
return textResult(stdout.trim() || '(no terminal output)', { target, lines, source });
|
|
1579
|
+
} catch {
|
|
1580
|
+
// Agent detection is dropped once the pane's pi exited — fall back
|
|
1581
|
+
// to a plain terminal read so finished runs stay inspectable.
|
|
1582
|
+
try {
|
|
1583
|
+
const { stdout } = await execFileAsync(
|
|
1584
|
+
'herdr',
|
|
1585
|
+
[
|
|
1586
|
+
'pane',
|
|
1587
|
+
'read',
|
|
1588
|
+
resolved,
|
|
1589
|
+
'--source',
|
|
1590
|
+
source,
|
|
1591
|
+
'--lines',
|
|
1592
|
+
String(lines),
|
|
1593
|
+
'--format',
|
|
1594
|
+
'text',
|
|
1595
|
+
],
|
|
1596
|
+
{ encoding: 'utf8' }
|
|
1597
|
+
);
|
|
1598
|
+
return textResult(stdout.trim() || '(no terminal output)', {
|
|
1599
|
+
target,
|
|
1600
|
+
lines,
|
|
1601
|
+
source,
|
|
1602
|
+
fallback: true,
|
|
1603
|
+
});
|
|
1604
|
+
} catch (error: any) {
|
|
1605
|
+
return {
|
|
1606
|
+
content: [
|
|
1607
|
+
{
|
|
1608
|
+
type: 'text',
|
|
1609
|
+
text: `Could not read "${target}": ${error?.message ?? String(error)}`,
|
|
1610
|
+
},
|
|
1611
|
+
],
|
|
1612
|
+
details: { target, error: String(error?.message ?? error) },
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
case 'prune': {
|
|
1619
|
+
const pruned = pruneStaleCreatedPanes();
|
|
1620
|
+
const remaining = loadCreatedPanes().length;
|
|
1621
|
+
return textResult(
|
|
1622
|
+
pruned === 0
|
|
1623
|
+
? `No stale pi-shepherd panes found (${remaining} registered).`
|
|
1624
|
+
: `Removed ${pruned} stale pane registration(s); ${remaining} remain.`,
|
|
1625
|
+
{ pruned, remaining }
|
|
1626
|
+
);
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
default:
|
|
1630
|
+
return textResult(`Unknown shepherd action: ${String((args as any).action)}`, {});
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
/**
|
|
1635
|
+
* Shared execution path for every registered shepherd tool: gate on a running
|
|
1636
|
+
* Herdr, delegate to doAction() (the single source of truth), and map thrown
|
|
1637
|
+
* errors to a friendly text result. `label` is the action verb used in errors.
|
|
1638
|
+
*/
|
|
1639
|
+
async function executeShepherd(
|
|
1640
|
+
label: string,
|
|
1641
|
+
args: ShepherdArgs,
|
|
1642
|
+
ctx: any,
|
|
1643
|
+
signal?: AbortSignal,
|
|
1644
|
+
onUpdate?: (partial: AgentToolResult<Record<string, unknown>>) => void
|
|
1645
|
+
): Promise<AgentToolResult<Record<string, unknown>>> {
|
|
1646
|
+
// Watch registration/unregistration operate on the parent lifecycle
|
|
1647
|
+
// registry and remain useful even if the backend briefly disappears. The
|
|
1648
|
+
// watcher will resume polling when the runtime is reachable again.
|
|
1649
|
+
// Phase 2: gate on the resolved backend, not always Herdr. An hc caller
|
|
1650
|
+
// with a pinned-but-unreachable backend gets the resolver's clean refusal
|
|
1651
|
+
// (with setup hint, no fallback) instead of a stale Herdr gate.
|
|
1652
|
+
if (label !== 'watch') {
|
|
1653
|
+
let backend: ResolvedBackend;
|
|
1654
|
+
try {
|
|
1655
|
+
backend = commandBackend({ cwd: ctx?.cwd ?? process.cwd() } as any);
|
|
1656
|
+
} catch (error: any) {
|
|
1657
|
+
const failure = unavailableResult(label, args);
|
|
1658
|
+
const hint = String(error?.message ?? error);
|
|
1659
|
+
throw new Error(
|
|
1660
|
+
(formatToolResultText({ ...failure, details: { ...(failure.details as any), error: hint } }) ?? hint)
|
|
1661
|
+
);
|
|
1662
|
+
}
|
|
1663
|
+
if (backend === 'hc') {
|
|
1664
|
+
if (!isHcAvailable()) {
|
|
1665
|
+
throw new Error(
|
|
1666
|
+
`Herd ${label} failed (return code 1): backend "hc" is unreachable. ${HC_SETUP_HINT}`
|
|
1667
|
+
);
|
|
1668
|
+
}
|
|
1669
|
+
} else if (!isHerdrAvailable()) {
|
|
1670
|
+
const failure = unavailableResult(label, args);
|
|
1671
|
+
throw new Error(formatToolResultText(failure) ?? HERDR_SETUP_HINT);
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
try {
|
|
1675
|
+
const result = await doAction(args, ctx, signal, onUpdate);
|
|
1676
|
+
const details = result.details && typeof result.details === 'object' ? result.details : {};
|
|
1677
|
+
return withToolResultText({
|
|
1678
|
+
...result,
|
|
1679
|
+
details: {
|
|
1680
|
+
call: publicToolCall(label, args, ctx.cwd),
|
|
1681
|
+
...(details as Record<string, unknown>),
|
|
1682
|
+
},
|
|
1683
|
+
});
|
|
1684
|
+
} catch (error: any) {
|
|
1685
|
+
const message = String(error?.message ?? error);
|
|
1686
|
+
const returnCode = typeof error?.returnCode === 'number' ? error.returnCode : 1;
|
|
1687
|
+
const code = typeof error?.code === 'string' ? error.code : 'shepherd_error';
|
|
1688
|
+
const failure = withToolResultText({
|
|
1689
|
+
content: [
|
|
1690
|
+
{ type: 'text', text: `Herd ${label} failed (return code ${returnCode}): ${message}` },
|
|
1691
|
+
],
|
|
1692
|
+
details: {
|
|
1693
|
+
call: publicToolCall(label, args, ctx.cwd),
|
|
1694
|
+
action: label,
|
|
1695
|
+
code,
|
|
1696
|
+
returnCode,
|
|
1697
|
+
returnValue: { code, error: message, returnCode },
|
|
1698
|
+
error: message,
|
|
1699
|
+
},
|
|
1700
|
+
});
|
|
1701
|
+
// Pi colors the complete tool shell using its native error state only
|
|
1702
|
+
// when execute() throws. Preserve our structured protocol text in the
|
|
1703
|
+
// thrown message while allowing Pi to set isError=true for the TUI.
|
|
1704
|
+
throw new Error(failure.content[0]?.type === 'text' ? failure.content[0].text : message);
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
export function registerShepherdTools(pi: ExtensionAPI) {
|
|
1709
|
+
configurePromptWatcherBridge(pi);
|
|
1710
|
+
configureTaskWatcherBridge(pi);
|
|
1711
|
+
configureStaleWaitBridge(pi);
|
|
1712
|
+
configureHcTaskWatcherBridge(pi);
|
|
1713
|
+
configureHcStaleWaitBridge(pi);
|
|
1714
|
+
pi.registerTool({
|
|
1715
|
+
name: 'shepherd',
|
|
1716
|
+
label: 'Shepherd (manage Herdr agents)',
|
|
1717
|
+
description: [
|
|
1718
|
+
'Shepherd control plane: subagent framework for native Herdr agent orchestration inside Herdr panes.',
|
|
1719
|
+
'Terminology: the Shepherd is this parent pi session and acts as the orchestrator; the herd is the collection of agents; agents or subagents or sheep are the created workers.',
|
|
1720
|
+
'When enabled, fieldnotes are the durable session notes commonly called artifacts: one shared fieldnotes collection (the shepherd.md index) links the individual note assigned to each agent invocation.',
|
|
1721
|
+
'This tool only lists: herd (live agents in Herdr), agents (discoverable definitions), prune (drop stale registrations). All lifecycle operations are separate tools: shepherd_spawn, shepherd_delegate, shepherd_message, shepherd_prompt, shepherd_watch, shepherd_status, shepherd_close, shepherd_read.',
|
|
1722
|
+
'Lifecycle references are opaque session-scoped ids. Tool results print the id in their text and expose it as details.id; pass it as the top-level id argument, never as a Herdr pane id.',
|
|
1723
|
+
'Requires a running Herdr session (HERDR_ENV=1 or headless server).',
|
|
1724
|
+
].join(' '),
|
|
1725
|
+
promptSnippet: 'Subagent orchestration tool for herdr.',
|
|
1726
|
+
promptGuidelines: [
|
|
1727
|
+
'Use the Shepherd tool family as one lifecycle: discover an agent definition with shepherd/agents, create it with shepherd_spawn, submit tracked work with shepherd_delegate, collect results with shepherd_watch, inspect with shepherd_status or shepherd_read, and explicitly finish with shepherd_close.',
|
|
1728
|
+
'Use shepherd_watch after shepherd_delegate when the parent should continue without blocking; it accepts task ids and sends custom completion follow-ups. Waiting is non-blocking; close each agent explicitly when finished.',
|
|
1729
|
+
'When fieldnotes are enabled, read the shared shepherd.md fieldnotes index before assigning or reviewing work, and write only to the assigned note for note-producing prompts.',
|
|
1730
|
+
'Fieldnotes can be enabled or disabled in /shepherd settings; the change applies when the next parent pi session starts.',
|
|
1731
|
+
],
|
|
1732
|
+
parameters: Type.Object(
|
|
1733
|
+
{
|
|
1734
|
+
action: StringEnum(['herd', 'agents', 'prune'] as const, {
|
|
1735
|
+
description:
|
|
1736
|
+
'herd: list live agents detected in Herdr panes. agents: list available agent definitions and source metadata. prune: drop stale pane registrations.',
|
|
1737
|
+
}),
|
|
1738
|
+
agentScope: Type.Optional(AgentScopeSchema),
|
|
1739
|
+
},
|
|
1740
|
+
{
|
|
1741
|
+
description:
|
|
1742
|
+
'Shepherd control plane: subagent framework for native Herdr agent orchestration. List the live herd, discover agent definitions, or prune stale panes.',
|
|
1743
|
+
}
|
|
1744
|
+
),
|
|
1745
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
1746
|
+
return executeShepherd(String(params.action), params as ShepherdArgs, ctx, signal, onUpdate);
|
|
1747
|
+
},
|
|
1748
|
+
|
|
1749
|
+
renderCall(args, theme, context) {
|
|
1750
|
+
const render = formatShepherdCommand(
|
|
1751
|
+
String(args.action ?? 'unknown'),
|
|
1752
|
+
args as Record<string, any>,
|
|
1753
|
+
context.expanded
|
|
1754
|
+
);
|
|
1755
|
+
const component = reusableText(context.lastComponent);
|
|
1756
|
+
component.setText(
|
|
1757
|
+
theme.fg('toolTitle', theme.bold('shepherd ')) +
|
|
1758
|
+
theme.fg('accent', render.verb) +
|
|
1759
|
+
(render.rest ? theme.fg('dim', ` ${render.rest}`) : '')
|
|
1760
|
+
);
|
|
1761
|
+
return component;
|
|
1762
|
+
},
|
|
1763
|
+
|
|
1764
|
+
renderResult: (result, options, theme, context) =>
|
|
1765
|
+
renderUserFacingResult(result, options, theme, context),
|
|
1766
|
+
});
|
|
1767
|
+
|
|
1768
|
+
pi.registerTool({
|
|
1769
|
+
name: 'shepherd_spawn',
|
|
1770
|
+
label: 'Shepherd: spawn agent',
|
|
1771
|
+
description:
|
|
1772
|
+
'Spawn an idle, persistent agent in a Herdr pane (no task submitted). Provide a short task-specific label (for example label: "code review"). Use shepherd({ action: "agents" }) first if you do not know an exact agent name. ' +
|
|
1773
|
+
'The result prints an opaque agent id; pass it as the top-level id argument to shepherd_prompt, shepherd_status, or shepherd_close. Defaults to the configured working directory, inherited parent model and thinking level, and a new tab; the agent definition can override both. Use placement pane_right or pane_down to split the current pane.',
|
|
1774
|
+
promptSnippet: 'Spawn a new agent in a Herdr pane.',
|
|
1775
|
+
promptGuidelines: [
|
|
1776
|
+
'When using shepherd_spawn, copy the printed agent id into the top-level id argument of shepherd_prompt, shepherd_status, or shepherd_close. After shepherd_prompt, copy the printed prompt id into shepherd_watch. Do not use a Herdr pane id; lifecycle ids are session-scoped.',
|
|
1777
|
+
],
|
|
1778
|
+
parameters: Type.Object({
|
|
1779
|
+
agent: Type.String({
|
|
1780
|
+
description:
|
|
1781
|
+
'Exact discovered agent name (case-sensitive). If unsure, call shepherd with action "agents" first.',
|
|
1782
|
+
}),
|
|
1783
|
+
label: Type.String({ description: 'Short task-specific label (max 64 characters).' }),
|
|
1784
|
+
placement: Type.Optional(
|
|
1785
|
+
StringEnum(['pane_right', 'pane_down', 'tab', 'workspace'] as const, {
|
|
1786
|
+
description:
|
|
1787
|
+
'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.',
|
|
1788
|
+
})
|
|
1789
|
+
),
|
|
1790
|
+
cwd: Type.Optional(
|
|
1791
|
+
Type.String({ description: 'Working directory for the child; defaults to the parent cwd.' })
|
|
1792
|
+
),
|
|
1793
|
+
}),
|
|
1794
|
+
prepareArguments: input => prepareForSchema<Omit<Static<typeof SpawnParams>, 'action'>>(input),
|
|
1795
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
1796
|
+
executeShepherd(
|
|
1797
|
+
'spawn',
|
|
1798
|
+
{ action: 'spawn', ...params } as ShepherdArgs,
|
|
1799
|
+
ctx,
|
|
1800
|
+
signal,
|
|
1801
|
+
onUpdate
|
|
1802
|
+
),
|
|
1803
|
+
// Render a useful invocation preview instead of the default tool-name-only
|
|
1804
|
+
// row; the result renderer below supplies the completion state.
|
|
1805
|
+
renderCall(args, theme, context) {
|
|
1806
|
+
const component = reusableText(context.lastComponent);
|
|
1807
|
+
const agent = typeof args.agent === 'string' ? args.agent : 'agent';
|
|
1808
|
+
const label = typeof args.label === 'string' && args.label ? ` · ${args.label}` : '';
|
|
1809
|
+
const placement = typeof args.placement === 'string' ? ` · ${args.placement}` : '';
|
|
1810
|
+
component.setText(
|
|
1811
|
+
theme.fg('toolTitle', theme.bold('shepherd_spawn')) +
|
|
1812
|
+
` ${theme.fg('accent', agent)}` +
|
|
1813
|
+
theme.fg('dim', `${label}${placement}`)
|
|
1814
|
+
);
|
|
1815
|
+
return component;
|
|
1816
|
+
},
|
|
1817
|
+
renderResult: (result, options, theme, context) =>
|
|
1818
|
+
renderSpawnResult(result, options, theme, context),
|
|
1819
|
+
});
|
|
1820
|
+
|
|
1821
|
+
pi.registerTool({
|
|
1822
|
+
name: 'shepherd_delegate',
|
|
1823
|
+
label: 'Shepherd: delegate task',
|
|
1824
|
+
description:
|
|
1825
|
+
'Start tracked asynchronous work on a spawned agent and return a task id immediately. The task can span multiple Pi turns; use shepherd_watch to observe terminal completion. Do not treat an idle child or ended turn as task completion.',
|
|
1826
|
+
promptSnippet: 'Delegate tracked asynchronous work without blocking the parent.',
|
|
1827
|
+
promptGuidelines: [
|
|
1828
|
+
'Use shepherd_delegate for work that may span multiple child turns or wait for another agent. The returned task id, not a prompt id or pane id, is the completion handle.',
|
|
1829
|
+
'Use shepherd_watch after delegation when the parent should continue without blocking. A child must explicitly call shepherd_done before a successful task result is reported.',
|
|
1830
|
+
],
|
|
1831
|
+
parameters: Type.Object({
|
|
1832
|
+
target: Type.String({
|
|
1833
|
+
description: 'Opaque agent id returned by shepherd_spawn. Do not use a Herdr pane id.',
|
|
1834
|
+
}),
|
|
1835
|
+
task: Type.String({ description: 'Non-empty delegated task description.' }),
|
|
1836
|
+
timeout: Type.Optional(
|
|
1837
|
+
Type.Integer({ default: 60, description: 'Optional task deadline in minutes.' })
|
|
1838
|
+
),
|
|
1839
|
+
}),
|
|
1840
|
+
prepareArguments: input =>
|
|
1841
|
+
prepareForSchema<Omit<Static<typeof LifecycleDelegateParams>, 'action'>>(input),
|
|
1842
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
1843
|
+
executeShepherd(
|
|
1844
|
+
'delegate',
|
|
1845
|
+
{ action: 'delegate', ...params } as ShepherdArgs,
|
|
1846
|
+
ctx,
|
|
1847
|
+
signal,
|
|
1848
|
+
onUpdate
|
|
1849
|
+
),
|
|
1850
|
+
renderCall(args, theme, context) {
|
|
1851
|
+
return renderLifecycleCall(
|
|
1852
|
+
'shepherd_delegate',
|
|
1853
|
+
[
|
|
1854
|
+
args.target,
|
|
1855
|
+
args.task,
|
|
1856
|
+
args.timeout !== undefined ? `timeout ${args.timeout}m` : undefined,
|
|
1857
|
+
],
|
|
1858
|
+
theme,
|
|
1859
|
+
context
|
|
1860
|
+
);
|
|
1861
|
+
},
|
|
1862
|
+
renderResult: (result, options, theme, context) =>
|
|
1863
|
+
renderUserFacingResult(result, options, theme, context),
|
|
1864
|
+
});
|
|
1865
|
+
|
|
1866
|
+
pi.registerTool({
|
|
1867
|
+
name: 'shepherd_message',
|
|
1868
|
+
label: 'Shepherd: message agent',
|
|
1869
|
+
description:
|
|
1870
|
+
'Send one asynchronous message to a spawned agent and return immediately. target MUST be the exact opaque agent id returned by shepherd_spawn; copy that id verbatim. Never pass an agent definition name such as "planner", a display label such as "manual planner", a Herdr pane id, or a placeholder such as "<planner agent ID>"—the call will be rejected. The returned message id identifies this message for reply correlation. An accepted message means the broker queued it for delivery; it does not mean the recipient read it or replied. With expectsReply and a taskId the task enters waiting until a matching reply arrives.',
|
|
1871
|
+
promptSnippet:
|
|
1872
|
+
'send an asynchronous message using the exact opaque id returned by shepherd_spawn.',
|
|
1873
|
+
promptGuidelines: [
|
|
1874
|
+
'Before calling shepherd_message, copy target from the id field in shepherd_spawn output. Do not infer or substitute the agent definition name, display label, pane id, or any angle-bracket placeholder; invalid targets fail instead of being resolved by name.',
|
|
1875
|
+
'Use shepherd_message for questions to an agent while it is busy or idle; the recipient receives it as a queued follow-up. Do not use it to submit tracked work — that is shepherd_delegate.',
|
|
1876
|
+
"When expectsReply is set with a taskId, the task waits for the reply; a matching reply (replyTo = the returned message id) returns it to running. For peer replies, use the requester's task ID—the task whose request is being answered—not the responder's task ID. A plain message never alters task state.",
|
|
1877
|
+
],
|
|
1878
|
+
parameters: Type.Object({
|
|
1879
|
+
target: Type.String({
|
|
1880
|
+
description:
|
|
1881
|
+
'Exact opaque agent id returned by shepherd_spawn; copy it verbatim. Agent names (for example "planner"), labels, Herdr pane ids, and placeholders are rejected.',
|
|
1882
|
+
}),
|
|
1883
|
+
message: Type.String({ description: 'Non-empty message content.' }),
|
|
1884
|
+
taskId: Type.Optional(TaskIdSchema),
|
|
1885
|
+
threadId: Type.Optional(Type.String({ description: 'Conversation/thread correlation id.' })),
|
|
1886
|
+
replyTo: Type.Optional(
|
|
1887
|
+
Type.String({ description: 'Message id of the request being answered.' })
|
|
1888
|
+
),
|
|
1889
|
+
expectsReply: Type.Optional(
|
|
1890
|
+
Type.Boolean({ description: 'Track this message as a request that expects a reply.' })
|
|
1891
|
+
),
|
|
1892
|
+
delivery: Type.Optional(
|
|
1893
|
+
Type.Union([Type.Literal('followUp'), Type.Literal('steer')], {
|
|
1894
|
+
description: 'Delivery mode; steer is the default, followUp queues passively behind the current turn.',
|
|
1895
|
+
})
|
|
1896
|
+
),
|
|
1897
|
+
}),
|
|
1898
|
+
prepareArguments: input =>
|
|
1899
|
+
prepareForSchema<Omit<Static<typeof LifecycleMessageParams>, 'action'>>(input),
|
|
1900
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
1901
|
+
executeShepherd(
|
|
1902
|
+
'message',
|
|
1903
|
+
{ action: 'message', ...params } as ShepherdArgs,
|
|
1904
|
+
ctx,
|
|
1905
|
+
signal,
|
|
1906
|
+
onUpdate
|
|
1907
|
+
),
|
|
1908
|
+
renderCall(args, theme, context) {
|
|
1909
|
+
return renderLifecycleCall(
|
|
1910
|
+
'shepherd_message',
|
|
1911
|
+
[args.target, args.message, args.expectsReply ? 'expects reply' : undefined, args.delivery],
|
|
1912
|
+
theme,
|
|
1913
|
+
context
|
|
1914
|
+
);
|
|
1915
|
+
},
|
|
1916
|
+
renderResult: (result, options, theme, context) =>
|
|
1917
|
+
renderUserFacingResult(result, options, theme, context),
|
|
1918
|
+
});
|
|
1919
|
+
|
|
1920
|
+
pi.registerTool({
|
|
1921
|
+
name: 'shepherd_prompt',
|
|
1922
|
+
label: 'Shepherd: prompt agent (deprecated)',
|
|
1923
|
+
description:
|
|
1924
|
+
'Deprecated compatibility path: submits one message to a spawned agent and returns a prompt id without waiting, tying completion to a single child turn. For tracked work that must survive peer replies, prefer shepherd_delegate (a task) + shepherd_watch; use shepherd_message for follow-ups. Pass the agent id printed by shepherd_spawn as the top-level id argument, not a Herdr pane id. The result prints a prompt id; pass that id to shepherd_watch.',
|
|
1925
|
+
promptSnippet:
|
|
1926
|
+
'Deprecated: prompt a spawned agent with a one-turn message (prefer shepherd_delegate for tracked work).',
|
|
1927
|
+
parameters: Type.Object({
|
|
1928
|
+
id: Type.String({
|
|
1929
|
+
description: 'Opaque agent id returned by shepherd_spawn. Do not use a Herdr pane id.',
|
|
1930
|
+
}),
|
|
1931
|
+
message: Type.String({
|
|
1932
|
+
description:
|
|
1933
|
+
'One-turn message to submit to the spawned agent. For multi-step or reply-dependent work use shepherd_delegate instead. Submission returns immediately; use shepherd_watch for the result.',
|
|
1934
|
+
}),
|
|
1935
|
+
timeout: Type.Optional(
|
|
1936
|
+
Type.Integer({
|
|
1937
|
+
default: 60,
|
|
1938
|
+
description:
|
|
1939
|
+
'Optional readiness wait before submission; normally omit. It is capped at 15 seconds internally. Completion is reported asynchronously by shepherd_watch.',
|
|
1940
|
+
})
|
|
1941
|
+
),
|
|
1942
|
+
}),
|
|
1943
|
+
prepareArguments: input =>
|
|
1944
|
+
prepareForSchema<Omit<Static<typeof LifecyclePromptParams>, 'action'>>(input),
|
|
1945
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
1946
|
+
executeShepherd(
|
|
1947
|
+
'prompt',
|
|
1948
|
+
{ action: 'prompt', ...params } as ShepherdArgs,
|
|
1949
|
+
ctx,
|
|
1950
|
+
signal,
|
|
1951
|
+
onUpdate
|
|
1952
|
+
),
|
|
1953
|
+
renderCall(args, theme, context) {
|
|
1954
|
+
return renderLifecycleCall(
|
|
1955
|
+
'shepherd_prompt',
|
|
1956
|
+
[
|
|
1957
|
+
args.id,
|
|
1958
|
+
args.message,
|
|
1959
|
+
args.timeout !== undefined ? `timeout ${args.timeout}m` : undefined,
|
|
1960
|
+
],
|
|
1961
|
+
theme,
|
|
1962
|
+
context
|
|
1963
|
+
);
|
|
1964
|
+
},
|
|
1965
|
+
renderResult: (result, options, theme, context) =>
|
|
1966
|
+
renderUserFacingResult(result, options, theme, context),
|
|
1967
|
+
});
|
|
1968
|
+
|
|
1969
|
+
pi.registerTool({
|
|
1970
|
+
name: 'shepherd_watch',
|
|
1971
|
+
label: 'Shepherd: watch task',
|
|
1972
|
+
description:
|
|
1973
|
+
'Register a non-blocking one-shot watcher for one task or an array of task ids returned by shepherd_delegate. A watcher reports only terminal task outcomes—a child must explicitly call shepherd_done (or the task must fail, time out, or be cancelled) before a result is reported; idle, agent_end, and waiting states do not complete it. Returns immediately with pending and already-completed results; later completions arrive as custom Shepherd notifications delivered with steer. Unwatched settlements are surfaced at the next settle boundary or as one coalesced idle wake. Legacy prompt ids from shepherd_prompt are still accepted.',
|
|
1974
|
+
promptSnippet: 'Watch task completion asynchronously without blocking the parent turn.',
|
|
1975
|
+
promptGuidelines: [
|
|
1976
|
+
'Pass task ids returned by shepherd_delegate; legacy prompt ids from shepherd_prompt are also accepted. Never pass agent ids or Herdr pane ids.',
|
|
1977
|
+
'Array watchers report each task as it settles and may coalesce close-together completions into one notification.',
|
|
1978
|
+
'Use shepherd_status between watcher notifications to inspect running or waiting task state without blocking the parent turn.',
|
|
1979
|
+
],
|
|
1980
|
+
parameters: Type.Object({
|
|
1981
|
+
id: Type.Union(
|
|
1982
|
+
[
|
|
1983
|
+
Type.String({
|
|
1984
|
+
description:
|
|
1985
|
+
'Opaque task id returned by shepherd_delegate. A legacy prompt id from shepherd_prompt is also accepted. Do not use an agent id or pane id.',
|
|
1986
|
+
}),
|
|
1987
|
+
Type.Array(
|
|
1988
|
+
Type.String({
|
|
1989
|
+
description:
|
|
1990
|
+
'Opaque task id returned by shepherd_delegate; a legacy prompt id from shepherd_prompt is also accepted.',
|
|
1991
|
+
}),
|
|
1992
|
+
{
|
|
1993
|
+
minItems: 1,
|
|
1994
|
+
description:
|
|
1995
|
+
'Array of opaque task ids; completions are reported independently as each task settles.',
|
|
1996
|
+
}
|
|
1997
|
+
),
|
|
1998
|
+
],
|
|
1999
|
+
{
|
|
2000
|
+
description:
|
|
2001
|
+
'One opaque task id or a non-empty array of task ids returned by shepherd_delegate; legacy prompt ids are also accepted.',
|
|
2002
|
+
}
|
|
2003
|
+
),
|
|
2004
|
+
}),
|
|
2005
|
+
prepareArguments: input => prepareForSchema<Omit<Static<typeof WatchParams>, 'action'>>(input),
|
|
2006
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
2007
|
+
executeShepherd(
|
|
2008
|
+
'watch',
|
|
2009
|
+
{ action: 'watch', ...params } as ShepherdArgs,
|
|
2010
|
+
ctx,
|
|
2011
|
+
signal,
|
|
2012
|
+
onUpdate
|
|
2013
|
+
),
|
|
2014
|
+
renderCall(args, theme, context) {
|
|
2015
|
+
const ids = Array.isArray(args.id) ? args.id.join(', ') : args.id;
|
|
2016
|
+
return renderLifecycleCall('shepherd_watch', [ids], theme, context);
|
|
2017
|
+
},
|
|
2018
|
+
renderResult: (result, options, theme, context) =>
|
|
2019
|
+
renderUserFacingResult(result, options, theme, context),
|
|
2020
|
+
});
|
|
2021
|
+
|
|
2022
|
+
pi.registerTool({
|
|
2023
|
+
name: 'shepherd_status',
|
|
2024
|
+
label: 'Shepherd: status of agent',
|
|
2025
|
+
description:
|
|
2026
|
+
"Inspect an agent's current state without focusing or mutating its Herdr pane. Pass the agent id printed by shepherd_spawn; do not pass a prompt id or Herdr pane id.",
|
|
2027
|
+
promptSnippet: 'Check the current state of a spawned agent.',
|
|
2028
|
+
parameters: Type.Object({
|
|
2029
|
+
id: Type.String({
|
|
2030
|
+
description: 'Opaque agent id returned by shepherd_spawn. Do not use a Herdr pane id.',
|
|
2031
|
+
}),
|
|
2032
|
+
}),
|
|
2033
|
+
prepareArguments: input =>
|
|
2034
|
+
prepareForSchema<Omit<Static<typeof LifecycleStatusParams>, 'action'>>(input),
|
|
2035
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
2036
|
+
executeShepherd(
|
|
2037
|
+
'status',
|
|
2038
|
+
{ action: 'status', ...params } as ShepherdArgs,
|
|
2039
|
+
ctx,
|
|
2040
|
+
signal,
|
|
2041
|
+
onUpdate
|
|
2042
|
+
),
|
|
2043
|
+
renderCall(args, theme, context) {
|
|
2044
|
+
return renderLifecycleCall('shepherd_status', [args.id], theme, context);
|
|
2045
|
+
},
|
|
2046
|
+
renderResult: (result, options, theme, context) =>
|
|
2047
|
+
renderUserFacingResult(result, options, theme, context),
|
|
2048
|
+
});
|
|
2049
|
+
|
|
2050
|
+
pi.registerTool({
|
|
2051
|
+
name: 'shepherd_close',
|
|
2052
|
+
label: 'Shepherd: close agent',
|
|
2053
|
+
description:
|
|
2054
|
+
'Close an owned agent and cancel any unresolved prompt. Pass the agent id printed by shepherd_spawn, not a Herdr pane id. Waiting does not close agents, so close each agent when finished.',
|
|
2055
|
+
promptSnippet: 'Close an owned agent and cancel any unresolved prompt.',
|
|
2056
|
+
parameters: Type.Object({
|
|
2057
|
+
id: Type.String({
|
|
2058
|
+
description: 'Opaque agent id returned by shepherd_spawn. Do not use a Herdr pane id.',
|
|
2059
|
+
}),
|
|
2060
|
+
}),
|
|
2061
|
+
prepareArguments: input =>
|
|
2062
|
+
prepareForSchema<Omit<Static<typeof LifecycleCloseParams>, 'action'>>(input),
|
|
2063
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
2064
|
+
executeShepherd(
|
|
2065
|
+
'close',
|
|
2066
|
+
{ action: 'close', ...params } as ShepherdArgs,
|
|
2067
|
+
ctx,
|
|
2068
|
+
signal,
|
|
2069
|
+
onUpdate
|
|
2070
|
+
),
|
|
2071
|
+
renderCall(args, theme, context) {
|
|
2072
|
+
return renderLifecycleCall('shepherd_close', [args.id], theme, context);
|
|
2073
|
+
},
|
|
2074
|
+
renderResult: (result, options, theme, context) =>
|
|
2075
|
+
renderUserFacingResult(result, options, theme, context),
|
|
2076
|
+
});
|
|
2077
|
+
|
|
2078
|
+
pi.registerTool({
|
|
2079
|
+
name: 'shepherd_read',
|
|
2080
|
+
label: 'Shepherd: read terminal output',
|
|
2081
|
+
description:
|
|
2082
|
+
'Read recent terminal output for diagnostics. Pass an agent name, Herdr pane id, or an agent id; unlike lifecycle tools, this diagnostic tool intentionally accepts several target forms.',
|
|
2083
|
+
promptSnippet: 'Read recent terminal output for diagnostics.',
|
|
2084
|
+
parameters: Type.Object({
|
|
2085
|
+
name: Type.String({
|
|
2086
|
+
description: 'Agent name, Herdr pane id, or opaque agent id of the target.',
|
|
2087
|
+
}),
|
|
2088
|
+
lines: Type.Optional(
|
|
2089
|
+
Type.Integer({ description: 'Number of recent lines for read (default 40)', default: 40 })
|
|
2090
|
+
),
|
|
2091
|
+
source: Type.Optional(SourceSchema),
|
|
2092
|
+
}),
|
|
2093
|
+
prepareArguments: input => prepareForSchema<Omit<Static<typeof ReadParams>, 'action'>>(input),
|
|
2094
|
+
execute: (_id, params, signal, onUpdate, ctx) =>
|
|
2095
|
+
executeShepherd('read', { action: 'read', ...params } as ShepherdArgs, ctx, signal, onUpdate),
|
|
2096
|
+
renderCall(args, theme, context) {
|
|
2097
|
+
return renderLifecycleCall(
|
|
2098
|
+
'shepherd_read',
|
|
2099
|
+
[args.name, args.source, args.lines !== undefined ? `${args.lines} lines` : undefined],
|
|
2100
|
+
theme,
|
|
2101
|
+
context
|
|
2102
|
+
);
|
|
2103
|
+
},
|
|
2104
|
+
renderResult: (result, options, theme, context) =>
|
|
2105
|
+
renderUserFacingResult(result, options, theme, context),
|
|
2106
|
+
});
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
function compactCallValue(value: unknown, maxLength = 72): string {
|
|
2110
|
+
const text = String(value ?? '')
|
|
2111
|
+
.replace(/\s+/g, ' ')
|
|
2112
|
+
.trim();
|
|
2113
|
+
if (text.length <= maxLength) return text;
|
|
2114
|
+
return `${text.slice(0, Math.max(1, maxLength - 1))}…`;
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
function renderLifecycleCall(name: string, parts: unknown[], theme: any, context: any): Text {
|
|
2118
|
+
const component = reusableText(context.lastComponent);
|
|
2119
|
+
const values = parts
|
|
2120
|
+
.filter(value => value !== undefined && value !== null && value !== '')
|
|
2121
|
+
.map(value => compactCallValue(value));
|
|
2122
|
+
component.setText(
|
|
2123
|
+
theme.fg('toolTitle', theme.bold(name)) +
|
|
2124
|
+
(values.length ? ` ${theme.fg('accent', values[0])}` : '') +
|
|
2125
|
+
(values.length > 1
|
|
2126
|
+
? theme.fg(
|
|
2127
|
+
'dim',
|
|
2128
|
+
` ${values
|
|
2129
|
+
.slice(1)
|
|
2130
|
+
.map(value => `· ${value}`)
|
|
2131
|
+
.join(' ')}`
|
|
2132
|
+
)
|
|
2133
|
+
: '')
|
|
2134
|
+
);
|
|
2135
|
+
return component;
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
function renderSpawnResult(
|
|
2139
|
+
result: any,
|
|
2140
|
+
options: { expanded?: boolean; isPartial?: boolean },
|
|
2141
|
+
theme: any,
|
|
2142
|
+
context: any
|
|
2143
|
+
) {
|
|
2144
|
+
const component = reusableText(context.lastComponent);
|
|
2145
|
+
const details = result?.details && typeof result.details === 'object' ? result.details : {};
|
|
2146
|
+
const failed =
|
|
2147
|
+
context?.isError === true ||
|
|
2148
|
+
details.error !== undefined ||
|
|
2149
|
+
(details.returnCode !== undefined && Number(details.returnCode) !== 0);
|
|
2150
|
+
|
|
2151
|
+
if (options.isPartial) {
|
|
2152
|
+
component.setText(theme.fg('warning', 'spawning…'));
|
|
2153
|
+
return component;
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
const rendered = formatToolResultText(result);
|
|
2157
|
+
if (rendered === undefined) return renderToolResult(result, options, theme, context);
|
|
2158
|
+
|
|
2159
|
+
const firstLine = rendered.split('\n')[0] ?? '';
|
|
2160
|
+
const errorMessage = failed
|
|
2161
|
+
? typeof details.error === 'string'
|
|
2162
|
+
? details.error
|
|
2163
|
+
: firstLine.replace(/^Herd spawn failed(?: \(return code \d+\))?:\s*/, '') || 'unknown error'
|
|
2164
|
+
: undefined;
|
|
2165
|
+
const status = failed
|
|
2166
|
+
? theme.fg('error', `✗ failed${errorMessage ? ` · ${errorMessage}` : ''}`)
|
|
2167
|
+
: theme.fg('success', '✓ success');
|
|
2168
|
+
|
|
2169
|
+
// The call row already contains the agent, label, and placement. Keep the
|
|
2170
|
+
// result row to a status only and reserve protocol details for expansion.
|
|
2171
|
+
if (!options.expanded) {
|
|
2172
|
+
component.setText(status);
|
|
2173
|
+
return component;
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
const expanded = formatExpandedToolResult(result);
|
|
2177
|
+
if (expanded !== undefined) {
|
|
2178
|
+
component.setText(`${status}\n\n${styleExpandedToolResult(expanded, theme)}`);
|
|
2179
|
+
return component;
|
|
2180
|
+
}
|
|
2181
|
+
|
|
2182
|
+
const newline = rendered.indexOf('\n');
|
|
2183
|
+
const remainder = newline >= 0 ? rendered.slice(newline) : '';
|
|
2184
|
+
const styledRemainder = remainder
|
|
2185
|
+
.split('\n')
|
|
2186
|
+
.map(line =>
|
|
2187
|
+
['call:', 'return:', 'details:'].includes(line)
|
|
2188
|
+
? theme.fg('accent', line)
|
|
2189
|
+
: theme.fg('toolOutput', line)
|
|
2190
|
+
)
|
|
2191
|
+
.join('\n');
|
|
2192
|
+
component.setText(status + styledRemainder);
|
|
2193
|
+
return component;
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
/** Render every Shepherd result with the same user-facing structure. */
|
|
2197
|
+
function renderUserFacingResult(
|
|
2198
|
+
result: any,
|
|
2199
|
+
options: { expanded?: boolean },
|
|
2200
|
+
theme: any,
|
|
2201
|
+
context: any
|
|
2202
|
+
) {
|
|
2203
|
+
const rendered = formatToolResultText(result);
|
|
2204
|
+
if (rendered === undefined) return renderToolResult(result, options, theme, context);
|
|
2205
|
+
const component = reusableText(context.lastComponent);
|
|
2206
|
+
const callName = result?.details?.call?.name;
|
|
2207
|
+
if (typeof callName !== 'string') {
|
|
2208
|
+
component.setText(theme.fg('toolOutput', rendered));
|
|
2209
|
+
return component;
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
if (options.expanded) {
|
|
2213
|
+
const expanded = formatExpandedToolResult(result);
|
|
2214
|
+
if (expanded !== undefined) {
|
|
2215
|
+
// Keep the expanded result visually separate from the outer invocation
|
|
2216
|
+
// row. Spawn adds its own status block; the shared result path needs one
|
|
2217
|
+
// leading blank line before the `call` section.
|
|
2218
|
+
component.setText(`\n${styleExpandedToolResult(expanded, theme)}`);
|
|
2219
|
+
return component;
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
const lifecycleStatus = renderCollapsedLifecycleResult(result, callName, theme, context);
|
|
2224
|
+
if (lifecycleStatus !== undefined) {
|
|
2225
|
+
component.setText(lifecycleStatus);
|
|
2226
|
+
return component;
|
|
2227
|
+
}
|
|
2228
|
+
|
|
2229
|
+
const lines = rendered.split('\n');
|
|
2230
|
+
const firstLine = lines.shift() ?? '';
|
|
2231
|
+
const prefix = `${callName} `;
|
|
2232
|
+
const summary = firstLine.startsWith(prefix) ? firstLine.slice(prefix.length) : firstLine;
|
|
2233
|
+
const styled =
|
|
2234
|
+
theme.fg('toolTitle', theme.bold(callName)) +
|
|
2235
|
+
(summary ? ` ${theme.fg('accent', summary)}` : '');
|
|
2236
|
+
const remainder = lines
|
|
2237
|
+
.map(line =>
|
|
2238
|
+
['call:', 'return:', 'details:'].includes(line)
|
|
2239
|
+
? theme.fg('accent', line)
|
|
2240
|
+
: theme.fg('toolOutput', line)
|
|
2241
|
+
)
|
|
2242
|
+
.join('\n');
|
|
2243
|
+
component.setText(styled + (lines.length ? `\n${remainder}` : ''));
|
|
2244
|
+
return component;
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
export function formatExpandedToolResult(result: any): string | undefined {
|
|
2248
|
+
const details = result?.details && typeof result.details === 'object' ? result.details : {};
|
|
2249
|
+
const call = details.call;
|
|
2250
|
+
if (!call || typeof call.name !== 'string') return undefined;
|
|
2251
|
+
|
|
2252
|
+
const callArguments = call.arguments && typeof call.arguments === 'object' ? call.arguments : {};
|
|
2253
|
+
const lines = ['call'];
|
|
2254
|
+
// Keep top-level call arguments flat. This lets raw message blocks start at
|
|
2255
|
+
// the same visual edge as their label and avoids a misleading hanging
|
|
2256
|
+
// indent when Pi wraps a long single-line value. Include optional arguments
|
|
2257
|
+
// whenever they were present in the invocation.
|
|
2258
|
+
lines.push(...formatHumanRecord(callArguments, ''));
|
|
2259
|
+
|
|
2260
|
+
const body = resultTextBody(result);
|
|
2261
|
+
const summary = humanReturnSummary(call.name, body, details);
|
|
2262
|
+
if (lines.at(-1) !== '') lines.push('');
|
|
2263
|
+
lines.push('return', `status: ${summary}`);
|
|
2264
|
+
if (call.name === 'shepherd' && Array.isArray(details.agents) && details.scope === undefined) {
|
|
2265
|
+
const activeCount = details.agents.filter((agent: any) => agent?.shepherd === true).length;
|
|
2266
|
+
lines.push(...formatHumanField('active agents', activeCount, ''));
|
|
2267
|
+
} else if (body.includes('\n')) {
|
|
2268
|
+
lines.push(...formatHumanField('output', body, ''));
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
const returnValueKeys = ['returnValue', 'result'].filter(key =>
|
|
2272
|
+
Object.prototype.hasOwnProperty.call(details, key)
|
|
2273
|
+
);
|
|
2274
|
+
for (const key of returnValueKeys) {
|
|
2275
|
+
lines.push(
|
|
2276
|
+
...formatHumanReturnValue(
|
|
2277
|
+
key === 'returnValue' ? details[key] : details[key],
|
|
2278
|
+
call.name,
|
|
2279
|
+
callArguments,
|
|
2280
|
+
'',
|
|
2281
|
+
body
|
|
2282
|
+
)
|
|
2283
|
+
);
|
|
2284
|
+
}
|
|
2285
|
+
|
|
2286
|
+
const returnValueObject =
|
|
2287
|
+
returnValueKeys.length === 1 &&
|
|
2288
|
+
details[returnValueKeys[0]] &&
|
|
2289
|
+
typeof details[returnValueKeys[0]] === 'object' &&
|
|
2290
|
+
!Array.isArray(details[returnValueKeys[0]])
|
|
2291
|
+
? details[returnValueKeys[0]]
|
|
2292
|
+
: undefined;
|
|
2293
|
+
const returnedKeys = new Set(returnValueObject ? Object.keys(returnValueObject) : []);
|
|
2294
|
+
const extraEntries = Object.entries(details).filter(([key]) => {
|
|
2295
|
+
if (
|
|
2296
|
+
['call', 'returnValue', 'result', 'artifactSession', 'fieldnote', 'returnCode'].includes(key)
|
|
2297
|
+
)
|
|
2298
|
+
return false;
|
|
2299
|
+
if (call.name === 'shepherd_status' && key === 'status') return false;
|
|
2300
|
+
if (key === 'error') return true;
|
|
2301
|
+
return !returnedKeys.has(key) && !['agent', 'label', 'model', 'id'].includes(key);
|
|
2302
|
+
});
|
|
2303
|
+
for (const [key, value] of extraEntries) {
|
|
2304
|
+
if (call.name === 'shepherd' && key === 'agents' && Array.isArray(value)) {
|
|
2305
|
+
lines.push('agents:', ...formatHerdAgentList(shepherdHerdAgents(value)));
|
|
2306
|
+
continue;
|
|
2307
|
+
}
|
|
2308
|
+
lines.push(...formatHumanField(humanizeKey(key), value, ''));
|
|
2309
|
+
}
|
|
2310
|
+
if (typeof details.returnCode === 'number' && details.returnCode !== 0) {
|
|
2311
|
+
lines.push(...formatHumanField('return code', details.returnCode, ''));
|
|
2312
|
+
}
|
|
2313
|
+
return lines.join('\n');
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
function humanReturnSummary(callName: string, body: string, details: Record<string, any>): string {
|
|
2317
|
+
if (details.error !== undefined || /failed/i.test(body)) return 'failed';
|
|
2318
|
+
if (callName === 'shepherd_spawn' && /spawned/i.test(body)) return 'spawned';
|
|
2319
|
+
if (callName === 'shepherd_message' && /queued/i.test(body)) return 'queued';
|
|
2320
|
+
if (callName === 'shepherd_delegate' && /delegated/i.test(body)) return 'delegated';
|
|
2321
|
+
if (callName === 'shepherd_prompt' && /prompted/i.test(body)) return 'prompted';
|
|
2322
|
+
if (callName === 'shepherd_watch' && /watching|already settled/i.test(body)) {
|
|
2323
|
+
return /watching/i.test(body) ? 'watching…' : 'completed';
|
|
2324
|
+
}
|
|
2325
|
+
if (callName === 'shepherd_status') {
|
|
2326
|
+
const returned =
|
|
2327
|
+
details.returnValue && typeof details.returnValue === 'object'
|
|
2328
|
+
? details.returnValue
|
|
2329
|
+
: details.result && typeof details.result === 'object'
|
|
2330
|
+
? details.result
|
|
2331
|
+
: undefined;
|
|
2332
|
+
if (typeof returned?.state === 'string') return returned.state;
|
|
2333
|
+
const state = body.match(/\bagent\s+([a-z-]+)/i)?.[1];
|
|
2334
|
+
return (state ?? body) || 'completed';
|
|
2335
|
+
}
|
|
2336
|
+
if (callName === 'shepherd_close' && /closed/i.test(body)) return 'closed';
|
|
2337
|
+
if (body.includes('\n')) return 'output';
|
|
2338
|
+
return body || 'completed';
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
export function renderCollapsedLifecycleResult(
|
|
2342
|
+
result: any,
|
|
2343
|
+
callName: string,
|
|
2344
|
+
theme: any,
|
|
2345
|
+
context: any
|
|
2346
|
+
): string | undefined {
|
|
2347
|
+
const details = result?.details && typeof result.details === 'object' ? result.details : {};
|
|
2348
|
+
const failed =
|
|
2349
|
+
context?.isError === true ||
|
|
2350
|
+
details.error !== undefined ||
|
|
2351
|
+
(details.returnCode !== undefined && Number(details.returnCode) !== 0);
|
|
2352
|
+
if (failed) {
|
|
2353
|
+
const body = resultTextBody(result);
|
|
2354
|
+
const firstLine = body.split('\n')[0] ?? '';
|
|
2355
|
+
const error =
|
|
2356
|
+
typeof details.error === 'string'
|
|
2357
|
+
? details.error
|
|
2358
|
+
: firstLine.replace(/^Herd \w+ failed(?: \(return code \d+\))?:\s*/, '') || 'unknown error';
|
|
2359
|
+
return theme.fg('error', `✗ failed${error ? ` · ${error}` : ''}`);
|
|
2360
|
+
}
|
|
2361
|
+
if (callName === 'shepherd' && Array.isArray(details.agents)) {
|
|
2362
|
+
if (details.scope === undefined) {
|
|
2363
|
+
const agents = details.agents.filter((agent: any) => agent?.shepherd === true);
|
|
2364
|
+
return theme.fg('toolOutput', `Active agents: ${agents.length}`);
|
|
2365
|
+
}
|
|
2366
|
+
const names = details.agents
|
|
2367
|
+
.map((agent: any) => (agent && typeof agent.name === 'string' ? agent.name : undefined))
|
|
2368
|
+
.filter((name: string | undefined): name is string => name !== undefined);
|
|
2369
|
+
return (
|
|
2370
|
+
theme.fg('accent', 'Available agents:') +
|
|
2371
|
+
(names.length > 0 ? ` ${theme.fg('toolOutput', names.join(', '))}` : '')
|
|
2372
|
+
);
|
|
2373
|
+
}
|
|
2374
|
+
if (callName === 'shepherd_delegate') return theme.fg('success', '✓ delegated');
|
|
2375
|
+
if (callName === 'shepherd_message') {
|
|
2376
|
+
return details.targetTaskState === 'waiting'
|
|
2377
|
+
? theme.fg('warning', 'waiting…')
|
|
2378
|
+
: theme.fg('success', '✓ queued');
|
|
2379
|
+
}
|
|
2380
|
+
if (callName === 'shepherd_prompt') return theme.fg('success', '✓ prompted');
|
|
2381
|
+
if (callName === 'shepherd_watch') {
|
|
2382
|
+
const pending = Array.isArray(details.pending) ? details.pending.length : 0;
|
|
2383
|
+
return pending > 0 ? theme.fg('warning', 'watching…') : theme.fg('success', '✓ completed');
|
|
2384
|
+
}
|
|
2385
|
+
if (callName === 'shepherd_close') return theme.fg('success', '✓ closed');
|
|
2386
|
+
|
|
2387
|
+
// Status, read, and umbrella actions do not need a synthetic success icon;
|
|
2388
|
+
// their first result line is already the useful collapsed summary. Never
|
|
2389
|
+
// fall back to the protocol-oriented call/return/details text here.
|
|
2390
|
+
const body = resultTextBody(result);
|
|
2391
|
+
const firstLine = body.split('\n')[0] ?? '';
|
|
2392
|
+
return theme.fg('toolOutput', firstLine || 'completed');
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
function formatHumanReturnValue(
|
|
2396
|
+
value: unknown,
|
|
2397
|
+
callName: string,
|
|
2398
|
+
callArguments: Record<string, unknown>,
|
|
2399
|
+
indent: string,
|
|
2400
|
+
body: string
|
|
2401
|
+
): string[] {
|
|
2402
|
+
if (typeof value === 'string' && value === body) return [];
|
|
2403
|
+
if (callName === 'shepherd_watch' && Array.isArray(value)) {
|
|
2404
|
+
return formatHumanField('completions', value.map(compactWatcherCompletion), indent);
|
|
2405
|
+
}
|
|
2406
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
2407
|
+
return formatHumanField('value', value, indent);
|
|
2408
|
+
}
|
|
2409
|
+
return Object.entries(value).flatMap(([key, entry]) => {
|
|
2410
|
+
if (callName === 'shepherd_watch' && key === 'completed' && Array.isArray(entry)) {
|
|
2411
|
+
return formatHumanField('completions', entry.map(compactWatcherCompletion), indent);
|
|
2412
|
+
}
|
|
2413
|
+
if (callName === 'shepherd_spawn' && ['agent', 'label'].includes(key)) return [];
|
|
2414
|
+
if (callName === 'shepherd_status' && key === 'id' && callArguments.id === entry) return [];
|
|
2415
|
+
if (callName === 'shepherd_status' && key === 'state') return [];
|
|
2416
|
+
if (key === 'id' && callName === 'shepherd_spawn') {
|
|
2417
|
+
return formatHumanField('agent id', entry, indent);
|
|
2418
|
+
}
|
|
2419
|
+
if (key === 'placement' && callArguments.placement === entry) return [];
|
|
2420
|
+
return formatHumanField(humanizeKey(key), entry, indent);
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
function resultTextBody(result: any): string {
|
|
2425
|
+
const body = result?.content?.[0]?.type === 'text' ? String(result.content[0].text ?? '') : '';
|
|
2426
|
+
const protocolMarker = '\n\ncall:\n';
|
|
2427
|
+
const markerIndex = body.indexOf(protocolMarker);
|
|
2428
|
+
return markerIndex >= 0 ? body.slice(0, markerIndex) : body;
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
function formatHumanRecord(value: unknown, indent: string): string[] {
|
|
2432
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
2433
|
+
return formatHumanField('value', value, indent);
|
|
2434
|
+
}
|
|
2435
|
+
return Object.entries(value).flatMap(([key, entry]) =>
|
|
2436
|
+
formatHumanField(humanizeKey(key), entry, indent)
|
|
2437
|
+
);
|
|
2438
|
+
}
|
|
2439
|
+
|
|
2440
|
+
function formatHumanField(label: string, value: unknown, indent: string): string[] {
|
|
2441
|
+
const isTextBlock =
|
|
2442
|
+
typeof value === 'string' &&
|
|
2443
|
+
(value.includes('\n') ||
|
|
2444
|
+
['message', 'task', 'question', 'description', 'output', 'text'].includes(label));
|
|
2445
|
+
if (isTextBlock) {
|
|
2446
|
+
return [`${indent}${label}:`, value as string, ''];
|
|
2447
|
+
}
|
|
2448
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
2449
|
+
return [`${indent}${label}:`, ...formatHumanRecord(value, `${indent} `)];
|
|
2450
|
+
}
|
|
2451
|
+
if (Array.isArray(value)) {
|
|
2452
|
+
if (value.length === 0) return [`${indent}${label}: []`];
|
|
2453
|
+
return [
|
|
2454
|
+
`${indent}${label}:`,
|
|
2455
|
+
...value.flatMap(item => {
|
|
2456
|
+
if (item && typeof item === 'object' && !Array.isArray(item)) {
|
|
2457
|
+
const entries = Object.entries(item);
|
|
2458
|
+
if (entries.length === 0) return [`${indent} -`];
|
|
2459
|
+
const [[firstKey, firstValue], ...rest] = entries;
|
|
2460
|
+
const firstLines = formatHumanField(humanizeKey(firstKey), firstValue, `${indent} `);
|
|
2461
|
+
const firstLine = firstLines.shift() ?? `${indent} ${humanizeKey(firstKey)}:`;
|
|
2462
|
+
return [
|
|
2463
|
+
`${indent} - ${firstLine.trimStart()}`,
|
|
2464
|
+
...firstLines,
|
|
2465
|
+
...rest.flatMap(([key, value]) =>
|
|
2466
|
+
formatHumanField(humanizeKey(key), value, `${indent} `)
|
|
2467
|
+
),
|
|
2468
|
+
];
|
|
2469
|
+
}
|
|
2470
|
+
return [`${indent} - ${formatHumanScalar(item)}`];
|
|
2471
|
+
}),
|
|
2472
|
+
];
|
|
2473
|
+
}
|
|
2474
|
+
return [`${indent}${label}: ${formatHumanScalar(value)}`];
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
function formatHumanScalar(value: unknown): string {
|
|
2478
|
+
if (value === null || value === undefined) return 'null';
|
|
2479
|
+
if (typeof value === 'boolean') return value ? 'yes' : 'no';
|
|
2480
|
+
return String(value);
|
|
2481
|
+
}
|
|
2482
|
+
|
|
2483
|
+
function humanizeKey(key: string): string {
|
|
2484
|
+
return key
|
|
2485
|
+
.replace(/([a-z])([A-Z])/g, '$1 $2')
|
|
2486
|
+
.replace(/[_-]+/g, ' ')
|
|
2487
|
+
.toLowerCase();
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
export function styleExpandedToolResult(
|
|
2491
|
+
text: string,
|
|
2492
|
+
theme: any,
|
|
2493
|
+
options: { boldFields?: string[] } = {}
|
|
2494
|
+
): string {
|
|
2495
|
+
// A raw text field (notably `message`) is deliberately left untouched. In
|
|
2496
|
+
// particular, lines such as `Status: pending` inside the message are data,
|
|
2497
|
+
// not human-readable field labels. The formatter emits a blank separator
|
|
2498
|
+
// after these blocks, which gives us an unambiguous end marker while keeping
|
|
2499
|
+
// the block flat and copy-friendly.
|
|
2500
|
+
let rawBlock = false;
|
|
2501
|
+
return text
|
|
2502
|
+
.split('\n')
|
|
2503
|
+
.map(line => {
|
|
2504
|
+
if (/^(call|return)$/.test(line)) {
|
|
2505
|
+
rawBlock = false;
|
|
2506
|
+
return theme.bold(line);
|
|
2507
|
+
}
|
|
2508
|
+
if (rawBlock) {
|
|
2509
|
+
if (line === '') rawBlock = false;
|
|
2510
|
+
return theme.fg('toolOutput', line);
|
|
2511
|
+
}
|
|
2512
|
+
const field = line.match(/^(\s*)(-\s+)?([A-Za-z][A-Za-z0-9 _-]*):(\s*)(.*)$/);
|
|
2513
|
+
if (field) {
|
|
2514
|
+
const isRawField =
|
|
2515
|
+
field[5] === '' &&
|
|
2516
|
+
['message', 'task', 'question', 'description', 'output', 'actions', 'text'].includes(
|
|
2517
|
+
field[3].toLowerCase()
|
|
2518
|
+
);
|
|
2519
|
+
rawBlock = isRawField;
|
|
2520
|
+
const label = options.boldFields?.some(
|
|
2521
|
+
name => name.toLowerCase() === field[3].toLowerCase()
|
|
2522
|
+
)
|
|
2523
|
+
? theme.bold(`${field[3]}:`)
|
|
2524
|
+
: theme.fg('accent', `${field[3]}:`);
|
|
2525
|
+
return field[1] + (field[2] ?? '') + label + field[4] + theme.fg('toolOutput', field[5]);
|
|
2526
|
+
}
|
|
2527
|
+
return theme.fg('toolOutput', line);
|
|
2528
|
+
})
|
|
2529
|
+
.join('\n');
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
function renderToolResult(result: any, options: { expanded?: boolean }, theme: any, context: any) {
|
|
2533
|
+
const text = result.content[0];
|
|
2534
|
+
const body = text?.type === 'text' ? (text.text ?? '') : '';
|
|
2535
|
+
const expanded = options?.expanded ?? false;
|
|
2536
|
+
let rendered: string;
|
|
2537
|
+
if (!expanded && body.includes('\n')) {
|
|
2538
|
+
const firstLine = body.split('\n')[0];
|
|
2539
|
+
rendered =
|
|
2540
|
+
theme.fg('accent', firstLine) +
|
|
2541
|
+
`\n${theme.fg('muted', `… +${body.split('\n').length - 1} more lines (Ctrl+O to expand)`)}`;
|
|
2542
|
+
} else {
|
|
2543
|
+
rendered = theme.fg('toolOutput', body || '(no output)');
|
|
2544
|
+
}
|
|
2545
|
+
const component = reusableText(context.lastComponent);
|
|
2546
|
+
component.setText(rendered);
|
|
2547
|
+
return component;
|
|
2548
|
+
}
|