@howaboua/pi-shepherdr 0.1.5 → 0.1.6

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.
@@ -1,8 +1,13 @@
1
1
  import type { HerdrConnection } from "./herdr-client.js";
2
- import type { HerdrEvent } from "./types.js";
2
+ import type { HerdrEvent, MonitoringIssue } from "./types.js";
3
+
4
+ interface SubscriptionAttempt {
5
+ key: string;
6
+ controller: AbortController;
7
+ }
3
8
 
4
9
  interface Subscription {
5
- generation: number;
10
+ attempt: SubscriptionAttempt;
6
11
  unsubscribe: () => void;
7
12
  }
8
13
 
@@ -10,19 +15,23 @@ interface MonitorEventsOptions {
10
15
  client: HerdrConnection;
11
16
  reconnect?: boolean;
12
17
  onEvent: (event: HerdrEvent) => void;
13
- onReconnect: () => Promise<void>;
14
- onWarning: (message: string) => void;
18
+ reconcile: () => Promise<void>;
19
+ onWarning: (issue: MonitoringIssue) => void;
20
+ onRecovered: () => void;
15
21
  targets: () => string[];
16
22
  }
17
23
 
18
24
  export class MonitorEvents {
19
25
  private readonly options: MonitorEventsOptions;
20
26
  private active = false;
21
- private generation = 0;
22
- private readonly live = new Set<number>();
27
+ private epoch = 0;
28
+ private dirty = false;
29
+ private resync = false;
30
+ private refreshTask: Promise<void> | undefined;
31
+ private pending: SubscriptionAttempt | undefined;
23
32
  private reconnectTimer: NodeJS.Timeout | undefined;
24
33
  private subscription: Subscription | undefined;
25
- private warningShown = false;
34
+ private warning: "degraded" | "unavailable" | undefined;
26
35
 
27
36
  constructor(options: MonitorEventsOptions) {
28
37
  this.options = options;
@@ -35,102 +44,183 @@ export class MonitorEvents {
35
44
 
36
45
  stop(): void {
37
46
  this.active = false;
38
- this.generation += 1;
39
- this.live.clear();
40
- this.subscription?.unsubscribe();
41
- this.subscription = undefined;
42
- this.warningShown = false;
43
- if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
44
- this.reconnectTimer = undefined;
47
+ this.epoch += 1;
48
+ this.dirty = false;
49
+ this.resync = false;
50
+ this.cancelPending();
51
+ this.closeSubscription();
52
+ this.warning = undefined;
53
+ this.clearReconnect();
45
54
  }
46
55
 
47
56
  async refresh(): Promise<void> {
48
- const generation = ++this.generation;
49
- const previous = this.subscription;
50
- if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
51
- this.reconnectTimer = undefined;
52
- const targets = this.options.targets();
53
- if (!this.active || targets.length === 0) {
54
- this.close(previous);
55
- this.subscription = undefined;
56
- return;
57
+ this.dirty = this.active;
58
+ this.clearReconnect();
59
+ const key = this.targetKey();
60
+ if (this.pending && this.pending.key !== key) this.cancelPending();
61
+ if (!this.active || key === "[]") {
62
+ this.cancelPending();
63
+ this.closeSubscription();
64
+ if (this.active) this.recovered();
65
+ }
66
+ while (this.dirty || this.refreshTask) {
67
+ this.refreshTask ??= Promise.resolve().then(async () => {
68
+ while (this.active && this.dirty) {
69
+ this.dirty = false;
70
+ await this.update();
71
+ }
72
+ });
73
+ const task = this.refreshTask;
74
+ try {
75
+ await task;
76
+ } finally {
77
+ if (this.refreshTask === task) this.refreshTask = undefined;
78
+ }
57
79
  }
80
+ }
81
+
82
+ retry(): Promise<void> {
83
+ this.resync = true;
84
+ return this.refresh();
85
+ }
86
+
87
+ private targetKey(): string {
88
+ return JSON.stringify([...new Set(this.options.targets())].sort());
89
+ }
58
90
 
59
- const subscriptions = [
60
- ...targets.map((paneId) => ({
61
- type: "pane.agent_status_changed",
62
- pane_id: paneId,
63
- })),
64
- { type: "pane.moved" },
65
- { type: "pane.closed" },
66
- ];
67
- this.live.add(generation);
91
+ private async update(): Promise<void> {
92
+ const epoch = this.epoch;
93
+ let attempt: SubscriptionAttempt | undefined;
68
94
  try {
69
- const unsubscribe = await this.options.client.subscribe(
70
- subscriptions,
71
- (event) => {
72
- if (this.active && this.live.has(generation)) {
73
- this.options.onEvent(event);
74
- }
75
- },
76
- (error) => {
77
- this.live.delete(generation);
78
- if (error)
79
- this.warn(`Herdr monitoring disconnected: ${error.message}`);
80
- this.scheduleReconnect(generation, true);
81
- },
82
- );
83
- if (
84
- !this.active ||
85
- generation !== this.generation ||
86
- !this.live.has(generation)
87
- ) {
88
- this.live.delete(generation);
89
- unsubscribe();
95
+ if (this.resync) {
96
+ this.resync = false;
97
+ // Remap panes moved during the outage before requesting new coverage.
98
+ await this.options.reconcile();
99
+ if (!this.active || epoch !== this.epoch) return;
100
+ }
101
+ const key = this.targetKey();
102
+ if (key === "[]") {
103
+ this.closeSubscription();
104
+ this.recovered();
90
105
  return;
91
106
  }
92
- this.close(previous);
93
- this.subscription = { generation, unsubscribe };
94
- this.warningShown = false;
107
+ if (this.subscription?.attempt.key !== key) {
108
+ const candidate = { key, controller: new AbortController() };
109
+ attempt = candidate;
110
+ this.pending = candidate;
111
+ const subscriptions = [
112
+ ...this.options.targets().map((paneId) => ({
113
+ type: "pane.agent_status_changed",
114
+ pane_id: paneId,
115
+ })),
116
+ { type: "pane.moved" },
117
+ { type: "pane.closed" },
118
+ ];
119
+ const unsubscribe = await this.options.client.subscribe(
120
+ subscriptions,
121
+ (event) => {
122
+ if (this.isLive(candidate)) this.options.onEvent(event);
123
+ },
124
+ (error) => this.disconnected(candidate, error),
125
+ candidate.controller.signal,
126
+ );
127
+ if (!this.isLive(candidate) || key !== this.targetKey()) {
128
+ unsubscribe();
129
+ return;
130
+ }
131
+ this.closeSubscription();
132
+ this.subscription = { attempt: candidate, unsubscribe };
133
+ this.pending = undefined;
134
+ }
135
+ // Herdr baselines status before ACK; reconcile afterward to cover setup transitions.
136
+ await this.options.reconcile();
137
+ if (!this.active || epoch !== this.epoch) return;
138
+ if (key !== this.targetKey()) {
139
+ this.dirty = true;
140
+ return;
141
+ }
142
+ if (this.subscription) this.recovered();
95
143
  } catch (error) {
96
- this.live.delete(generation);
97
- if (!this.active || generation !== this.generation) return;
144
+ if (
145
+ !this.active ||
146
+ epoch !== this.epoch ||
147
+ attempt?.controller.signal.aborted
148
+ )
149
+ return;
98
150
  const failure = error instanceof Error ? error : new Error(String(error));
99
- this.warn(`Herdr monitoring unavailable: ${failure.message}`);
151
+ this.warn(failure.message);
100
152
  if (this.options.reconnect === false) throw failure;
101
- this.scheduleReconnect(generation, false);
153
+ this.scheduleReconnect();
154
+ } finally {
155
+ if (attempt && this.pending === attempt) this.cancelPending();
102
156
  }
103
157
  }
104
158
 
105
- private close(subscription: Subscription | undefined): void {
106
- if (!subscription) return;
107
- this.live.delete(subscription.generation);
108
- subscription.unsubscribe();
159
+ private isLive(attempt: SubscriptionAttempt): boolean {
160
+ return (
161
+ this.active &&
162
+ !attempt.controller.signal.aborted &&
163
+ (this.pending === attempt || this.subscription?.attempt === attempt)
164
+ );
109
165
  }
110
166
 
111
- private warn(message: string): void {
112
- if (this.warningShown) return;
113
- this.warningShown = true;
114
- this.options.onWarning(message);
167
+ private cancelPending(): void {
168
+ const pending = this.pending;
169
+ this.pending = undefined;
170
+ pending?.controller.abort();
115
171
  }
116
172
 
117
- private scheduleReconnect(generation: number, disconnected: boolean): void {
118
- if (!this.active || generation !== this.generation) return;
119
- if (this.options.reconnect === false) return;
120
- if (disconnected && this.subscription?.generation === generation) {
121
- this.subscription = undefined;
122
- }
173
+ private closeSubscription(): void {
174
+ const subscription = this.subscription;
175
+ this.subscription = undefined;
176
+ subscription?.attempt.controller.abort();
177
+ subscription?.unsubscribe();
178
+ }
179
+
180
+ private disconnected(attempt: SubscriptionAttempt, error?: Error): void {
181
+ if (!this.isLive(attempt)) return;
182
+ if (this.subscription?.attempt === attempt) this.closeSubscription();
183
+ if (this.pending === attempt) this.cancelPending();
184
+ this.warn(error?.message ?? "event stream closed");
185
+ this.scheduleReconnect();
186
+ }
187
+
188
+ private warn(detail: string): void {
189
+ const state = this.subscription ? "degraded" : "unavailable";
190
+ if (this.warning === state) return;
191
+ this.warning = state;
192
+ const message =
193
+ state === "degraded"
194
+ ? "Herdr monitor update failed. Existing stream retained, coverage may be incomplete"
195
+ : "Herdr monitoring unavailable";
196
+ this.options.onWarning({
197
+ state,
198
+ message: `${message}: ${detail}${this.options.reconnect === false ? "" : ". Retrying"}`,
199
+ });
200
+ }
201
+
202
+ private recovered(): void {
203
+ if (!this.warning) return;
204
+ this.warning = undefined;
205
+ this.options.onRecovered();
206
+ }
207
+
208
+ private clearReconnect(): void {
209
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
210
+ this.reconnectTimer = undefined;
211
+ }
212
+
213
+ private scheduleReconnect(): void {
214
+ if (!this.active || this.options.reconnect === false || this.reconnectTimer)
215
+ return;
216
+ const epoch = this.epoch;
123
217
  this.reconnectTimer = setTimeout(() => {
124
218
  this.reconnectTimer = undefined;
125
- void this.options
126
- .onReconnect()
127
- .then(() => this.refresh())
128
- .catch((error) => {
129
- this.warn(
130
- `Herdr monitoring reconnect failed: ${error instanceof Error ? error.message : String(error)}`,
131
- );
132
- this.scheduleReconnect(generation, false);
133
- });
219
+ void this.retry().catch((error) => {
220
+ if (!this.active || epoch !== this.epoch) return;
221
+ this.warn(error instanceof Error ? error.message : String(error));
222
+ this.scheduleReconnect();
223
+ });
134
224
  }, 1_000);
135
225
  this.reconnectTimer.unref();
136
226
  }
@@ -95,7 +95,7 @@ export class MonitorState {
95
95
  !existing &&
96
96
  (panel.agent_status === "done" || panel.agent_status === "blocked");
97
97
  const activity = reportCurrent
98
- ? ({ phase: "working" } as const)
98
+ ? ({ attemptId: randomUUID(), phase: "working" } as const)
99
99
  : (existing?.activity ?? activityForPanel(panel));
100
100
  const record = recordForPanel(
101
101
  panel,
@@ -208,6 +208,28 @@ export class MonitorState {
208
208
  this.agents.set(record.terminalId, { ...record, activity: next });
209
209
  return { changed };
210
210
  }
211
+ if (
212
+ status === "blocked" &&
213
+ record.activity.phase === "settled" &&
214
+ record.activity.status !== "blocked"
215
+ ) {
216
+ const observed = {
217
+ ...record,
218
+ activity: {
219
+ attemptId: randomUUID(),
220
+ phase: "working",
221
+ } as const,
222
+ };
223
+ this.agents.set(record.terminalId, observed);
224
+ return {
225
+ changed: true,
226
+ completion: {
227
+ record: observed,
228
+ requireNewReply: false,
229
+ status,
230
+ },
231
+ };
232
+ }
211
233
  if (isSettledStatus(status) && record.activity.phase !== "settled") {
212
234
  const task = activityTask(record.activity);
213
235
  return {
@@ -273,6 +295,19 @@ export class MonitorState {
273
295
  ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
274
296
  ...(task ? { task } : {}),
275
297
  };
298
+ } else if (
299
+ panel.agent_status === "blocked" &&
300
+ activity.phase === "settled" &&
301
+ activity.status !== "blocked"
302
+ ) {
303
+ activity = {
304
+ attemptId: randomUUID(),
305
+ phase: "working",
306
+ };
307
+ completion = {
308
+ requireNewReply: false,
309
+ status: panel.agent_status,
310
+ };
276
311
  } else if (
277
312
  isSettledStatus(panel.agent_status) &&
278
313
  activity.phase !== "settled"
package/src/monitor.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  import type {
18
18
  HerdrEvent,
19
19
  MonitoredAgent,
20
+ MonitoringIssue,
20
21
  PaneInfo,
21
22
  SessionView,
22
23
  } from "./types.js";
@@ -27,7 +28,8 @@ interface AgentMonitorOptions {
27
28
  onChange: () => void;
28
29
  onRefresh: () => void;
29
30
  operatorPrefix: string;
30
- onWarning: (message: string) => void;
31
+ onWarning: (issue: MonitoringIssue) => void;
32
+ onRecovered: () => void;
31
33
  reader?: AssistantReader;
32
34
  reconnect: boolean;
33
35
  selfPaneId?: string;
@@ -39,7 +41,6 @@ export class AgentMonitor {
39
41
  private readonly onChange: () => void;
40
42
  private readonly onRefresh: () => void;
41
43
  private readonly selfPaneId: string | undefined;
42
- private readonly onWarning: (message: string) => void;
43
44
  private readonly state = new MonitorState();
44
45
  private readonly events: MonitorEvents;
45
46
  private readonly settlements: SettlementReporter;
@@ -52,7 +53,6 @@ export class AgentMonitor {
52
53
  this.onChange = options.onChange;
53
54
  this.onRefresh = options.onRefresh;
54
55
  this.selfPaneId = options.selfPaneId;
55
- this.onWarning = options.onWarning;
56
56
  this.settlements = new SettlementReporter(
57
57
  pi,
58
58
  this.client,
@@ -66,8 +66,9 @@ export class AgentMonitor {
66
66
  client: this.client,
67
67
  reconnect: options.reconnect,
68
68
  onEvent: (event) => this.handleEvent(event),
69
- onReconnect: () => this.reconcileNow(),
70
- onWarning: (message) => this.onWarning(message),
69
+ reconcile: () => this.reconcileNow(),
70
+ onWarning: options.onWarning,
71
+ onRecovered: options.onRecovered,
71
72
  targets: () => this.list().map((record) => record.paneId),
72
73
  });
73
74
  }
@@ -131,7 +132,6 @@ export class AgentMonitor {
131
132
  );
132
133
  this.persist();
133
134
  await this.events.refresh();
134
- await this.reconcile(this.activationGeneration, this.context);
135
135
  if (reportCurrent && isSettledStatus(panel.agent_status)) {
136
136
  await this.report({ record, status: panel.agent_status });
137
137
  }
@@ -205,6 +205,10 @@ export class AgentMonitor {
205
205
  await this.reconcile(this.activationGeneration, this.context);
206
206
  }
207
207
 
208
+ retryMonitoring(): Promise<void> {
209
+ return this.events.retry();
210
+ }
211
+
208
212
  private persist(): void {
209
213
  this.onChange();
210
214
  }
@@ -257,14 +261,14 @@ export class AgentMonitor {
257
261
  new Error(`${parsed.paneId} closed before its work settled`),
258
262
  );
259
263
  this.persist();
260
- void this.events.refresh();
264
+ this.refreshAfterEvent();
261
265
  }
262
266
  return;
263
267
  }
264
268
  if (parsed.type === "moved") {
265
269
  if (!this.state.movePane(parsed.previousPaneId, parsed.pane)) return;
266
270
  this.persist();
267
- void this.events.refresh();
271
+ this.refreshAfterEvent();
268
272
  return;
269
273
  }
270
274
  const result = this.state.applyStatus(parsed.paneId, parsed.status);
@@ -279,6 +283,11 @@ export class AgentMonitor {
279
283
  }
280
284
  }
281
285
 
286
+ private refreshAfterEvent(): void {
287
+ // MonitorEvents reports failures through onWarning before rejecting awaited updates.
288
+ void this.events.refresh().catch(() => undefined);
289
+ }
290
+
282
291
  private report(request: SettlementRequest): Promise<void> {
283
292
  const generation = this.activationGeneration;
284
293
  const context = this.context;
@@ -4,7 +4,7 @@ import { createConnection } from "node:net";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
 
7
- const BRIDGE_VERSION = 3;
7
+ const BRIDGE_VERSION = 4;
8
8
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
9
9
  const READ_CHUNK_BYTES = 64 * 1024;
10
10
  const subscriptions = new Map();
@@ -145,16 +145,24 @@ function subscribe(id, requested) {
145
145
  const requestId = `pi-shepherdr-bridge:subscribe:${crypto.randomUUID()}`;
146
146
  let acknowledged = false;
147
147
  let closed = false;
148
+ let ended = false;
148
149
  let socket;
149
- const timer = setTimeout(() => {
150
- socket.destroy();
151
- reject(new Error("Herdr events.subscribe timed out"));
152
- }, 10_000);
150
+ const timer = setTimeout(
151
+ () => disconnected(new Error("Herdr events.subscribe timed out")),
152
+ 10_000,
153
+ );
153
154
  timer.unref();
154
155
  const disconnected = (error) => {
156
+ if (ended) return;
157
+ ended = true;
155
158
  clearTimeout(timer);
159
+ subscriptions.delete(id);
160
+ socket.destroy();
156
161
  if (!acknowledged)
157
- reject(error ?? new Error("Herdr subscription disconnected"));
162
+ reject(
163
+ error ??
164
+ new Error("Herdr events.subscribe closed before acknowledgement"),
165
+ );
158
166
  else if (!closed) {
159
167
  process.stderr.write(
160
168
  `Herdr monitoring disconnected${error ? `: ${error.message}` : ""}\n`,
@@ -171,6 +179,7 @@ function subscribe(id, requested) {
171
179
  params: { subscriptions: requested },
172
180
  },
173
181
  (value) => {
182
+ if (ended) return;
174
183
  if (!acknowledged && value.id === requestId) {
175
184
  if (value.error !== undefined) {
176
185
  disconnected(errorFromResponse(value.error));
@@ -188,10 +197,6 @@ function subscribe(id, requested) {
188
197
  }
189
198
  acknowledged = true;
190
199
  clearTimeout(timer);
191
- subscriptions.set(id, () => {
192
- closed = true;
193
- socket.destroy();
194
- });
195
200
  resolveSubscription();
196
201
  return;
197
202
  }
@@ -209,6 +214,10 @@ function subscribe(id, requested) {
209
214
  },
210
215
  disconnected,
211
216
  );
217
+ subscriptions.set(id, () => {
218
+ closed = true;
219
+ disconnected(new Error("Herdr subscription cancelled"));
220
+ });
212
221
  });
213
222
  }
214
223
 
@@ -287,20 +296,22 @@ function askCall(value) {
287
296
  typeof value !== "object" ||
288
297
  value.type !== "toolCall" ||
289
298
  value.name !== "ask" ||
290
- typeof value.id !== "string" ||
291
- !value.arguments ||
292
- typeof value.arguments !== "object"
299
+ typeof value.id !== "string"
293
300
  )
294
301
  return undefined;
295
- const prompts = (
296
- Array.isArray(value.arguments.prompts) ? value.arguments.prompts : []
297
- )
302
+ return askFromInput(value.id, value.arguments);
303
+ }
304
+
305
+ function askFromInput(toolCallId, input) {
306
+ if (!input || typeof input !== "object" || Array.isArray(input))
307
+ return undefined;
308
+ const prompts = (Array.isArray(input.prompts) ? input.prompts : [])
298
309
  .map(askPrompt)
299
310
  .filter(Boolean);
300
311
  if (prompts.length === 0) return undefined;
301
312
  return {
302
- toolCallId: value.id,
303
- handoff: value.arguments.handoff === true,
313
+ toolCallId,
314
+ handoff: input.handoff === true,
304
315
  prompts,
305
316
  };
306
317
  }
@@ -336,6 +347,19 @@ async function sessionView(path, size) {
336
347
  if (entry.id !== targetId) return false;
337
348
  const currentDepth = depth;
338
349
  depth += 1;
350
+ if (entry.type === "custom" && entry.customType === "pi-ask-active") {
351
+ const update = entry.data;
352
+ if (update?.version === 1 && typeof update.id === "string") {
353
+ if (update.state === "closed") resolved.add(update.id);
354
+ else if (
355
+ update.state === "active" &&
356
+ !ask &&
357
+ !resolved.has(update.id)
358
+ ) {
359
+ ask = askFromInput(update.id, update);
360
+ }
361
+ }
362
+ }
339
363
  const message = entry.message;
340
364
  if (message && typeof message === "object") {
341
365
  if (
@@ -7,7 +7,7 @@ import type { RemoteMachineConfig } from "./machines-config.js";
7
7
  import type { AssistantReader } from "./session-reader.js";
8
8
  import type { HerdrEvent, LatestAssistant, SessionView } from "./types.js";
9
9
 
10
- const BRIDGE_VERSION = 3;
10
+ const BRIDGE_VERSION = 4;
11
11
  const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
12
12
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
13
13
  const MAX_DIAGNOSTIC_BYTES = 8 * 1024;
@@ -212,21 +212,29 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
212
212
  subscriptions: object[],
213
213
  onEvent: (event: HerdrEvent) => void,
214
214
  onDisconnect: (error?: Error) => void,
215
+ signal?: AbortSignal,
215
216
  ): Promise<() => void> {
217
+ signal?.throwIfAborted();
216
218
  const id = randomUUID();
217
219
  this.subscriptions.set(id, { onEvent, onDisconnect });
218
- try {
219
- await this.call({ id, op: "subscribe", subscriptions }, 11_000);
220
- } catch (error) {
221
- this.subscriptions.delete(id);
222
- throw error;
223
- }
224
- return () => {
220
+ const unsubscribe = () => {
221
+ signal?.removeEventListener("abort", unsubscribe);
225
222
  if (!this.subscriptions.delete(id) || this.closed) return;
226
223
  void this.call({ op: "unsubscribe", subscription: id }).catch(
227
224
  () => undefined,
228
225
  );
229
226
  };
227
+ try {
228
+ const ready = this.call({ id, op: "subscribe", subscriptions }, 11_000);
229
+ signal?.addEventListener("abort", unsubscribe, { once: true });
230
+ if (signal?.aborted) unsubscribe();
231
+ await ready;
232
+ signal?.throwIfAborted();
233
+ } catch (error) {
234
+ unsubscribe();
235
+ throw error;
236
+ }
237
+ return unsubscribe;
230
238
  }
231
239
 
232
240
  async latest(path?: string): Promise<LatestAssistant | undefined> {
@@ -101,14 +101,21 @@ function askCall(value: unknown): PendingAsk | undefined {
101
101
  ) {
102
102
  return undefined;
103
103
  }
104
- const args = record(part["arguments"]);
104
+ return askFromInput(part["id"], part["arguments"]);
105
+ }
106
+
107
+ function askFromInput(
108
+ toolCallId: string,
109
+ input: unknown,
110
+ ): PendingAsk | undefined {
111
+ const args = record(input);
105
112
  if (!args) return undefined;
106
113
  const prompts = (Array.isArray(args["prompts"]) ? args["prompts"] : [])
107
114
  .map(askPrompt)
108
115
  .filter((prompt): prompt is NonNullable<typeof prompt> => Boolean(prompt));
109
116
  if (prompts.length === 0) return undefined;
110
117
  return {
111
- toolCallId: part["id"],
118
+ toolCallId,
112
119
  handoff: args["handoff"] === true,
113
120
  prompts,
114
121
  };
@@ -159,6 +166,20 @@ async function readSessionView(
159
166
  if (id !== targetId) return false;
160
167
  const currentDepth = depth;
161
168
  depth += 1;
169
+ if (entry["type"] === "custom" && entry["customType"] === "pi-ask-active") {
170
+ const update = record(entry["data"]);
171
+ if (update?.["version"] === 1 && typeof update["id"] === "string") {
172
+ const callId = update["id"];
173
+ if (update["state"] === "closed") resolved.add(callId);
174
+ else if (
175
+ update["state"] === "active" &&
176
+ !ask &&
177
+ !resolved.has(callId)
178
+ ) {
179
+ ask = askFromInput(callId, update);
180
+ }
181
+ }
182
+ }
162
183
  const message = record(entry["message"]);
163
184
  if (message) {
164
185
  const resolvedId = resolvedToolCallId(message);