@howaboua/pi-shepherdr 0.1.2 → 0.1.4

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,158 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentFleet } from "./fleet.js";
3
+ import {
4
+ isMachineName,
5
+ LOCAL_MACHINE,
6
+ readMachinesConfig,
7
+ writeMachinesConfig,
8
+ } from "./machines-config.js";
9
+
10
+ function parseSshArguments(value: string): string[] {
11
+ const parts: string[] = [];
12
+ let current = "";
13
+ let quote: "'" | '"' | undefined;
14
+ let escaped = false;
15
+ let started = false;
16
+ for (const character of value) {
17
+ if (escaped) {
18
+ current += character;
19
+ escaped = false;
20
+ started = true;
21
+ continue;
22
+ }
23
+ if (character === "\\" && quote !== "'") {
24
+ escaped = true;
25
+ started = true;
26
+ continue;
27
+ }
28
+ if (quote) {
29
+ if (character === quote) quote = undefined;
30
+ else current += character;
31
+ continue;
32
+ }
33
+ if (character === "'" || character === '"') {
34
+ quote = character;
35
+ started = true;
36
+ } else if (/\s/.test(character)) {
37
+ if (started) {
38
+ parts.push(current);
39
+ current = "";
40
+ started = false;
41
+ }
42
+ } else {
43
+ current += character;
44
+ started = true;
45
+ }
46
+ }
47
+ if (quote) throw new Error("SSH arguments contain an unclosed quote");
48
+ if (escaped) throw new Error("SSH arguments end with an incomplete escape");
49
+ if (started) parts.push(current);
50
+ if (parts.length === 0) throw new Error("SSH target is required");
51
+ const target = parts.pop()!;
52
+ return [...parts, "--", target];
53
+ }
54
+
55
+ export async function showMachineMenu(
56
+ fleet: AgentFleet,
57
+ ctx: ExtensionContext,
58
+ ): Promise<void> {
59
+ const config = await readMachinesConfig().catch((error) => {
60
+ ctx.ui.notify(
61
+ `Shepherdr machine config is invalid: ${error instanceof Error ? error.message : String(error)}`,
62
+ "error",
63
+ );
64
+ return undefined;
65
+ });
66
+ if (!config) return;
67
+ const statuses = fleet.isActive()
68
+ ? fleet.statuses()
69
+ : Object.keys(config.machines).map((name) => ({
70
+ local: false,
71
+ name,
72
+ status: "unavailable" as const,
73
+ }));
74
+ const selected = await ctx.ui.select("Shepherdr machines", [
75
+ "Add machine",
76
+ ...statuses
77
+ .filter((machine) => !machine.local)
78
+ .map(
79
+ (machine) =>
80
+ `${machine.status === "connected" ? "●" : machine.status === "connecting" ? "◌" : "○"} ${machine.name} · ${machine.status}`,
81
+ ),
82
+ ]);
83
+ if (!selected) return;
84
+ if (selected === "Add machine") {
85
+ await addMachine(ctx, fleet);
86
+ return;
87
+ }
88
+ const name = selected.slice(2).split(" · ", 1)[0];
89
+ if (!name) return;
90
+ const status = statuses.find((machine) => machine.name === name);
91
+ const action = await ctx.ui.select(name, [
92
+ ...(status?.status !== "connected" ? ["Connect"] : []),
93
+ "Remove",
94
+ ]);
95
+ if (action === "Connect") {
96
+ if (!fleet.isActive()) {
97
+ ctx.ui.notify("Run /herdr to activate agents first", "warning");
98
+ return;
99
+ }
100
+ ctx.ui.notify(fleet.connect(name), "info");
101
+ } else if (action === "Remove") {
102
+ const confirmed = await ctx.ui.confirm(
103
+ `Remove ${name}?`,
104
+ "The remote Shepherdr helper will remain available for other controllers",
105
+ );
106
+ if (!confirmed) return;
107
+ delete config.machines[name];
108
+ await writeMachinesConfig(config);
109
+ await fleet.reload();
110
+ ctx.ui.notify(`Removed ${name}`, "info");
111
+ }
112
+ }
113
+
114
+ async function addMachine(
115
+ ctx: ExtensionContext,
116
+ fleet: AgentFleet,
117
+ ): Promise<void> {
118
+ const name = (await ctx.ui.input("Machine name", "desktop"))?.trim();
119
+ if (!name) return;
120
+ if (!isMachineName(name)) {
121
+ ctx.ui.notify("Machine name must match [a-z][a-z0-9_-]{0,31}", "error");
122
+ return;
123
+ }
124
+ const ssh = (
125
+ await ctx.ui.input("SSH options and target (target last)", name)
126
+ )?.trim();
127
+ if (!ssh) return;
128
+ let sshArguments: string[];
129
+ try {
130
+ sshArguments = parseSshArguments(ssh);
131
+ } catch (error) {
132
+ ctx.ui.notify(
133
+ error instanceof Error ? error.message : String(error),
134
+ "error",
135
+ );
136
+ return;
137
+ }
138
+ const session = (
139
+ await ctx.ui.input("Herdr session", "default (leave blank)")
140
+ )?.trim();
141
+ const config = await readMachinesConfig();
142
+ if (name === LOCAL_MACHINE || Object.hasOwn(config.machines, name)) {
143
+ ctx.ui.notify(`Machine ${name} already exists`, "error");
144
+ return;
145
+ }
146
+ config.machines[name] = {
147
+ command: ["ssh", "-o", "BatchMode=yes", ...sshArguments],
148
+ herdr: "herdr",
149
+ node: "node",
150
+ ...(session && session !== "default (leave blank)" ? { session } : {}),
151
+ };
152
+ const path = await writeMachinesConfig(config);
153
+ await fleet.reload();
154
+ ctx.ui.notify(
155
+ `Added ${name} in ${path}; Shepherdr manages ~/.pi/agent/shepherdr.mjs remotely`,
156
+ "info",
157
+ );
158
+ }
package/src/messages.ts CHANGED
@@ -5,10 +5,12 @@ import {
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import { Box, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
7
7
  import { activityTask } from "./activity.js";
8
+ import { sendPolicyMessage } from "./delivery.js";
8
9
  import type {
9
10
  LatestAssistant,
10
11
  MonitoredAgent,
11
12
  PaneInfo,
13
+ PendingAsk,
12
14
  SettledAgentStatus,
13
15
  } from "./types.js";
14
16
 
@@ -33,6 +35,8 @@ interface AgentEventLabels {
33
35
 
34
36
  interface AgentEventOptions {
35
37
  agent: PaneInfo;
38
+ agentToolName: string;
39
+ ask?: PendingAsk;
36
40
  blockedMessage?: string;
37
41
  labels: AgentEventLabels;
38
42
  machine: string;
@@ -43,6 +47,7 @@ interface AgentEventOptions {
43
47
  }
44
48
 
45
49
  interface AgentEventDetails {
50
+ ask?: PendingAsk;
46
51
  blockedOn?: string;
47
52
  cwd?: string;
48
53
  machine: string;
@@ -55,6 +60,54 @@ interface AgentEventDetails {
55
60
  workspace?: string;
56
61
  }
57
62
 
63
+ function eventAsk(value: unknown): PendingAsk | undefined {
64
+ if (typeof value !== "object" || value === null) return undefined;
65
+ const record = value as Record<string, unknown>;
66
+ if (
67
+ typeof record["toolCallId"] !== "string" ||
68
+ typeof record["handoff"] !== "boolean" ||
69
+ !Array.isArray(record["prompts"])
70
+ ) {
71
+ return undefined;
72
+ }
73
+ const prompts: PendingAsk["prompts"] = [];
74
+ for (const value of record["prompts"]) {
75
+ if (typeof value !== "object" || value === null) return undefined;
76
+ const prompt = value as Record<string, unknown>;
77
+ if (
78
+ typeof prompt["title"] !== "string" ||
79
+ typeof prompt["multiple"] !== "boolean" ||
80
+ !Array.isArray(prompt["choices"])
81
+ ) {
82
+ return undefined;
83
+ }
84
+ const choices: PendingAsk["prompts"][number]["choices"] = [];
85
+ for (const value of prompt["choices"]) {
86
+ if (typeof value !== "object" || value === null) return undefined;
87
+ const choice = value as Record<string, unknown>;
88
+ if (typeof choice["label"] !== "string") return undefined;
89
+ choices.push({
90
+ label: choice["label"],
91
+ ...(typeof choice["description"] === "string"
92
+ ? { description: choice["description"] }
93
+ : {}),
94
+ });
95
+ }
96
+ prompts.push({
97
+ title: prompt["title"],
98
+ multiple: prompt["multiple"],
99
+ choices,
100
+ ...(typeof prompt["body"] === "string" ? { body: prompt["body"] } : {}),
101
+ });
102
+ }
103
+ if (prompts.length === 0) return undefined;
104
+ return {
105
+ toolCallId: record["toolCallId"],
106
+ handoff: record["handoff"],
107
+ prompts,
108
+ };
109
+ }
110
+
58
111
  function boundedVoicePrompt(prompt: string, truncationNotice: string): string {
59
112
  const encoder = new TextEncoder();
60
113
  const bytes = encoder.encode(prompt);
@@ -88,6 +141,11 @@ function agentVoicePrompt(details: AgentEventDetails): string {
88
141
  "The blocked worker details above were truncated. Tell the user and ask whether they would like the rest.";
89
142
  if (details.blockedOn?.trim())
90
143
  lines.push(`Reason:\n${details.blockedOn.trim()}`);
144
+ if (details.ask) {
145
+ lines.push(
146
+ `Questions:\n${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
147
+ );
148
+ }
91
149
  } else {
92
150
  instruction =
93
151
  details.state === "failed"
@@ -123,19 +181,21 @@ function operatorCommand(operatorPrefix: string, command: string): string {
123
181
  }
124
182
 
125
183
  function blockedOperatorHint(
184
+ agentToolName: string,
126
185
  machine: string,
127
186
  operatorPrefix: string,
128
187
  paneId: string,
129
188
  ): string {
130
- return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through herdr_agents with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
189
+ return `Inspect first with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source visible`)}; respond through ${agentToolName} with machine=${JSON.stringify(machine)}, or use ${operatorCommand(operatorPrefix, `agent send-keys ${paneId} <keys>`)} for interactive controls.`;
131
190
  }
132
191
 
133
192
  function failedOperatorHint(
193
+ agentToolName: string,
134
194
  machine: string,
135
195
  operatorPrefix: string,
136
196
  paneId: string,
137
197
  ): string {
138
- return `Inspect with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source recent-unwrapped --lines 80`)} and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once through herdr_agents with machine=${JSON.stringify(machine)}. If it fails again or the setup looks broken, stop retrying and tell the user.`;
198
+ return `Inspect with ${operatorCommand(operatorPrefix, `agent read ${paneId} --source recent-unwrapped --lines 80`)} and assess the failure. If this task has not already been retried and one simple corrective prompt could recover it, try once through ${agentToolName} with machine=${JSON.stringify(machine)}. If it fails again or the setup looks broken, stop retrying and tell the user.`;
139
199
  }
140
200
 
141
201
  function eventDetails(value: unknown): AgentEventDetails | undefined {
@@ -155,11 +215,13 @@ function eventDetails(value: unknown): AgentEventDetails | undefined {
155
215
  typeof details[field] === "string"
156
216
  ? { [field]: details[field] as string }
157
217
  : {};
218
+ const ask = eventAsk(details["ask"]);
158
219
  return {
159
220
  machine:
160
221
  typeof details["machine"] === "string" ? details["machine"] : "local",
161
222
  paneId: details["paneId"],
162
223
  state: details["state"],
224
+ ...(ask ? { ask } : {}),
163
225
  ...optional("blockedOn"),
164
226
  ...optional("cwd"),
165
227
  ...optional("name"),
@@ -176,6 +238,8 @@ function agentEvent(options: AgentEventOptions): {
176
238
  } {
177
239
  const {
178
240
  agent,
241
+ agentToolName,
242
+ ask,
179
243
  blockedMessage,
180
244
  labels,
181
245
  machine,
@@ -206,14 +270,19 @@ function agentEvent(options: AgentEventOptions): {
206
270
  if (blockedMessage) {
207
271
  lines.push(`<blocked_on>${xml(blockedMessage)}</blocked_on>`);
208
272
  }
273
+ if (blocked && ask) {
274
+ lines.push(
275
+ `<ask>${xml(JSON.stringify({ handoff: ask.handoff, prompts: ask.prompts }))}</ask>`,
276
+ );
277
+ }
209
278
  if (blocked) {
210
279
  lines.push(
211
- `<operator_hint>${xml(blockedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
280
+ `<operator_hint>${xml(blockedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
212
281
  );
213
282
  }
214
283
  if (failed) {
215
284
  lines.push(
216
- `<operator_hint>${xml(failedOperatorHint(machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
285
+ `<operator_hint>${xml(failedOperatorHint(agentToolName, machine, operatorPrefix, agent.pane_id))}</operator_hint>`,
217
286
  );
218
287
  }
219
288
  if (reply) lines.push(`<response>${xml(reply.text)}</response>`);
@@ -225,6 +294,7 @@ function agentEvent(options: AgentEventOptions): {
225
294
  machine,
226
295
  paneId: agent.pane_id,
227
296
  state: blocked ? "blocked" : failed ? "failed" : "finished",
297
+ ...(blocked && ask ? { ask } : {}),
228
298
  ...(record.name ? { name: record.name } : {}),
229
299
  ...(cwd ? { cwd } : {}),
230
300
  ...(labels.workspace ? { workspace: labels.workspace } : {}),
@@ -245,7 +315,8 @@ export function injectAgentEvent(
245
315
  const delivery = ctx.isIdle()
246
316
  ? { triggerTurn: true, deliverAs: "steer" as const }
247
317
  : { deliverAs: "steer" as const };
248
- pi.sendMessage(
318
+ sendPolicyMessage(
319
+ pi,
249
320
  {
250
321
  customType: AGENT_EVENT_MESSAGE_TYPE,
251
322
  content: message.content,
@@ -308,6 +379,38 @@ export function registerAgentEventRenderer(pi: ExtensionAPI): void {
308
379
  0,
309
380
  ),
310
381
  );
382
+ if (details.ask) {
383
+ box.addChild(
384
+ new Text(
385
+ theme.fg(
386
+ "muted",
387
+ `Questions: ${details.ask.prompts.map((prompt) => prompt.title).join(", ")}`,
388
+ ),
389
+ 0,
390
+ 0,
391
+ ),
392
+ );
393
+ if (expanded) {
394
+ for (const prompt of details.ask.prompts) {
395
+ box.addChild(new Spacer(1));
396
+ box.addChild(new Text(theme.fg("muted", prompt.title), 0, 0));
397
+ if (prompt.body) {
398
+ box.addChild(
399
+ new Markdown(prompt.body, 0, 0, getMarkdownTheme()),
400
+ );
401
+ }
402
+ if (prompt.choices.length > 0) {
403
+ box.addChild(
404
+ new Text(
405
+ `Choices: ${prompt.choices.map((choice) => choice.label).join(", ")}`,
406
+ 0,
407
+ 0,
408
+ ),
409
+ );
410
+ }
411
+ }
412
+ }
413
+ }
311
414
  }
312
415
  if (expanded && details?.task) {
313
416
  box.addChild(new Spacer(1));
@@ -16,6 +16,18 @@ function optionalString(
16
16
  : false;
17
17
  }
18
18
 
19
+ function optionalNullableString(
20
+ value: Record<string, unknown>,
21
+ field: string,
22
+ ): string | null | undefined | false {
23
+ const candidate = value[field];
24
+ return candidate === undefined ||
25
+ candidate === null ||
26
+ typeof candidate === "string"
27
+ ? candidate
28
+ : false;
29
+ }
30
+
19
31
  function stableActivity(value: unknown): StableAgentActivity | undefined {
20
32
  if (typeof value !== "object" || value === null) return undefined;
21
33
  const activity = value as Record<string, unknown>;
@@ -28,9 +40,24 @@ function stableActivity(value: unknown): StableAgentActivity | undefined {
28
40
  }
29
41
  if (activity["phase"] !== "working") return undefined;
30
42
  const task = optionalString(activity, "task");
43
+ const attemptId = optionalString(activity, "attemptId");
44
+ const expectedUserAfter = optionalNullableString(
45
+ activity,
46
+ "expectedUserAfter",
47
+ );
31
48
  return task === false
32
49
  ? undefined
33
- : { phase: "working", ...(task ? { task } : {}) };
50
+ : attemptId === false
51
+ ? undefined
52
+ : expectedUserAfter === false ||
53
+ (expectedUserAfter !== undefined && !task)
54
+ ? undefined
55
+ : {
56
+ phase: "working",
57
+ ...(attemptId ? { attemptId } : {}),
58
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
59
+ ...(task ? { task } : {}),
60
+ };
34
61
  }
35
62
 
36
63
  function parsedActivity(value: unknown): AgentActivity | undefined {
@@ -39,10 +66,15 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
39
66
  if (typeof value !== "object" || value === null) return undefined;
40
67
  const activity = value as Record<string, unknown>;
41
68
  const previous = stableActivity(activity["previous"]);
69
+ const expectedUserAfter = optionalNullableString(
70
+ activity,
71
+ "expectedUserAfter",
72
+ );
42
73
  if (
43
74
  activity["phase"] !== "submitting" ||
44
75
  typeof activity["attemptId"] !== "string" ||
45
76
  typeof activity["task"] !== "string" ||
77
+ expectedUserAfter === false ||
46
78
  !previous
47
79
  ) {
48
80
  return undefined;
@@ -52,6 +84,7 @@ function parsedActivity(value: unknown): AgentActivity | undefined {
52
84
  phase: "submitting",
53
85
  previous,
54
86
  task: activity["task"],
87
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
55
88
  };
56
89
  }
57
90
 
@@ -34,6 +34,7 @@ interface CompletionCandidate {
34
34
  interface ReconcileResult {
35
35
  changed: boolean;
36
36
  completions: CompletionCandidate[];
37
+ removed: MonitoredAgent[];
37
38
  }
38
39
 
39
40
  interface StatusResult {
@@ -85,10 +86,12 @@ export class MonitorState {
85
86
  watch(
86
87
  panel: PaneInfo,
87
88
  lastAssistantId?: string,
89
+ reportSettled = true,
88
90
  ): { record: MonitoredAgent; reportCurrent: boolean } {
89
91
  const existing =
90
92
  this.byTerminal(panel.terminal_id) ?? this.byPane(panel.pane_id);
91
93
  const reportCurrent =
94
+ reportSettled &&
92
95
  !existing &&
93
96
  (panel.agent_status === "done" || panel.agent_status === "blocked");
94
97
  const activity = reportCurrent
@@ -114,7 +117,11 @@ export class MonitorState {
114
117
  return record;
115
118
  }
116
119
 
117
- beginWork(paneId: string, task: string): WorkAttempt | undefined {
120
+ beginWork(
121
+ paneId: string,
122
+ task: string,
123
+ expectedUserAfter?: string | null,
124
+ ): WorkAttempt | undefined {
118
125
  const record = this.byPane(paneId);
119
126
  if (!record) return undefined;
120
127
  if (record.activity.phase === "submitting") {
@@ -133,6 +140,7 @@ export class MonitorState {
133
140
  phase: "submitting",
134
141
  previous: record.activity,
135
142
  task,
143
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
136
144
  },
137
145
  });
138
146
  return attempt;
@@ -149,7 +157,14 @@ export class MonitorState {
149
157
  }
150
158
  this.agents.set(record.terminalId, {
151
159
  ...record,
152
- activity: { phase: "working", task: record.activity.task },
160
+ activity: {
161
+ attemptId: record.activity.attemptId,
162
+ ...(record.activity.expectedUserAfter !== undefined
163
+ ? { expectedUserAfter: record.activity.expectedUserAfter }
164
+ : {}),
165
+ phase: "working",
166
+ task: record.activity.task,
167
+ },
153
168
  });
154
169
  return true;
155
170
  }
@@ -175,8 +190,18 @@ export class MonitorState {
175
190
  if (!record) return { changed: false };
176
191
  if (status === "working") {
177
192
  const task = activityTask(record.activity);
193
+ const attemptId =
194
+ record.activity.phase === "settled"
195
+ ? undefined
196
+ : record.activity.attemptId;
197
+ const expectedUserAfter =
198
+ record.activity.phase === "settled"
199
+ ? undefined
200
+ : record.activity.expectedUserAfter;
178
201
  const next: AgentActivity = {
179
202
  phase: "working",
203
+ ...(attemptId ? { attemptId } : {}),
204
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
180
205
  ...(task ? { task } : {}),
181
206
  };
182
207
  const changed = !sameAgentActivity(record.activity, next);
@@ -210,6 +235,7 @@ export class MonitorState {
210
235
  ): ReconcileResult {
211
236
  let changed = false;
212
237
  const completions: CompletionCandidate[] = [];
238
+ const removed: MonitoredAgent[] = [];
213
239
  for (const record of this.list()) {
214
240
  const panel =
215
241
  snapshot.agents.find(
@@ -226,6 +252,7 @@ export class MonitorState {
226
252
  );
227
253
  if (!paneStillExists) {
228
254
  this.agents.delete(record.terminalId);
255
+ removed.push(record);
229
256
  changed = true;
230
257
  }
231
258
  continue;
@@ -236,7 +263,16 @@ export class MonitorState {
236
263
  let completion: Omit<CompletionCandidate, "record"> | undefined;
237
264
  if (panel.agent_status === "working") {
238
265
  const task = activityTask(activity);
239
- activity = { phase: "working", ...(task ? { task } : {}) };
266
+ const attemptId =
267
+ activity.phase === "settled" ? undefined : activity.attemptId;
268
+ const expectedUserAfter =
269
+ activity.phase === "settled" ? undefined : activity.expectedUserAfter;
270
+ activity = {
271
+ phase: "working",
272
+ ...(attemptId ? { attemptId } : {}),
273
+ ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
274
+ ...(task ? { task } : {}),
275
+ };
240
276
  } else if (
241
277
  isSettledStatus(panel.agent_status) &&
242
278
  activity.phase !== "settled"
@@ -259,7 +295,7 @@ export class MonitorState {
259
295
  this.agents.set(updated.terminalId, updated);
260
296
  if (completion) completions.push({ ...completion, record: updated });
261
297
  }
262
- return { changed, completions };
298
+ return { changed, completions, removed };
263
299
  }
264
300
 
265
301
  movePane(
package/src/monitor.ts CHANGED
@@ -9,8 +9,17 @@ 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
11
  import type { AssistantReader } from "./session-reader.js";
12
- import { SettlementReporter, type SettlementRequest } from "./settlement.js";
13
- import type { HerdrEvent, MonitoredAgent, PaneInfo } from "./types.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";
14
23
 
15
24
  interface AgentMonitorOptions {
16
25
  client: HerdrConnection;
@@ -100,11 +109,26 @@ export class AgentMonitor {
100
109
  }
101
110
 
102
111
  async watch(panel: PaneInfo): Promise<MonitoredAgent> {
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> {
103
123
  if (panel.pane_id === this.selfPaneId) {
104
124
  throw new Error("refusing to monitor the controlling Pi session");
105
125
  }
106
126
  const reply = await this.settlements.latest(panel);
107
- const { record, reportCurrent } = this.state.watch(panel, reply?.id);
127
+ const { record, reportCurrent } = this.state.watch(
128
+ panel,
129
+ reply?.id,
130
+ reportSettled,
131
+ );
108
132
  this.persist();
109
133
  await this.events.refresh();
110
134
  await this.reconcile(this.activationGeneration, this.context);
@@ -117,17 +141,40 @@ export class AgentMonitor {
117
141
  async unwatch(paneId: string): Promise<boolean> {
118
142
  const record = this.state.removePane(paneId);
119
143
  if (!record) return false;
144
+ this.settlements.releaseAgentClaim(
145
+ record,
146
+ new Error(`${paneId} was unwatched before its work settled`),
147
+ );
120
148
  this.persist();
121
149
  await this.events.refresh();
122
150
  return true;
123
151
  }
124
152
 
125
- beginWork(paneId: string, task: string): WorkAttempt | undefined {
126
- 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);
127
159
  if (attempt) this.persist();
128
160
  return attempt;
129
161
  }
130
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
+
131
178
  acceptWork(attempt: WorkAttempt | undefined): void {
132
179
  if (this.state.acceptWork(attempt)) this.persist();
133
180
  }
@@ -182,10 +229,16 @@ export class AgentMonitor {
182
229
  const snapshot = await getSnapshot(this.client);
183
230
  if (generation !== this.activationGeneration || context !== this.context)
184
231
  return;
185
- const { changed, completions } = this.state.reconcile(
232
+ const { changed, completions, removed } = this.state.reconcile(
186
233
  snapshot,
187
234
  this.selfPaneId,
188
235
  );
236
+ for (const record of removed) {
237
+ this.settlements.releaseAgentClaim(
238
+ record,
239
+ new Error(`${record.paneId} closed before its work settled`),
240
+ );
241
+ }
189
242
  if (changed || persistRestoration) this.persist();
190
243
  else this.onRefresh();
191
244
  for (const completion of completions) {
@@ -199,6 +252,10 @@ export class AgentMonitor {
199
252
  if (parsed.type === "closed") {
200
253
  const record = this.state.removePane(parsed.paneId);
201
254
  if (record) {
255
+ this.settlements.releaseAgentClaim(
256
+ record,
257
+ new Error(`${parsed.paneId} closed before its work settled`),
258
+ );
202
259
  this.persist();
203
260
  void this.events.refresh();
204
261
  }