@juanhuttemann/pi-deep-research 0.1.6 → 0.2.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/README.md CHANGED
@@ -32,8 +32,9 @@ setup, while Exa, Tavily and Firecrawl use their keys from `drsh setup`.
32
32
  ## What it adds
33
33
 
34
34
  - **`deep_research` tool.** Ask Pi to research something.
35
- - While the run goes, the call shows the phase, each sub-agent, the
36
- searches, pages and sources so far, and the model's reasoning.
35
+ - While the run goes, the call shows the phase with a spinner and how
36
+ long it has taken, each sub-agent, and the searches, pages and sources
37
+ so far.
37
38
  - When it ends, the call shows the confidence, the fact-check's verdicts,
38
39
  the claims it did not confirm, and the report's path.
39
40
  - Esc stops a run. It keeps a checkpoint, and resuming from it skips the
@@ -52,10 +53,16 @@ setup, while Exa, Tavily and Firecrawl use their keys from `drsh setup`.
52
53
  fact-checked.
53
54
  - **`/research [--topics 3 --follow-ups off --domains a,b …] question`**
54
55
  runs a research yourself.
55
- - With no flags it opens the settings screen first.
56
+ - With no flags it opens the settings screen first: ←/→ steps the
57
+ setting under the cursor through its values, Enter lists them all.
56
58
  - You answer the clarifying questions and review the plan, then the run
57
59
  starts and the agent reports what it found.
58
- - `/research-stop` ends the run.
60
+ - `/research-stop` ends the run, keeping a checkpoint.
61
+ - `/research-resume` continues the last stopped, failed or incomplete
62
+ run from its checkpoint without repeating finished searches;
63
+ `/research-resume <checkpoint>` continues another. A run stopped
64
+ before its plan was made has no checkpoint and nothing spent: it
65
+ starts again with the same question, settings and answers.
59
66
  - **`/research-model`** picks the model research runs use:
60
67
  - Pi's current model, the default.
61
68
  - Another of Pi's models, for example a cheaper one for the many calls a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanhuttemann/pi-deep-research",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Fact-checked, cited web research inside Pi: runs the deep-research CLI (drsh) on Pi's own model, with live progress, clarifying questions and plan review",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/events.ts CHANGED
@@ -66,9 +66,6 @@ export interface RunState {
66
66
  tokens: number;
67
67
  // status is the latest transient line: which model is asked, a retry.
68
68
  status: string;
69
- // thinking is the tail of the reasoning streaming now, for a model that
70
- // thinks for minutes before its first word.
71
- thinking: string;
72
69
  errors: string[];
73
70
  domains: DomainCheck[];
74
71
  }
@@ -83,15 +80,11 @@ export function initialState(): RunState {
83
80
  sources: 0,
84
81
  tokens: 0,
85
82
  status: "",
86
- thinking: "",
87
83
  errors: [],
88
84
  domains: [],
89
85
  };
90
86
  }
91
87
 
92
- // thinkingTail bounds the reasoning kept: the view shows a line or two of it.
93
- const thinkingTail = 240;
94
-
95
88
  // maxErrors bounds the non-fatal errors kept for the view; the full list is
96
89
  // in the run's timeline.
97
90
  const maxErrors = 5;
