@pasko70/pibo 1.7.12 → 1.8.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.
@@ -20,6 +20,7 @@ import { withWorkflowSessionKind } from "../sessions/workflow-session-kind.js";
20
20
  import { PiboRuntimeTelemetryRecorder } from "./runtime-telemetry.js";
21
21
  import { createPiboProviderTelemetryExtension } from "./provider-telemetry.js";
22
22
  const DEFAULT_SUBAGENT_REPLY_TIMEOUT_MS = 10 * 60 * 1000;
23
+ const DEFAULT_ROUTED_SESSION_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
23
24
  export const RALPH_RUNTIME_RETRY_DEFAULTS = {
24
25
  enabled: true,
25
26
  maxRetries: 7,
@@ -132,6 +133,8 @@ export class PiboSessionRouter {
132
133
  signalRegistry;
133
134
  runtimeRegistry;
134
135
  scheduledRunReminders = new Map();
136
+ idleSessionTimers = new Map();
137
+ routedSessionIdleTimeoutMs;
135
138
  baseProfile;
136
139
  pluginRegistry;
137
140
  sessionStore;
@@ -146,6 +149,12 @@ export class PiboSessionRouter {
146
149
  this.telemetryRecorder = this.telemetryStore
147
150
  ? new PiboRuntimeTelemetryRecorder(this.telemetryStore, undefined, { providerEventMode: providerEventTelemetryModeFromEnv() })
148
151
  : undefined;
152
+ const idleTimeoutMs = options.routedSessionIdleTimeoutMs;
153
+ this.routedSessionIdleTimeoutMs = idleTimeoutMs === false
154
+ ? false
155
+ : typeof idleTimeoutMs === "number" && Number.isFinite(idleTimeoutMs) && idleTimeoutMs > 0
156
+ ? idleTimeoutMs
157
+ : DEFAULT_ROUTED_SESSION_IDLE_TIMEOUT_MS;
149
158
  const defaultProfileName = selectDefaultPiboProfileName(this.pluginRegistry);
150
159
  this.baseProfile = options.profile ?? createPiboProfileFromRegistryOrDefault(this.pluginRegistry, defaultProfileName);
151
160
  this.reliabilityStore = options.reliabilityStore ?? (options.persistSession === false ? undefined : createDefaultPiboReliabilityStore());
@@ -165,20 +174,29 @@ export class PiboSessionRouter {
165
174
  }
166
175
  async emit(event) {
167
176
  const session = await this.getOrCreateSession(event.piboSessionId);
168
- if (event.type === "message") {
169
- return session.enqueueMessage(event);
170
- }
171
- const output = await session.executeAction(event);
172
- if (event.action === "abort") {
173
- this.signalRegistry.project({ type: "session_interrupted", piboSessionId: event.piboSessionId, reason: "abort action" });
174
- }
175
- if (event.action === "dispose") {
176
- this.disposeSignalSubtree(event.piboSessionId, "dispose action");
177
+ this.clearIdleSessionTimer(event.piboSessionId);
178
+ try {
179
+ if (event.type === "message") {
180
+ return session.enqueueMessage(event);
181
+ }
182
+ const output = await session.executeAction(event);
183
+ if (event.action === "abort") {
184
+ this.signalRegistry.project({ type: "session_interrupted", piboSessionId: event.piboSessionId, reason: "abort action" });
185
+ }
186
+ if (event.action === "dispose") {
187
+ await this.disposeSessionSubtree(event.piboSessionId, "dispose action", { cancelRuns: true });
188
+ }
189
+ else if (event.action === "kill" || event.action === "kill_all") {
190
+ await this.disposeSessionSubtree(event.piboSessionId, `${event.action} action`, { cancelRuns: event.action === "kill_all" });
191
+ }
192
+ else if (shouldResetSessionAfterAction(event.action)) {
193
+ await this.resetCachedSession(event.piboSessionId, "provider auth changed");
194
+ }
195
+ return output;
177
196
  }
178
- else if (shouldResetSessionAfterAction(event.action)) {
179
- await this.resetCachedSession(event.piboSessionId, "provider auth changed");
197
+ finally {
198
+ this.scheduleIdleSessionEvictionIfIdle(event.piboSessionId);
180
199
  }
181
- return output;
182
200
  }
183
201
  async killSession(piboSessionId, options) {
184
202
  const killed = [];
@@ -190,23 +208,32 @@ export class PiboSessionRouter {
190
208
  const runs = this.runRegistry.cancelControllerRuns(piboSessionId);
191
209
  cancelledRuns.push(...runs.map((r) => r.runId));
192
210
  }
193
- await this.runtimeRegistry.closeControllerSessions(piboSessionId, { force: true });
194
211
  this.signalRegistry.project({ type: "session_interrupted", piboSessionId, reason: "kill" });
195
212
  const children = await this.killChildSessions(piboSessionId, options);
196
213
  killed.push(...children.killed);
197
214
  cancelledRuns.push(...children.cancelledRuns);
215
+ await this.disposeSessionSubtree(piboSessionId, "kill", { cancelRuns: false });
198
216
  }
199
217
  return { killed, cancelledRuns };
200
218
  }
201
- disposeSignalSubtree(piboSessionId, reason) {
202
- const descendants = this.descendantSessionIds(piboSessionId);
203
- for (const id of [piboSessionId, ...descendants]) {
204
- this.runRegistry.cancelControllerRuns(id);
205
- void this.runtimeRegistry.closeControllerSessions(id, { force: true });
206
- this.signalRegistry.project({ type: "session_disposed", piboSessionId: id, reason });
219
+ async disposeSessionSubtree(piboSessionId, reason, options) {
220
+ const ids = [piboSessionId, ...this.descendantSessionIds(piboSessionId)];
221
+ const sessions = [];
222
+ for (const id of ids) {
223
+ if (options.cancelRuns)
224
+ this.runRegistry.cancelControllerRuns(id);
225
+ this.clearIdleSessionTimer(id);
207
226
  this.scheduledRunReminders.delete(id);
227
+ const cached = this.sessions.get(id);
228
+ if (cached)
229
+ sessions.push(cached);
208
230
  this.sessions.delete(id);
209
231
  }
232
+ await Promise.all(ids.map((id) => this.runtimeRegistry.closeControllerSessions(id, { force: true })));
233
+ await Promise.all(sessions.map((session) => session.dispose()));
234
+ for (const id of ids) {
235
+ this.signalRegistry.project({ type: "session_disposed", piboSessionId: id, reason });
236
+ }
210
237
  }
211
238
  descendantSessionIds(parentId) {
212
239
  const output = [];
@@ -327,6 +354,9 @@ export class PiboSessionRouter {
327
354
  async disposeAll() {
328
355
  const sessions = [...this.sessions.values()];
329
356
  this.sessions.clear();
357
+ for (const timer of this.idleSessionTimers.values())
358
+ clearTimeout(timer);
359
+ this.idleSessionTimers.clear();
330
360
  this.runRegistry.cancelAll("Pibo session router was disposed.");
331
361
  for (const session of sessions)
332
362
  this.signalRegistry.project({ type: "session_disposed", piboSessionId: session.getStatus().piboSessionId, reason: "router disposed" });
@@ -334,10 +364,54 @@ export class PiboSessionRouter {
334
364
  await this.runtimeRegistry.closeAll({ force: true });
335
365
  await Promise.all(sessions.map((session) => session.dispose()));
336
366
  }
367
+ clearIdleSessionTimer(piboSessionId) {
368
+ const timer = this.idleSessionTimers.get(piboSessionId);
369
+ if (timer)
370
+ clearTimeout(timer);
371
+ this.idleSessionTimers.delete(piboSessionId);
372
+ }
373
+ scheduleIdleSessionEvictionIfIdle(piboSessionId) {
374
+ if (this.routedSessionIdleTimeoutMs === false)
375
+ return;
376
+ const session = this.sessions.get(piboSessionId);
377
+ if (!session)
378
+ return;
379
+ const status = session.getStatus();
380
+ if (status.disposed || status.processing || status.streaming || status.queuedMessages > 0) {
381
+ this.clearIdleSessionTimer(piboSessionId);
382
+ return;
383
+ }
384
+ this.clearIdleSessionTimer(piboSessionId);
385
+ const timer = setTimeout(() => {
386
+ this.idleSessionTimers.delete(piboSessionId);
387
+ void this.evictIdleSession(piboSessionId, session).catch((error) => {
388
+ const message = error instanceof Error ? error.message : String(error);
389
+ this.emitOutput({
390
+ type: "session_error",
391
+ piboSessionId,
392
+ error: `Failed to dispose idle routed runtime: ${message}`,
393
+ errorDetails: runtimeSessionErrorDetails(message),
394
+ });
395
+ });
396
+ }, this.routedSessionIdleTimeoutMs);
397
+ timer.unref();
398
+ this.idleSessionTimers.set(piboSessionId, timer);
399
+ }
400
+ async evictIdleSession(piboSessionId, expected) {
401
+ const current = this.sessions.get(piboSessionId);
402
+ if (current !== expected)
403
+ return;
404
+ const status = current.getStatus();
405
+ if (status.disposed || status.processing || status.streaming || status.queuedMessages > 0)
406
+ return;
407
+ await this.resetCachedSession(piboSessionId, "routed runtime idle timeout");
408
+ }
337
409
  async getOrCreateSession(piboSessionId) {
338
410
  const existing = this.sessions.get(piboSessionId);
339
- if (existing)
411
+ if (existing) {
412
+ this.clearIdleSessionTimer(piboSessionId);
340
413
  return existing;
414
+ }
341
415
  const pending = this.pendingSessions.get(piboSessionId);
342
416
  if (pending)
343
417
  return pending;
@@ -388,7 +462,16 @@ export class PiboSessionRouter {
388
462
  const initialFastMode = resolvePiboSessionInitialFastMode(piboSession) ?? selectRequestedFastMode(profileForSession(profile, piboSession.piSessionId, parentPiSessionId), modelDefaults) ?? false;
389
463
  const session = new RoutedSession(piboSession.id, runtime, this.emitOutput, this.pluginRegistry, this.options.forwardPiEvents ?? false, this.telemetryRecorder
390
464
  ? (id, event, context) => this.telemetryRecorder?.recordPiEvent(id, event, { session: this.sessionStore.get(id), status: context.status, activeEventId: context.activeEventId })
391
- : undefined, initialFastMode, (result, event) => this.handleSessionOperation(result, event), (id, opts) => this.killChildSessions(id, opts), (state) => this.signalRegistry.project({ type: "session_processing_changed", piboSessionId: piboSession.id, processing: state.processing, queuedMessages: state.queuedMessages }));
465
+ : undefined, initialFastMode, (result, event) => this.handleSessionOperation(result, event), (id, opts) => this.killChildSessions(id, opts), (state) => {
466
+ this.signalRegistry.project({ type: "session_processing_changed", piboSessionId: piboSession.id, processing: state.processing, queuedMessages: state.queuedMessages });
467
+ if (state.disposed || state.processing || state.queuedMessages > 0)
468
+ this.clearIdleSessionTimer(piboSession.id);
469
+ else
470
+ this.scheduleIdleSessionEvictionIfIdle(piboSession.id);
471
+ }, (messages, reason) => this.telemetryRecorder?.recordMessagesInterrupted(messages, {
472
+ session: this.sessionStore.get(piboSession.id),
473
+ status: this.sessions.get(piboSession.id)?.getStatus(),
474
+ }, reason));
392
475
  this.sessions.set(piboSession.id, session);
393
476
  return session;
394
477
  }
@@ -447,6 +530,7 @@ export class PiboSessionRouter {
447
530
  }
448
531
  async resetCachedSession(piboSessionId, reason) {
449
532
  const cached = this.sessions.get(piboSessionId);
533
+ this.clearIdleSessionTimer(piboSessionId);
450
534
  this.sessions.delete(piboSessionId);
451
535
  await this.runtimeRegistry.closeControllerSessions(piboSessionId, { force: true });
452
536
  await cached?.dispose();
@@ -17,6 +17,61 @@ export class TelemetryStore {
17
17
  getTurnTimeline(turnIdOrEventId, input = {}) {
18
18
  return getTelemetryTurnTimeline(this.db, turnIdOrEventId, input);
19
19
  }
20
+ getOpenPhaseForTurn(turnId, name) {
21
+ const row = this.db.prepare(`
22
+ SELECT * FROM telemetry_phases
23
+ WHERE turn_id = ? AND name = ? AND status = 'open'
24
+ ORDER BY COALESCE(last_progress_at, started_at) DESC, created_at DESC
25
+ LIMIT 1
26
+ `).get(turnId, name);
27
+ return row ? phaseFromRow(row) : undefined;
28
+ }
29
+ countPhasesForTurn(turnId, name) {
30
+ const row = this.db.prepare("SELECT COUNT(*) AS count FROM telemetry_phases WHERE turn_id = ? AND name = ?").get(turnId, name);
31
+ return Number(row.count);
32
+ }
33
+ listOpenPhasesForTurn(turnId) {
34
+ const rows = this.db.prepare(`
35
+ SELECT * FROM telemetry_phases
36
+ WHERE turn_id = ? AND status = 'open'
37
+ ORDER BY started_at ASC, created_at ASC
38
+ `).all(turnId);
39
+ return rows.map(phaseFromRow);
40
+ }
41
+ getLatestProviderRequestForTurn(turnId) {
42
+ const row = this.db.prepare(`
43
+ SELECT * FROM telemetry_provider_requests
44
+ WHERE turn_id = ?
45
+ ORDER BY started_at DESC, created_at DESC
46
+ LIMIT 1
47
+ `).get(turnId);
48
+ return row ? providerRequestFromRow(row) : undefined;
49
+ }
50
+ getActiveProviderRequestForTurn(turnId) {
51
+ const row = this.db.prepare(`
52
+ SELECT * FROM telemetry_provider_requests
53
+ WHERE turn_id = ? AND status NOT IN ('completed', 'error', 'aborted', 'timeout')
54
+ ORDER BY started_at DESC, created_at DESC
55
+ LIMIT 1
56
+ `).get(turnId);
57
+ return row ? providerRequestFromRow(row) : undefined;
58
+ }
59
+ listActiveProviderRequestsForTurn(turnId) {
60
+ const rows = this.db.prepare(`
61
+ SELECT * FROM telemetry_provider_requests
62
+ WHERE turn_id = ? AND status NOT IN ('completed', 'error', 'aborted', 'timeout')
63
+ ORDER BY started_at ASC, created_at ASC
64
+ `).all(turnId);
65
+ return rows.map(providerRequestFromRow);
66
+ }
67
+ listActiveToolCallsForTurn(turnId) {
68
+ const rows = this.db.prepare(`
69
+ SELECT * FROM telemetry_tool_calls
70
+ WHERE turn_id = ? AND status NOT IN ('ok', 'error', 'aborted', 'timeout')
71
+ ORDER BY created_at ASC
72
+ `).all(turnId);
73
+ return rows.map(toolCallFromRow);
74
+ }
20
75
  listProviderEventsPage(providerRequestId, input = {}) {
21
76
  return listTelemetryProviderEventsPage(this.db, providerRequestId, input);
22
77
  }
@@ -176,6 +231,53 @@ export class TelemetryStore {
176
231
  const normalizedDelta = input.normalizedEventDelta ?? (input.normalizedType ? 1 : 0);
177
232
  this.incrementProviderCounters(input.providerRequestId, input.eventType, receivedAt, byteSize, parseStatus, normalizedDelta);
178
233
  }
234
+ recordProviderProgress(input) {
235
+ const existing = this.getProviderRequest(input.providerRequestId);
236
+ if (!existing)
237
+ return undefined;
238
+ const eventTypeCounts = { ...existing.eventTypeCounts };
239
+ for (const [eventType, delta] of Object.entries(input.eventTypeCounts ?? {})) {
240
+ if (!Number.isFinite(delta) || delta <= 0)
241
+ continue;
242
+ const current = typeof eventTypeCounts[eventType] === "number" ? eventTypeCounts[eventType] : 0;
243
+ eventTypeCounts[eventType] = current + delta;
244
+ }
245
+ const rawEventCount = Math.max(0, input.rawEventCount ?? 0);
246
+ const normalizedEventCount = Math.max(0, input.normalizedEventCount ?? 0);
247
+ const parseErrorCount = Math.max(0, input.parseErrorCount ?? 0);
248
+ const unknownEventCount = Math.max(0, input.unknownEventCount ?? 0);
249
+ const bytesReceived = Math.max(0, input.bytesReceived ?? 0);
250
+ const updatedAt = input.updatedAt ?? input.lastNormalizedEventAt ?? input.lastRawEventAt ?? new Date().toISOString();
251
+ this.db.prepare(`
252
+ UPDATE telemetry_provider_requests SET
253
+ status = CASE WHEN status IN ('completed', 'error', 'aborted', 'timeout') THEN status ELSE COALESCE(?, status) END,
254
+ last_raw_event_at = COALESCE(?, last_raw_event_at),
255
+ last_normalized_event_at = COALESCE(?, last_normalized_event_at),
256
+ upstream_response_id = COALESCE(?, upstream_response_id),
257
+ raw_event_count = raw_event_count + ?,
258
+ normalized_event_count = normalized_event_count + ?,
259
+ parse_error_count = parse_error_count + ?,
260
+ unknown_event_count = unknown_event_count + ?,
261
+ bytes_received = CASE WHEN ? = 0 THEN bytes_received ELSE COALESCE(bytes_received, 0) + ? END,
262
+ event_type_counts_json = ?,
263
+ updated_at = ?
264
+ WHERE provider_request_id = ?
265
+ `).run(input.status ?? null, input.lastRawEventAt ?? null, input.lastNormalizedEventAt ?? null, input.upstreamResponseId ?? null, rawEventCount, normalizedEventCount, parseErrorCount, unknownEventCount, bytesReceived, bytesReceived, JSON.stringify(eventTypeCounts), updatedAt, input.providerRequestId);
266
+ return {
267
+ ...existing,
268
+ status: isTerminalProviderRequestStatus(existing.status) ? existing.status : input.status ?? existing.status,
269
+ lastRawEventAt: input.lastRawEventAt ?? existing.lastRawEventAt,
270
+ lastNormalizedEventAt: input.lastNormalizedEventAt ?? existing.lastNormalizedEventAt,
271
+ upstreamResponseId: input.upstreamResponseId ?? existing.upstreamResponseId,
272
+ rawEventCount: existing.rawEventCount + rawEventCount,
273
+ normalizedEventCount: existing.normalizedEventCount + normalizedEventCount,
274
+ parseErrorCount: existing.parseErrorCount + parseErrorCount,
275
+ unknownEventCount: existing.unknownEventCount + unknownEventCount,
276
+ bytesReceived: bytesReceived > 0 ? (existing.bytesReceived ?? 0) + bytesReceived : existing.bytesReceived,
277
+ eventTypeCounts,
278
+ updatedAt,
279
+ };
280
+ }
179
281
  appendProviderEventSummary(input) {
180
282
  const now = input.updatedAt ?? new Date().toISOString();
181
283
  const receivedAt = input.receivedAt ?? now;
@@ -293,34 +395,15 @@ export class TelemetryStore {
293
395
  return row.next_sequence;
294
396
  }
295
397
  incrementProviderCounters(providerRequestId, eventType, receivedAt, byteSize, parseStatus, normalizedDelta) {
296
- const existing = this.getProviderRequest(providerRequestId);
297
- if (!existing)
298
- return;
299
- const eventTypeCounts = { ...existing.eventTypeCounts };
300
- const currentCount = typeof eventTypeCounts[eventType] === "number" ? eventTypeCounts[eventType] : 0;
301
- eventTypeCounts[eventType] = currentCount + 1;
302
- this.upsertProviderRequest({
398
+ this.recordProviderProgress({
303
399
  providerRequestId,
304
- piboSessionId: existing.piboSessionId,
305
- rootSessionId: existing.rootSessionId,
306
- roomId: existing.roomId,
307
- turnId: existing.turnId,
308
- phaseId: existing.phaseId,
309
- provider: existing.provider,
310
- api: existing.api,
311
- model: existing.model,
312
- transport: existing.transport,
313
- serviceTier: existing.serviceTier,
314
- status: existing.status,
315
400
  lastRawEventAt: receivedAt,
316
- rawEventCount: existing.rawEventCount + 1,
317
- normalizedEventCount: existing.normalizedEventCount + normalizedDelta,
318
- parseErrorCount: existing.parseErrorCount + (parseStatus === "invalid_json" ? 1 : 0),
319
- unknownEventCount: existing.unknownEventCount + (parseStatus === "unknown_type" ? 1 : 0),
320
- bytesReceived: (existing.bytesReceived ?? 0) + byteSize,
321
- eventTypeCounts,
322
- captureMode: existing.captureMode,
323
- retentionClass: existing.retentionClass,
401
+ rawEventCount: 1,
402
+ normalizedEventCount: normalizedDelta,
403
+ parseErrorCount: parseStatus === "invalid_json" ? 1 : 0,
404
+ unknownEventCount: parseStatus === "unknown_type" ? 1 : 0,
405
+ bytesReceived: byteSize,
406
+ eventTypeCounts: { [eventType]: 1 },
324
407
  updatedAt: receivedAt,
325
408
  });
326
409
  }
@@ -347,6 +430,9 @@ export class BestEffortTelemetryService {
347
430
  recordProviderEventSummary(input) {
348
431
  this.safe(() => this.store?.recordProviderEventSummary(input));
349
432
  }
433
+ recordProviderProgress(input) {
434
+ return this.safe(() => this.store?.recordProviderProgress(input));
435
+ }
350
436
  appendProviderEventSummary(input) {
351
437
  return this.safe(() => this.store?.appendProviderEventSummary(input));
352
438
  }
@@ -363,6 +449,9 @@ export class BestEffortTelemetryService {
363
449
  }
364
450
  }
365
451
  }
452
+ function isTerminalProviderRequestStatus(status) {
453
+ return status === "completed" || status === "error" || status === "aborted" || status === "timeout";
454
+ }
366
455
  function fail(message) {
367
456
  throw new Error(message);
368
457
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pasko70/pibo",
3
- "version": "1.7.12",
3
+ "version": "1.8.0",
4
4
  "type": "module",
5
5
  "imports": {
6
6
  "vscode": "./src/apps/chat-vscode/extension/src/vscode-shim.js"