@howaboua/pi-shepherdr 0.2.17 → 0.2.19

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.
@@ -104,20 +104,31 @@ export function parseMonitoredAgent(
104
104
  }
105
105
  const cwd = optionalString(record, "cwd");
106
106
  const lastAssistantId = optionalString(record, "lastAssistantId");
107
- const lastQuestionId = optionalString(record, "lastQuestionId");
107
+ const notifiedExtensionMessages =
108
+ record["notifiedExtensionMessages"] === undefined
109
+ ? undefined
110
+ : Array.isArray(record["notifiedExtensionMessages"]) &&
111
+ record["notifiedExtensionMessages"].every(
112
+ (value) => typeof value === "string",
113
+ )
114
+ ? (record["notifiedExtensionMessages"] as string[])
115
+ : false;
108
116
  const name = optionalString(record, "name");
117
+ const instructions = optionalString(record, "instructions");
109
118
  const activity = parsedActivity(record["activity"]);
110
119
  if (
111
120
  cwd === false ||
112
121
  lastAssistantId === false ||
113
- lastQuestionId === false ||
122
+ notifiedExtensionMessages === false ||
114
123
  name === false ||
124
+ instructions === false ||
115
125
  !activity
116
126
  ) {
117
127
  return undefined;
118
128
  }
119
129
  return {
120
130
  scope: record["scope"],
131
+ ...(instructions ? { instructions } : {}),
121
132
  activity,
122
133
  paneId: record["paneId"],
123
134
  terminalId: record["terminalId"],
@@ -125,7 +136,7 @@ export function parseMonitoredAgent(
125
136
  tabId: record["tabId"],
126
137
  ...(cwd ? { cwd } : {}),
127
138
  ...(lastAssistantId ? { lastAssistantId } : {}),
128
- ...(lastQuestionId ? { lastQuestionId } : {}),
139
+ ...(notifiedExtensionMessages ? { notifiedExtensionMessages } : {}),
129
140
  ...(name ? { name } : {}),
130
141
  };
131
142
  }
