pi-bro 0.25.0 → 0.26.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.
package/src/advisor.ts CHANGED
@@ -4,7 +4,7 @@ import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-wor
4
4
  import { convertToLlm, getAgentDir, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
5
5
  import { Container, Markdown, Text } from "@earendil-works/pi-tui";
6
6
  import { Type } from "typebox";
7
- import { execute as executeBackend, type BackendSelection } from "./backend.ts";
7
+ import { execute as executeBackend, setPiHostContext, type BackendSelection } from "./backend.ts";
8
8
  import { MAX_ADVISOR_STEERING_CHARS, buildAdvisorPrompt } from "./prompt.ts";
9
9
  import { type BackendName, readSettings, selectionForCapability } from "./settings.ts";
10
10
  import { errorMessage, isRecord } from "./util.ts";
@@ -228,8 +228,7 @@ export type AdvisorActivityCallback = (label: string, timestamp: number) => void
228
228
  // Thin wrapper around the shared backend: advisor's stdin/stream-json transport, activity parsing,
229
229
  // and process lifecycle now live in backend.ts (see docs/plans/2026-09-19-bro-advisor-design.md,
230
230
  // "Transport" for why stdin rather than --print). This function keeps its exact existing
231
- // signature/throw contract -- it is called directly by tests and by runAdvisorWithRetries below,
232
- // which owns the 3-attempt retry/backoff policy the backend itself never performs.
231
+ // signature/throw contract -- it is called directly by tests and by runAdvisor below.
233
232
  export class TerminalConsultError extends Error {
234
233
  readonly status: "failure" | "cancelled" | "timeout";
235
234
  constructor(status: "failure" | "cancelled" | "timeout", message: string) {
@@ -262,32 +261,6 @@ export async function runAdvisorConsultation(
262
261
  throw new TerminalConsultError(outcome.status, outcome.message);
263
262
  }
264
263
 
265
- function advisorDelay(ms: number, signal: AbortSignal, onTick?: (remainingMs: number) => void): Promise<void> {
266
- return new Promise((resolve, reject) => {
267
- if (signal.aborted) {
268
- reject(new Error("Canceled."));
269
- return;
270
- }
271
- const startedAt = Date.now();
272
- const interval = onTick ? setInterval(() => onTick(Math.max(0, ms - (Date.now() - startedAt))), 1_000) : undefined;
273
- interval?.unref();
274
- const cleanup = () => {
275
- clearTimeout(timer);
276
- if (interval) clearInterval(interval);
277
- signal.removeEventListener("abort", onAbort);
278
- };
279
- const onAbort = () => {
280
- cleanup();
281
- reject(new Error("Canceled."));
282
- };
283
- const timer = setTimeout(() => {
284
- cleanup();
285
- resolve();
286
- }, ms);
287
- signal.addEventListener("abort", onAbort, { once: true });
288
- });
289
- }
290
-
291
264
  export type AdvisorConsult = (
292
265
  prompt: string,
293
266
  selection: BackendSelection,
@@ -296,14 +269,9 @@ export type AdvisorConsult = (
296
269
  killEscalationMs?: number,
297
270
  onActivity?: AdvisorActivityCallback,
298
271
  ) => Promise<string>;
299
- export type AdvisorDelayFn = (ms: number, signal: AbortSignal, onTick?: (remainingMs: number) => void) => Promise<void>;
300
272
  export type AdvisorToolDetails = {
301
- status: "investigating" | "retrying" | "done";
302
- attempt: number;
303
- of: number;
273
+ status: "investigating" | "done";
304
274
  elapsedMs: number;
305
- error?: string;
306
- retryInMs?: number;
307
275
  backend?: BackendName;
308
276
  model?: string;
309
277
  effort?: string;
@@ -314,145 +282,107 @@ export type AdvisorToolDetails = {
314
282
  snapshotChars?: number;
315
283
  broTruncated?: false;
316
284
  omissions?: string;
317
- // Real backend-reported activity for the current attempt only -- reset to empty whenever a new
318
- // attempt (including a retry) starts, never carried over from a prior failed attempt.
285
+ // Real backend-reported activity for this consultation, bounded to the last 4 labels.
319
286
  activity?: string[];
320
287
  lastActivityAt?: number;
321
288
  // Total count of accepted activity events (tool calls AND user-facing text deltas -- "activity"
322
- // is the honest label, not "tool calls") observed across the whole consultation, including every
323
- // retry attempt. Unlike `activity` above, this never resets on a retry; the final "done" details
324
- // carry the same running total.
289
+ // is the honest label, not "tool calls") observed across the consultation.
325
290
  activityCount?: number;
326
291
  };
327
292
  export type AdvisorProgressCallback = (details: AdvisorToolDetails) => void;
328
- export type AdvisorRunResult = { advice: string; attempts: number; durationMs: number; activityCount: number };
293
+ export type AdvisorRunResult = { advice: string; durationMs: number; activityCount: number };
329
294
 
330
295
  // Bursts of chunked NDJSON activity events are coalesced to this cadence so a fast stream of tool
331
296
  // calls/text deltas doesn't flood onProgress; the 1s elapsed-time heartbeat below is unaffected and
332
297
  // keeps ticking independently.
333
298
  const ADVISOR_ACTIVITY_THROTTLE_MS = 250;
334
299
 
335
- // `consult`/`delayFn` are injectable so tests can swap in a fake process spawn and a fake clock
336
- // instead of spawning real processes and waiting 15 real seconds. Every attempt sends the
337
- // identical prompt/selection/cwd to a fresh, standalone backend process — never resumed via
338
- // --conversation, even across retries.
339
- export async function runAdvisorWithRetries(
300
+ // `consult` is injectable so tests can swap in a fake process spawn instead of spawning real
301
+ // processes. Every consultation runs once against a fresh, standalone backend process — never
302
+ // resumed via --conversation and never automatically retried.
303
+ export async function runAdvisor(
340
304
  prompt: string,
341
305
  selection: BackendSelection,
342
306
  cwd: string,
343
307
  signal: AbortSignal,
344
308
  consult: AdvisorConsult = runAdvisorConsultation,
345
- delayFn: AdvisorDelayFn = advisorDelay,
346
309
  onProgress?: AdvisorProgressCallback,
347
310
  progressIntervalMs = 1_000,
348
311
  activityThrottleMs = ADVISOR_ACTIVITY_THROTTLE_MS,
349
312
  ): Promise<AdvisorRunResult> {
350
- const delays = [5_000, 10_000];
351
- const totalAttempts = delays.length + 1;
313
+ if (signal.aborted) throw new Error("Canceled.");
352
314
  const startedAt = Date.now();
353
- let lastError: unknown;
354
- // Cumulative across every attempt in this consultation, including retries -- unlike `activity`
355
- // below, a retry must never reset this back to zero.
315
+ const activity: string[] = [];
356
316
  let totalActivityCount = 0;
357
- for (let attempt = 0; attempt <= delays.length; attempt++) {
358
- if (signal.aborted) throw new Error("Canceled.");
359
- // Fresh per attempt: a retry must never show the previous attempt's activity trail.
360
- const activity: string[] = [];
361
- let lastActivityAt: number | undefined;
362
- let lastActivityEmitAt = 0;
363
- let pendingActivityTimer: ReturnType<typeof setTimeout> | undefined;
317
+ let lastActivityAt: number | undefined;
318
+ let lastActivityEmitAt = 0;
319
+ let pendingActivityTimer: ReturnType<typeof setTimeout> | undefined;
364
320
 
365
- const running = (): AdvisorToolDetails => ({
366
- status: "investigating",
367
- attempt: attempt + 1,
368
- of: totalAttempts,
369
- elapsedMs: Date.now() - startedAt,
370
- activity: [...activity],
371
- lastActivityAt,
372
- activityCount: totalActivityCount,
373
- });
374
- const emitRunning = () => onProgress?.(running());
375
- emitRunning();
376
- const progressTimer = onProgress ? setInterval(emitRunning, progressIntervalMs) : undefined;
377
- progressTimer?.unref();
321
+ const running = (): AdvisorToolDetails => ({
322
+ status: "investigating",
323
+ elapsedMs: Date.now() - startedAt,
324
+ activity: [...activity],
325
+ lastActivityAt,
326
+ activityCount: totalActivityCount,
327
+ });
328
+ const emitRunning = () => onProgress?.(running());
329
+ emitRunning();
330
+ const progressTimer = onProgress ? setInterval(emitRunning, progressIntervalMs) : undefined;
331
+ progressTimer?.unref();
378
332
 
379
- const stopActivityThrottle = () => {
380
- if (pendingActivityTimer) {
381
- clearTimeout(pendingActivityTimer);
333
+ const stopActivityThrottle = () => {
334
+ if (pendingActivityTimer) {
335
+ clearTimeout(pendingActivityTimer);
336
+ pendingActivityTimer = undefined;
337
+ }
338
+ };
339
+ const onActivity: AdvisorActivityCallback = (label, timestamp) => {
340
+ const normalized = label.replace(/\s+/g, " ").trim();
341
+ if (!normalized) return;
342
+ activity.push(normalized);
343
+ if (activity.length > MAX_ADVISOR_ACTIVITY_LINES) activity.splice(0, activity.length - MAX_ADVISOR_ACTIVITY_LINES);
344
+ totalActivityCount += 1;
345
+ lastActivityAt = timestamp;
346
+ if (!onProgress) return;
347
+ const elapsed = Date.now() - lastActivityEmitAt;
348
+ if (elapsed >= activityThrottleMs) {
349
+ lastActivityEmitAt = Date.now();
350
+ emitRunning();
351
+ return;
352
+ }
353
+ if (!pendingActivityTimer) {
354
+ pendingActivityTimer = setTimeout(() => {
382
355
  pendingActivityTimer = undefined;
383
- }
384
- };
385
- const onActivity: AdvisorActivityCallback = (label, timestamp) => {
386
- const normalized = label.replace(/\s+/g, " ").trim();
387
- if (!normalized) return;
388
- activity.push(normalized);
389
- if (activity.length > MAX_ADVISOR_ACTIVITY_LINES) activity.splice(0, activity.length - MAX_ADVISOR_ACTIVITY_LINES);
390
- totalActivityCount += 1;
391
- lastActivityAt = timestamp;
392
- if (!onProgress) return;
393
- const elapsed = Date.now() - lastActivityEmitAt;
394
- if (elapsed >= activityThrottleMs) {
395
356
  lastActivityEmitAt = Date.now();
396
357
  emitRunning();
397
- return;
398
- }
399
- if (!pendingActivityTimer) {
400
- pendingActivityTimer = setTimeout(() => {
401
- pendingActivityTimer = undefined;
402
- lastActivityEmitAt = Date.now();
403
- emitRunning();
404
- }, activityThrottleMs - elapsed);
405
- pendingActivityTimer.unref?.();
406
- }
407
- };
408
-
409
- try {
410
- const advice = await consult(prompt, selection, cwd, signal, undefined, onActivity);
411
- // `totalActivityCount` is read directly here rather than from the last onProgress snapshot,
412
- // which may lag behind by up to `activityThrottleMs` -- the final count must be exact.
413
- return { advice, attempts: attempt + 1, durationMs: Date.now() - startedAt, activityCount: totalActivityCount };
414
- } catch (error) {
415
- if (progressTimer) clearInterval(progressTimer);
416
- stopActivityThrottle();
417
- if (signal.aborted || errorMessage(error) === "Canceled." ||
418
- (error instanceof TerminalConsultError && error.status !== "failure")) throw error;
419
- lastError = error;
420
- if (attempt === delays.length) break;
421
- const delay = delays[attempt]!;
422
- const retrying = (remainingMs: number): AdvisorToolDetails => ({
423
- status: "retrying",
424
- attempt: attempt + 2,
425
- of: totalAttempts,
426
- elapsedMs: Date.now() - startedAt,
427
- error: errorMessage(error),
428
- retryInMs: remainingMs,
429
- activityCount: totalActivityCount,
430
- });
431
- onProgress?.(retrying(delay));
432
- await delayFn(delay, signal, (remainingMs) => onProgress?.(retrying(remainingMs)));
433
- } finally {
434
- if (progressTimer) clearInterval(progressTimer);
435
- stopActivityThrottle();
358
+ }, activityThrottleMs - elapsed);
359
+ pendingActivityTimer.unref?.();
436
360
  }
361
+ };
362
+
363
+ try {
364
+ const advice = await consult(prompt, selection, cwd, signal, undefined, onActivity);
365
+ // `totalActivityCount` is read directly here rather than from the last onProgress snapshot,
366
+ // which may lag behind by up to `activityThrottleMs` -- the final count must be exact.
367
+ return { advice, durationMs: Date.now() - startedAt, activityCount: totalActivityCount };
368
+ } finally {
369
+ if (progressTimer) clearInterval(progressTimer);
370
+ stopActivityThrottle();
437
371
  }
438
- throw lastError;
439
372
  }
440
373
 
441
374
  export function advisorAttemptLabel(details: AdvisorToolDetails): string {
442
- if (details.status === "retrying") {
443
- return `Bro advisor · retrying in ${Math.ceil((details.retryInMs ?? 0) / 1_000)}s · attempt ${details.attempt}/${details.of}${details.error ? ` — ${details.error}` : ""}`;
444
- }
445
375
  if (details.status === "done") {
446
- return `Bro advisor · ${details.model ?? "unknown model"} · ${details.attempt} attempt${details.attempt === 1 ? "" : "s"} · ${Math.ceil((details.durationMs ?? details.elapsedMs) / 1_000)}s`;
376
+ return `Bro advisor · ${details.model ?? "unknown model"} · ${Math.ceil((details.durationMs ?? details.elapsedMs) / 1_000)}s`;
447
377
  }
448
378
  const latest = details.activity?.at(-1);
449
- const backendLabel = details.backend === "claude" ? "Claude" : details.backend === "grok" ? "Grok" : details.backend === "codex" ? "Codex" : details.backend === "muse" ? "Muse" : "Agy";
379
+ const backendLabel = details.backend === "claude" ? "Claude" : details.backend === "grok" ? "Grok" : details.backend === "codex" ? "Codex" : details.backend === "muse" ? "Muse" : details.backend === "pi" ? "Pi" : "Agy";
450
380
  // "last reported" + freshness, never a claim about what the backend is doing right now and never
451
381
  // "stalled" -- silence since lastActivityAt is not itself evidence of a stuck run.
452
382
  const activityLabel = latest
453
383
  ? `last reported: ${advisorActivityPreview(latest)} (${Math.max(0, Math.floor((Date.now() - (details.lastActivityAt ?? Date.now())) / 1_000))}s ago)`
454
384
  : `awaiting first activity from ${backendLabel}`;
455
- return `Bro advisor · running · ${Math.floor(details.elapsedMs / 1_000)}s · attempt ${details.attempt}/${details.of} · ${activityLabel}`;
385
+ return `Bro advisor · running · ${Math.floor(details.elapsedMs / 1_000)}s · ${activityLabel}`;
456
386
  }
457
387
 
458
388
  export function registerAdvisorTool(pi: ExtensionAPI): void {
@@ -460,8 +390,8 @@ export function registerAdvisorTool(pi: ExtensionAPI): void {
460
390
  name: ADVISOR_TOOL_NAME,
461
391
  label: "Bro advisor",
462
392
  description:
463
- "Consult a fresh, independent process of the configured advisor backend for a second opinion mid-task. It has real, unsandboxed tool access in the current workspace (read files, search, run commands) with permissions auto-approved, and is instructed to investigate before advising and to leave edits to you — that is a behavioral instruction to the advisor, not an enforced restriction, so treat its findings as advice rather than a delegated implementation. No need to prepare a summary or evidence first: Bro automatically captures your system instructions, active tools, and the conversation so far, plus any human-set steering priorities, and sends them to the advisor.",
464
- promptSnippet: "Consult a fresh configured-backend process for a second opinion mid-task; it investigates the workspace itself and returns advice",
393
+ "Consult a fresh, independent process of the configured advisor backend for a second opinion mid-task. It has real, unsandboxed tool access in the current workspace (read files, search, run commands) with permissions auto-approved, and is instructed to use the captured snapshot first, inspect the workspace only when needed, and leave edits to you — that is a behavioral instruction to the advisor, not an enforced restriction, so treat its findings as advice rather than a delegated implementation. No need to prepare a summary or evidence first: Bro automatically captures your system instructions, active tools, and the conversation so far, plus any human-set steering priorities, and sends them to the advisor.",
394
+ promptSnippet: "Consult a fresh configured-backend process for a second opinion mid-task; it reviews the captured session snapshot, can inspect the workspace when needed, and returns advice",
465
395
  promptGuidelines: [
466
396
  "Use bro_advisor when the user asks for an independent opinion, or when one would likely settle real uncertainty or catch a costly mistake. Routine decisions do not require consultation.",
467
397
  "bro_advisor's question parameter is optional — Bro captures context automatically, so you do not need to prepare a summary or evidence before calling.",
@@ -474,6 +404,8 @@ export function registerAdvisorTool(pi: ExtensionAPI): void {
474
404
  ),
475
405
  }),
476
406
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
407
+ // The in-process Pi backend needs the host registry; publish it before any consultation.
408
+ setPiHostContext(ctx);
477
409
  const state = resolveAdvisorState(ctx.sessionManager.getBranch());
478
410
  const durableSteering = await readAdvisorSteering();
479
411
  const settings = await readSettings();
@@ -483,21 +415,20 @@ export function registerAdvisorTool(pi: ExtensionAPI): void {
483
415
  const prompt = buildAdvisorPrompt({ durable: durableSteering, session: state.steering }, snapshot.text, params?.question);
484
416
  const hasDurable = Boolean(durableSteering.trim());
485
417
  const hasSession = Boolean(state.steering.trim());
486
- let lastAttempt: AdvisorToolDetails = { status: "investigating", attempt: 1, of: 3, elapsedMs: 0, backend };
418
+ let lastProgress: AdvisorToolDetails = { status: "investigating", elapsedMs: 0, backend };
487
419
  try {
488
- const run = await runAdvisorWithRetries(
420
+ const run = await runAdvisor(
489
421
  prompt,
490
422
  selection,
491
423
  ctx.cwd,
492
424
  signal ?? new AbortController().signal,
493
425
  undefined,
494
- undefined,
495
426
  (details) => {
496
- lastAttempt = { ...details, backend };
497
- const label = advisorAttemptLabel(lastAttempt);
427
+ lastProgress = { ...details, backend };
428
+ const label = advisorAttemptLabel(lastProgress);
498
429
  onUpdate?.({
499
430
  content: [{ type: "text", text: label }],
500
- details: lastAttempt,
431
+ details: lastProgress,
501
432
  });
502
433
  // A host's tool-card renderer may replace onUpdate's partial renderResult with its
503
434
  // own generic placeholder for the whole run (observed with pi-cc-extensions' default
@@ -511,9 +442,8 @@ export function registerAdvisorTool(pi: ExtensionAPI): void {
511
442
  const effort = selection.effort ?? "model default";
512
443
  const omissions = `image/reasoning bodies omitted when present; ${snapshot.hadCompaction ? "Pi compaction summaries replace earlier turns" : "no Pi compaction summary present"}`;
513
444
  const details: AdvisorToolDetails = {
514
- ...lastAttempt,
445
+ ...lastProgress,
515
446
  status: "done",
516
- attempt: run.attempts,
517
447
  backend,
518
448
  model: selection.model,
519
449
  effort,
@@ -524,12 +454,12 @@ export function registerAdvisorTool(pi: ExtensionAPI): void {
524
454
  snapshotChars: snapshot.text.length,
525
455
  broTruncated: false,
526
456
  omissions,
527
- // run.activityCount is the exact final total; lastAttempt's may lag behind by up to
457
+ // run.activityCount is the exact final total; lastProgress's may lag behind by up to
528
458
  // the activity throttle window.
529
459
  activityCount: run.activityCount,
530
460
  };
531
- // The backend qualifier appears only off Agy, keeping the Agy header byte-identical.
532
- const header = `Bro advisor · ${backend === "agy" ? "" : `backend: ${backend} · `}model: ${selection.model} · effort: ${effort} · ${run.attempts} attempt${run.attempts === 1 ? "" : "s"} · ${Math.ceil(run.durationMs / 1_000)}s`;
461
+ // The backend qualifier appears only off Agy, keeping the Agy header concise.
462
+ const header = `Bro advisor · ${backend === "agy" ? "" : `backend: ${backend} · `}model: ${selection.model} · effort: ${effort} · ${Math.ceil(run.durationMs / 1_000)}s`;
533
463
  const steeringSummary = hasDurable && hasSession
534
464
  ? "included (durable+session)"
535
465
  : hasDurable