@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,295 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ activityForPanel,
4
+ activityTask,
5
+ isSettledStatus,
6
+ sameAgentActivity,
7
+ } from "./activity.js";
8
+ import {
9
+ parseMonitoredAgent,
10
+ recordForPanel,
11
+ sameMonitorRecord,
12
+ } from "./monitor-record.js";
13
+ import type {
14
+ AgentActivity,
15
+ AgentStatus,
16
+ MonitoredAgent,
17
+ PaneInfo,
18
+ SessionSnapshot,
19
+ SettledAgentStatus,
20
+ } from "./types.js";
21
+
22
+ export interface WorkAttempt {
23
+ attemptId: string;
24
+ terminalId: string;
25
+ }
26
+
27
+ interface CompletionCandidate {
28
+ record: MonitoredAgent;
29
+ requireNewReply: boolean;
30
+ status: SettledAgentStatus;
31
+ task?: string;
32
+ }
33
+
34
+ interface ReconcileResult {
35
+ changed: boolean;
36
+ completions: CompletionCandidate[];
37
+ }
38
+
39
+ interface StatusResult {
40
+ changed: boolean;
41
+ completion?: CompletionCandidate;
42
+ }
43
+
44
+ export class MonitorState {
45
+ private readonly agents = new Map<string, MonitoredAgent>();
46
+
47
+ restore(values: unknown[], controllingPaneId?: string): number {
48
+ this.agents.clear();
49
+ let dropped = 0;
50
+ for (const value of values) {
51
+ const record = parseMonitoredAgent(value);
52
+ if (!record) {
53
+ dropped += 1;
54
+ continue;
55
+ }
56
+ if (
57
+ record.paneId !== controllingPaneId &&
58
+ !this.agents.has(record.terminalId) &&
59
+ !this.byPane(record.paneId)
60
+ ) {
61
+ this.agents.set(record.terminalId, record);
62
+ } else if (record.paneId !== controllingPaneId) {
63
+ dropped += 1;
64
+ }
65
+ }
66
+ return dropped;
67
+ }
68
+
69
+ list(): MonitoredAgent[] {
70
+ return [...this.agents.values()];
71
+ }
72
+
73
+ byPane(paneId: string): MonitoredAgent | undefined {
74
+ return this.list().find((record) => record.paneId === paneId);
75
+ }
76
+
77
+ byTerminal(terminalId: string): MonitoredAgent | undefined {
78
+ return this.agents.get(terminalId);
79
+ }
80
+
81
+ isMonitored(paneId: string): boolean {
82
+ return this.byPane(paneId) !== undefined;
83
+ }
84
+
85
+ watch(
86
+ panel: PaneInfo,
87
+ lastAssistantId?: string,
88
+ ): { record: MonitoredAgent; reportCurrent: boolean } {
89
+ const existing =
90
+ this.byTerminal(panel.terminal_id) ?? this.byPane(panel.pane_id);
91
+ const reportCurrent =
92
+ !existing &&
93
+ (panel.agent_status === "done" || panel.agent_status === "blocked");
94
+ const activity = reportCurrent
95
+ ? ({ phase: "working" } as const)
96
+ : (existing?.activity ?? activityForPanel(panel));
97
+ const record = recordForPanel(
98
+ panel,
99
+ activity,
100
+ reportCurrent
101
+ ? undefined
102
+ : (existing?.lastAssistantId ?? lastAssistantId),
103
+ );
104
+ if (existing && existing.terminalId !== record.terminalId) {
105
+ this.agents.delete(existing.terminalId);
106
+ }
107
+ this.agents.set(record.terminalId, record);
108
+ return { record, reportCurrent };
109
+ }
110
+
111
+ removePane(paneId: string): MonitoredAgent | undefined {
112
+ const record = this.byPane(paneId);
113
+ if (record) this.agents.delete(record.terminalId);
114
+ return record;
115
+ }
116
+
117
+ beginWork(paneId: string, task: string): WorkAttempt | undefined {
118
+ const record = this.byPane(paneId);
119
+ if (!record) return undefined;
120
+ if (record.activity.phase === "submitting") {
121
+ throw new Error(
122
+ `prompt submission to ${record.name ?? paneId} is still unresolved`,
123
+ );
124
+ }
125
+ const attempt = {
126
+ attemptId: randomUUID(),
127
+ terminalId: record.terminalId,
128
+ };
129
+ this.agents.set(record.terminalId, {
130
+ ...record,
131
+ activity: {
132
+ attemptId: attempt.attemptId,
133
+ phase: "submitting",
134
+ previous: record.activity,
135
+ task,
136
+ },
137
+ });
138
+ return attempt;
139
+ }
140
+
141
+ acceptWork(attempt: WorkAttempt | undefined): boolean {
142
+ const record = attempt ? this.byTerminal(attempt.terminalId) : undefined;
143
+ if (
144
+ !record ||
145
+ record.activity.phase !== "submitting" ||
146
+ record.activity.attemptId !== attempt?.attemptId
147
+ ) {
148
+ return false;
149
+ }
150
+ this.agents.set(record.terminalId, {
151
+ ...record,
152
+ activity: { phase: "working", task: record.activity.task },
153
+ });
154
+ return true;
155
+ }
156
+
157
+ rejectWork(attempt: WorkAttempt | undefined): boolean {
158
+ const record = attempt ? this.byTerminal(attempt.terminalId) : undefined;
159
+ if (
160
+ !record ||
161
+ record.activity.phase !== "submitting" ||
162
+ record.activity.attemptId !== attempt?.attemptId
163
+ ) {
164
+ return false;
165
+ }
166
+ this.agents.set(record.terminalId, {
167
+ ...record,
168
+ activity: record.activity.previous,
169
+ });
170
+ return true;
171
+ }
172
+
173
+ applyStatus(paneId: string, status: AgentStatus): StatusResult {
174
+ const record = this.byPane(paneId);
175
+ if (!record) return { changed: false };
176
+ if (status === "working") {
177
+ const task = activityTask(record.activity);
178
+ const next: AgentActivity = {
179
+ phase: "working",
180
+ ...(task ? { task } : {}),
181
+ };
182
+ const changed = !sameAgentActivity(record.activity, next);
183
+ this.agents.set(record.terminalId, { ...record, activity: next });
184
+ return { changed };
185
+ }
186
+ if (isSettledStatus(status) && record.activity.phase !== "settled") {
187
+ const task = activityTask(record.activity);
188
+ return {
189
+ changed: false,
190
+ completion: {
191
+ record,
192
+ requireNewReply: record.activity.phase === "submitting",
193
+ status,
194
+ ...(task ? { task } : {}),
195
+ },
196
+ };
197
+ }
198
+ if (status === "unknown" && record.activity.phase !== "settled") {
199
+ return { changed: false };
200
+ }
201
+ const next: AgentActivity = { phase: "settled", status };
202
+ const changed = !sameAgentActivity(record.activity, next);
203
+ this.agents.set(record.terminalId, { ...record, activity: next });
204
+ return { changed };
205
+ }
206
+
207
+ reconcile(
208
+ snapshot: SessionSnapshot,
209
+ controllingPaneId?: string,
210
+ ): ReconcileResult {
211
+ let changed = false;
212
+ const completions: CompletionCandidate[] = [];
213
+ for (const record of this.list()) {
214
+ const panel =
215
+ snapshot.agents.find(
216
+ (candidate) => candidate.terminal_id === record.terminalId,
217
+ ) ??
218
+ snapshot.agents.find(
219
+ (candidate) => candidate.pane_id === record.paneId,
220
+ );
221
+ if (!panel) {
222
+ const paneStillExists = snapshot.panes.some(
223
+ (candidate) =>
224
+ candidate.terminal_id === record.terminalId ||
225
+ candidate.pane_id === record.paneId,
226
+ );
227
+ if (!paneStillExists) {
228
+ this.agents.delete(record.terminalId);
229
+ changed = true;
230
+ }
231
+ continue;
232
+ }
233
+ if (panel.agent !== "pi" || panel.pane_id === controllingPaneId) continue;
234
+
235
+ let activity = record.activity;
236
+ let completion: Omit<CompletionCandidate, "record"> | undefined;
237
+ if (panel.agent_status === "working") {
238
+ const task = activityTask(activity);
239
+ activity = { phase: "working", ...(task ? { task } : {}) };
240
+ } else if (
241
+ isSettledStatus(panel.agent_status) &&
242
+ activity.phase !== "settled"
243
+ ) {
244
+ const task = activityTask(activity);
245
+ completion = {
246
+ requireNewReply: activity.phase === "submitting",
247
+ status: panel.agent_status,
248
+ ...(task ? { task } : {}),
249
+ };
250
+ } else if (activity.phase === "settled") {
251
+ activity = { phase: "settled", status: panel.agent_status };
252
+ }
253
+
254
+ const updated = recordForPanel(panel, activity, record.lastAssistantId);
255
+ if (!sameMonitorRecord(record, updated)) changed = true;
256
+ if (record.terminalId !== updated.terminalId) {
257
+ this.agents.delete(record.terminalId);
258
+ }
259
+ this.agents.set(updated.terminalId, updated);
260
+ if (completion) completions.push({ ...completion, record: updated });
261
+ }
262
+ return { changed, completions };
263
+ }
264
+
265
+ movePane(
266
+ previousPaneId: string,
267
+ pane: { pane_id: string; tab_id?: string; workspace_id?: string },
268
+ ): boolean {
269
+ const record = this.byPane(previousPaneId);
270
+ if (!record) return false;
271
+ this.agents.set(record.terminalId, {
272
+ ...record,
273
+ paneId: pane.pane_id,
274
+ ...(pane.workspace_id ? { workspaceId: pane.workspace_id } : {}),
275
+ ...(pane.tab_id ? { tabId: pane.tab_id } : {}),
276
+ });
277
+ return true;
278
+ }
279
+
280
+ complete(
281
+ terminalId: string,
282
+ status: SettledAgentStatus,
283
+ task: string | undefined,
284
+ lastAssistantId?: string,
285
+ ): boolean {
286
+ const record = this.byTerminal(terminalId);
287
+ if (!record || activityTask(record.activity) !== task) return false;
288
+ this.agents.set(terminalId, {
289
+ ...record,
290
+ activity: { phase: "settled", status },
291
+ ...(lastAssistantId ? { lastAssistantId } : {}),
292
+ });
293
+ return true;
294
+ }
295
+ }
package/src/monitor.ts ADDED
@@ -0,0 +1,228 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { isSettledStatus } from "./activity.js";
6
+ import { getSnapshot } from "./herdr.js";
7
+ import { HerdrClient, isHerdrResponseError } from "./herdr-client.js";
8
+ import { parseMonitorEvent } from "./monitor-event.js";
9
+ import { MonitorEvents } from "./monitor-events.js";
10
+ import { MonitorState, type WorkAttempt } from "./monitor-state.js";
11
+ import { SettlementReporter, type SettlementRequest } from "./settlement.js";
12
+ import type { HerdrEvent, MonitoredAgent, PaneInfo } from "./types.js";
13
+ import { renderAgentWidget } from "./widget.js";
14
+
15
+ const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
16
+
17
+ interface MonitorStateEntry {
18
+ agents: MonitoredAgent[];
19
+ }
20
+
21
+ export class AgentMonitor {
22
+ readonly client: HerdrClient;
23
+ private readonly pi: ExtensionAPI;
24
+ private readonly state = new MonitorState();
25
+ private readonly events: MonitorEvents;
26
+ private readonly settlements: SettlementReporter;
27
+ private context: ExtensionContext | undefined;
28
+ private activationGeneration = 0;
29
+
30
+ constructor(pi: ExtensionAPI, client = new HerdrClient()) {
31
+ this.pi = pi;
32
+ this.client = client;
33
+ this.settlements = new SettlementReporter(pi, client, this.state, () =>
34
+ this.persist(),
35
+ );
36
+ this.events = new MonitorEvents({
37
+ client,
38
+ onEvent: (event) => this.handleEvent(event),
39
+ onReconnect: () => this.reconcileNow(),
40
+ onWarning: (message) => this.context?.ui.notify(message, "warning"),
41
+ targets: () => this.list().map((record) => record.paneId),
42
+ });
43
+ }
44
+
45
+ async activate(ctx: ExtensionContext): Promise<void> {
46
+ this.deactivate();
47
+ const generation = this.activationGeneration;
48
+ this.context = ctx;
49
+ this.restore(ctx);
50
+ renderAgentWidget(this.context, this.list());
51
+ await this.reconcile(generation, ctx);
52
+ if (generation !== this.activationGeneration || ctx !== this.context)
53
+ return;
54
+ await this.events.start();
55
+ }
56
+
57
+ deactivate(): void {
58
+ this.activationGeneration += 1;
59
+ renderAgentWidget(this.context, []);
60
+ this.context = undefined;
61
+ this.events.stop();
62
+ this.settlements.stop();
63
+ }
64
+
65
+ list(): MonitoredAgent[] {
66
+ return this.state.list();
67
+ }
68
+
69
+ isMonitored(paneId: string): boolean {
70
+ return this.state.isMonitored(paneId);
71
+ }
72
+
73
+ async watch(panel: PaneInfo): Promise<MonitoredAgent> {
74
+ if (panel.pane_id === process.env["HERDR_PANE_ID"]) {
75
+ throw new Error("refusing to monitor the controlling Pi session");
76
+ }
77
+ const reply = await this.settlements.latest(panel);
78
+ const { record, reportCurrent } = this.state.watch(panel, reply?.id);
79
+ this.persist();
80
+ await this.events.refresh();
81
+ await this.reconcile(this.activationGeneration, this.context);
82
+ if (reportCurrent && isSettledStatus(panel.agent_status)) {
83
+ await this.report({ record, status: panel.agent_status });
84
+ }
85
+ return record;
86
+ }
87
+
88
+ async unwatch(paneId: string): Promise<boolean> {
89
+ const record = this.state.removePane(paneId);
90
+ if (!record) return false;
91
+ this.persist();
92
+ await this.events.refresh();
93
+ return true;
94
+ }
95
+
96
+ beginWork(paneId: string, task: string): WorkAttempt | undefined {
97
+ const attempt = this.state.beginWork(paneId, task);
98
+ if (attempt) this.persist();
99
+ return attempt;
100
+ }
101
+
102
+ acceptWork(attempt: WorkAttempt | undefined): void {
103
+ if (this.state.acceptWork(attempt)) this.persist();
104
+ }
105
+
106
+ rejectWork(attempt: WorkAttempt | undefined): void {
107
+ if (this.state.rejectWork(attempt)) this.persist();
108
+ }
109
+
110
+ async handleWorkFailure(
111
+ attempt: WorkAttempt | undefined,
112
+ error: unknown,
113
+ ): Promise<void> {
114
+ if (isHerdrResponseError(error)) {
115
+ this.rejectWork(attempt);
116
+ return;
117
+ }
118
+ try {
119
+ await this.reconcileNow();
120
+ } catch (reconcileError) {
121
+ this.context?.ui.notify(
122
+ `Herdr prompt outcome remains uncertain: ${reconcileError instanceof Error ? reconcileError.message : String(reconcileError)}`,
123
+ "warning",
124
+ );
125
+ }
126
+ }
127
+
128
+ async reconcileNow(): Promise<void> {
129
+ await this.reconcile(this.activationGeneration, this.context);
130
+ }
131
+
132
+ private restore(ctx: ExtensionContext): void {
133
+ let latest: MonitorStateEntry | undefined;
134
+ for (const entry of ctx.sessionManager.getBranch()) {
135
+ if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
136
+ continue;
137
+ const data = entry.data as Partial<MonitorStateEntry>;
138
+ if (Array.isArray(data?.agents)) {
139
+ latest = { agents: data.agents };
140
+ }
141
+ }
142
+ const dropped = this.state.restore(
143
+ latest?.agents ?? [],
144
+ process.env["HERDR_PANE_ID"],
145
+ );
146
+ if (dropped > 0) {
147
+ ctx.ui.notify(
148
+ `Ignored ${dropped} invalid saved Shepherdr monitor ${dropped === 1 ? "record" : "records"}`,
149
+ "warning",
150
+ );
151
+ }
152
+ }
153
+
154
+ private persist(): void {
155
+ this.pi.appendEntry(MONITOR_STATE_TYPE, { agents: this.list() });
156
+ renderAgentWidget(this.context, this.list());
157
+ }
158
+
159
+ private async reconcile(
160
+ generation: number,
161
+ context: ExtensionContext | undefined,
162
+ ): Promise<void> {
163
+ if (
164
+ !context ||
165
+ generation !== this.activationGeneration ||
166
+ context !== this.context ||
167
+ this.list().length === 0
168
+ ) {
169
+ return;
170
+ }
171
+ const snapshot = await getSnapshot(this.client);
172
+ if (generation !== this.activationGeneration || context !== this.context)
173
+ return;
174
+ const { changed, completions } = this.state.reconcile(
175
+ snapshot,
176
+ process.env["HERDR_PANE_ID"],
177
+ );
178
+ if (changed) this.persist();
179
+ else renderAgentWidget(this.context, this.list());
180
+ for (const completion of completions) {
181
+ void this.report(completion);
182
+ }
183
+ }
184
+
185
+ private handleEvent(event: HerdrEvent): void {
186
+ const parsed = parseMonitorEvent(event);
187
+ if (!parsed) return;
188
+ if (parsed.type === "closed") {
189
+ const record = this.state.removePane(parsed.paneId);
190
+ if (record) {
191
+ this.persist();
192
+ void this.events.refresh();
193
+ }
194
+ return;
195
+ }
196
+ if (parsed.type === "moved") {
197
+ if (!this.state.movePane(parsed.previousPaneId, parsed.pane)) return;
198
+ this.persist();
199
+ void this.events.refresh();
200
+ return;
201
+ }
202
+ const result = this.state.applyStatus(parsed.paneId, parsed.status);
203
+ if (result.changed) this.persist();
204
+ if (result.completion) {
205
+ void this.report({
206
+ ...result.completion,
207
+ ...(parsed.blockedMessage
208
+ ? { blockedMessage: parsed.blockedMessage }
209
+ : {}),
210
+ });
211
+ }
212
+ }
213
+
214
+ private report(request: SettlementRequest): Promise<void> {
215
+ const generation = this.activationGeneration;
216
+ const context = this.context;
217
+ if (!context) return Promise.resolve();
218
+ return this.settlements.report(
219
+ {
220
+ context,
221
+ generation,
222
+ isCurrent: () =>
223
+ generation === this.activationGeneration && context === this.context,
224
+ },
225
+ request,
226
+ );
227
+ }
228
+ }
@@ -0,0 +1,109 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import type { LatestAssistant } from "./types.js";
3
+
4
+ interface SessionNode {
5
+ assistant?: LatestAssistant;
6
+ parentId?: string;
7
+ }
8
+
9
+ function latestAssistantFromLines(
10
+ lines: string[],
11
+ ): LatestAssistant | undefined {
12
+ const nodes = new Map<string, SessionNode>();
13
+ let leafId: string | undefined;
14
+ for (const line of lines) {
15
+ let entry: Record<string, unknown>;
16
+ try {
17
+ entry = JSON.parse(line) as Record<string, unknown>;
18
+ } catch {
19
+ continue;
20
+ }
21
+ if (typeof entry["id"] !== "string") continue;
22
+ const node: SessionNode = {
23
+ ...(typeof entry["parentId"] === "string"
24
+ ? { parentId: entry["parentId"] }
25
+ : {}),
26
+ };
27
+ const message = entry["message"];
28
+ if (
29
+ typeof message === "object" &&
30
+ message !== null &&
31
+ "role" in message &&
32
+ message.role === "assistant"
33
+ ) {
34
+ const text: string[] = [];
35
+ if ("content" in message && typeof message.content === "string") {
36
+ text.push(message.content);
37
+ } else if ("content" in message && Array.isArray(message.content)) {
38
+ for (const part of message.content) {
39
+ if (
40
+ typeof part === "object" &&
41
+ part !== null &&
42
+ "type" in part &&
43
+ part.type === "text" &&
44
+ "text" in part &&
45
+ typeof part.text === "string"
46
+ ) {
47
+ text.push(part.text);
48
+ }
49
+ }
50
+ }
51
+ const joined = text.join("");
52
+ const stopReason =
53
+ "stopReason" in message && typeof message.stopReason === "string"
54
+ ? message.stopReason
55
+ : undefined;
56
+ if (joined || stopReason === "error") {
57
+ node.assistant = {
58
+ id: entry["id"],
59
+ text: joined,
60
+ ...(stopReason ? { stopReason } : {}),
61
+ };
62
+ }
63
+ }
64
+ nodes.set(entry["id"], node);
65
+ leafId = entry["id"];
66
+ }
67
+
68
+ const visited = new Set<string>();
69
+ let current = leafId;
70
+ while (current && !visited.has(current)) {
71
+ visited.add(current);
72
+ const node = nodes.get(current);
73
+ if (!node) break;
74
+ if (node.assistant) return node.assistant;
75
+ current = node.parentId;
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ export class SessionReader {
81
+ private readonly cache = new Map<
82
+ string,
83
+ { mtimeMs: number; result: LatestAssistant | undefined; size: number }
84
+ >();
85
+
86
+ async latest(path?: string): Promise<LatestAssistant | undefined> {
87
+ if (!path) return undefined;
88
+ let metadata;
89
+ try {
90
+ metadata = await stat(path);
91
+ } catch (error) {
92
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
93
+ throw error;
94
+ }
95
+ const cached = this.cache.get(path);
96
+ if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs) {
97
+ return cached.result;
98
+ }
99
+ const result = latestAssistantFromLines(
100
+ (await readFile(path, "utf8")).split("\n"),
101
+ );
102
+ this.cache.set(path, {
103
+ mtimeMs: metadata.mtimeMs,
104
+ result,
105
+ size: metadata.size,
106
+ });
107
+ return result;
108
+ }
109
+ }