@@ -135,7 +146,7 @@ export function recordForPanel(
135
146
  activity: AgentActivity,
136
147
  scope: MonitoredAgent["scope"],
137
148
  lastAssistantId?: string,
138
- lastQuestionId?: string,
149
+ notifiedExtensionMessages?: string[],
139
150
  ): MonitoredAgent {
140
151
  const cwd = panel.foreground_cwd ?? panel.cwd;
141
152
  return {
@@ -148,7 +159,7 @@ export function recordForPanel(
148
159
  ...(panel.name ? { name: panel.name } : {}),
149
160
  ...(cwd ? { cwd } : {}),
150
161
  ...(lastAssistantId ? { lastAssistantId } : {}),
151
- ...(lastQuestionId ? { lastQuestionId } : {}),
162
+ ...(notifiedExtensionMessages ? { notifiedExtensionMessages } : {}),
152
163
  };
153
164
  }
154
165
 
@@ -158,6 +169,7 @@ export function sameMonitorRecord(
158
169
  ): boolean {
159
170
  return (
160
171
  left.scope === right.scope &&
172
+ left.instructions === right.instructions &&
161
173
  left.paneId === right.paneId &&
162
174
  left.terminalId === right.terminalId &&
163
175
  left.workspaceId === right.workspaceId &&
@@ -165,7 +177,8 @@ export function sameMonitorRecord(
165
177
  left.cwd === right.cwd &&
166
178
  left.name === right.name &&
167
179
  left.lastAssistantId === right.lastAssistantId &&
168
- left.lastQuestionId === right.lastQuestionId &&
180
+ JSON.stringify(left.notifiedExtensionMessages) ===
181
+ JSON.stringify(right.notifiedExtensionMessages) &&
169
182
  sameAgentActivity(left.activity, right.activity)
170
183
  );
171
184
  }
@@ -81,10 +81,30 @@ export class MonitorState {
81
81
  return this.agents.get(terminalId);
82
82
  }
83
83
 
84
- markQuestion(terminalId: string, id: string): boolean {
84
+ markExtensionMessage(terminalId: string, id: string): boolean {
85
85
  const record = this.byTerminal(terminalId);
86
- if (!record || record.lastQuestionId === id) return false;
87
- this.agents.set(terminalId, { ...record, lastQuestionId: id });
86
+ if (!record || record.notifiedExtensionMessages?.includes(id)) return false;
87
+ this.agents.set(terminalId, {
88
+ ...record,
89
+ notifiedExtensionMessages: [
90
+ ...(record.notifiedExtensionMessages ?? []),
91
+ id,
92
+ ],
93
+ });
94
+ return true;
95
+ }
96
+ retainExtensionNotifications(terminalId: string, live: string[]): boolean {
97
+ const record = this.byTerminal(terminalId);
98
+ if (!record?.notifiedExtensionMessages) return false;
99
+ const retained = record.notifiedExtensionMessages.filter((id) =>
100
+ live.includes(id),
101
+ );
102
+ if (retained.length === record.notifiedExtensionMessages.length)
103
+ return false;
104
+ this.agents.set(terminalId, {
105
+ ...record,
106
+ notifiedExtensionMessages: retained,
107
+ });
88
108
  return true;
89
109
  }
90
110
 
@@ -102,15 +122,20 @@ export class MonitorState {
102
122
  const activity = reportCurrent
103
123
  ? ({ attemptId: randomUUID(), phase: "working" } as const)
104
124
  : (existing?.activity ?? activityForPanel(panel));
105
- const record = recordForPanel(
106
- panel,
107
- activity,
108
- reportSettled ? "persistent" : (existing?.scope ?? "task"),
109
- reportCurrent
110
- ? undefined
111
- : (existing?.lastAssistantId ?? lastAssistantId),
112
- existing?.lastQuestionId,
113
- );
125
+ const record = {
126
+ ...(existing?.instructions
127
+ ? { instructions: existing.instructions }
128
+ : {}),
129
+ ...recordForPanel(
130
+ panel,
131
+ activity,
132
+ reportSettled ? "persistent" : (existing?.scope ?? "task"),
133
+ reportCurrent
134
+ ? undefined
135
+ : (existing?.lastAssistantId ?? lastAssistantId),
136
+ existing?.notifiedExtensionMessages,
137
+ ),
138
+ };
114
139
  if (existing && existing.terminalId !== record.terminalId) {
115
140
  this.agents.delete(existing.terminalId);
116
141
  }
@@ -136,11 +161,11 @@ export class MonitorState {
136
161
  `prompt submission to ${record.name ?? paneId} is still unresolved`,
137
162
  );
138
163
  }
139
- if (record.activity.phase === "working" && record.activity.task) {
140
- throw new Error("Agent already has delegated work; use send for updates");
141
- }
142
164
  const attempt = {
143
- attemptId: randomUUID(),
165
+ attemptId:
166
+ record.activity.phase === "working"
167
+ ? (record.activity.attemptId ?? randomUUID())
168
+ : randomUUID(),
144
169
  terminalId: record.terminalId,
145
170
  };
146
171
  this.pendingSubmissions.add(attempt.attemptId);
@@ -150,13 +175,25 @@ export class MonitorState {
150
175
  attemptId: attempt.attemptId,
151
176
  phase: "submitting",
152
177
  previous: record.activity,
153
- task,
178
+ task: activityTask(record.activity) ?? task,
154
179
  ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
155
180
  },
156
181
  });
157
182
  return attempt;
158
183
  }
159
184
 
185
+ noteMessage(paneId: string, message: string): boolean {
186
+ const record = this.byPane(paneId);
187
+ if (!record) return false;
188
+ const prior = record.instructions ?? activityTask(record.activity);
189
+ this.agents.set(record.terminalId, {
190
+ ...record,
191
+ instructions:
192
+ prior && prior !== message ? `${prior}\n\n${message}` : message,
193
+ });
194
+ return true;
195
+ }
196
+
160
197
  endSubmission(attempt: WorkAttempt | undefined): void {
161
198
  if (attempt) this.pendingSubmissions.delete(attempt.attemptId);
162
199
  }
@@ -351,13 +388,16 @@ export class MonitorState {
351
388
  activity = { phase: "settled", status: panel.agent_status };
352
389
  }
353
390
 
354
- const updated = recordForPanel(
355
- panel,
356
- activity,
357
- record.scope,
358
- record.lastAssistantId,
359
- record.lastQuestionId,
360
- );
391
+ const updated = {
392
+ ...(record.instructions ? { instructions: record.instructions } : {}),
393
+ ...recordForPanel(
394
+ panel,
395
+ activity,
396
+ record.scope,
397
+ record.lastAssistantId,
398
+ record.notifiedExtensionMessages,
399
+ ),
400
+ };
361
401
  if (!sameMonitorRecord(record, updated)) changed = true;
