@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,204 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { activityTask, isSettledStatus } from "./activity.js";
6
+ import { getAgent, getSnapshot, sessionPath } from "./herdr.js";
7
+ import type { HerdrClient } from "./herdr-client.js";
8
+ import { injectAgentEvent } from "./messages.js";
9
+ import type { MonitorState } from "./monitor-state.js";
10
+ import { SessionReader } from "./session-reader.js";
11
+ import type {
12
+ LatestAssistant,
13
+ MonitoredAgent,
14
+ PaneInfo,
15
+ SettledAgentStatus,
16
+ } from "./types.js";
17
+
18
+ interface SettlementLabels {
19
+ tab?: string;
20
+ workspace?: string;
21
+ }
22
+
23
+ export interface CollectedSettlement {
24
+ agent: PaneInfo;
25
+ labels: SettlementLabels;
26
+ reply?: LatestAssistant;
27
+ status: SettledAgentStatus;
28
+ }
29
+
30
+ export interface SettlementRequest {
31
+ blockedMessage?: string;
32
+ record: MonitoredAgent;
33
+ requireNewReply?: boolean;
34
+ status: SettledAgentStatus;
35
+ task?: string;
36
+ }
37
+
38
+ export interface SettlementLifecycle {
39
+ context: ExtensionContext;
40
+ generation: number;
41
+ isCurrent: () => boolean;
42
+ }
43
+
44
+ export class SettlementCollector {
45
+ private readonly client: HerdrClient;
46
+ private readonly reader = new SessionReader();
47
+
48
+ constructor(client: HerdrClient) {
49
+ this.client = client;
50
+ }
51
+
52
+ latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
53
+ return this.reader.latest(sessionPath(panel));
54
+ }
55
+
56
+ async collect(
57
+ record: MonitoredAgent,
58
+ ): Promise<CollectedSettlement | undefined> {
59
+ const agent = await getAgent(this.client, record.paneId);
60
+ if (agent.terminal_id !== record.terminalId || agent.agent !== "pi") {
61
+ return undefined;
62
+ }
63
+ const [current, snapshot] = await Promise.all([
64
+ getAgent(this.client, record.paneId),
65
+ getSnapshot(this.client),
66
+ ]);
67
+ if (
68
+ current.terminal_id !== record.terminalId ||
69
+ current.agent !== "pi" ||
70
+ !isSettledStatus(current.agent_status)
71
+ ) {
72
+ return undefined;
73
+ }
74
+ const reply = await this.latest(current);
75
+ const workspace = snapshot.workspaces.find(
76
+ (candidate) => candidate.workspace_id === current.workspace_id,
77
+ )?.label;
78
+ const tab = snapshot.tabs.find(
79
+ (candidate) => candidate.tab_id === current.tab_id,
80
+ )?.label;
81
+ return {
82
+ agent: current,
83
+ labels: {
84
+ ...(workspace ? { workspace } : {}),
85
+ ...(tab ? { tab } : {}),
86
+ },
87
+ ...(reply ? { reply } : {}),
88
+ status: current.agent_status,
89
+ };
90
+ }
91
+ }
92
+
93
+ export class SettlementReporter {
94
+ private readonly collector: SettlementCollector;
95
+ private readonly persist: () => void;
96
+ private readonly pi: ExtensionAPI;
97
+ private readonly reporting = new Set<string>();
98
+ private readonly retries = new Map<string, NodeJS.Timeout>();
99
+ private readonly state: MonitorState;
100
+
101
+ constructor(
102
+ pi: ExtensionAPI,
103
+ client: HerdrClient,
104
+ state: MonitorState,
105
+ persist: () => void,
106
+ ) {
107
+ this.pi = pi;
108
+ this.collector = new SettlementCollector(client);
109
+ this.state = state;
110
+ this.persist = persist;
111
+ }
112
+
113
+ latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
114
+ return this.collector.latest(panel);
115
+ }
116
+
117
+ stop(): void {
118
+ this.reporting.clear();
119
+ for (const timer of this.retries.values()) clearTimeout(timer);
120
+ this.retries.clear();
121
+ }
122
+
123
+ async report(
124
+ lifecycle: SettlementLifecycle,
125
+ request: SettlementRequest,
126
+ retried = false,
127
+ ): Promise<void> {
128
+ const task = request.task ?? activityTask(request.record.activity);
129
+ const key = `${lifecycle.generation}:${request.record.terminalId}`;
130
+ if (this.reporting.has(key)) return;
131
+ this.reporting.add(key);
132
+ try {
133
+ const settlement = await this.collector.collect(request.record);
134
+ if (!settlement || !lifecycle.isCurrent()) return;
135
+ const current = this.state.byPane(settlement.agent.pane_id);
136
+ if (!current || current.terminalId !== request.record.terminalId) return;
137
+ const newReply =
138
+ settlement.reply?.id !== current.lastAssistantId
139
+ ? settlement.reply
140
+ : undefined;
141
+ if (request.requireNewReply && !newReply) return;
142
+ if (activityTask(current.activity) !== task) return;
143
+ injectAgentEvent(this.pi, lifecycle.context, {
144
+ agent: settlement.agent,
145
+ ...(settlement.status === request.status && request.blockedMessage
146
+ ? { blockedMessage: request.blockedMessage }
147
+ : {}),
148
+ labels: settlement.labels,
149
+ record: current,
150
+ ...(newReply ? { reply: newReply } : {}),
151
+ status: settlement.status,
152
+ });
153
+ if (
154
+ this.state.complete(
155
+ current.terminalId,
156
+ settlement.status,
157
+ task,
158
+ settlement.reply?.id,
159
+ )
160
+ ) {
161
+ this.clearRetry(current.terminalId);
162
+ this.persist();
163
+ }
164
+ } catch (error) {
165
+ lifecycle.context.ui.notify(
166
+ `Could not collect ${request.record.name ?? request.record.paneId}: ${error instanceof Error ? error.message : String(error)}`,
167
+ "warning",
168
+ );
169
+ if (!retried) {
170
+ this.retry(lifecycle, task ? { ...request, task } : request);
171
+ }
172
+ } finally {
173
+ this.reporting.delete(key);
174
+ }
175
+ }
176
+
177
+ private clearRetry(terminalId: string): void {
178
+ const retry = this.retries.get(terminalId);
179
+ if (retry) clearTimeout(retry);
180
+ this.retries.delete(terminalId);
181
+ }
182
+
183
+ private retry(
184
+ lifecycle: SettlementLifecycle,
185
+ request: SettlementRequest,
186
+ ): void {
187
+ if (
188
+ !lifecycle.isCurrent() ||
189
+ !this.state.byTerminal(request.record.terminalId) ||
190
+ this.retries.has(request.record.terminalId)
191
+ ) {
192
+ return;
193
+ }
194
+ const timer = setTimeout(() => {
195
+ this.retries.delete(request.record.terminalId);
196
+ if (!lifecycle.isCurrent()) return;
197
+ const current = this.state.byTerminal(request.record.terminalId);
198
+ if (!current) return;
199
+ void this.report(lifecycle, { ...request, record: current }, true);
200
+ }, 1_000);
201
+ this.retries.set(request.record.terminalId, timer);
202
+ timer.unref();
203
+ }
204
+ }
package/src/tool.ts ADDED
@@ -0,0 +1,195 @@
1
+ import { StringEnum, Type } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import { getSnapshot, resolvePiAgent } from "./herdr.js";
4
+ import {
5
+ START_PLACEMENTS,
6
+ type StartAgentParams,
7
+ startAgent,
8
+ } from "./launch.js";
9
+ import type { AgentMonitor } from "./monitor.js";
10
+ import type { MonitoredAgent, PaneInfo, SessionSnapshot } from "./types.js";
11
+
12
+ const ACTIONS = ["list", "start", "watch", "unwatch", "send"] as const;
13
+ const FIRE_AND_FORGET =
14
+ "Do not poll; completion or blockage will be delivered automatically";
15
+
16
+ type ToolParams = StartAgentParams & {
17
+ action: (typeof ACTIONS)[number];
18
+ target?: string;
19
+ };
20
+
21
+ function required(value: string | undefined, field: string): string {
22
+ if (!value?.trim()) throw new Error(`${field} is required for this action`);
23
+ return value.trim();
24
+ }
25
+
26
+ function result(value: Record<string, unknown>) {
27
+ return {
28
+ content: [{ type: "text" as const, text: JSON.stringify(value) }],
29
+ details: value,
30
+ };
31
+ }
32
+
33
+ function labels(snapshot: SessionSnapshot) {
34
+ return {
35
+ workspaces: new Map(
36
+ snapshot.workspaces.map((workspace) => [
37
+ workspace.workspace_id,
38
+ workspace.label,
39
+ ]),
40
+ ),
41
+ tabs: new Map(snapshot.tabs.map((tab) => [tab.tab_id, tab.label])),
42
+ };
43
+ }
44
+
45
+ function compactAgent(
46
+ agent: PaneInfo,
47
+ snapshot: SessionSnapshot,
48
+ monitored: boolean,
49
+ ): Record<string, unknown> {
50
+ const names = labels(snapshot);
51
+ return {
52
+ id: agent.pane_id,
53
+ ...(agent.name ? { name: agent.name } : {}),
54
+ status: agent.agent_status,
55
+ cwd: agent.foreground_cwd ?? agent.cwd ?? null,
56
+ workspace: names.workspaces.get(agent.workspace_id) ?? agent.workspace_id,
57
+ workspaceId: agent.workspace_id,
58
+ tab: names.tabs.get(agent.tab_id) ?? agent.tab_id,
59
+ tabId: agent.tab_id,
60
+ monitored,
61
+ };
62
+ }
63
+
64
+ function findRecord(
65
+ monitor: AgentMonitor,
66
+ target: string,
67
+ ): MonitoredAgent | undefined {
68
+ const matches = monitor
69
+ .list()
70
+ .filter((agent) => agent.paneId === target || agent.name === target);
71
+ if (matches.length > 1) {
72
+ throw new Error(
73
+ `monitored agent name ${JSON.stringify(target)} is ambiguous`,
74
+ );
75
+ }
76
+ return matches[0];
77
+ }
78
+
79
+ export function registerHerdrAgentsTool(
80
+ pi: ExtensionAPI,
81
+ getMonitor: () => AgentMonitor,
82
+ ): void {
83
+ pi.registerTool({
84
+ name: "herdr_agents",
85
+ label: "Shepherdr",
86
+ description:
87
+ "Herdr Pi agents. start needs name and placement; new_tab needs workspace; pane placement needs pane ID. watch/unwatch need target; send needs target and prompt.",
88
+ promptGuidelines: [
89
+ "Act as an orchestrator: delegate project implementation, synthesize worker results, and report them to the user. Work directly only when explicitly asked or for configuration, documentation, and routine operations in the current working directory",
90
+ ],
91
+ parameters: Type.Object({
92
+ action: StringEnum(ACTIONS),
93
+ target: Type.Optional(
94
+ Type.String({ description: "Agent name or pane ID" }),
95
+ ),
96
+ name: Type.Optional(
97
+ Type.String({
98
+ description: "Agent name; [a-z][a-z0-9_-]{0,31}",
99
+ }),
100
+ ),
101
+ label: Type.Optional(
102
+ Type.String({
103
+ description:
104
+ "Pi session label; also labels a new tab; defaults to name",
105
+ }),
106
+ ),
107
+ placement: Type.Optional(StringEnum(START_PLACEMENTS)),
108
+ workspace: Type.Optional(
109
+ Type.String({ description: "Workspace label or ID" }),
110
+ ),
111
+ pane: Type.Optional(Type.String()),
112
+ cwd: Type.Optional(
113
+ Type.String({
114
+ description:
115
+ "Working directory for a new location; defaults to current",
116
+ }),
117
+ ),
118
+ prompt: Type.Optional(
119
+ Type.String({
120
+ description: "Initial task (start) or message (send)",
121
+ }),
122
+ ),
123
+ }),
124
+ executionMode: "sequential",
125
+ async execute(_toolCallId, params: ToolParams, _signal, _onUpdate, ctx) {
126
+ const monitor = getMonitor();
127
+ const client = monitor.client;
128
+ if (params.action === "list") {
129
+ const snapshot = await getSnapshot(client);
130
+ return result({
131
+ agents: snapshot.agents
132
+ .filter(
133
+ (agent) =>
134
+ agent.agent === "pi" &&
135
+ agent.pane_id !== process.env["HERDR_PANE_ID"],
136
+ )
137
+ .map((agent) =>
138
+ compactAgent(agent, snapshot, monitor.isMonitored(agent.pane_id)),
139
+ ),
140
+ workspaces: snapshot.workspaces.map((workspace) => ({
141
+ id: workspace.workspace_id,
142
+ label: workspace.label,
143
+ })),
144
+ });
145
+ }
146
+ if (params.action === "start") {
147
+ const started = await startAgent(client, monitor, params, ctx.cwd);
148
+ return result({
149
+ started: true,
150
+ id: started.id,
151
+ ...(params.prompt?.trim() ? { next: FIRE_AND_FORGET } : {}),
152
+ });
153
+ }
154
+
155
+ const target = required(params.target, "target");
156
+ if (params.action === "unwatch") {
157
+ const record = findRecord(monitor, target);
158
+ if (!record) return result({ unwatched: false, target });
159
+ await monitor.unwatch(record.paneId);
160
+ return result({ unwatched: true, id: record.paneId });
161
+ }
162
+
163
+ const agent = await resolvePiAgent(client, target);
164
+ if (params.action === "watch") {
165
+ await monitor.watch(agent);
166
+ return result({
167
+ watched: true,
168
+ id: agent.pane_id,
169
+ next: FIRE_AND_FORGET,
170
+ });
171
+ }
172
+ if (params.action === "send") {
173
+ const prompt = required(params.prompt, "prompt");
174
+ if (!monitor.isMonitored(agent.pane_id)) await monitor.watch(agent);
175
+ const attempt = monitor.beginWork(agent.pane_id, prompt);
176
+ try {
177
+ await client.request("agent.prompt", {
178
+ target: agent.pane_id,
179
+ text: prompt,
180
+ });
181
+ monitor.acceptWork(attempt);
182
+ } catch (error) {
183
+ await monitor.handleWorkFailure(attempt, error);
184
+ throw error;
185
+ }
186
+ return result({
187
+ sent: true,
188
+ id: agent.pane_id,
189
+ next: FIRE_AND_FORGET,
190
+ });
191
+ }
192
+ throw new Error(`unsupported action ${params.action}`);
193
+ },
194
+ });
195
+ }
package/src/types.ts ADDED
@@ -0,0 +1,78 @@
1
+ export type AgentStatus = "idle" | "working" | "blocked" | "done" | "unknown";
2
+
3
+ export type SettledAgentStatus = Exclude<AgentStatus, "working">;
4
+
5
+ export type StableAgentActivity =
6
+ | { readonly phase: "settled"; readonly status: SettledAgentStatus }
7
+ | { readonly phase: "working"; readonly task?: string };
8
+
9
+ export type AgentActivity =
10
+ | StableAgentActivity
11
+ | {
12
+ readonly attemptId: string;
13
+ readonly phase: "submitting";
14
+ readonly previous: StableAgentActivity;
15
+ readonly task: string;
16
+ };
17
+
18
+ interface AgentSessionInfo {
19
+ agent: string;
20
+ kind: "id" | "path";
21
+ source: string;
22
+ value: string;
23
+ }
24
+
25
+ export interface PaneInfo {
26
+ agent?: string | null;
27
+ agent_session?: AgentSessionInfo | null;
28
+ agent_status: AgentStatus;
29
+ cwd?: string | null;
30
+ foreground_cwd?: string | null;
31
+ interactive_ready?: boolean;
32
+ launch_pending?: boolean;
33
+ name?: string | null;
34
+ pane_id: string;
35
+ tab_id: string;
36
+ terminal_id: string;
37
+ workspace_id: string;
38
+ }
39
+
40
+ interface TabInfo {
41
+ label: string;
42
+ tab_id: string;
43
+ workspace_id: string;
44
+ }
45
+
46
+ export interface WorkspaceInfo {
47
+ label: string;
48
+ workspace_id: string;
49
+ }
50
+
51
+ export interface SessionSnapshot {
52
+ agents: PaneInfo[];
53
+ panes: PaneInfo[];
54
+ tabs: TabInfo[];
55
+ workspaces: WorkspaceInfo[];
56
+ }
57
+
58
+ export interface MonitoredAgent {
59
+ readonly activity: AgentActivity;
60
+ readonly cwd?: string;
61
+ readonly lastAssistantId?: string;
62
+ readonly name?: string;
63
+ readonly paneId: string;
64
+ readonly tabId: string;
65
+ readonly terminalId: string;
66
+ readonly workspaceId: string;
67
+ }
68
+
69
+ export interface LatestAssistant {
70
+ id: string;
71
+ stopReason?: string;
72
+ text: string;
73
+ }
74
+
75
+ export interface HerdrEvent {
76
+ data: Record<string, unknown>;
77
+ event: string;
78
+ }
package/src/widget.ts ADDED
@@ -0,0 +1,75 @@
1
+ import { basename } from "node:path";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { activityStatus } from "./activity.js";
4
+ import type { AgentStatus, MonitoredAgent } from "./types.js";
5
+
6
+ const WIDGET_ID = "herdr-agents";
7
+ const MAX_VISIBLE_AGENTS = 8;
8
+
9
+ function statusAppearance(status: AgentStatus): {
10
+ icon: string;
11
+ tone: "dim" | "error" | "success" | "warning";
12
+ } {
13
+ switch (status) {
14
+ case "working":
15
+ return { icon: "◉", tone: "warning" };
16
+ case "blocked":
17
+ return { icon: "●", tone: "error" };
18
+ case "done":
19
+ return { icon: "✓", tone: "success" };
20
+ case "idle":
21
+ return { icon: "○", tone: "dim" };
22
+ default:
23
+ return { icon: "?", tone: "dim" };
24
+ }
25
+ }
26
+
27
+ function agentLine(ctx: ExtensionContext, agent: MonitoredAgent): string {
28
+ const theme = ctx.ui.theme;
29
+ const status = activityStatus(agent.activity);
30
+ const appearance = statusAppearance(status);
31
+ const name = agent.name ?? agent.paneId;
32
+ const location = agent.cwd ? basename(agent.cwd) : agent.paneId;
33
+ return [
34
+ theme.fg("muted", "│"),
35
+ theme.fg(appearance.tone, appearance.icon),
36
+ theme.fg("accent", name),
37
+ theme.fg(appearance.tone, status),
38
+ theme.fg("dim", `· ${location}`),
39
+ ].join(" ");
40
+ }
41
+
42
+ export function renderAgentWidget(
43
+ ctx: ExtensionContext | undefined,
44
+ agents: MonitoredAgent[],
45
+ ): void {
46
+ if (!ctx?.hasUI) return;
47
+ if (agents.length === 0) {
48
+ ctx.ui.setWidget(WIDGET_ID, undefined);
49
+ return;
50
+ }
51
+ const theme = ctx.ui.theme;
52
+ const ordered = [...agents].sort(
53
+ (left, right) =>
54
+ statusOrder(activityStatus(left.activity)) -
55
+ statusOrder(activityStatus(right.activity)) ||
56
+ (left.name ?? left.paneId).localeCompare(right.name ?? right.paneId),
57
+ );
58
+ const lines = [
59
+ `${theme.fg("accent", "╭─ herdr agents")} ${theme.fg("dim", String(agents.length))}`,
60
+ ...ordered
61
+ .slice(0, MAX_VISIBLE_AGENTS)
62
+ .map((agent) => agentLine(ctx, agent)),
63
+ ];
64
+ if (ordered.length > MAX_VISIBLE_AGENTS) {
65
+ lines.push(
66
+ `${theme.fg("muted", "│")} ${theme.fg("dim", `+${ordered.length - MAX_VISIBLE_AGENTS} more`)}`,
67
+ );
68
+ }
69
+ lines.push(theme.fg("muted", "╰─"));
70
+ ctx.ui.setWidget(WIDGET_ID, lines, { placement: "aboveEditor" });
71
+ }
72
+
73
+ function statusOrder(status: AgentStatus): number {
74
+ return ["blocked", "working", "done", "idle", "unknown"].indexOf(status);
75
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["index.ts", "src/**/*.ts", "tests/**/*.ts"]
4
+ }