@howaboua/pi-shepherdr 0.1.1 → 0.1.3

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/src/monitor.ts CHANGED
@@ -4,51 +4,90 @@ import type {
4
4
  } from "@earendil-works/pi-coding-agent";
5
5
  import { isSettledStatus } from "./activity.js";
6
6
  import { getSnapshot } from "./herdr.js";
7
- import { HerdrClient, isHerdrResponseError } from "./herdr-client.js";
7
+ import { type HerdrConnection, isHerdrResponseError } from "./herdr-client.js";
8
8
  import { parseMonitorEvent } from "./monitor-event.js";
9
9
  import { MonitorEvents } from "./monitor-events.js";
10
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";
11
+ import type { AssistantReader } from "./session-reader.js";
12
+ import {
13
+ type ClaimedSettlement,
14
+ SettlementReporter,
15
+ type SettlementRequest,
16
+ } from "./settlement.js";
17
+ import type {
18
+ HerdrEvent,
19
+ MonitoredAgent,
20
+ PaneInfo,
21
+ SessionView,
22
+ } from "./types.js";
16
23
 
17
- interface MonitorStateEntry {
18
- agents: MonitoredAgent[];
24
+ interface AgentMonitorOptions {
25
+ client: HerdrConnection;
26
+ machine: string;
27
+ onChange: () => void;
28
+ onRefresh: () => void;
29
+ operatorPrefix: string;
30
+ onWarning: (message: string) => void;
31
+ reader?: AssistantReader;
32
+ reconnect: boolean;
33
+ selfPaneId?: string;
19
34
  }
20
35
 
21
36
  export class AgentMonitor {
22
- readonly client: HerdrClient;
23
- private readonly pi: ExtensionAPI;
37
+ readonly client: HerdrConnection;
38
+ readonly machine: string;
39
+ private readonly onChange: () => void;
40
+ private readonly onRefresh: () => void;
41
+ private readonly selfPaneId: string | undefined;
42
+ private readonly onWarning: (message: string) => void;
24
43
  private readonly state = new MonitorState();
25
44
  private readonly events: MonitorEvents;
26
45
  private readonly settlements: SettlementReporter;
27
46
  private context: ExtensionContext | undefined;
28
47
  private activationGeneration = 0;
29
48
 
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(),
49
+ constructor(pi: ExtensionAPI, options: AgentMonitorOptions) {
50
+ this.client = options.client;
51
+ this.machine = options.machine;
52
+ this.onChange = options.onChange;
53
+ this.onRefresh = options.onRefresh;
54
+ this.selfPaneId = options.selfPaneId;
55
+ this.onWarning = options.onWarning;
56
+ this.settlements = new SettlementReporter(
57
+ pi,
58
+ this.client,
59
+ this.state,
60
+ () => this.persist(),
61
+ options.reader,
62
+ this.machine,
63
+ options.operatorPrefix,
35
64
  );
36
65
  this.events = new MonitorEvents({
37
- client,
66
+ client: this.client,
67
+ reconnect: options.reconnect,
38
68
  onEvent: (event) => this.handleEvent(event),
39
69
  onReconnect: () => this.reconcileNow(),
40
- onWarning: (message) => this.context?.ui.notify(message, "warning"),
70
+ onWarning: (message) => this.onWarning(message),
41
71
  targets: () => this.list().map((record) => record.paneId),
42
72
  });
43
73
  }
44
74
 
45
- async activate(ctx: ExtensionContext): Promise<void> {
75
+ async activate(
76
+ ctx: ExtensionContext,
77
+ restored: unknown[] = [],
78
+ ): Promise<void> {
46
79
  this.deactivate();
47
80
  const generation = this.activationGeneration;
48
81
  this.context = ctx;
49
- this.restore(ctx);
50
- renderAgentWidget(this.context, this.list());
51
- await this.reconcile(generation, ctx);
82
+ const dropped = this.state.restore(restored, this.selfPaneId);
83
+ if (dropped > 0) {
84
+ ctx.ui.notify(
85
+ `Ignored ${dropped} invalid saved Shepherdr monitor ${dropped === 1 ? "record" : "records"} for ${this.machine}`,
86
+ "warning",
87
+ );
88
+ }
89
+ this.onRefresh();
90
+ await this.reconcile(generation, ctx, dropped > 0);
52
91
  if (generation !== this.activationGeneration || ctx !== this.context)
53
92
  return;
54
93
  await this.events.start();
@@ -56,7 +95,6 @@ export class AgentMonitor {
56
95
 
57
96
  deactivate(): void {
58
97
  this.activationGeneration += 1;
59
- renderAgentWidget(this.context, []);
60
98
  this.context = undefined;
61
99
  this.events.stop();
62
100
  this.settlements.stop();
@@ -71,11 +109,26 @@ export class AgentMonitor {
71
109
  }
72
110
 
73
111
  async watch(panel: PaneInfo): Promise<MonitoredAgent> {
74
- if (panel.pane_id === process.env["HERDR_PANE_ID"]) {
112
+ return this.watchPanel(panel, true);
113
+ }
114
+
115
+ async track(panel: PaneInfo): Promise<MonitoredAgent> {
116
+ return this.watchPanel(panel, false);
117
+ }
118
+
119
+ private async watchPanel(
120
+ panel: PaneInfo,
121
+ reportSettled: boolean,
122
+ ): Promise<MonitoredAgent> {
123
+ if (panel.pane_id === this.selfPaneId) {
75
124
  throw new Error("refusing to monitor the controlling Pi session");
76
125
  }
77
126
  const reply = await this.settlements.latest(panel);
78
- const { record, reportCurrent } = this.state.watch(panel, reply?.id);
127
+ const { record, reportCurrent } = this.state.watch(
128
+ panel,
129
+ reply?.id,
130
+ reportSettled,
131
+ );
79
132
  this.persist();
80
133
  await this.events.refresh();
81
134
  await this.reconcile(this.activationGeneration, this.context);
@@ -88,17 +141,40 @@ export class AgentMonitor {
88
141
  async unwatch(paneId: string): Promise<boolean> {
89
142
  const record = this.state.removePane(paneId);
90
143
  if (!record) return false;
144
+ this.settlements.releaseAgentClaim(
145
+ record,
146
+ new Error(`${paneId} was unwatched before its work settled`),
147
+ );
91
148
  this.persist();
92
149
  await this.events.refresh();
93
150
  return true;
94
151
  }
95
152
 
96
- beginWork(paneId: string, task: string): WorkAttempt | undefined {
97
- const attempt = this.state.beginWork(paneId, task);
153
+ beginWork(
154
+ paneId: string,
155
+ task: string,
156
+ expectedUserAfter?: string | null,
157
+ ): WorkAttempt | undefined {
158
+ const attempt = this.state.beginWork(paneId, task, expectedUserAfter);
98
159
  if (attempt) this.persist();
99
160
  return attempt;
100
161
  }
101
162
 
163
+ claimWork(
164
+ attempt: WorkAttempt,
165
+ signal: AbortSignal,
166
+ ): Promise<ClaimedSettlement> {
167
+ return this.settlements.claim(attempt, signal);
168
+ }
169
+
170
+ releaseWorkClaim(attempt: WorkAttempt | undefined, error: unknown): void {
171
+ this.settlements.releaseClaim(attempt, error);
172
+ }
173
+
174
+ view(panel: PaneInfo): Promise<SessionView> {
175
+ return this.settlements.view(panel);
176
+ }
177
+
102
178
  acceptWork(attempt: WorkAttempt | undefined): void {
103
179
  if (this.state.acceptWork(attempt)) this.persist();
104
180
  }
@@ -129,54 +205,42 @@ export class AgentMonitor {
129
205
  await this.reconcile(this.activationGeneration, this.context);
130
206
  }
131
207
 
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
208
  private persist(): void {
155
- this.pi.appendEntry(MONITOR_STATE_TYPE, { agents: this.list() });
156
- renderAgentWidget(this.context, this.list());
209
+ this.onChange();
157
210
  }
158
211
 
159
212
  private async reconcile(
160
213
  generation: number,
161
214
  context: ExtensionContext | undefined,
215
+ persistRestoration = false,
162
216
  ): Promise<void> {
163
217
  if (
164
218
  !context ||
165
219
  generation !== this.activationGeneration ||
166
- context !== this.context ||
167
- this.list().length === 0
220
+ context !== this.context
168
221
  ) {
169
222
  return;
170
223
  }
224
+ if (this.list().length === 0) {
225
+ if (persistRestoration) this.persist();
226
+ else this.onRefresh();
227
+ return;
228
+ }
171
229
  const snapshot = await getSnapshot(this.client);
172
230
  if (generation !== this.activationGeneration || context !== this.context)
173
231
  return;
174
- const { changed, completions } = this.state.reconcile(
232
+ const { changed, completions, removed } = this.state.reconcile(
175
233
  snapshot,
176
- process.env["HERDR_PANE_ID"],
234
+ this.selfPaneId,
177
235
  );
178
- if (changed) this.persist();
179
- else renderAgentWidget(this.context, this.list());
236
+ for (const record of removed) {
237
+ this.settlements.releaseAgentClaim(
238
+ record,
239
+ new Error(`${record.paneId} closed before its work settled`),
240
+ );
241
+ }
242
+ if (changed || persistRestoration) this.persist();
243
+ else this.onRefresh();
180
244
  for (const completion of completions) {
181
245
  void this.report(completion);
182
246
  }
@@ -188,6 +252,10 @@ export class AgentMonitor {
188
252
  if (parsed.type === "closed") {
189
253
  const record = this.state.removePane(parsed.paneId);
190
254
  if (record) {
255
+ this.settlements.releaseAgentClaim(
256
+ record,
257
+ new Error(`${parsed.paneId} closed before its work settled`),
258
+ );
191
259
  this.persist();
192
260
  void this.events.refresh();
193
261
  }
@@ -0,0 +1,291 @@
1
+ import {
2
+ cp,
3
+ mkdir,
4
+ mkdtemp,
5
+ readdir,
6
+ readFile,
7
+ rename,
8
+ rm,
9
+ stat,
10
+ writeFile,
11
+ } from "node:fs/promises";
12
+ import { homedir } from "node:os";
13
+ import { join, resolve } from "node:path";
14
+ import { fileURLToPath, pathToFileURL } from "node:url";
15
+
16
+ const PROFILE_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
17
+ const AGENT_DIRECTORY =
18
+ process.env["PI_CODING_AGENT_DIR"] ?? join(homedir(), ".pi", "agent");
19
+ const PROFILES_ROOT = join(AGENT_DIRECTORY, "shepherdr");
20
+ const PROFILES_DIRECTORY = join(PROFILES_ROOT, "profiles");
21
+ const PROFILE_INSTALL_MARKER = join(PROFILES_ROOT, ".profiles-initialized");
22
+ const BUNDLED_PROFILES_DIRECTORY = fileURLToPath(
23
+ new URL("../profiles", import.meta.url),
24
+ );
25
+
26
+ export interface AgentProfile {
27
+ accepts: string[];
28
+ description: string;
29
+ model: string;
30
+ name: string;
31
+ piArgs: string[];
32
+ prepare?: string;
33
+ prompt?: string;
34
+ promptPath?: string;
35
+ thinking: string;
36
+ }
37
+
38
+ interface ProfilePreparationInput {
39
+ base?: string;
40
+ cwd: string;
41
+ message: string;
42
+ }
43
+
44
+ type ProfilePreparationContext = ProfilePreparationInput & { local: boolean };
45
+
46
+ interface ProfileFile {
47
+ accepts?: unknown;
48
+ description?: unknown;
49
+ model?: unknown;
50
+ pi_args?: unknown;
51
+ prepare?: unknown;
52
+ prompt?: unknown;
53
+ thinking?: unknown;
54
+ }
55
+
56
+ function stringArray(value: unknown, field: string): string[] {
57
+ if (
58
+ !Array.isArray(value) ||
59
+ value.some((item) => typeof item !== "string" || item.length === 0)
60
+ ) {
61
+ throw new Error(`${field} must be an array of non-empty strings`);
62
+ }
63
+ return value;
64
+ }
65
+
66
+ function optionalString(value: unknown, field: string): string | undefined {
67
+ if (value === undefined) return undefined;
68
+ if (typeof value !== "string" || value.trim().length === 0) {
69
+ throw new Error(`${field} must be a non-empty string`);
70
+ }
71
+ return value.trim();
72
+ }
73
+
74
+ async function readProfile(
75
+ name: string,
76
+ directory: string,
77
+ ): Promise<AgentProfile> {
78
+ const path = join(directory, "profile.json");
79
+ let parsed: ProfileFile;
80
+ try {
81
+ parsed = JSON.parse(await readFile(path, "utf8")) as ProfileFile;
82
+ } catch (error) {
83
+ throw new Error(
84
+ `invalid ${name} profile: ${error instanceof Error ? error.message : String(error)}`,
85
+ );
86
+ }
87
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
88
+ throw new Error(`${name} profile must be an object`);
89
+ }
90
+ const allowed = new Set([
91
+ "accepts",
92
+ "description",
93
+ "model",
94
+ "pi_args",
95
+ "prepare",
96
+ "prompt",
97
+ "thinking",
98
+ ]);
99
+ const unknown = Object.keys(parsed).filter((key) => !allowed.has(key));
100
+ if (unknown.length > 0) {
101
+ throw new Error(`unknown ${name} profile field(s): ${unknown.join(", ")}`);
102
+ }
103
+ const description = optionalString(parsed.description, `${name}.description`);
104
+ if (!description) throw new Error(`${name}.description is required`);
105
+ const model = optionalString(parsed.model, `${name}.model`);
106
+ if (!model) throw new Error(`${name}.model is required`);
107
+ const thinking = optionalString(parsed.thinking, `${name}.thinking`);
108
+ if (!thinking) throw new Error(`${name}.thinking is required`);
109
+ const promptPath = optionalString(parsed.prompt, `${name}.prompt`);
110
+ const preparePath = optionalString(parsed.prepare, `${name}.prepare`);
111
+ const resolvedPromptPath = promptPath
112
+ ? resolve(directory, promptPath)
113
+ : undefined;
114
+ const prepare = preparePath ? resolve(directory, preparePath) : undefined;
115
+ if (resolvedPromptPath && !(await stat(resolvedPromptPath)).isFile()) {
116
+ throw new Error(`${name}.prompt is not a file`);
117
+ }
118
+ if (prepare && !(await stat(prepare)).isFile()) {
119
+ throw new Error(`${name}.prepare is not a file`);
120
+ }
121
+ return {
122
+ name,
123
+ description,
124
+ model,
125
+ thinking,
126
+ accepts: parsed.accepts
127
+ ? stringArray(parsed.accepts, `${name}.accepts`)
128
+ : [],
129
+ piArgs: parsed.pi_args
130
+ ? stringArray(parsed.pi_args, `${name}.pi_args`)
131
+ : [],
132
+ ...(resolvedPromptPath
133
+ ? {
134
+ prompt: await readFile(resolvedPromptPath, "utf8"),
135
+ promptPath: resolvedPromptPath,
136
+ }
137
+ : {}),
138
+ ...(prepare ? { prepare } : {}),
139
+ };
140
+ }
141
+
142
+ function hasCode(error: unknown, ...codes: string[]): boolean {
143
+ return (
144
+ error instanceof Error &&
145
+ "code" in error &&
146
+ typeof error.code === "string" &&
147
+ codes.includes(error.code)
148
+ );
149
+ }
150
+
151
+ async function exists(path: string): Promise<boolean> {
152
+ try {
153
+ await stat(path);
154
+ return true;
155
+ } catch (error) {
156
+ if (hasCode(error, "ENOENT")) return false;
157
+ throw error;
158
+ }
159
+ }
160
+
161
+ async function installProfile(name: string): Promise<void> {
162
+ const target = join(PROFILES_DIRECTORY, name);
163
+ if (await exists(target)) return;
164
+ const stagingRoot = await mkdtemp(join(PROFILES_ROOT, `.${name}-`));
165
+ const staging = join(stagingRoot, name);
166
+ try {
167
+ await cp(join(BUNDLED_PROFILES_DIRECTORY, name), staging, {
168
+ errorOnExist: true,
169
+ force: false,
170
+ recursive: true,
171
+ });
172
+ try {
173
+ await rename(staging, target);
174
+ } catch (error) {
175
+ if (!hasCode(error, "EEXIST", "ENOTEMPTY")) throw error;
176
+ }
177
+ } finally {
178
+ await rm(stagingRoot, { force: true, recursive: true });
179
+ }
180
+ }
181
+
182
+ export async function installAgentProfiles(): Promise<void> {
183
+ if (await exists(PROFILE_INSTALL_MARKER)) return;
184
+ await mkdir(PROFILES_DIRECTORY, { mode: 0o700, recursive: true });
185
+ const entries = await readdir(BUNDLED_PROFILES_DIRECTORY, {
186
+ withFileTypes: true,
187
+ });
188
+ for (const entry of entries.sort((left, right) =>
189
+ left.name.localeCompare(right.name),
190
+ )) {
191
+ if (!entry.isDirectory()) continue;
192
+ if (!PROFILE_NAME.test(entry.name)) {
193
+ throw new Error(`invalid bundled agent profile: ${entry.name}`);
194
+ }
195
+ await installProfile(entry.name);
196
+ }
197
+ try {
198
+ await writeFile(PROFILE_INSTALL_MARKER, "1\n", {
199
+ flag: "wx",
200
+ mode: 0o600,
201
+ });
202
+ } catch (error) {
203
+ if (!hasCode(error, "EEXIST")) throw error;
204
+ }
205
+ }
206
+
207
+ export async function loadAgentProfiles(): Promise<Map<string, AgentProfile>> {
208
+ const profiles = new Map<string, AgentProfile>();
209
+ let entries;
210
+ try {
211
+ entries = await readdir(PROFILES_DIRECTORY, { withFileTypes: true });
212
+ } catch (error) {
213
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return profiles;
214
+ throw error;
215
+ }
216
+ for (const entry of entries.sort((left, right) =>
217
+ left.name.localeCompare(right.name),
218
+ )) {
219
+ if (!entry.isDirectory()) continue;
220
+ if (!PROFILE_NAME.test(entry.name)) {
221
+ throw new Error(`invalid agent profile directory: ${entry.name}`);
222
+ }
223
+ profiles.set(
224
+ entry.name,
225
+ await readProfile(entry.name, join(PROFILES_DIRECTORY, entry.name)),
226
+ );
227
+ }
228
+ return profiles;
229
+ }
230
+
231
+ function promptArgument(
232
+ profile: AgentProfile,
233
+ targetLocal: boolean,
234
+ ): string | undefined {
235
+ if (
236
+ targetLocal &&
237
+ profile.promptPath &&
238
+ ![...profile.promptPath].some((character) => /\p{Cc}/u.test(character))
239
+ ) {
240
+ return profile.promptPath;
241
+ }
242
+ return profile.prompt
243
+ ?.replace(/\p{Cc}+/gu, " ")
244
+ .replace(/\s+/gu, " ")
245
+ .trim();
246
+ }
247
+
248
+ export function profileAgentArgs(
249
+ profile: AgentProfile,
250
+ options: { targetLocal?: boolean } = {},
251
+ ): string[] {
252
+ const prompt = promptArgument(profile, options.targetLocal !== false);
253
+ return [
254
+ "--model",
255
+ profile.model,
256
+ "--thinking",
257
+ profile.thinking,
258
+ ...(prompt ? ["--append-system-prompt", prompt] : []),
259
+ ...profile.piArgs,
260
+ ];
261
+ }
262
+
263
+ export async function prepareProfileMessage(
264
+ profile: AgentProfile,
265
+ input: ProfilePreparationInput,
266
+ options: { targetLocal?: boolean } = {},
267
+ ): Promise<string> {
268
+ if (input.base && !profile.accepts.includes("base")) {
269
+ throw new Error(`base is not supported by ${profile.name}`);
270
+ }
271
+ if (profile.prepare) {
272
+ const metadata = await stat(profile.prepare);
273
+ const module = (await import(
274
+ `${pathToFileURL(profile.prepare).href}?mtime=${metadata.mtimeMs}`
275
+ )) as { prepare?: (value: ProfilePreparationContext) => unknown };
276
+ if (typeof module.prepare !== "function") {
277
+ throw new Error(`${profile.name}.prepare must export prepare()`);
278
+ }
279
+ const prepared = await module.prepare({
280
+ ...input,
281
+ local: options.targetLocal !== false,
282
+ });
283
+ if (typeof prepared !== "string" || prepared.trim().length === 0) {
284
+ throw new Error(`${profile.name}.prepare must return a non-empty string`);
285
+ }
286
+ return prepared;
287
+ }
288
+ return input.base
289
+ ? `Review base: ${input.base}\n\n${input.message}`
290
+ : input.message;
291
+ }