362
402
  if (record.terminalId !== updated.terminalId) {
363
403
  this.agents.delete(record.terminalId);
@@ -390,7 +430,13 @@ export class MonitorState {
390
430
  lastAssistantId?: string,
391
431
  ): boolean {
392
432
  const record = this.byTerminal(terminalId);
393
- if (!record || activityTask(record.activity) !== task) return false;
433
+ if (
434
+ !record ||
435
+ activityTask(record.activity) !== task ||
436
+ (record.activity.phase === "submitting" &&
437
+ this.pendingSubmissions.has(record.activity.attemptId))
438
+ )
439
+ return false;
394
440
  this.agents.set(terminalId, {
395
441
  ...record,
396
442
  scope: "persistent",
package/src/monitor.ts CHANGED
@@ -8,7 +8,7 @@ import { type HerdrConnection, isDispatchRejected } from "./herdr-client.js";
8
8
  import { injectAgentEvent } from "./messages.js";
9
9
  import { parseMonitorEvent } from "./monitor-event.js";
10
10
  import { MonitorEvents } from "./monitor-events.js";
11
- import { MonitorQuestions } from "./monitor-questions.js";
11
+ import { MonitorExtensionMessages } from "./monitor-extension-messages.js";
12
12
  import { MonitorState, type WorkAttempt } from "./monitor-state.js";
13
13
  import { type AssistantReader, SessionReader } from "./session-reader.js";
14
14
  import {
@@ -17,6 +17,7 @@ import {
17
17
  type SettlementRequest,
18
18
  } from "./settlement.js";
19
19
  import type {
20
+ ExtensionReply,
20
21
  HerdrEvent,
21
22
  MonitoredAgent,
22
23
  MonitoringIssue,
@@ -47,7 +48,7 @@ export class AgentMonitor {
47
48
  private readonly state = new MonitorState();
48
49
  private readonly events: MonitorEvents;
49
50
  private readonly settlements: SettlementReporter;
50
- private readonly questions: MonitorQuestions;
51
+ private readonly extensionMessages: MonitorExtensionMessages;
51
52
  private context: ExtensionContext | undefined;
52
53
  private activationGeneration = 0;
53
54
 
@@ -58,16 +59,16 @@ export class AgentMonitor {
58
59
  this.onRefresh = options.onRefresh;
59
60
  this.selfPaneId = options.selfPaneId;
60
61
  const reader = options.reader ?? new SessionReader();
61
- this.questions = new MonitorQuestions({
62
+ this.extensionMessages = new MonitorExtensionMessages({
62
63
  client: this.client,
63
64
  reader,
64
65
  state: this.state,
65
- notify: (ctx, record, agent, ask) => {
66
+ notify: (ctx, record, agent, message) => {
66
67
  injectAgentEvent(pi, ctx, {
67
68
  agent,
68
- ask,
69
+ extensionMessages: [message],
69
70
  record,
70
- status: "question",
71
+ status: "extension-message",
71
72
  labels: {},
72
73
  agentToolName: "agents",
73
74
  machine: this.machine,
@@ -110,7 +111,7 @@ export class AgentMonitor {
110
111
  this.deactivate();
111
112
  const generation = this.activationGeneration;
112
113
  this.context = ctx;
113
- this.questions.start(ctx);
114
+ this.extensionMessages.start(ctx);
114
115
  const dropped = this.state.restore(restored, this.selfPaneId);
115
116
  if (dropped > 0) {
116
117
  ctx.ui.notify(
@@ -129,7 +130,7 @@ export class AgentMonitor {
129
130
  this.activationGeneration += 1;
130
131
  this.context = undefined;
131
132
  this.events.stop();
132
- this.questions.stop();
133
+ this.extensionMessages.stop();
133
134
  this.settlements.stop();
134
135
  }
135
136
 
@@ -174,7 +175,7 @@ export class AgentMonitor {
174
175
  new Error(`${paneId} was unwatched before its work settled`),
175
176
  );
176
177
  this.persist();
177
- await this.questions.refresh();
178
+ await this.extensionMessages.refresh();
178
179
  await this.events.refresh();
179
180
  return true;
180
181
  }
@@ -192,9 +193,13 @@ export class AgentMonitor {
192
193
  claimWork(
193
194
  attempt: WorkAttempt,
194
195
  signal: AbortSignal,
195
- answeringAskId?: string,
196
- ): Promise<ClaimedSettlement> {
197
- return this.settlements.claim(attempt, signal, answeringAskId);
196
+ replyingTo?: ExtensionReply,
197
+ ): Promise<ClaimedSettlement> | undefined {
198
+ return this.settlements.claim(attempt, signal, replyingTo);
199
+ }
200
+
201
+ noteMessage(paneId: string, message: string): void {
202
+ if (this.state.noteMessage(paneId, message)) this.persist();
198
203
  }
199
204
 
200
205
  releaseWorkClaim(attempt: WorkAttempt | undefined, error: unknown): void {
@@ -205,15 +210,6 @@ export class AgentMonitor {
205
210
  return this.settlements.view(panel);
206
211
  }
207
212
 
208
- submitAskAnswer(
209
- panel: PaneInfo,
210
- askId: string,
211
- submit: (signal: AbortSignal) => Promise<void>,
212
- signal: AbortSignal,
213
- ) {
214
- return this.questions.submitAnswer(panel, askId, submit, signal);
215
- }
216
-
217
213
  acceptWork(attempt: WorkAttempt | undefined): void {
218
214
  if (this.state.acceptWork(attempt)) this.persist();
219
215
  }
@@ -267,7 +263,7 @@ export class AgentMonitor {
267
263
  return;
268
264
  }
269
265
  if (this.list().length === 0) {
270
- await this.questions.refresh([]);
266
+ await this.extensionMessages.refresh([]);
271
267
  if (persistRestoration) this.persist();
272
268
  else this.onRefresh();
273
269
  return;
@@ -287,7 +283,7 @@ export class AgentMonitor {
287
283
  }
288
284
  if (changed || persistRestoration) this.persist();
289
285
  else this.onRefresh();
290
- await this.questions.refresh(snapshot.agents);
286
+ await this.extensionMessages.refresh(snapshot.agents);
291
287
  for (const completion of completions) {
292
288
  void this.report(completion);
293
289
  }
@@ -327,7 +323,7 @@ export class AgentMonitor {
327
323
  }
328
324
 
329
325
  private refreshAfterEvent(): void {
330
- void this.questions.refresh();
326
+ void this.extensionMessages.refresh();
331
327
  // MonitorEvents reports failures through onWarning before rejecting awaited updates.
332
328
  void this.events.refresh().catch(() => undefined);
333
329
  }
package/src/peer-inbox.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
  import { acceptFocus, readFocus } from "./agents-focus.js";
9
9
  import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
10
+ import { dispatchExtensionReply } from "./extension-reply.js";
10
11
  import type { AgentFleet } from "./fleet.js";
11
12
  import { getCurrentPane } from "./herdr.js";
12
13
  import { HerdrClient } from "./herdr-client.js";
@@ -118,10 +119,12 @@ async function openInbox(
118
119
  (request["kind"] !== "focus" &&
119
120
  request["kind"] !== "commands" &&
120
121
  request["kind"] !== "message" &&
121
- request["kind"] !== "channel") ||
122
+ request["kind"] !== "channel" &&
123
+ request["kind"] !== "extension-reply") ||
122
124
  (request["kind"] !== "focus" &&
123
125
  request["kind"] !== "commands" &&
124
126
  request["kind"] !== "channel" &&
127
+ request["kind"] !== "extension-reply" &&
125
128
  (typeof request["text"] !== "string" ||
126
129
  !request["text"].trim() ||
127
130
  typeof request["sender"] !== "string" ||
@@ -136,6 +139,42 @@ async function openInbox(
136
139
  });
137
140
  return;
138
141
  }
142
+ if (request["kind"] === "extension-reply") {
143
+ const extension = request["extension"],
144
+ id = request["messageId"],
145
+ message = request["message"];
146
+ if (
147
+ typeof extension !== "string" ||
148
+ !extension.trim() ||
149
+ typeof id !== "string" ||
150
+ !id.trim() ||
151
+ typeof message !== "string"
152
+ ) {
153
+ reply({
154
+ ok: false,
155
+ rejected: true,
156
+ error: "Extension reply requires extension, id and message strings",
157
+ });
158
+ return;
159
+ }
160
+ // No agent turn, UI automation or idle/busy restriction: the producer owns delivery.
161
+ socket.setTimeout(60_000, () => socket.destroy());
162
+ try {
163
+ const result = await dispatchExtensionReply(pi, {
164
+ extension,
165
+ id,
166
+ message,
167
+ });
168
+ reply({ ok: true, command: false, result });
169
+ } catch (error) {
170
+ reply({
171
+ ok: false,
172
+ rejected: false,
173
+ error: error instanceof Error ? error.message : String(error),
174
+ });
175
+ }
176
+ return;
177
+ }
139
178
  if (request["kind"] === "commands") {
140
179
  try {
141
180
  reply({ ok: true, command: false, commands: commands.available() });
@@ -160,7 +160,6 @@ export async function openPeerChannel(request, expected, focus) {
160
160
  const { descriptor, sessionFile, agent } = await resolvePeerReceiver(
161
161
  request,
162
162
  expected,
163
- true,
164
163
  );
165
164
  const id = randomUUID();
166
165
  const frame = `${JSON.stringify({ protocol: PEER_PROTOCOL, kind: "channel", id, token: descriptor.token, sessionFile, terminalId: agent.terminal_id, focus })}\n`;
@@ -99,7 +99,6 @@ export async function sendPeerMessage(
99
99
  const { descriptor, sessionFile, agent } = await resolvePeerReceiver(
100
100
  request,
101
101
  expected,
102
- Boolean(focus) || commands,
103
102
  );
104
103
  const id = randomUUID();
105
104
  const frame =
@@ -130,9 +129,51 @@ export async function sendPeerMessage(
130
129
  /**
131
130
  * @param {(method: string, params: object) => Promise<unknown>} request
132
131
  * @param {import("../types.js").PaneInfo} expected
133
- * @param {boolean} allowBlocked
132
+ * @param {import("../types.js").ExtensionReply} reply
133
+ * @returns {Promise<string>}
134
134
  */
135
- export async function resolvePeerReceiver(request, expected, allowBlocked) {
135
+ export async function sendPeerExtensionReply(request, expected, reply) {
136
+ const { descriptor, sessionFile, agent } = await resolvePeerReceiver(
137
+ request,
138
+ expected,
139
+ );
140
+ const id = randomUUID();
141
+ const frame =
142
+ JSON.stringify({
143
+ protocol: PEER_PROTOCOL,
144
+ kind: "extension-reply",
145
+ id,
146
+ token: descriptor.token,
147
+ sessionFile,
148
+ terminalId: agent.terminal_id,
149
+ extension: reply.extension,
150
+ messageId: reply.id,
151
+ message: reply.message,
152
+ }) + "\n";
153
+ const receipt = await deliverPeerFrame(
154
+ request,
155
+ expected,
156
+ { text: "", sender: "" },
157
+ undefined,
158
+ descriptor,
159
+ sessionFile,
160
+ id,
161
+ frame,
162
+ true,
163
+ );
164
+ if (typeof receipt.result !== "string")
165
+ throw deliveryError(
166
+ "Extension reply was not acknowledged; inspect the target before retrying",
167
+ false,
168
+ );
169
+ return receipt.result;
170
+ }
171
+
172
+ /**
173
+ * @param {(method: string, params: object) => Promise<unknown>} request
174
+ * @param {import("../types.js").PaneInfo} expected
175
+ */
176
+ export async function resolvePeerReceiver(request, expected) {
136
177
  const result = await request("agent.get", { target: expected.pane_id });
137
178
  const agent =
138
179
  result &&
@@ -167,16 +208,6 @@ export async function resolvePeerReceiver(request, expected, allowBlocked) {
167
208
  true,
168
209
  );
169
210
  }
170
- if (
171
- !allowBlocked &&
172
- "agent_status" in agent &&
173
- agent.agent_status === "blocked"
174
- ) {
175
- throw deliveryError(
176
- "Target is blocked; answer its pending question first",
177
- true,
178
- );
179
- }
180
211
  let descriptor;
181
212
  try {
182
213
  descriptor = JSON.parse(
@@ -215,6 +246,7 @@ export async function resolvePeerReceiver(request, expected, allowBlocked) {
215
246
  * @param {string} sessionFile
216
247
  * @param {string} id
217
248
  * @param {string} frame
249
+ * @param {boolean} [extensionReply]
218
250
  * @returns {Promise<import("../types.js").PeerDelivery>}
219
251
  */
220
252
  function deliverPeerFrame(
@@ -226,6 +258,7 @@ function deliverPeerFrame(
226
258
  sessionFile,
227
259
  id,
228
260
  frame,
261
+ extensionReply = false,
229
262
  ) {
230
263
  if (Buffer.byteLength(frame) > MAX_PEER_FRAME_BYTES) {
231
264
  throw deliveryError("Peer message is too large", true);
@@ -257,7 +290,7 @@ function deliverPeerFrame(
257
290
  !attempted,
258
291
  ),
259
292
  );
260
- const timer = setTimeout(failed, focus ? 55_000 : 10_000);
293
+ const timer = setTimeout(failed, focus || extensionReply ? 55_000 : 10_000);
261
294
  timer.unref();
262
295
  socket.setEncoding("utf8");
263
296
  socket.on("error", failed);
@@ -305,6 +338,9 @@ function deliverPeerFrame(
305
338
  } else
306
339
  finish(undefined, {
307
340
  command: reply.command,
341
+ ...(typeof reply.result === "string"
342
+ ? { result: reply.result }
343
+ : {}),
308
344
  ...(reply.commands === undefined
309
345
  ? {}
310
346
  : { commands: reply.commands }),