@howaboua/pi-shepherdr 0.1.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.
@@ -0,0 +1,218 @@
1
+ import {
2
+ type ExtensionAPI,
3
+ type ExtensionContext,
4
+ getMarkdownTheme,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
7
+ import { activityTask } from "./activity.js";
8
+ import type {
9
+ LatestAssistant,
10
+ MonitoredAgent,
11
+ PaneInfo,
12
+ SettledAgentStatus,
13
+ } from "./types.js";
14
+
15
+ const AGENT_EVENT_MESSAGE_TYPE = "herdr-agent-event";
16
+
17
+ function xml(value: string): string {
18
+ return value
19
+ .replaceAll("&", "&")
20
+ .replaceAll("<", "&lt;")
21
+ .replaceAll(">", "&gt;")
22
+ .replaceAll('"', "&quot;")
23
+ .replaceAll("'", "&apos;");
24
+ }
25
+
26
+ interface AgentEventLabels {
27
+ tab?: string;
28
+ workspace?: string;
29
+ }
30
+
31
+ interface AgentEventOptions {
32
+ agent: PaneInfo;
33
+ blockedMessage?: string;
34
+ labels: AgentEventLabels;
35
+ record: MonitoredAgent;
36
+ reply?: LatestAssistant;
37
+ status: SettledAgentStatus;
38
+ }
39
+
40
+ interface AgentEventDetails {
41
+ blockedOn?: string;
42
+ cwd?: string;
43
+ name?: string;
44
+ paneId: string;
45
+ response?: string;
46
+ state: "blocked" | "failed" | "finished";
47
+ tab?: string;
48
+ task?: string;
49
+ workspace?: string;
50
+ }
51
+
52
+ function operatorHint(paneId: string): string {
53
+ return `Inspect first with \`herdr agent read ${paneId} --source visible\`; respond with \`herdr agent prompt ${paneId} "<text>"\` or use \`herdr agent send-keys ${paneId} <keys>\` for interactive controls.`;
54
+ }
55
+
56
+ function eventDetails(value: unknown): AgentEventDetails | undefined {
57
+ if (typeof value !== "object" || value === null) return undefined;
58
+ const details = value as Record<string, unknown>;
59
+ if (
60
+ typeof details["paneId"] !== "string" ||
61
+ (details["state"] !== "blocked" &&
62
+ details["state"] !== "failed" &&
63
+ details["state"] !== "finished")
64
+ ) {
65
+ return undefined;
66
+ }
67
+ const optional = (field: keyof AgentEventDetails) =>
68
+ typeof details[field] === "string"
69
+ ? { [field]: details[field] as string }
70
+ : {};
71
+ return {
72
+ paneId: details["paneId"],
73
+ state: details["state"],
74
+ ...optional("blockedOn"),
75
+ ...optional("cwd"),
76
+ ...optional("name"),
77
+ ...optional("response"),
78
+ ...optional("tab"),
79
+ ...optional("task"),
80
+ ...optional("workspace"),
81
+ };
82
+ }
83
+
84
+ function agentEvent(options: AgentEventOptions): {
85
+ content: string;
86
+ details: AgentEventDetails;
87
+ } {
88
+ const { agent, blockedMessage, labels, record, reply, status } = options;
89
+ const task = activityTask(record.activity);
90
+ const blocked = status === "blocked";
91
+ const failed = !blocked && reply?.stopReason === "error";
92
+ const cwd = agent.foreground_cwd ?? agent.cwd ?? record.cwd;
93
+ const tag = blocked
94
+ ? "herdr_agent_blocked"
95
+ : failed
96
+ ? "herdr_agent_failed"
97
+ : "herdr_agent_result";
98
+ const attributes = [
99
+ `pane="${xml(agent.pane_id)}"`,
100
+ record.name ? `name="${xml(record.name)}"` : undefined,
101
+ cwd ? `directory="${xml(cwd)}"` : undefined,
102
+ ]
103
+ .filter(Boolean)
104
+ .join(" ");
105
+ const lines = [`<${tag} ${attributes}>`];
106
+ if (task) lines.push(`<task>${xml(task)}</task>`);
107
+ if (blockedMessage) {
108
+ lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
109
+ }
110
+ if (blocked) {
111
+ lines.push(
112
+ `<operator_hint>${xml(operatorHint(agent.pane_id))}</operator_hint>`,
113
+ );
114
+ }
115
+ if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
116
+ lines.push(`</${tag}>`);
117
+
118
+ return {
119
+ content: lines.join("\n"),
120
+ details: {
121
+ paneId: agent.pane_id,
122
+ state: blocked ? "blocked" : failed ? "failed" : "finished",
123
+ ...(record.name ? { name: record.name } : {}),
124
+ ...(cwd ? { cwd } : {}),
125
+ ...(labels.workspace ? { workspace: labels.workspace } : {}),
126
+ ...(labels.tab ? { tab: labels.tab } : {}),
127
+ ...(task ? { task } : {}),
128
+ ...(blockedMessage ? { blockedOn: blockedMessage } : {}),
129
+ ...(reply ? { response: reply.text } : {}),
130
+ },
131
+ };
132
+ }
133
+
134
+ export function injectAgentEvent(
135
+ pi: ExtensionAPI,
136
+ ctx: ExtensionContext,
137
+ options: AgentEventOptions,
138
+ ): void {
139
+ const message = agentEvent(options);
140
+ const delivery = ctx.isIdle()
141
+ ? { triggerTurn: true, deliverAs: "steer" as const }
142
+ : { deliverAs: "steer" as const };
143
+ pi.sendMessage(
144
+ {
145
+ customType: AGENT_EVENT_MESSAGE_TYPE,
146
+ content: message.content,
147
+ details: message.details,
148
+ display: true,
149
+ },
150
+ delivery,
151
+ );
152
+ }
153
+
154
+ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
155
+ pi.registerMessageRenderer<AgentEventDetails>(
156
+ AGENT_EVENT_MESSAGE_TYPE,
157
+ (message, { expanded, outputPad }, theme) => {
158
+ const details = eventDetails(message.details);
159
+ if (!details) {
160
+ const box = new Box(outputPad, 1, (value) =>
161
+ theme.bg("customMessageBg", value),
162
+ );
163
+ box.addChild(
164
+ new Text(
165
+ typeof message.content === "string"
166
+ ? message.content
167
+ : "Herdr agent event unavailable",
168
+ 0,
169
+ 0,
170
+ ),
171
+ );
172
+ return box;
173
+ }
174
+ const blocked = details?.state === "blocked";
175
+ const failed = details?.state === "failed";
176
+ const identity = details?.name
177
+ ? `${details.name} (${details.paneId})`
178
+ : (details?.paneId ?? "unknown");
179
+ const title = theme.fg(
180
+ blocked || failed ? "error" : "success",
181
+ `Herdr agent ${identity} · ${blocked ? "blocked" : failed ? "failed" : "finished"}`,
182
+ );
183
+ const location = [details?.workspace, details?.tab]
184
+ .filter(Boolean)
185
+ .join(" / ");
186
+ const metadata = [location, details?.cwd].filter(Boolean).join(" · ");
187
+ const box = new Box(outputPad, 1, (value) =>
188
+ theme.bg("customMessageBg", value),
189
+ );
190
+ box.addChild(new Text(title, 0, 0));
191
+ if (metadata) box.addChild(new Text(theme.fg("dim", metadata), 0, 0));
192
+ if (blocked) {
193
+ box.addChild(new Spacer(1));
194
+ box.addChild(
195
+ new Text(
196
+ theme.fg(
197
+ "warning",
198
+ details?.blockedOn ?? "Agent needs input or approval",
199
+ ),
200
+ 0,
201
+ 0,
202
+ ),
203
+ );
204
+ }
205
+ if (expanded && details?.task) {
206
+ box.addChild(new Spacer(1));
207
+ box.addChild(new Text(theme.fg("muted", "Task"), 0, 0));
208
+ box.addChild(new Markdown(details.task, 0, 0, getMarkdownTheme()));
209
+ }
210
+ if (details?.response) {
211
+ box.addChild(new Spacer(1));
212
+ box.addChild(new Text(theme.fg("muted", "Response"), 0, 0));
213
+ box.addChild(new Markdown(details.response, 0, 0, getMarkdownTheme()));
214
+ }
215
+ return box;
216
+ },
217
+ );
218
+ }
@@ -0,0 +1,84 @@
1
+ import { isAgentStatus } from "./activity.js";
2
+ import type { AgentStatus, HerdrEvent } from "./types.js";
3
+
4
+ export type MonitorEvent =
5
+ | { paneId: string; type: "closed" }
6
+ | {
7
+ pane: { pane_id: string; tab_id?: string; workspace_id?: string };
8
+ previousPaneId: string;
9
+ type: "moved";
10
+ }
11
+ | {
12
+ blockedMessage?: string;
13
+ paneId: string;
14
+ status: AgentStatus;
15
+ type: "status";
16
+ };
17
+
18
+ function blockedReason(data: Record<string, unknown>): string | undefined {
19
+ const labels = data["state_labels"];
20
+ if (
21
+ typeof labels === "object" &&
22
+ labels !== null &&
23
+ "blocked" in labels &&
24
+ typeof labels.blocked === "string"
25
+ ) {
26
+ return labels.blocked;
27
+ }
28
+ return typeof data["title"] === "string" ? data["title"] : undefined;
29
+ }
30
+
31
+ export function parseMonitorEvent(event: HerdrEvent): MonitorEvent | undefined {
32
+ const paneId = event.data["pane_id"];
33
+ if (event.event === "pane.closed") {
34
+ if (typeof paneId !== "string") {
35
+ throw new Error("Herdr pane.closed event has no pane_id");
36
+ }
37
+ return { paneId, type: "closed" };
38
+ }
39
+ if (event.event === "pane.agent_status_changed") {
40
+ const status = event.data["agent_status"];
41
+ if (typeof paneId !== "string" || !isAgentStatus(status)) {
42
+ throw new Error("Herdr pane.agent_status_changed event is invalid");
43
+ }
44
+ const blockedMessage =
45
+ status === "blocked" ? blockedReason(event.data) : undefined;
46
+ return {
47
+ paneId,
48
+ status,
49
+ type: "status",
50
+ ...(blockedMessage ? { blockedMessage } : {}),
51
+ };
52
+ }
53
+ if (event.event !== "pane.moved") return undefined;
54
+ const previousPaneId = event.data["previous_pane_id"];
55
+ const pane = event.data["pane"];
56
+ if (
57
+ typeof previousPaneId !== "string" ||
58
+ typeof pane !== "object" ||
59
+ pane === null ||
60
+ !("pane_id" in pane) ||
61
+ typeof pane.pane_id !== "string"
62
+ ) {
63
+ throw new Error("Herdr pane.moved event is invalid");
64
+ }
65
+ if (
66
+ ("workspace_id" in pane && typeof pane.workspace_id !== "string") ||
67
+ ("tab_id" in pane && typeof pane.tab_id !== "string")
68
+ ) {
69
+ throw new Error("Herdr pane.moved event has invalid location IDs");
70
+ }
71
+ return {
72
+ pane: {
73
+ pane_id: pane.pane_id,
74
+ ...("workspace_id" in pane && typeof pane.workspace_id === "string"
75
+ ? { workspace_id: pane.workspace_id }
76
+ : {}),
77
+ ...("tab_id" in pane && typeof pane.tab_id === "string"
78
+ ? { tab_id: pane.tab_id }
79
+ : {}),
80
+ },
81
+ previousPaneId,
82
+ type: "moved",
83
+ };
84
+ }
@@ -0,0 +1,135 @@
1
+ import type { HerdrClient } from "./herdr-client.js";
2
+ import type { HerdrEvent } from "./types.js";
3
+
4
+ interface Subscription {
5
+ generation: number;
6
+ unsubscribe: () => void;
7
+ }
8
+
9
+ interface MonitorEventsOptions {
10
+ client: HerdrClient;
11
+ onEvent: (event: HerdrEvent) => void;
12
+ onReconnect: () => Promise<void>;
13
+ onWarning: (message: string) => void;
14
+ targets: () => string[];
15
+ }
16
+
17
+ export class MonitorEvents {
18
+ private readonly options: MonitorEventsOptions;
19
+ private active = false;
20
+ private generation = 0;
21
+ private readonly live = new Set<number>();
22
+ private reconnectTimer: NodeJS.Timeout | undefined;
23
+ private subscription: Subscription | undefined;
24
+ private warningShown = false;
25
+
26
+ constructor(options: MonitorEventsOptions) {
27
+ this.options = options;
28
+ }
29
+
30
+ async start(): Promise<void> {
31
+ this.active = true;
32
+ await this.refresh();
33
+ }
34
+
35
+ stop(): void {
36
+ this.active = false;
37
+ this.generation += 1;
38
+ this.live.clear();
39
+ this.subscription?.unsubscribe();
40
+ this.subscription = undefined;
41
+ this.warningShown = false;
42
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
43
+ this.reconnectTimer = undefined;
44
+ }
45
+
46
+ async refresh(): Promise<void> {
47
+ const generation = ++this.generation;
48
+ const previous = this.subscription;
49
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
50
+ this.reconnectTimer = undefined;
51
+ const targets = this.options.targets();
52
+ if (!this.active || targets.length === 0) {
53
+ this.close(previous);
54
+ this.subscription = undefined;
55
+ return;
56
+ }
57
+
58
+ const subscriptions = [
59
+ ...targets.map((paneId) => ({
60
+ type: "pane.agent_status_changed",
61
+ pane_id: paneId,
62
+ })),
63
+ { type: "pane.moved" },
64
+ { type: "pane.closed" },
65
+ ];
66
+ this.live.add(generation);
67
+ try {
68
+ const unsubscribe = await this.options.client.subscribe(
69
+ subscriptions,
70
+ (event) => {
71
+ if (this.active && this.live.has(generation)) {
72
+ this.options.onEvent(event);
73
+ }
74
+ },
75
+ (error) => {
76
+ this.live.delete(generation);
77
+ if (error)
78
+ this.warn(`Herdr monitoring disconnected: ${error.message}`);
79
+ this.scheduleReconnect(generation, true);
80
+ },
81
+ );
82
+ if (
83
+ !this.active ||
84
+ generation !== this.generation ||
85
+ !this.live.has(generation)
86
+ ) {
87
+ this.live.delete(generation);
88
+ unsubscribe();
89
+ return;
90
+ }
91
+ this.close(previous);
92
+ this.subscription = { generation, unsubscribe };
93
+ this.warningShown = false;
94
+ } catch (error) {
95
+ this.live.delete(generation);
96
+ if (!this.active || generation !== this.generation) return;
97
+ this.warn(
98
+ `Herdr monitoring unavailable: ${error instanceof Error ? error.message : String(error)}`,
99
+ );
100
+ this.scheduleReconnect(generation, false);
101
+ }
102
+ }
103
+
104
+ private close(subscription: Subscription | undefined): void {
105
+ if (!subscription) return;
106
+ this.live.delete(subscription.generation);
107
+ subscription.unsubscribe();
108
+ }
109
+
110
+ private warn(message: string): void {
111
+ if (this.warningShown) return;
112
+ this.warningShown = true;
113
+ this.options.onWarning(message);
114
+ }
115
+
116
+ private scheduleReconnect(generation: number, disconnected: boolean): void {
117
+ if (!this.active || generation !== this.generation) return;
118
+ if (disconnected && this.subscription?.generation === generation) {
119
+ this.subscription = undefined;
120
+ }
121
+ this.reconnectTimer = setTimeout(() => {
122
+ this.reconnectTimer = undefined;
123
+ void this.options
124
+ .onReconnect()
125
+ .then(() => this.refresh())
126
+ .catch((error) => {
127
+ this.warn(
128
+ `Herdr monitoring reconnect failed: ${error instanceof Error ? error.message : String(error)}`,
129
+ );
130
+ this.scheduleReconnect(generation, false);
131
+ });
132
+ }, 1_000);
133
+ this.reconnectTimer.unref();
134
+ }
135
+ }
@@ -0,0 +1,145 @@
1
+ import { isAgentStatus, sameAgentActivity } from "./activity.js";
2
+ import type {
3
+ AgentActivity,
4
+ MonitoredAgent,
5
+ PaneInfo,
6
+ StableAgentActivity,
7
+ } from "./types.js";
8
+
9
+ function optionalString(
10
+ value: Record<string, unknown>,
11
+ field: string,
12
+ ): string | undefined | false {
13
+ const candidate = value[field];
14
+ return candidate === undefined || typeof candidate === "string"
15
+ ? candidate
16
+ : false;
17
+ }
18
+
19
+ function stableActivity(value: unknown): StableAgentActivity | undefined {
20
+ if (typeof value !== "object" || value === null) return undefined;
21
+ const activity = value as Record<string, unknown>;
22
+ if (
23
+ activity["phase"] === "settled" &&
24
+ isAgentStatus(activity["status"]) &&
25
+ activity["status"] !== "working"
26
+ ) {
27
+ return { phase: "settled", status: activity["status"] };
28
+ }
29
+ if (activity["phase"] !== "working") return undefined;
30
+ const task = optionalString(activity, "task");
31
+ return task === false
32
+ ? undefined
33
+ : { phase: "working", ...(task ? { task } : {}) };
34
+ }
35
+
36
+ function parsedActivity(value: unknown): AgentActivity | undefined {
37
+ const stable = stableActivity(value);
38
+ if (stable) return stable;
39
+ if (typeof value !== "object" || value === null) return undefined;
40
+ const activity = value as Record<string, unknown>;
41
+ const previous = stableActivity(activity["previous"]);
42
+ if (
43
+ activity["phase"] !== "submitting" ||
44
+ typeof activity["attemptId"] !== "string" ||
45
+ typeof activity["task"] !== "string" ||
46
+ !previous
47
+ ) {
48
+ return undefined;
49
+ }
50
+ return {
51
+ attemptId: activity["attemptId"],
52
+ phase: "submitting",
53
+ previous,
54
+ task: activity["task"],
55
+ };
56
+ }
57
+
58
+ function legacyActivity(
59
+ record: Record<string, unknown>,
60
+ ): AgentActivity | undefined {
61
+ if (!isAgentStatus(record["lastStatus"])) return undefined;
62
+ const task = optionalString(record, "task");
63
+ if (task === false) return undefined;
64
+ if (record["lastStatus"] === "working") {
65
+ return { phase: "working", ...(task ? { task } : {}) };
66
+ }
67
+ if (!task) return { phase: "settled", status: record["lastStatus"] };
68
+ return {
69
+ attemptId: `restored:${String(record["terminalId"])}`,
70
+ phase: "submitting",
71
+ previous: { phase: "settled", status: record["lastStatus"] },
72
+ task,
73
+ };
74
+ }
75
+
76
+ export function parseMonitoredAgent(
77
+ value: unknown,
78
+ ): MonitoredAgent | undefined {
79
+ if (typeof value !== "object" || value === null) return undefined;
80
+ const record = value as Record<string, unknown>;
81
+ if (
82
+ typeof record["paneId"] !== "string" ||
83
+ typeof record["terminalId"] !== "string" ||
84
+ typeof record["workspaceId"] !== "string" ||
85
+ typeof record["tabId"] !== "string"
86
+ ) {
87
+ return undefined;
88
+ }
89
+ const cwd = optionalString(record, "cwd");
90
+ const lastAssistantId = optionalString(record, "lastAssistantId");
91
+ const name = optionalString(record, "name");
92
+ const activity = parsedActivity(record["activity"]) ?? legacyActivity(record);
93
+ if (
94
+ cwd === false ||
95
+ lastAssistantId === false ||
96
+ name === false ||
97
+ !activity
98
+ ) {
99
+ return undefined;
100
+ }
101
+ return {
102
+ activity,
103
+ paneId: record["paneId"],
104
+ terminalId: record["terminalId"],
105
+ workspaceId: record["workspaceId"],
106
+ tabId: record["tabId"],
107
+ ...(cwd ? { cwd } : {}),
108
+ ...(lastAssistantId ? { lastAssistantId } : {}),
109
+ ...(name ? { name } : {}),
110
+ };
111
+ }
112
+
113
+ export function recordForPanel(
114
+ panel: PaneInfo,
115
+ activity: AgentActivity,
116
+ lastAssistantId?: string,
117
+ ): MonitoredAgent {
118
+ const cwd = panel.foreground_cwd ?? panel.cwd;
119
+ return {
120
+ activity,
121
+ paneId: panel.pane_id,
122
+ terminalId: panel.terminal_id,
123
+ workspaceId: panel.workspace_id,
124
+ tabId: panel.tab_id,
125
+ ...(panel.name ? { name: panel.name } : {}),
126
+ ...(cwd ? { cwd } : {}),
127
+ ...(lastAssistantId ? { lastAssistantId } : {}),
128
+ };
129
+ }
130
+
131
+ export function sameMonitorRecord(
132
+ left: MonitoredAgent,
133
+ right: MonitoredAgent,
134
+ ): boolean {
135
+ return (
136
+ left.paneId === right.paneId &&
137
+ left.terminalId === right.terminalId &&
138
+ left.workspaceId === right.workspaceId &&
139
+ left.tabId === right.tabId &&
140
+ left.cwd === right.cwd &&
141
+ left.name === right.name &&
142
+ left.lastAssistantId === right.lastAssistantId &&
143
+ sameAgentActivity(left.activity, right.activity)
144
+ );
145
+ }