@@ -130,7 +123,6 @@ export function reduce(s: RunState, e: DrshEvent): RunState {
130
123
  case "phase":
131
124
  s.phase = e.phase ?? s.phase;
132
125
  s.phaseDetail = e.detail ?? "";
133
- s.thinking = "";
134
126
  break;
135
127
  case "subagent":
136
128
  subagent(s, e);
@@ -145,7 +137,6 @@ export function reduce(s: RunState, e: DrshEvent): RunState {
145
137
  case "report":
146
138
  s.phase = e.phase || "Report";
147
139
  s.phaseDetail = e.detail ?? "";
148
- s.thinking = "";
149
140
  if (e.sources) s.sources = e.sources;
150
141
  break;
151
142
  case "citation":
@@ -156,10 +147,6 @@ export function reduce(s: RunState, e: DrshEvent): RunState {
156
147
  case "info":
157
148
  if (e.transient && e.detail) s.status = e.detail.split("\n")[0];
158
149
  break;
159
- case "thinking":
160
- s.thinking = (e.status === "start" ? "" : s.thinking) + (e.detail ?? "");
161
- s.thinking = s.thinking.slice(-thinkingTail);
162
- break;
163
150
  case "error":
164
151
  if (e.detail) s.errors = [...s.errors, e.detail].slice(-maxErrors);
165
152
  break;
package/src/index.ts CHANGED
@@ -16,7 +16,7 @@ import { checkAnswers, clip, maxAnswerChars, maxAnswers, type Answer } from "./a
16
16
  import { startBridge, type Bridge } from "./bridge.ts";
17
17
  import type { Question } from "./events.ts";
18
18
  import { planLines, subTopicNames, withSubTopics, type Plan } from "./plan.ts";
19
- import { outcomeLines, progressLines, type ResearchDetails } from "./render.ts";
19
+ import { count, outcomeLines, progressLines, type ResearchDetails, tickMs } from "./render.ts";
20
20
  import { research, type Hooks, type Request, type Result, type RunRecord } from "./research.ts";
21
21
  import { runPlain } from "./runner.ts";
22
22
  import {
@@ -28,9 +28,11 @@ import {
28
28
  paramName,
29
29
  parseCommandArgs,
30
30
  parseSettings,
31
+ step,
31
32
  valueLabel,
32
33
  type Setting,
33
34
  } from "./settings.ts";
35
+ import { type MenuResult, pick as pickWithNotice, SettingsMenu, startLabel } from "./menu.ts";
34
36
 
35
37
  const modelEntry = "deep-research-model";
36
38
  const runEntry = "deep-research-run";
@@ -67,27 +69,26 @@ async function newReportsDir(question: string): Promise<string> {
67
69
  return mkdtemp(join(reportsRoot(), `${stamp}-${slug}-`));
68
70
  }
69
71
 
70
- // throttle limits f to once per ms. cancel drops a pending call: one firing
71
- // after the run ended would redraw progress the run already cleared.
72
- function throttle(f: () => void, ms: number): { call(): void; cancel(): void } {
73
- let last = 0;
72
+ // ticker draws the live view every ms while live() holds, not only when
73
+ // drsh sends an event: a model call is a minute with no events, and the
74
+ // spinner and clock must keep moving through it. While the view is still
75
+ // (the user answering or reviewing) it draws on each update only, so a
76
+ // tool call does not send the same view ten times a second. cancel stops
77
+ // it: one firing after the run ended would redraw progress the run already
78
+ // cleared.
79
+ function ticker(f: () => void, ms: number, live: () => boolean): { call(): void; cancel(): void } {
74
80
  let timer: NodeJS.Timeout | undefined;
75
81
  return {
76
82
  call() {
77
- const wait = last + ms - Date.now();
78
- if (wait <= 0) {
79
- last = Date.now();
83
+ if (!timer) {
84
+ timer = setInterval(() => live() && f(), ms);
85
+ f();
86
+ } else if (!live()) {
80
87
  f();
81
- } else if (!timer) {
82
- timer = setTimeout(() => {
83
- timer = undefined;
84
- last = Date.now();
85
- f();
86
- }, wait);
87
88
  }
88
89
  },
89
90
  cancel() {
90
- if (timer) clearTimeout(timer);
91
+ if (timer) clearInterval(timer);
91
92
  timer = undefined;
92
93
  },
93
94
  };
@@ -124,7 +125,16 @@ export default function deepResearch(pi: ExtensionAPI) {
124
125
  // by default: a run stopped or failed after it leaves none, and must not
125
126
  // hide the one before.
126
127
  let lastReport: RunRecord | undefined;
128
+ // lastRun is the last run of any outcome: /research-resume continues it
129
+ // when it left a checkpoint.
130
+ let lastRun: RunRecord | undefined;
127
131
  let commandRun: AbortController | undefined;
132
+ // commandEnded settles when commandRun's run has wound down.
133
+ let commandEnded: Promise<void> = Promise.resolve();
134
+ // session counts session starts. A run stopped by a session switch ends
135
+ // after the next session has started; recorded there, it became that
136
+ // session's last run, the one /research-resume picks.
137
+ let session = 0;
128
138
 
129
139
  async function loadSettings(): Promise<Setting[]> {
130
140
  try {
@@ -197,6 +207,7 @@ export default function deepResearch(pi: ExtensionAPI) {
197
207
  function remember(rec: RunRecord | undefined): void {
198
208
  if (!rec) return;
199
209
  if (rec.json) lastReport = rec;
210
+ lastRun = rec;
200
211
  pi.appendEntry(runEntry, rec);
201
212
  }
202
213
 
@@ -225,10 +236,13 @@ export default function deepResearch(pi: ExtensionAPI) {
225
236
  const edit = "Edit sub-topics";
226
237
  const stop = "Cancel";
227
238
  let plan = (raw ?? {}) as Plan;
239
+ // notice is why the last edit was not taken, shown under the options.
240
+ let notice: string | undefined;
228
241
  try {
229
242
  for (;;) {
230
243
  ctx.ui.setWidget("deep-research-plan", planLines(plan));
231
- const pick = await ctx.ui.select("Review the plan", [run, edit, stop], { signal });
244
+ const pick = await pickWithNotice(ctx, "Review the plan", [run, edit, stop], { notice, signal });
245
+ notice = undefined;
232
246
  if (pick === undefined || pick === stop) return "stop";
233
247
  if (pick === run) return plan;
234
248
  const text = await untilAborted(
@@ -238,7 +252,7 @@ export default function deepResearch(pi: ExtensionAPI) {
238
252
  if (text === undefined) continue;
239
253
  const edited = withSubTopics(plan, text);
240
254
  if (!edited.sub_topics?.length) {
241
- ctx.ui.notify("A plan needs at least one sub-topic", "warning");
255
+ notice = "A plan needs at least one sub-topic";
242
256
  continue;
243
257
  }
244
258
  plan = edited;
@@ -255,13 +269,14 @@ export default function deepResearch(pi: ExtensionAPI) {
255
269
  signal: AbortSignal | undefined,
256
270
  hooks: Hooks,
257
271
  ): Promise<{ result: Result; bridge?: Bridge }> {
272
+ const started = session;
258
273
  const s = await ensureSettings();
259
274
  const { model, label } = resolveModel(ctx, modelName);
260
275
  const reports = await newReportsDir(req.kind === "new" ? req.run.question : "resume");
261
276
  const { value, bridge } = await withEndpoint(ctx, model, signal, (env) =>
262
277
  research({ bin, settings: s, env, signal, reports, model: label, req, hooks }),
263
278
  );
264
- remember(value.record);
279
+ if (started === session) remember(value.record);
265
280
  return { result: value, bridge };
266
281
  }
267
282
 
@@ -348,9 +363,9 @@ export default function deepResearch(pi: ExtensionAPI) {
348
363
  const p = params as Record<string, unknown>;
349
364
  const req = requestOf(await ensureSettings(), p);
350
365
  let latest: ResearchDetails | undefined;
351
- const push = throttle(() => {
366
+ const push = ticker(() => {
352
367
  if (latest) onUpdate?.({ content: [{ type: "text", text: progressLines(latest, plainTheme).join("\n") }], details: latest });
353
- }, 250);
368
+ }, tickMs, () => latest?.started !== undefined);
354
369
  const hooks: Hooks = {
355
370
  update: (d) => {
356
371
  latest = d;
@@ -441,11 +456,14 @@ export default function deepResearch(pi: ExtensionAPI) {
441
456
  }
442
457
 
443
458
  pi.on("session_start", async (_event, ctx) => {
459
+ session++;
444
460
  choice = { kind: "pi" };
445
461
  lastReport = undefined;
462
+ lastRun = undefined;
446
463
  for (const e of ctx.sessionManager.getBranch()) {
447
464
  if (e.type !== "custom") continue;
448
465
  if (e.customType === modelEntry && e.data) choice = e.data as ModelChoice;
466
+ if (e.customType === runEntry && e.data) lastRun = e.data as RunRecord;
449
467
  if (e.customType === runEntry && (e.data as RunRecord | undefined)?.json) lastReport = e.data as RunRecord;
450
468
  }
451
469
  try {
@@ -459,21 +477,62 @@ export default function deepResearch(pi: ExtensionAPI) {
459
477
  commandRun?.abort();
460
478
  });
461
479
 
462
- // settingsScreen is the start screen: each setting at its value, what
463
- // instant holds shown as held, Start first.
480
+ // settingsScreen is the start screen: each setting at its value, Start
481
+ // first.
482
+ // ←/→ step a row through its choices in place; Enter opens its full
483
+ // option list, and the cursor comes back to that row. A row the depth
484
+ // holds (instant) is not changed under it, as drsh's own /mode refuses:
485
+ // the depth wins, so a value chosen there would do nothing for this run
486
+ // and come into force unseen if the depth were changed after.
464
487
  async function settingsScreen(ctx: ExtensionContext, s: Setting[], values: Record<string, string>): Promise<Record<string, string> | undefined> {
465
- const start = "▶ Start";
466
- for (;;) {
488
+ let selected = 0;
489
+ const rows = () => {
467
490
  const eff = effective(s, values);
468
- const held = implied(s, values);
469
- const rows = s.map((x) => {
470
- const mark = held[x.key] !== undefined && values[x.key] === undefined ? " (held by the depth)" : "";
471
- return `${x.label}: ${valueLabel(x, eff[x.key])}${mark}`;
491
+ return s.map((x) => `${x.label}: ${valueLabel(x, eff[x.key])}`);
492
+ };
493
+ // heldWhy is why x cannot change now, or undefined when it can.
494
+ const heldWhy = (x: Setting) => {
495
+ if (implied(s, values)[x.key] === undefined) return undefined;
496
+ const by = s.find((y) => y.choices.find((o) => o.value === (values[y.key] ?? y.value))?.implies?.[x.key] !== undefined);
497
+ const name = by?.label ?? "depth";
498
+ const depth = by ? `${valueLabel(by, values[by.key] ?? by.value)} ${name}` : "the depth";
499
+ return `${depth} holds every option at its least: pick another ${name} to change ${x.label}`;
500
+ };
501
+ // The menu checks heldWhy before stepping; this is the select's guard.
502
+ const stepRow = (row: number, dir: 1 | -1) => {
503
+ const x = s[row];
504
+ if (heldWhy(x) === undefined) values = { ...values, [x.key]: step(x, effective(s, values)[x.key], dir) };
505
+ };
506
+ const title = "deep-research settings";
507
+ // Outside the terminal (Pi's RPC mode) custom components are not
508
+ // drawn and custom() answers undefined: the plain select, no arrows.
509
+ const viaSelect = async (): Promise<MenuResult> => {
510
+ const r = rows();
511
+ const pick = await ctx.ui.select(title, [startLabel, ...r]);
512
+ if (pick === undefined) return { kind: "cancel" };
513
+ return pick === startLabel ? { kind: "start" } : { kind: "edit", row: r.indexOf(pick) };
514
+ };
515
+ const viaMenu = () =>
516
+ ctx.ui.custom<MenuResult | undefined>((_tui, theme, kb, done) => {
517
+ const held = (row: number) => heldWhy(s[row]);
518
+ const menu = new SettingsMenu(theme, kb, { title, rows, step: stepRow, held, selected }, (r) => {
519
+ selected = menu.selectedLine;
520
+ done(r);
521
+ });
522
+ return menu;
472
523
  });
473
- const pick = await ctx.ui.select("deep-research settings", [start, ...rows]);
474
- if (pick === undefined) return undefined;
475
- if (pick === start) return values;
476
- const x = s[rows.indexOf(pick)];
524
+ for (;;) {
525
+ const pick = (ctx.mode === "tui" ? await viaMenu() : undefined) ?? (await viaSelect());
526
+ if (pick.kind === "cancel") return undefined;
527
+ if (pick.kind === "start") return values;
528
+ const x = s[pick.row];
529
+ // Only the select lets Enter through on a held row: it has no
530
+ // line of its own to say why.
531
+ const why = heldWhy(x);
532
+ if (why !== undefined) {
533
+ ctx.ui.notify(why, "warning");
534
+ continue;
535
+ }
477
536
  const opts = x.choices.map((o) => `${o.label}${o.note ? ` — ${o.note}` : ""}`);
478
537
  const v = await ctx.ui.select(`${x.label}: ${x.help}`, opts);
479
538
  if (v !== undefined) values = { ...values, [x.key]: x.choices[opts.indexOf(v)].value };
@@ -483,27 +542,72 @@ export default function deepResearch(pi: ExtensionAPI) {
483
542
  pi.registerCommand("research", {
484
543
  description: "Research a question: settings, clarifying questions and plan review, then a live run",
485
544
  getArgumentCompletions: (prefix) => (settings.length ? completions(settings, prefix) : null),
486
- handler: async (args, ctx) => {
487
- if (commandRun) {
488
- ctx.ui.notify("A research run is already going; /research-stop ends it", "warning");
489
- return;
490
- }
491
- // Taken before the first await: the settings and the prompts wait
492
- // on the user, and a second /research in that time passed the
493
- // check above and started a run of its own; the first to end then
494
- // cleared this while the other went on, past /research-stop.
495
- const abort = new AbortController();
496
- commandRun = abort;
497
- try {
498
- await researchCommand(args, ctx, abort);
499
- } finally {
500
- commandRun = undefined;
501
- }
502
- },
545
+ handler: (args, ctx) => commandRunWith(ctx, (abort) => researchCommand(args, ctx, abort)),
503
546
  });
504
547
 
505
- // researchCommand is /research once it holds commandRun.
506
- async function researchCommand(args: string, ctx: ExtensionContext, abort: AbortController): Promise<void> {
548
+ pi.registerCommand("research-resume", {
549
+ description: "Resume the last stopped, failed or incomplete research run from its checkpoint (or the checkpoint path given); one stopped before its plan starts again",
550
+ handler: (args, ctx) =>
551
+ commandRunWith(ctx, async (abort) => {
552
+ const checkpoint = args.trim() || lastRun?.checkpoint;
553
+ if (checkpoint) return { running: backgroundRun(ctx, abort, { kind: "resume", checkpoint }) };
554
+ // Stopped before its plan: nothing was spent and drsh kept no
555
+ // checkpoint, so it is asked again as it was, settings and
556
+ // answers included, with the plan to review.
557
+ if (lastRun?.request) {
558
+ return { running: backgroundRun(ctx, abort, { kind: "new", run: structuredClone(lastRun.request), review: true }) };
559
+ }
560
+ // Only the last run is resumed: one that ended after a
561
+ // stopped run superseded it.
562
+ const why = lastRun ? `The last research run (${lastRun.status}) left nothing to resume` : "No research run in this session yet";
563
+ ctx.ui.notify(`${why}; /research-resume <checkpoint path> resumes another`, "info");
564
+ return undefined;
565
+ }),
566
+ });
567
+
568
+ // commandRunWith runs start holding commandRun, the one /research run
569
+ // /research-stop ends. start awaits its prompts and hands back the run
570
+ // it started, unawaited; undefined when it ended before a run.
571
+ async function commandRunWith(ctx: ExtensionContext, start: (abort: AbortController) => Promise<{ running: Promise<void> } | undefined>): Promise<void> {
572
+ // A stopped run takes a moment to wind down (drsh's exit, the
573
+ // bridge closing): a command typed in it was refused as "already
574
+ // going". Wait for it instead.
575
+ if (commandRun?.signal.aborted) await commandEnded;
576
+ if (commandRun) {
577
+ ctx.ui.notify("A research run is already going; /research-stop ends it", "warning");
578
+ return;
579
+ }
580
+ // Taken before the first await: the settings and the prompts wait
581
+ // on the user, and a second /research in that time passed the
582
+ // check above and started a run of its own; the first to end then
583
+ // cleared this while the other went on, past /research-stop.
584
+ const abort = new AbortController();
585
+ commandRun = abort;
586
+ let running: Promise<void> | undefined;
587
+ try {
588
+ running = (await start(abort))?.running;
589
+ } finally {
590
+ if (!running) commandRun = undefined;
591
+ }
592
+ // The run goes on after the handler returns: Pi runs one submitted
593
+ // command at a time, and a handler that awaited the whole run left
594
+ // /research-stop queued behind it until the run had ended on its own.
595
+ // backgroundRun catches its own failures; the catch is for one in
596
+ // its cleanup, which would otherwise be an unhandled rejection.
597
+ if (running) {
598
+ commandEnded = running
599
+ .catch((err) => ctx.ui.notify(`research failed: ${(err as Error).message}`, "error"))
600
+ .finally(() => {
601
+ if (commandRun === abort) commandRun = undefined;
602
+ });
603
+ }
604
+ }
605
+
606
+ // researchCommand is /research once it holds commandRun: the prompts,
607
+ // awaited, then the run, started and handed back unawaited (in an
608
+ // object: await would unwrap a promise returned bare, and wait for the
609
+ // whole run again); undefined when the prompts ended it before a run.
610
+ async function researchCommand(args: string, ctx: ExtensionContext, abort: AbortController): Promise<{ running: Promise<void> } | undefined> {
507
611
  let s: Setting[];
508
612
  try {
509
613
  s = await ensureSettings();
@@ -532,15 +636,22 @@ export default function deepResearch(pi: ExtensionAPI) {
532
636
  }
533
637
  // /research-stop while the prompts were open.
534
638
  if (abort.signal.aborted) return;
535
- const status = throttle(() => {
639
+ const req: Request = { kind: "new", run: { question, values, domains: parsed.domains }, review: true };
640
+ return { running: backgroundRun(ctx, abort, req) };
641
+ }
642
+
643
+ // backgroundRun is a /research run from its clarifying questions on (or
644
+ // a resumed one), with its live view; every failure ends in a notice, so
645
+ // the promise never rejects.
646
+ async function backgroundRun(ctx: ExtensionContext, abort: AbortController, req: Request): Promise<void> {
647
+ const status = ticker(() => {
536
648
  if (!latest) return;
537
649
  const lines = progressLines(latest, ctx.ui.theme);
538
650
  ctx.ui.setWidget("deep-research", lines);
539
651
  ctx.ui.setStatus("deep-research", `research: ${latest.state?.phase || latest.stage}`);
540
- }, 250);
652
+ }, tickMs, () => latest?.started !== undefined);
541
653
  let latest: ResearchDetails | undefined;
542
654
  try {
543
- const req: Request = { kind: "new", run: { question, values, domains: parsed.domains }, review: true };
544
655
  const { result, bridge } = await run(ctx, req, undefined, abort.signal, {
545
656
  update: (d) => {
546
657
  latest = d;
@@ -554,7 +665,7 @@ export default function deepResearch(pi: ExtensionAPI) {
554
665
  { triggerTurn: result.details.outcome !== undefined && result.details.outcome.status !== "cancelled" },
555
666
  );
556
667
  if (bridge?.usage.totalTokens) {
557
- ctx.ui.notify(`research used ${bridge.usage.totalTokens} tokens ($${bridge.usage.cost.total.toFixed(4)}) on ${bridge.modelName}`, "info");
668
+ ctx.ui.notify(`research used ${count(bridge.usage.totalTokens)} tokens ($${bridge.usage.cost.total.toFixed(4)}) on ${bridge.modelName}`, "info");
558
669
  }
559
670
  } catch (err) {
560
671
  ctx.ui.notify(`research failed: ${(err as Error).message}`, "error");
@@ -566,7 +677,7 @@ export default function deepResearch(pi: ExtensionAPI) {
566
677
  }
567
678
 
568
679
  pi.registerCommand("research-stop", {
569
- description: "Stop the research run /research started; it keeps a checkpoint to resume from",
680
+ description: "Stop the research run /research started; it keeps a checkpoint /research-resume continues from",
570
681
  handler: async (_args, ctx) => {
571
682
  if (!commandRun) {
572
683
  ctx.ui.notify("No /research run is going (a run the agent started stops with Esc)", "info");
package/src/menu.ts ADDED
@@ -0,0 +1,208 @@
1
+ // The extension's lists: Pi's own select dialog, drawn the same way
2
+ // (ExtensionSelectorComponent), plus a warning line under the options.
3
+ // ctx.ui.select has no place for one, so a warning went to ctx.ui.notify
4
+ // and showed at the top of the screen, far from the list it was about. The
5
+ // settings screen's list adds ←/→ to step a setting through its choices in
6
+ // place; Enter still hands the row back for the full option list.
7
+
8
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
9
+ import { Container, type KeybindingsManager, matchesKey, Spacer, Text } from "@earendil-works/pi-tui";
10
+
11
+ // Menu is a list of lines with a cursor and an optional warning under them.
12
+ // Enter picks the line under the cursor, the cancel key closes it.
13
+ export class Menu extends Container {
14
+ protected selected: number;
15
+ // notice is the warning under the list, until the next key that moves
16
+ // or changes something.
17
+ protected notice: string | undefined;
18
+ private readonly list = new Container();
19
+ protected readonly theme: Theme;
20
+ protected readonly kb: KeybindingsManager;
21
+ private readonly lines: () => string[];
22
+ private readonly close: (line: number | undefined) => void;
23
+
24
+ constructor(
25
+ theme: Theme,
26
+ kb: KeybindingsManager,
27
+ o: { title: string; lines: () => string[]; selected?: number; notice?: string; arrows?: boolean },
28
+ close: (line: number | undefined) => void,
29
+ ) {
30
+ super();
31
+ this.theme = theme;
32
+ this.kb = kb;
33
+ this.lines = o.lines;
34
+ this.close = close;
35
+ this.selected = o.selected ?? 0;
36
+ this.notice = o.notice;
37
+ this.addChild(new Border(theme));
38
+ this.addChild(new Spacer(1));
39
+ this.addChild(new Text(theme.fg("accent", theme.bold(o.title)), 1, 0));
40
+ this.addChild(new Spacer(1));
41
+ this.addChild(this.list);
42
+ this.addChild(new Spacer(1));
43
+ const hint = (k: string, d: string) => theme.fg("dim", k) + theme.fg("muted", ` ${d}`);
44
+ // The keys Pi's own dialog names, from the user's keybindings.
45
+ const keys = (k: "tui.select.confirm" | "tui.select.cancel") => kb.getKeys(k).join("/");
46
+ const line = [
47
+ hint("↑↓", "navigate"),
48
+ ...(o.arrows ? [hint("←→", "change")] : []),
49
+ hint(keys("tui.select.confirm"), "select"),
50
+ hint(keys("tui.select.cancel"), "cancel"),
51
+ ];
52
+ this.addChild(new Text(line.join(" "), 1, 0));
53
+ this.addChild(new Spacer(1));
54
+ this.addChild(new Border(theme));
55
+ this.draw();
56
+ }
57
+
58
+ // selectedLine is where the cursor is.
59
+ get selectedLine(): number {
60
+ return this.selected;
61
+ }
62
+
63
+ protected draw(): void {
64
+ const lines = this.lines();
65
+ this.selected = Math.min(this.selected, lines.length - 1);
66
+ this.list.clear();
67
+ lines.forEach((l, i) => {
68
+ const text = i === this.selected ? this.theme.fg("accent", `→ ${l}`) : ` ${this.theme.fg("text", l)}`;
69
+ this.list.addChild(new Text(text, 1, 0));
70
+ });
71
+ if (this.notice) {
72
+ this.list.addChild(new Spacer(1));
73
+ this.list.addChild(new Text(this.theme.fg("warning", this.notice), 1, 0));
74
+ }
75
+ }
76
+
77
+ // warn shows why under the list, until the next move.
78
+ protected warn(why: string): void {
79
+ this.notice = why;
80
+ this.draw();
81
+ }
82
+
83
+ // key handles a key a subclass adds; true when it changed something to
84
+ // redraw.
85
+ protected key(_data: string): boolean {
86
+ return false;
87
+ }
88
+
89
+ // confirm is Enter on the line under the cursor.
90
+ protected confirm(): void {
91
+ this.close(this.selected);
92
+ }
93
+
94
+ handleInput(data: string): void {
95
+ // Pi's own bindings first: a user who bound ← or → to confirm or
96
+ // cancel keeps that.
97
+ if (this.kb.matches(data, "tui.select.confirm") || data === "\n") {
98
+ this.confirm();
99
+ return;
100
+ }
101
+ if (this.kb.matches(data, "tui.select.cancel")) {
102
+ this.close(undefined);
103
+ return;
104
+ }
105
+ if (this.kb.matches(data, "tui.select.up") || data === "k") {
106
+ this.selected = Math.max(0, this.selected - 1);
107
+ } else if (this.kb.matches(data, "tui.select.down") || data === "j") {
108
+ this.selected = Math.min(this.lines().length - 1, this.selected + 1);
109
+ } else if (!this.key(data)) {
110
+ return;
111
+ }
112
+ this.notice = undefined;
113
+ this.draw();
114
+ }
115
+ }
116
+
117
+ // pick is ctx.ui.select with a warning under the options, closed when the
118
+ // signal aborts as select is. Outside the terminal (Pi's RPC mode) custom
119
+ // components are not drawn: there it is the plain select, the warning a
120
+ // notice.
121
+ export async function pick(
122
+ ctx: ExtensionContext,
123
+ title: string,
124
+ options: string[],
125
+ o: { notice?: string; signal?: AbortSignal } = {},
126
+ ): Promise<string | undefined> {
127
+ if (ctx.mode !== "tui") {
128
+ if (o.notice) ctx.ui.notify(o.notice, "warning");
129
+ return ctx.ui.select(title, options, { signal: o.signal });
130
+ }
131
+ if (o.signal?.aborted) return undefined;
132
+ let onAbort = () => {};
133
+ const line = await ctx.ui.custom<number | undefined>((_tui, theme, kb, done) => {
134
+ onAbort = () => done(undefined);
135
+ o.signal?.addEventListener("abort", onAbort, { once: true });
136
+ return new Menu(theme, kb, { title, lines: () => options, notice: o.notice }, done);
137
+ });
138
+ o.signal?.removeEventListener("abort", onAbort);
139
+ return line === undefined ? undefined : options[line];
140
+ }
141
+
142
+ // MenuResult is how the settings menu closed: on Start, on a setting row
143
+ // (Enter, to pick from its option list) or cancelled.
144
+ export type MenuResult = { kind: "start" } | { kind: "edit"; row: number } | { kind: "cancel" };
145
+
146
+ export interface MenuOptions {
147
+ title: string;
148
+ // rows draws the setting rows at their current values; it is called again
149
+ // after every step.
150
+ rows: () => string[];
151
+ // step moves setting row `row` (0-based, Start not counted) one choice
152
+ // forward (1) or back (-1).
153
+ step: (row: number, dir: 1 | -1) => void;
154
+ // held says why setting row `row` cannot change now (the depth holds
155
+ // it), or undefined when it can. A held row's ←/→ and Enter show that
156
+ // under the list instead of changing it.
157
+ held?: (row: number) => string | undefined;
158
+ // selected is the line the cursor starts on: 0 is Start, 1 the first row.
159
+ selected?: number;
160
+ }
161
+
162
+ export const startLabel = "▶ Start";
163
+
164
+ // SettingsMenu is the start screen's list: Start, then a row per setting.
165
+ export class SettingsMenu extends Menu {
166
+ private readonly opts: MenuOptions;
167
+
168
+ constructor(theme: Theme, kb: KeybindingsManager, opts: MenuOptions, done: (r: MenuResult) => void) {
169
+ super(theme, kb, { title: opts.title, lines: () => [startLabel, ...opts.rows()], selected: opts.selected, arrows: true }, (line) =>
170
+ done(line === undefined ? { kind: "cancel" } : line === 0 ? { kind: "start" } : { kind: "edit", row: line - 1 }),
171
+ );
172
+ this.opts = opts;
173
+ }
174
+
175
+ // refused shows why the row under the cursor is held, if it is.
176
+ private refused(): boolean {
177
+ const why = this.selected > 0 ? this.opts.held?.(this.selected - 1) : undefined;
178
+ if (why === undefined) return false;
179
+ this.warn(why);
180
+ return true;
181
+ }
182
+
183
+ protected override confirm(): void {
184
+ if (!this.refused()) super.confirm();
185
+ }
186
+
187
+ // ←/→ step the row under the cursor. On Start there is nothing to step;
188
+ // a held row says why, and its warning stays.
189
+ protected override key(data: string): boolean {
190
+ if (!matchesKey(data, "left") && !matchesKey(data, "right")) return false;
191
+ if (this.selected === 0 || this.refused()) return false;
192
+ this.opts.step(this.selected - 1, matchesKey(data, "right") ? 1 : -1);
193
+ return true;
194
+ }
195
+ }
196
+
197
+ // Border is DynamicBorder drawn with the theme Pi hands the component: Pi's
198
+ // own reads a global theme that an extension's module copy may not have set.
199
+ class Border {
200
+ private readonly theme: Theme;
201
+ constructor(theme: Theme) {
202
+ this.theme = theme;
203
+ }
204
+ invalidate(): void {}
205
+ render(width: number): string[] {
206
+ return [this.theme.fg("border", "─".repeat(Math.max(1, width)))];
207
+ }
208
+ }
package/src/render.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // How a research call looks in Pi's transcript: the run's progress while it
2
- // goes (phase, one line per sub-agent, counts, the latest status or
3
- // reasoning), then what it found.
2
+ // goes (phase with a spinner and its clock, one line per sub-agent, counts,
3
+ // the latest status), then what it found. As in drsh's own live frame, the
4
+ // streaming reasoning is not shown: its latest words, replaced as they
5
+ // streamed, were too hard to read and follow.
4
6
 
5
7
  import type { Theme } from "@earendil-works/pi-coding-agent";
6
8
  import type { RunState, SubAgent } from "./events.ts";
@@ -20,18 +22,52 @@ export interface ResearchDetails {
20
22
  question: string;
21
23
  model?: string;
22
24
  stage: "clarify" | "plan" | "run" | "done";
25
+ // started is when the stage began, in ms since the epoch: the clock
26
+ // beside the spinner counts from it. Unset, nothing is working (the
27
+ // user is answering or reviewing): no spinner and no clock.
28
+ started?: number;
23
29
  state?: RunState;
24
30
  outcome?: OutcomeDetails;
25
31
  }
26
32
 
27
- function glyph(a: SubAgent, t: Theme): string {
33
+ // spinnerFrames and tickMs are drsh's (spinnerFrames, tickInterval in
34
+ // internal/ui/render.go): the frame is the time over tickMs, so every view
35
+ // drawn at the same moment shows the same one.
36
+ const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
37
+ export const tickMs = 120;
38
+
39
+ function spinner(now: number, t: Theme): string {
40
+ return t.fg("accent", spinnerFrames[Math.floor(now / tickMs) % spinnerFrames.length]);
41
+ }
42
+
43
+ // clock is a duration as drsh writes it (formatDuration): m:ss, and h:mm:ss
44
+ // past an hour.
45
+ export function clock(ms: number): string {
46
+ const total = Math.max(0, Math.floor(ms / 1000));
47
+ const h = Math.floor(total / 3600);
48
+ const m = Math.floor((total % 3600) / 60);
49
+ const s = String(total % 60).padStart(2, "0");
50
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
51
+ }
52
+
53
+ // count abbreviates a large count: 10063 is 10.1K, 1500000 is 1.5M, and
54
+ // below a thousand the number as is. One decimal, as drsh's formatCount,
55
+ // dropped when it is .0 (1K, not 1.0K).
56
+ export function count(n: number): string {
57
+ // From 999,950 the thousands round to 1000.0: that is 1M, not 1000K.
58
+ const [div, unit] = n >= 999_950 ? [1e6, "M"] : n >= 1_000 ? [1e3, "K"] : [1, ""];
59
+ if (!unit) return String(n);
60
+ return `${(n / div).toFixed(1).replace(/\.0$/, "")}${unit}`;
61
+ }
62
+
63
+ function glyph(a: SubAgent, t: Theme, now: number): string {
28
64
  switch (a.state) {
29
65
  case "done":
30
66
  return t.fg("success", "●");
31
67
  case "error":
32
68
  return t.fg("error", "✗");
33
69
  case "running":
34
- return t.fg("accent", "◐");
70
+ return spinner(now, t);
35
71
  default:
36
72
  return t.fg("dim", "○");
37
73
  }
@@ -49,11 +85,15 @@ const stageLabel: Record<ResearchDetails["stage"], string> = {
49
85
  done: "Done",
50
86
  };
51
87
 
52
- export function progressLines(d: ResearchDetails, t: Theme): string[] {
88
+ // progressLines is the live view at now: the spinner's frame and the clock
89
+ // are read from it, so a view redrawn with no new event still moves.
90
+ export function progressLines(d: ResearchDetails, t: Theme, now = Date.now()): string[] {
53
91
  const s = d.state;
54
92
  const lines: string[] = [];
55
93
  const phase = s?.phase || stageLabel[d.stage];
56
- lines.push(`${t.fg("accent", phase)}${s?.phaseDetail ? t.fg("muted", ` · ${s.phaseDetail}`) : ""}`);
94
+ const time = d.started ? t.fg("muted", ` · ${clock(now - d.started)}`) : "";
95
+ const spin = d.started ? `${spinner(now, t)} ` : "";
96
+ lines.push(`${spin}${t.fg("accent", phase)}${s?.phaseDetail ? t.fg("muted", ` · ${s.phaseDetail}`) : ""}${time}`);
57
97
  if (!s) {
58
98
  return lines;
59
99
  }
@@ -64,14 +104,12 @@ export function progressLines(d: ResearchDetails, t: Theme): string[] {
64
104
  for (const a of s.subagents) {
65
105
  const pct = a.progress ? t.fg("muted", ` ${a.progress}%`) : "";
66
106
  const line = a.line && a.state !== "done" ? t.fg("dim", ` ${oneLine(a.line, 70)}`) : "";
67
- lines.push(` ${glyph(a, t)} ${oneLine(a.name, 50)}${pct}${line}`);
107
+ lines.push(` ${glyph(a, t, now)} ${oneLine(a.name, 50)}${pct}${line}`);
68
108
  }
69
109
  const counts = [`${s.searches} searches`, `${s.reads} pages`, `${s.sources} sources`];
70
- if (s.tokens) counts.push(`${s.tokens} tokens`);
110
+ if (s.tokens) counts.push(`${count(s.tokens)} tokens`);
71
111
  lines.push(t.fg("muted", counts.join(" · ")));
72
- if (s.thinking) {
73
- lines.push(t.fg("dim", t.italic(`… ${oneLine(s.thinking, 110)}`)));
74
- } else if (s.status) {
112
+ if (s.status) {
75
113
  lines.push(t.fg("dim", oneLine(s.status, 110)));
76
114
  }
77
115
  for (const e of s.errors.slice(-2)) {
package/src/research.ts CHANGED
@@ -42,6 +42,10 @@ export interface RunRecord {
42
42
  md?: string;
43
43
  checkpoint?: string;
44
44
  status: string;
45
+ // request is a run that ended before its plan was made, when drsh
46
+ // keeps no checkpoint: nothing was spent, so resuming it is asking it
47
+ // again, with the settings and answers it had.
48
+ request?: NewRun;
45
49
  }
46
50
 
47
51
  export interface Result {
@@ -87,11 +91,24 @@ function failedStage(details: ResearchDetails, r: JsonlResult, what: string): Re
87
91
  return { text: `deep-research run failed while ${what}: ${detail}`, details, isError: true };
88
92
  }
89
93
 
94
+ // enter starts a stage of the call: the view's clock counts from here.
95
+ function enter(details: ResearchDetails, stage: "clarify" | "plan" | "run"): void {
96
+ details.stage = stage;
97
+ details.started = Date.now();
98
+ }
99
+
100
+ // waiting is the view while the user answers the questions or reviews the
101
+ // plan: nothing is working, so no spinner and no clock counting their time.
102
+ function waiting(c: Call, details: ResearchDetails): void {
103
+ details.started = undefined;
104
+ c.hooks.update(details);
105
+ }
106
+
90
107
  async function clarify(c: Call, run: NewRun, details: ResearchDetails): Promise<Result | undefined> {
91
108
  if (run.answers) {
92
109
  return undefined;
93
110
  }
94
- details.stage = "clarify";
111
+ enter(details, "clarify");
95
112
  c.hooks.update(details);
96
113
  const r = await stage(c, details, newRunArgs(c.settings, run, c.reports, "clarify"));
97
114
  const failed = failedStage(details, r, "asking the clarifying questions");
@@ -101,7 +118,9 @@ async function clarify(c: Call, run: NewRun, details: ResearchDetails): Promise<
101
118
  return undefined;
102
119
  }
103
120
  if (!c.hooks.ask) {
104
- details.stage = "clarify";
121
+ // A finished call: Pi redraws it from these details, and a clock
122
+ // left set would spin there.
123
+ details.started = undefined;
105
124
  const list = qs.map((q, i) => `${i + 1}. ${q.text}${q.options?.length ? ` (for example: ${q.options.join(" / ")})` : ""}`);
106
125
  return {
107
126
  text: [
@@ -113,6 +132,7 @@ async function clarify(c: Call, run: NewRun, details: ResearchDetails): Promise<
113
132
  isError: false,
114
133
  };
115
134
  }
135
+ waiting(c, details);
116
136
  const answers = await c.hooks.ask(qs);
117
137
  if (answers === "stop") {
118
138
  return stopped(details, "the clarifying questions were dismissed");
@@ -127,11 +147,12 @@ async function planned(c: Call, run: NewRun, review: boolean, details: ResearchD
127
147
  if (!review || !c.hooks.review) {
128
148
  return newRunArgs(c.settings, run, c.reports, "run");
129
149
  }
130
- details.stage = "plan";
150
+ enter(details, "plan");
131
151
  c.hooks.update(details);
132
152
  const r = await stage(c, details, newRunArgs(c.settings, run, c.reports, "plan"));
133
153
  const failed = failedStage(details, r, "planning");
134
154
  if (failed) return failed;
155
+ waiting(c, details);
135
156
  const plan = await c.hooks.review(r.plan);
136
157
  if (plan === "stop") {
137
158
  return stopped(details, "the plan was not confirmed");
@@ -229,6 +250,16 @@ function finish(details: ResearchDetails, o: Outcome, question: string): Pick<Re
229
250
  };
230
251
  }
231
252
 
253
+ // beforeRun records a run that ended before its plan, stopped or failed,
254
+ // with the request that asks it again. It recorded nothing, and
255
+ // /research-resume after a stop while planning said no run had happened.
256
+ // Questions handed back to the agent are not an end: they record nothing.
257
+ function beforeRun(r: Result, run: NewRun): Result {
258
+ const status = r.details.outcome?.status;
259
+ if (!status) return r;
260
+ return { ...r, record: { question: run.question, status, request: structuredClone(run) } };
261
+ }
262
+
232
263
  export async function research(c: Call): Promise<Result> {
233
264
  const details: ResearchDetails = { question: questionOf(c.req), model: c.model, stage: "run" };
234
265
  let args: string[];
@@ -236,12 +267,12 @@ export async function research(c: Call): Promise<Result> {
236
267
  args = resumeArgs(c.req.checkpoint, c.reports);
237
268
  } else {
238
269
  const asked = await clarify(c, c.req.run, details);
239
- if (asked) return asked;
270
+ if (asked) return beforeRun(asked, c.req.run);
240
271
  const p = await planned(c, c.req.run, c.req.review, details);
241
- if (!Array.isArray(p)) return p;
272
+ if (!Array.isArray(p)) return beforeRun(p, c.req.run);
242
273
  args = p;
243
274
  }
244
- details.stage = "run";
275
+ enter(details, "run");
245
276
  details.state = initialState();
246
277
  c.hooks.update(details);
247
278
  const r = await stage(c, details, args);
package/src/result.ts CHANGED
@@ -55,7 +55,7 @@ interface RunJSON {
55
55
  confidence?: string;
56
56
  error?: string;
57
57
  analysis?: {
58
- claims?: { id: string; claim: string; status?: string; note?: string; computed?: string }[];
58
+ claims?: { id: string; claim: string; status?: string; note?: string; computed?: string; qualifier?: string }[];
59
59
  computations?: { id: string; label?: string; result?: string; unit?: string; formula?: string; valid?: boolean; reason?: string }[];
60
60
  recommendations?: Rec[];
61
61
  conclusions?: Rec[];
@@ -209,7 +209,7 @@ function recovery(o: Outcome): string[] {
209
209
  }
210
210
  const limited = /rate.?limit|challenge/i.test(o.detail ?? "");
211
211
  return [
212
- `Checkpoint: ${o.checkpoint}. Call deep_research with resume set to it to continue without repeating finished searches.` +
212
+ `Checkpoint: ${o.checkpoint}. Call deep_research with resume set to it (or the user runs /research-resume) to continue without repeating finished searches.` +
213
213
  (limited ? " The searches were rate-limited: offer to resume in about ten minutes, not right away." : ""),
214
214
  ];
215
215
  }
package/src/settings.ts CHANGED
@@ -73,6 +73,21 @@ export function valueLabel(s: Setting, v: string): string {
73
73
  return s.choices.find((o) => o.value === v)?.label ?? v;
74
74
  }
75
75
 
76
+ // step is the choice next to v, forward (1) or back (-1), wrapping round
77
+ // from the last to the first. A count at a number not among its choices
78
+ // (topics 5 from a flag, with no 5 offered) steps to the nearest choice on
79
+ // that side.
80
+ export function step(s: Setting, v: string, dir: 1 | -1): string {
81
+ const values = s.choices.map((o) => o.value);
82
+ const i = values.indexOf(v);
83
+ if (i >= 0) {
84
+ return values[(i + dir + values.length) % values.length];
85
+ }
86
+ const n = Number(v);
87
+ const side = dir > 0 ? values.find((c) => Number(c) > n) : values.findLast((c) => Number(c) < n);
88
+ return side ?? (dir > 0 ? values[0] : values[values.length - 1]);
89
+ }
90
+
76
91
  // implied is what the chosen values imply for the other settings, by key:
77
92
  // what instant holds at its least.
78
93
  export function implied(settings: Setting[], values: Record<string, string>): Record<string, string> {