@juanhuttemann/pi-deep-research 0.2.1 → 0.3.1

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
@@ -6,7 +6,7 @@ runs [deep-research](https://github.com/juanhuttemann/deep-research)
6
6
  evidence, and checks every claim against the text of the pages it fetched.
7
7
  Pi's own model answers the model calls, through Pi's sign-in.
8
8
 
9
- ![A deep_research run in Pi: sub-agents searching, with the pages and sources so far](https://raw.githubusercontent.com/juanhuttemann/deep-research/main/docs/images/pi-research.png)
9
+ ![A research run in Pi: the planned sub-topics searched, two follow-up searches running, and the searches, pages and sources so far](https://raw.githubusercontent.com/juanhuttemann/deep-research/main/docs/images/pi-research.png)
10
10
 
11
11
  ## Install
12
12
 
@@ -29,49 +29,73 @@ drsh's search and scraper settings still apply. SearXNG works with no
29
29
  setup, while Exa, Tavily and Firecrawl use their keys from `drsh setup`.
30
30
  `/research-doctor` checks them.
31
31
 
32
- ## What it adds
33
-
34
- - **`deep_research` tool.** Ask Pi to research something.
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.
38
- - When it ends, the call shows the confidence, the fact-check's verdicts,
39
- the claims it did not confirm, and the report's path.
40
- - Esc stops a run. It keeps a checkpoint, and resuming from it skips the
41
- searches already done.
42
- - When the question leaves something open, the clarifying questions open
43
- as Pi dialogs. In print or JSON mode they go back to the model, which
44
- asks you.
45
- - Every run setting drsh has is a tool parameter: depth (instant, quick,
46
- standard, deep), sub-topics, pages per topic, follow-ups, format,
47
- words, tables and clarify. `domains`, `trace` and `review_plan`
48
- (review and edit the plan before any search) are parameters too. The
49
- settings come from `drsh settings`, so a new setting in drsh appears
50
- here with no update.
51
- - **`research_ask` tool.** Answers a follow-up question from the pages a
52
- run already fetched, without searching again. The answer is not
53
- fact-checked.
54
- - **`/research [--topics 3 --follow-ups off --domains a,b …] question`**
55
- runs a research yourself.
56
- - With no flags it opens the settings screen first: ←/→ steps the
57
- setting under the cursor through its values, Enter lists them all.
58
- - You answer the clarifying questions and review the plan, then the run
59
- starts and the agent reports what it found. An instant run has no plan
60
- review: it searches the question as asked.
61
- - `/research-stop` ends the run, keeping a checkpoint.
62
- - `/research-resume` continues the last stopped, failed or incomplete
63
- run from its checkpoint without repeating finished searches;
64
- `/research-resume <checkpoint>` continues another. A run stopped
65
- before drsh's first checkpoint has nothing searched: it starts again
66
- with the same question, settings and answers, and with the plan you
67
- approved, edits included, when you had approved one.
68
- - **`/research-model`** picks the model research runs use:
69
- - Pi's current model, the default.
70
- - Another of Pi's models, for example a cheaper one for the many calls a
71
- run makes.
72
- - drsh's own configured model.
73
- - **`/research-doctor`** checks the model (through Pi), search and the
74
- scraper.
32
+ ## Ask Pi
33
+
34
+ Ask Pi to research something, and it calls the `deep_research` tool. A run
35
+ takes minutes and makes many model calls, so Pi uses it for questions that
36
+ need sources, not quick lookups.
37
+
38
+ - **While it runs**, the call shows the phase with a spinner and its clock,
39
+ what the model is doing, each sub-agent and its search (follow-ups
40
+ marked), and the searches, pages and sources so far. Once the search is
41
+ over, the sub-agents fold into one line, and the fact-check shows its
42
+ tally when it has one.
43
+ - **When it ends**, the call shows the result: the confidence, the claims
44
+ as the run concluded them, the ones the fact-check did not confirm, and
45
+ the folder the run's files are in. Ctrl+O expands it to every claim and
46
+ each file's full path. Pi then answers from the report, keeping its
47
+ citations.
48
+
49
+ ![The result of a run: complete, confidence high, 7 claims supported and 1 partial, with the partial claim named and the run's files](https://raw.githubusercontent.com/juanhuttemann/deep-research/main/docs/images/pi-research-result.png)
50
+
51
+ - **Esc stops a run.** It keeps a checkpoint, and resuming from it skips
52
+ the searches already done.
53
+ - **Clarifying questions**, when the question leaves something open, open
54
+ as Pi dialogs. In print or JSON mode they go back to the model, which
55
+ asks you.
56
+
57
+ Every run setting drsh has is a tool parameter: depth (instant, quick,
58
+ standard, deep), sub-topics, pages per topic, follow-ups, format, words,
59
+ tables and clarify. `domains`, `trace` and `review_plan` (review and edit
60
+ the plan before any search) are parameters too. The settings come from
61
+ `drsh settings`, so a new setting in drsh appears here with no update.
62
+
63
+ For a follow-up, Pi uses the `research_ask` tool: it answers from the pages
64
+ a run already fetched, without searching again. Its answers are not
65
+ fact-checked.
66
+
67
+ ## Run it yourself
68
+
69
+ `/research question` runs a research from the prompt.
70
+
71
+ 1. **Settings.** With no flags, the settings screen opens first. ←/→ steps
72
+ the setting under the cursor through its values, Enter lists them all,
73
+ and the line under the list says what the setting does. Flags skip it:
74
+ `/research --mode quick --follow-ups off --domains a.com,b.org question`.
75
+
76
+ ![The settings screen: Start, then depth, sub-topics, pages per topic, follow-ups, format, words, tables and clarify, with the help for depth under the list](https://raw.githubusercontent.com/juanhuttemann/deep-research/main/docs/images/pi-research-settings.png)
77
+
78
+ 2. **Questions.** You answer the clarifying questions, if any.
79
+ 3. **Plan.** You review the plan: its depth, pages per topic, follow-ups,
80
+ and the search each sub-topic starts from. Run it, edit the sub-topics
81
+ (one per line), or cancel. An edit past drsh's sub-topic limit is
82
+ refused here. An instant run has no plan review: it searches the
83
+ question as asked.
84
+
85
+ ![The plan review: three sub-topics, each with its search, the depth and pages per topic above them, and Run this plan, Edit sub-topics and Cancel below](https://raw.githubusercontent.com/juanhuttemann/deep-research/main/docs/images/pi-research-plan.png)
86
+
87
+ 4. **Run.** The run shows above the prompt as the tool's does, and ends in
88
+ the same result, with the tokens it used. Pi then reports what it found.
89
+
90
+ | Command | What it does |
91
+ | --- | --- |
92
+ | `/research [flags] question` | Runs a research, as above. |
93
+ | `/research-stop` | Ends the `/research` run, keeping a checkpoint. |
94
+ | `/research-resume [checkpoint]` | Continues the last stopped, failed or incomplete run, or the checkpoint given, without repeating finished searches. A run stopped before drsh's first checkpoint starts again with the same question, settings and answers, and the plan you approved, edits included. |
95
+ | `/research-model` | Picks the model runs use: Pi's current model (the default), another of Pi's models (a cheaper one, say, for the many calls a run makes), or drsh's own configured model. Type to filter the list. |
96
+ | `/research-doctor` | Checks the model (through Pi), search and the scraper. |
97
+
98
+ ## Files
75
99
 
76
100
  Each run's files (`.md`, `.pdf`, `.json`, checkpoint) go in
77
101
  `~/.cache/deep-research-pi/runs/` (`$DEEP_RESEARCH_PI_RUNS` to change it),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanhuttemann/pi-deep-research",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
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",
@@ -40,10 +40,10 @@
40
40
  "typebox": "*"
41
41
  },
42
42
  "devDependencies": {
43
- "@earendil-works/pi-agent-core": "1.4.0",
44
- "@earendil-works/pi-ai": "1.4.0",
45
- "@earendil-works/pi-coding-agent": "1.4.0",
46
- "@earendil-works/pi-tui": "1.4.0",
43
+ "@earendil-works/pi-agent-core": "1.7.0",
44
+ "@earendil-works/pi-ai": "1.7.0",
45
+ "@earendil-works/pi-coding-agent": "1.7.0",
46
+ "@earendil-works/pi-tui": "1.7.0",
47
47
  "@types/node": "^22.19.0",
48
48
  "jiti": "2.7.0",
49
49
  "typebox": "1.3.27",
package/src/events.ts CHANGED
@@ -52,6 +52,9 @@ export interface SubAgent {
52
52
  state: string;
53
53
  progress: number;
54
54
  line: string;
55
+ // errors counts the errors drsh sent for this sub-agent: a failed search
56
+ // is an error event naming it, and the sub-agent still ends "done".
57
+ errors?: number;
55
58
  }
56
59
 
57
60
  // RunState is what the live view shows. It is a tool result's details, so it
@@ -65,7 +68,14 @@ export interface RunState {
65
68
  sources: number;
66
69
  tokens: number;
67
70
  // status is the latest transient line: which model is asked, a retry.
71
+ // A phase change clears it: the line belongs to the call that sent it,
72
+ // and the fact-check showed the analysis's last line under its own
73
+ // header for minutes.
68
74
  status: string;
75
+ // checked is what the fact-check has said of its own progress, in
76
+ // drsh's words: how it split the check, the tally once its verdicts are
77
+ // applied ("11 of 12 claims supported…"), the revisions it approved.
78
+ checked: string[];
69
79
  errors: string[];
70
80
  domains: DomainCheck[];
71
81
  }
@@ -80,6 +90,7 @@ export function initialState(): RunState {
80
90
  sources: 0,
81
91
  tokens: 0,
82
92
  status: "",
93
+ checked: [],
83
94
  errors: [],
84
95
  domains: [],
85
96
  };
@@ -89,6 +100,30 @@ export function initialState(): RunState {
89
100
  // in the run's timeline.
90
101
  const maxErrors = 5;
91
102
 
103
+ // agentLog is a line of the agent's own log, which drsh sends as an info
104
+ // stamped with the phase it is in: the call it makes, in a column
105
+ // ("fact-check provider/model · effort"), or indented. Kept as the
106
+ // fact-check's notes, the model's name pushed out the tally.
107
+ const agentLog = /^(\s|\S+ {2,})/;
108
+
109
+ // maxChecked bounds the fact-check's notes.
110
+ const maxChecked = 3;
111
+
112
+ // tally is the fact-check's count of what it supported: of its notes the one
113
+ // to keep. A retry's notes (no verdicts, asking again) pushed it out.
114
+ const tally = /^\d+ of \d+ claims supported/;
115
+
116
+ // note adds a fact-check note, dropping the oldest past maxChecked, the
117
+ // tally last.
118
+ function note(notes: string[], n: string): string[] {
119
+ const out = [...notes, n];
120
+ while (out.length > maxChecked) {
121
+ const i = out.findIndex((x) => !tally.test(x));
122
+ out.splice(i < 0 ? 0 : i, 1);
123
+ }
124
+ return out;
125
+ }
126
+
92
127
  export function parseLine(line: string): DrshEvent | undefined {
93
128
  const s = line.trim();
94
129
  if (!s.startsWith("{")) {
@@ -123,6 +158,7 @@ export function reduce(s: RunState, e: DrshEvent): RunState {
123
158
  case "phase":
124
159
  s.phase = e.phase ?? s.phase;
125
160
  s.phaseDetail = e.detail ?? "";
161
+ s.status = "";
126
162
  break;
127
163
  case "subagent":
128
164
  subagent(s, e);
@@ -137,6 +173,7 @@ export function reduce(s: RunState, e: DrshEvent): RunState {
137
173
  case "report":
138
174
  s.phase = e.phase || "Report";
139
175
  s.phaseDetail = e.detail ?? "";
176
+ s.status = "";
140
177
  if (e.sources) s.sources = e.sources;
141
178
  break;
142
179
  case "citation":
@@ -146,10 +183,14 @@ export function reduce(s: RunState, e: DrshEvent): RunState {
146
183
  break;
147
184
  case "info":
148
185
  if (e.transient && e.detail) s.status = e.detail.split("\n")[0];
186
+ else if (e.phase === "Fact-Check" && e.detail && !agentLog.test(e.detail)) s.checked = note(s.checked, e.detail.split("\n")[0]);
149
187
  break;
150
- case "error":
188
+ case "error": {
151
189
  if (e.detail) s.errors = [...s.errors, e.detail].slice(-maxErrors);
190
+ const a = e.sub_id ? s.subagents.find((x) => x.id === e.sub_id) : undefined;
191
+ if (a) a.errors = (a.errors ?? 0) + 1;
152
192
  break;
193
+ }
153
194
  case "source":
154
195
  if (e.check) s.domains.push(e.check);
155
196
  break;
package/src/index.ts CHANGED
@@ -10,13 +10,13 @@ import { join } from "node:path";
10
10
  import type { Api, Model } from "@earendil-works/pi-ai";
11
11
  import { StringEnum } from "@earendil-works/pi-ai";
12
12
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
13
- import { Text } from "@earendil-works/pi-tui";
13
+ import { Box, Container, Text, TruncatedText } from "@earendil-works/pi-tui";
14
14
  import { Type, type TSchema } from "typebox";
15
15
  import { checkAnswers, clip, maxAnswerChars, maxAnswers, type Answer } from "./args.ts";
16
16
  import { startBridge, type Bridge } from "./bridge.ts";
17
17
  import type { Question } from "./events.ts";
18
- import { planLines, subTopicNames, withSubTopics, type Plan } from "./plan.ts";
19
- import { count, outcomeLines, progressLines, type ResearchDetails, tickMs } from "./render.ts";
18
+ import { planLines, subTopicNames, tooMany, withSubTopics, type Plan } from "./plan.ts";
19
+ import { outcomeLines, progressLines, type ResearchDetails, statusLabel, 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 {
@@ -32,7 +32,7 @@ import {
32
32
  valueLabel,
33
33
  type Setting,
34
34
  } from "./settings.ts";
35
- import { type MenuResult, pick as pickWithNotice, SettingsMenu, startLabel } from "./menu.ts";
35
+ import { type MenuResult, pick as pickWithNotice, pickFiltered, SettingsMenu, startLabel } from "./menu.ts";
36
36
 
37
37
  const modelEntry = "deep-research-model";
38
38
  const runEntry = "deep-research-run";
@@ -116,6 +116,31 @@ function untilAborted<T>(p: Promise<T>, signal?: AbortSignal): Promise<T | undef
116
116
  });
117
117
  }
118
118
 
119
+ // showLines puts lines in a widget above the editor. Pi cuts a widget given
120
+ // as lines at ten, and a run's view (the sub-agents of a deep plan and its
121
+ // follow-ups, the counts, the fact-check's notes) runs past that, losing
122
+ // its last lines; the plan of a review the same. In the terminal they go in
123
+ // as a component, which is not cut; elsewhere as lines. A run's view is
124
+ // one line per row, cut to the terminal's width: wrapped, a sub-agent's
125
+ // search ran onto a line of its own, mid-word. The plan wraps, its names
126
+ // and searches whole.
127
+ function showLines(ctx: ExtensionContext, key: string, lines: string[] | undefined, o: { cut?: boolean } = {}): void {
128
+ if (lines === undefined || ctx.mode !== "tui") {
129
+ ctx.ui.setWidget(key, lines);
130
+ return;
131
+ }
132
+ if (!o.cut) {
133
+ const text = lines.join("\n");
134
+ ctx.ui.setWidget(key, () => new Text(text, 1, 0));
135
+ return;
136
+ }
137
+ ctx.ui.setWidget(key, () => {
138
+ const c = new Container();
139
+ for (const l of lines) c.addChild(new TruncatedText(l, 1, 0));
140
+ return c;
141
+ });
142
+ }
143
+
119
144
  export default function deepResearch(pi: ExtensionAPI) {
120
145
  const bin = process.env.DRSH_BIN || "drsh";
121
146
  let settings: Setting[] = [];
@@ -236,11 +261,13 @@ export default function deepResearch(pi: ExtensionAPI) {
236
261
  const edit = "Edit sub-topics";
237
262
  const stop = "Cancel";
238
263
  let plan = (raw ?? {}) as Plan;
264
+ const planned = subTopicNames(plan).length;
265
+ const max = settings.find((x) => x.key === "topics")?.max;
239
266
  // notice is why the last edit was not taken, shown under the options.
240
267
  let notice: string | undefined;
241
268
  try {
242
269
  for (;;) {
243
- ctx.ui.setWidget("deep-research-plan", planLines(plan));
270
+ showLines(ctx, "deep-research-plan", planLines(plan, planned));
244
271
  const pick = await pickWithNotice(ctx, "Review the plan", [run, edit, stop], { notice, signal });
245
272
  notice = undefined;
246
273
  if (pick === undefined || pick === stop) return "stop";
@@ -255,10 +282,12 @@ export default function deepResearch(pi: ExtensionAPI) {
255
282
  notice = "A plan needs at least one sub-topic";
256
283
  continue;
257
284
  }
285
+ notice = tooMany(edited, max);
286
+ if (notice) continue;
258
287
  plan = edited;
259
288
  }
260
289
  } finally {
261
- ctx.ui.setWidget("deep-research-plan", undefined);
290
+ showLines(ctx, "deep-research-plan", undefined);
262
291
  }
263
292
  }
264
293
 
@@ -470,6 +499,21 @@ export default function deepResearch(pi: ExtensionAPI) {
470
499
  }
471
500
  }
472
501
 
502
+ // A /research run's message is drawn as its card: what it found,
503
+ // collapsed to the confidence, the claims the fact-check did not confirm
504
+ // and where the files are. Drawn as its text, it was the model's
505
+ // instructions and the whole report, which the agent's answer then said
506
+ // again. The text still goes to the model as it was.
507
+ pi.registerMessageRenderer<ResearchDetails>("deep-research", (message, { expanded, keyHint }, theme) => {
508
+ const d = message.details;
509
+ if (!d?.outcome) return undefined;
510
+ const lines = [theme.fg("toolTitle", theme.bold("deep research ")) + theme.fg("accent", d.question), ...outcomeLines(d, expanded, theme)];
511
+ lines.push(keyHint("app.tools.expand", expanded ? "to collapse" : "to expand"));
512
+ const box = new Box(1, 1, (t) => theme.bg("customMessageBg", t));
513
+ box.addChild(new Text(lines.join("\n"), 0, 0));
514
+ return box;
515
+ });
516
+
473
517
  pi.on("session_start", async (_event, ctx) => {
474
518
  session++;
475
519
  restoreBranch(ctx);
@@ -512,6 +556,13 @@ export default function deepResearch(pi: ExtensionAPI) {
512
556
  const depth = by ? `${valueLabel(by, values[by.key] ?? by.value)} ${name}` : "the depth";
513
557
  return `${depth} holds every option at its least: pick another ${name} to change ${x.label}`;
514
558
  };
559
+ // describe is the row's help and the note on its value ("≤3").
560
+ const describe = (row: number) => {
561
+ const x = s[row];
562
+ const v = effective(s, values)[x.key];
563
+ const note = x.choices.find((o) => o.value === v)?.note;
564
+ return note ? `${x.help} (${valueLabel(x, v)}: ${note})` : x.help;
565
+ };
515
566
  // The menu checks heldWhy before stepping; this is the select's guard.
516
567
  const stepRow = (row: number, dir: 1 | -1) => {
517
568
  const x = s[row];
@@ -529,7 +580,7 @@ export default function deepResearch(pi: ExtensionAPI) {
529
580
  const viaMenu = () =>
530
581
  ctx.ui.custom<MenuResult | undefined>((_tui, theme, kb, done) => {
531
582
  const held = (row: number) => heldWhy(s[row]);
532
- const menu = new SettingsMenu(theme, kb, { title, rows, step: stepRow, held, selected }, (r) => {
583
+ const menu = new SettingsMenu(theme, kb, { title, rows, step: stepRow, held, describe, selected }, (r) => {
533
584
  selected = menu.selectedLine;
534
585
  done(r);
535
586
  });
@@ -554,13 +605,13 @@ export default function deepResearch(pi: ExtensionAPI) {
554
605
  }
555
606
 
556
607
  pi.registerCommand("research", {
557
- description: "Research a question: settings, clarifying questions and plan review, then a live run",
608
+ description: "Research a question, with settings and plan review",
558
609
  getArgumentCompletions: (prefix) => (settings.length ? completions(settings, prefix) : null),
559
610
  handler: (args, ctx) => commandRunWith(ctx, (abort) => researchCommand(args, ctx, abort)),
560
611
  });
561
612
 
562
613
  pi.registerCommand("research-resume", {
563
- 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",
614
+ description: "Resume the last stopped research run, or the checkpoint given",
564
615
  handler: (args, ctx) =>
565
616
  commandRunWith(ctx, async (abort) => {
566
617
  const checkpoint = args.trim() || lastRun?.checkpoint;
@@ -660,9 +711,8 @@ export default function deepResearch(pi: ExtensionAPI) {
660
711
  async function backgroundRun(ctx: ExtensionContext, abort: AbortController, req: Request): Promise<void> {
661
712
  const status = ticker(() => {
662
713
  if (!latest) return;
663
- const lines = progressLines(latest, ctx.ui.theme);
664
- ctx.ui.setWidget("deep-research", lines);
665
- ctx.ui.setStatus("deep-research", `research: ${latest.state?.phase || latest.stage}`);
714
+ showLines(ctx, "deep-research", progressLines(latest, ctx.ui.theme), { cut: true });
715
+ ctx.ui.setStatus("deep-research", `research: ${statusLabel(latest)}`);
666
716
  }, tickMs, () => latest?.started !== undefined);
667
717
  let latest: ResearchDetails | undefined;
668
718
  try {
@@ -674,24 +724,26 @@ export default function deepResearch(pi: ExtensionAPI) {
674
724
  ask: (qs) => askQuestions(ctx, qs, abort.signal),
675
725
  review: (plan) => reviewPlan(ctx, plan, abort.signal),
676
726
  });
727
+ // The usage goes on the run's card: a notice of it passed in a
728
+ // moment, apart from the run it was for.
729
+ if (bridge?.usage.totalTokens) {
730
+ result.details.usage = { tokens: bridge.usage.totalTokens, cost: bridge.usage.cost.total };
731
+ }
677
732
  pi.sendMessage(
678
733
  { customType: "deep-research", content: result.text, display: true, details: result.details },
679
734
  { triggerTurn: result.details.outcome !== undefined && result.details.outcome.status !== "cancelled" },
680
735
  );
681
- if (bridge?.usage.totalTokens) {
682
- ctx.ui.notify(`research used ${count(bridge.usage.totalTokens)} tokens ($${bridge.usage.cost.total.toFixed(4)}) on ${bridge.modelName}`, "info");
683
- }
684
736
  } catch (err) {
685
737
  ctx.ui.notify(`research failed: ${(err as Error).message}`, "error");
686
738
  } finally {
687
739
  status.cancel();
688
- ctx.ui.setWidget("deep-research", undefined);
740
+ showLines(ctx, "deep-research", undefined);
689
741
  ctx.ui.setStatus("deep-research", undefined);
690
742
  }
691
743
  }
692
744
 
693
745
  pi.registerCommand("research-stop", {
694
- description: "Stop the research run /research started; it keeps a checkpoint /research-resume continues from",
746
+ description: "Stop the /research run, keeping a checkpoint to resume from",
695
747
  handler: async (_args, ctx) => {
696
748
  if (!commandRun) {
697
749
  ctx.ui.notify("No /research run is going (a run the agent started stops with Esc)", "info");
@@ -702,12 +754,12 @@ export default function deepResearch(pi: ExtensionAPI) {
702
754
  });
703
755
 
704
756
  pi.registerCommand("research-model", {
705
- description: "Choose the model research runs use: Pi's current model, another of Pi's models, or drsh's own",
757
+ description: "Choose the model research runs use",
706
758
  handler: async (_args, ctx) => {
707
759
  const current = "Pi's current model (follows /model)";
708
760
  const own = "drsh's own configured model (drsh setup)";
709
761
  const models = ctx.modelRegistry.getAvailable().map((m) => `${m.provider}/${m.id}`);
710
- const pick = await ctx.ui.select("Model for research runs", [current, own, ...models]);
762
+ const pick = await pickFiltered(ctx, "Model for research runs", [current, own, ...models]);
711
763
  if (pick === undefined) return;
712
764
  if (pick === current) choice = { kind: "pi" };
713
765
  else if (pick === own) choice = { kind: "drsh" };
@@ -721,7 +773,7 @@ export default function deepResearch(pi: ExtensionAPI) {
721
773
  });
722
774
 
723
775
  pi.registerCommand("research-doctor", {
724
- description: "Check what a research run depends on: the model (through Pi), search and the scraper",
776
+ description: "Check the model, search and scraper a run needs",
725
777
  handler: async (_args, ctx) => {
726
778
  let model: Model<Api> | undefined;
727
779
  try {
package/src/menu.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  // place; Enter still hands the row back for the full option list.
7
7
 
8
8
  import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
9
- import { Container, type KeybindingsManager, matchesKey, Spacer, Text } from "@earendil-works/pi-tui";
9
+ import { Container, decodeKittyPrintable, type KeybindingsManager, matchesKey, Spacer, Text } from "@earendil-works/pi-tui";
10
10
 
11
11
  // Menu is a list of lines with a cursor and an optional warning under them.
12
12
  // Enter picks the line under the cursor, the cancel key closes it.
@@ -68,12 +68,22 @@ export class Menu extends Container {
68
68
  const text = i === this.selected ? this.theme.fg("accent", `→ ${l}`) : ` ${this.theme.fg("text", l)}`;
69
69
  this.list.addChild(new Text(text, 1, 0));
70
70
  });
71
+ const about = this.notice ? undefined : this.about();
71
72
  if (this.notice) {
72
73
  this.list.addChild(new Spacer(1));
73
74
  this.list.addChild(new Text(this.theme.fg("warning", this.notice), 1, 0));
75
+ } else if (about) {
76
+ this.list.addChild(new Spacer(1));
77
+ this.list.addChild(new Text(this.theme.fg("muted", about), 1, 0));
74
78
  }
75
79
  }
76
80
 
81
+ // about is a line on the line under the cursor, shown under the list
82
+ // when there is no warning; none by default.
83
+ protected about(): string | undefined {
84
+ return undefined;
85
+ }
86
+
77
87
  // warn shows why under the list, until the next move.
78
88
  protected warn(why: string): void {
79
89
  this.notice = why;
@@ -155,6 +165,9 @@ export interface MenuOptions {
155
165
  // it), or undefined when it can. A held row's ←/→ and Enter show that
156
166
  // under the list instead of changing it.
157
167
  held?: (row: number) => string | undefined;
168
+ // describe says what setting row `row` does, at its current value,
169
+ // shown under the list while the cursor is on it.
170
+ describe?: (row: number) => string | undefined;
158
171
  // selected is the line the cursor starts on: 0 is Start, 1 the first row.
159
172
  selected?: number;
160
173
  }
@@ -170,6 +183,14 @@ export class SettingsMenu extends Menu {
170
183
  done(line === undefined ? { kind: "cancel" } : line === 0 ? { kind: "start" } : { kind: "edit", row: line - 1 }),
171
184
  );
172
185
  this.opts = opts;
186
+ // The first draw ran in Menu's constructor, before opts was set.
187
+ this.draw();
188
+ }
189
+
190
+ // A setting's help was only in the list Enter opens: the screen showed
191
+ // "words: auto" and "clarify: auto" with nothing on what they do.
192
+ protected override about(): string | undefined {
193
+ return this.selected > 0 ? this.opts?.describe?.(this.selected - 1) : undefined;
173
194
  }
174
195
 
175
196
  // refused shows why the row under the cursor is held, if it is.
@@ -194,6 +215,153 @@ export class SettingsMenu extends Menu {
194
215
  }
195
216
  }
196
217
 
218
+ // matching is the indices of the options holding every word of filter, in
219
+ // their order, case aside: drsh's own picker's rule (matching in
220
+ // internal/ui/pick.go), so "fable 5" finds "anthropic/claude-fable-5.2".
221
+ export function matching(options: string[], filter: string): number[] {
222
+ const words = filter.toLowerCase().split(/\s+/).filter(Boolean);
223
+ const out: number[] = [];
224
+ options.forEach((o, i) => {
225
+ const l = o.toLowerCase();
226
+ if (words.every((w) => l.includes(w))) out.push(i);
227
+ });
228
+ return out;
229
+ }
230
+
231
+ const control = (ch: string) => {
232
+ const c = ch.charCodeAt(0);
233
+ return c < 32 || c === 0x7f || (c >= 0x80 && c <= 0x9f);
234
+ };
235
+
236
+ // pasteStart and pasteEnd wrap a bracketed paste, which Pi hands on as it
237
+ // came: rejected for its escape bytes, a pasted model name was dropped.
238
+ const pasteStart = "\x1b[200~";
239
+ const pasteEnd = "\x1b[201~";
240
+
241
+ // typed is the text a key types, or undefined for a key that types none:
242
+ // a Kitty CSI-u sequence decoded, a bracketed paste (its line breaks and
243
+ // other control characters as spaces), or plain text with no control
244
+ // character.
245
+ function typed(data: string): string | undefined {
246
+ const kitty = decodeKittyPrintable(data);
247
+ if (kitty !== undefined) return kitty;
248
+ if (data.startsWith(pasteStart)) {
249
+ const body = data.slice(pasteStart.length).replace(pasteEnd, "");
250
+ return [...body].map((ch) => (control(ch) ? " " : ch)).join("");
251
+ }
252
+ return [...data].some(control) ? undefined : data;
253
+ }
254
+
255
+ // maxShown is how many rows the filtered list shows at once, as Pi's own
256
+ // select does.
257
+ const maxShown = 10;
258
+
259
+ // FilterMenu is a list under a filter box, drawn like Pi's select: typing
260
+ // keeps the rows holding every word typed, the arrows move, Enter picks,
261
+ // the cancel key closes. Pi's select has no filter, and the model list it
262
+ // showed ran to hundreds of rows, read ten at a time with the arrows.
263
+ export class FilterMenu extends Container {
264
+ private filter = "";
265
+ private shown: number[];
266
+ private selected = 0;
267
+ private readonly box = new Text("", 1, 0);
268
+ private readonly list = new Container();
269
+ private readonly theme: Theme;
270
+ private readonly kb: KeybindingsManager;
271
+ private readonly options: string[];
272
+ private readonly close: (index: number | undefined) => void;
273
+
274
+ constructor(theme: Theme, kb: KeybindingsManager, o: { title: string; options: string[] }, close: (index: number | undefined) => void) {
275
+ super();
276
+ this.theme = theme;
277
+ this.kb = kb;
278
+ this.options = o.options;
279
+ this.shown = o.options.map((_, i) => i);
280
+ this.close = close;
281
+ this.addChild(new Border(theme));
282
+ this.addChild(new Spacer(1));
283
+ this.addChild(new Text(theme.fg("accent", theme.bold(o.title)), 1, 0));
284
+ this.addChild(new Spacer(1));
285
+ this.addChild(this.box);
286
+ this.addChild(new Spacer(1));
287
+ this.addChild(this.list);
288
+ this.addChild(new Spacer(1));
289
+ const hint = (k: string, d: string) => theme.fg("dim", k) + theme.fg("muted", ` ${d}`);
290
+ const keys = (k: "tui.select.confirm" | "tui.select.cancel") => kb.getKeys(k).join("/");
291
+ this.addChild(new Text([hint("type", "filter"), hint("↑↓", "navigate"), hint(keys("tui.select.confirm"), "select"), hint(keys("tui.select.cancel"), "cancel")].join(" "), 1, 0));
292
+ this.addChild(new Spacer(1));
293
+ this.addChild(new Border(theme));
294
+ this.draw();
295
+ }
296
+
297
+ private draw(): void {
298
+ const t = this.theme;
299
+ this.box.setText(`${t.fg("accent", "> ")}${this.filter ? t.fg("text", this.filter) : t.fg("dim", "type to filter")}`);
300
+ this.list.clear();
301
+ if (!this.shown.length) {
302
+ this.list.addChild(new Text(t.fg("dim", " nothing matches"), 1, 0));
303
+ return;
304
+ }
305
+ // The window keeps the cursor in view, centred where it can be.
306
+ const start = Math.max(0, Math.min(this.selected - Math.floor(maxShown / 2), this.shown.length - maxShown));
307
+ this.shown.slice(start, start + maxShown).forEach((i, n) => {
308
+ const l = this.options[i];
309
+ const text = start + n === this.selected ? t.fg("accent", `→ ${l}`) : ` ${t.fg("text", l)}`;
310
+ this.list.addChild(new Text(text, 1, 0));
311
+ });
312
+ if (this.shown.length > maxShown) {
313
+ this.list.addChild(new Text(t.fg("dim", ` (${this.selected + 1}/${this.shown.length})`), 1, 0));
314
+ }
315
+ }
316
+
317
+ private refilter(text: string): void {
318
+ this.filter = text;
319
+ this.shown = matching(this.options, text);
320
+ this.selected = 0;
321
+ }
322
+
323
+ handleInput(data: string): void {
324
+ const kb = this.kb;
325
+ // Text typed goes in the filter before any binding is read: a letter
326
+ // bound to confirm picked the highlighted row at the first letter
327
+ // of a name.
328
+ const s = typed(data);
329
+ if (s !== undefined) {
330
+ this.refilter(this.filter + s);
331
+ this.draw();
332
+ return;
333
+ }
334
+ if (kb.matches(data, "tui.select.confirm") || data === "\n") {
335
+ // Enter on a filter that matches nothing does nothing.
336
+ if (this.shown.length) this.close(this.shown[this.selected]);
337
+ return;
338
+ }
339
+ if (kb.matches(data, "tui.select.cancel")) {
340
+ this.close(undefined);
341
+ return;
342
+ }
343
+ if (kb.matches(data, "tui.select.up")) {
344
+ this.selected = Math.max(0, this.selected - 1);
345
+ } else if (kb.matches(data, "tui.select.down")) {
346
+ this.selected = Math.min(this.shown.length - 1, this.selected + 1);
347
+ } else if (matchesKey(data, "backspace") || kb.matches(data, "tui.editor.deleteCharBackward")) {
348
+ if (!this.filter) return;
349
+ this.refilter([...this.filter].slice(0, -1).join(""));
350
+ } else {
351
+ return;
352
+ }
353
+ this.draw();
354
+ }
355
+ }
356
+
357
+ // pickFiltered is ctx.ui.select with a filter box, for a long list. Outside
358
+ // the terminal it is the plain select.
359
+ export async function pickFiltered(ctx: ExtensionContext, title: string, options: string[]): Promise<string | undefined> {
360
+ if (ctx.mode !== "tui") return ctx.ui.select(title, options);
361
+ const i = await ctx.ui.custom<number | undefined>((_tui, theme, kb, done) => new FilterMenu(theme, kb, { title, options }, done));
362
+ return i === undefined ? undefined : options[i];
363
+ }
364
+
197
365
  // Border is DynamicBorder drawn with the theme Pi hands the component: Pi's
198
366
  // own reads a global theme that an extension's module copy may not have set.
199
367
  class Border {
package/src/plan.ts CHANGED
@@ -6,11 +6,15 @@
6
6
 
7
7
  export interface SubTopic {
8
8
  name: string;
9
+ query?: string;
9
10
  [k: string]: unknown;
10
11
  }
11
12
 
12
13
  export interface Plan {
13
14
  question?: string;
15
+ depth?: { key?: string; label?: string };
16
+ max_sources?: number;
17
+ no_follow_ups?: boolean;
14
18
  sub_topics?: SubTopic[];
15
19
  [k: string]: unknown;
16
20
  }
@@ -37,11 +41,36 @@ export function withSubTopics(plan: Plan, text: string): Plan {
37
41
  return { ...plan, sub_topics: names.map((n) => old.get(n) ?? { name: n }) };
38
42
  }
39
43
 
40
- // planLines is the plan as the review shows it.
41
- export function planLines(plan: Plan): string[] {
44
+ // tooMany is why an edited plan cannot run, or undefined when it can: drsh
45
+ // refuses a plan of more sub-topics than its topics setting goes to
46
+ // (ReadPlan), and said so only once the run had started. max is that
47
+ // setting's own maximum, from drsh settings, not a copy of the number.
48
+ export function tooMany(plan: Plan, max: number | undefined): string | undefined {
49
+ const n = subTopicNames(plan).length;
50
+ return max && n > max ? `A plan has at most ${max} sub-topics; this one has ${n}` : undefined;
51
+ }
52
+
53
+ // planLines is the plan as the review shows it: what it runs at (the depth,
54
+ // the pages each sub-topic reads, the follow-up round), then each sub-topic
55
+ // with the search it starts from. Names alone left what the plan would do
56
+ // unsaid. planned is the count the planner gave: an edit that changes it
57
+ // changes the budget, which drsh derives again when the run starts.
58
+ export function planLines(plan: Plan, planned?: number): string[] {
42
59
  const names = subTopicNames(plan);
43
- return [
44
- `Plan: ${names.length} sub-topic${names.length === 1 ? "" : "s"}${plan.question ? ` for "${plan.question}"` : ""}`,
45
- ...names.map((n, i) => ` ${i + 1}. ${n}`),
46
- ];
60
+ const n = names.length;
61
+ const budget: string[] = [];
62
+ if (plan.depth?.label) budget.push(`${plan.depth.label.toLowerCase()} depth`);
63
+ if (planned !== undefined && planned !== n) {
64
+ budget.push("pages per topic recalculated when the run starts");
65
+ } else if (plan.max_sources && n) {
66
+ const per = Math.max(Math.floor(plan.max_sources / n), 1);
67
+ budget.push(`${per} page${per === 1 ? "" : "s"} per topic`);
68
+ }
69
+ budget.push(`follow-ups ${plan.no_follow_ups ? "off" : "on"}`);
70
+ const lines = [`Plan: ${n} sub-topic${n === 1 ? "" : "s"}${plan.question ? ` for "${plan.question}"` : ""}`, ` ${budget.join(" · ")}`];
71
+ (plan.sub_topics ?? []).forEach((t, i) => {
72
+ lines.push(` ${i + 1}. ${t.name}`);
73
+ lines.push(` ${t.query ? `search: ${t.query}` : "search worded when the run starts"}`);
74
+ });
75
+ return lines;
47
76
  }
package/src/render.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  // streaming reasoning is not shown: its latest words, replaced as they
5
5
  // streamed, were too hard to read and follow.
6
6
 
7
+ import { homedir } from "node:os";
8
+ import { basename, dirname, sep } from "node:path";
7
9
  import type { Theme } from "@earendil-works/pi-coding-agent";
8
10
  import type { RunState, SubAgent } from "./events.ts";
9
11
  import type { Digest } from "./result.ts";
@@ -28,6 +30,9 @@ export interface ResearchDetails {
28
30
  started?: number;
29
31
  state?: RunState;
30
32
  outcome?: OutcomeDetails;
33
+ // usage is what a /research run spent, shown on its card: Pi counts a
34
+ // tool call's usage itself, and the run's, sent as a message, nowhere.
35
+ usage?: { tokens: number; cost: number };
31
36
  }
32
37
 
33
38
  // spinnerFrames and tickMs are drsh's (spinnerFrames, tickInterval in
@@ -85,8 +90,84 @@ const stageLabel: Record<ResearchDetails["stage"], string> = {
85
90
  done: "Done",
86
91
  };
87
92
 
93
+ // statusWords names a stage in Pi's footer, in one case throughout: the
94
+ // footer showed drsh's internal stage IDs ("clarify") beside its display
95
+ // names ("Fact-Check"), and "research: Research" said nothing.
96
+ const statusWords: Record<string, string> = {
97
+ clarify: "Clarifying",
98
+ plan: "Planning",
99
+ run: "Starting",
100
+ done: "Done",
101
+ Plan: "Planning",
102
+ Research: "Searching",
103
+ Analyze: "Analyzing",
104
+ "Fact-Check": "Fact-checking",
105
+ Summarize: "Writing the report",
106
+ Answer: "Answering",
107
+ Report: "Writing the report",
108
+ };
109
+
110
+ // statusLabel is the footer's word for where a run is: the stage before the
111
+ // run, then drsh's phase, a phase this does not know shown as drsh names it.
112
+ export function statusLabel(d: ResearchDetails): string {
113
+ const key = (d.stage === "run" && d.state?.phase) || d.stage;
114
+ return statusWords[key] ?? key;
115
+ }
116
+
117
+ // isFollowUp is a sub-agent of the follow-up round: drsh numbers the planned
118
+ // sub-topics and opens a follow-up's ID with "f" (followUpPrefix in
119
+ // internal/ui/driver.go), which is how its own tree tells the two apart.
120
+ function isFollowUp(a: SubAgent): boolean {
121
+ return a.id.startsWith("f");
122
+ }
123
+
124
+ const finished = (a: SubAgent) => a.state === "done" || a.state === "error";
125
+
126
+ // troubled is a sub-agent that failed, or ended with errors: its row stays
127
+ // when the rest fold into one line.
128
+ const troubled = (a: SubAgent) => a.state === "error" || Boolean(a.errors);
129
+
130
+ // agentLines is one line per sub-agent while the search goes. Once it is
131
+ // over and the run has moved on, the finished rows are one line: four green
132
+ // rows at 100% through the analysis and the fact-check repeated what that
133
+ // line says, and pushed the phase's own lines down. A failed one is kept.
134
+ function agentLines(s: RunState, t: Theme, now: number): string[] {
135
+ const agents = s.subagents;
136
+ if (agents.length && s.phase !== "Research" && agents.every(finished)) {
137
+ const follow = agents.filter(isFollowUp).length;
138
+ const split = follow ? ` (${agents.length - follow} planned, ${follow} follow-up${follow === 1 ? "" : "s"})` : "";
139
+ const bad = agents.filter(troubled).length;
140
+ const issues = bad ? `, ${bad} with errors` : "";
141
+ const lines = [` ${t.fg(bad ? "warning" : "success", "●")} ${t.fg("muted", `${agents.length} sub-topic${agents.length === 1 ? "" : "s"} searched${split}${issues}`)}`];
142
+ for (const a of agents.filter(troubled)) lines.push(agentLine(a, t, now));
143
+ return lines;
144
+ }
145
+ return agents.map((a) => agentLine(a, t, now));
146
+ }
147
+
148
+ function agentLine(a: SubAgent, t: Theme, now: number): string {
149
+ const done = finished(a);
150
+ const pct = a.progress && !done ? t.fg("muted", ` ${a.progress}%`) : "";
151
+ const line = a.line && !done ? t.fg("dim", ` ${oneLine(a.line, 70)}`) : "";
152
+ const tag = isFollowUp(a) ? t.fg("muted", "follow-up · ") : "";
153
+ const errs = a.errors && a.state !== "error" ? t.fg("warning", ` ${a.errors} error${a.errors === 1 ? "" : "s"}`) : "";
154
+ return ` ${glyph(a, t, now)} ${tag}${oneLine(a.name, 50)}${pct}${errs}${line}`;
155
+ }
156
+
157
+ // statusText is the latest transient line as the view shows it. Its
158
+ // trailing clock is the call's, beside the stage's in the header: two
159
+ // clocks that disagreed. In the fact-check, an analyzer call is the repair
160
+ // pass revising what the check refused, not the analysis again.
161
+ function statusText(s: RunState): string {
162
+ let text = s.status.replace(/ · \d+:\d{2}(?::\d{2})?$/, "");
163
+ if (s.phase === "Fact-Check") text = text.replace(/^analyzing\b/, "revising");
164
+ return text;
165
+ }
166
+
88
167
  // 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.
168
+ // are read from it, so a view redrawn with no new event still moves. What is
169
+ // happening now (the status, an error) comes right under the header, before
170
+ // the list of sub-agents that can run long.
90
171
  export function progressLines(d: ResearchDetails, t: Theme, now = Date.now()): string[] {
91
172
  const s = d.state;
92
173
  const lines: string[] = [];
@@ -97,27 +178,63 @@ export function progressLines(d: ResearchDetails, t: Theme, now = Date.now()): s
97
178
  if (!s) {
98
179
  return lines;
99
180
  }
181
+ const status = statusText(s);
182
+ if (status) {
183
+ lines.push(t.fg("dim", ` ${oneLine(status, 110)}`));
184
+ }
185
+ for (const e of s.errors.slice(-2)) {
186
+ lines.push(t.fg("error", `! ${oneLine(e, 110)}`));
187
+ }
100
188
  for (const c of s.domains) {
101
189
  const ok = c.status === "ok";
102
190
  lines.push(` ${ok ? t.fg("success", "✓") : t.fg("warning", "!")} ${c.domain} ${t.fg("dim", c.status + (c.detail ? `: ${oneLine(c.detail, 60)}` : ""))}`);
103
191
  }
104
- for (const a of s.subagents) {
105
- const pct = a.progress ? t.fg("muted", ` ${a.progress}%`) : "";
106
- const line = a.line && a.state !== "done" ? t.fg("dim", ` ${oneLine(a.line, 70)}`) : "";
107
- lines.push(` ${glyph(a, t, now)} ${oneLine(a.name, 50)}${pct}${line}`);
108
- }
109
- const counts = [`${s.searches} searches`, `${s.reads} pages`, `${s.sources} sources`];
192
+ lines.push(...agentLines(s, t, now));
193
+ // Before the run, nothing is searched: "0 searches · 0 pages · 0
194
+ // sources" under the clarifier and the planner was noise.
195
+ const counts = d.stage === "run" || d.stage === "done" ? [`${s.searches} searches`, `${s.reads} pages`, `${s.sources} sources`] : [];
110
196
  if (s.tokens) counts.push(`${count(s.tokens)} tokens`);
111
- lines.push(t.fg("muted", counts.join(" · ")));
112
- if (s.status) {
113
- lines.push(t.fg("dim", oneLine(s.status, 110)));
114
- }
115
- for (const e of s.errors.slice(-2)) {
116
- lines.push(t.fg("error", `! ${oneLine(e, 110)}`));
197
+ if (counts.length) lines.push(t.fg("muted", counts.join(" · ")));
198
+ // A view saved before notes were kept has none.
199
+ for (const c of s.checked ?? []) {
200
+ lines.push(t.fg("muted", `fact-check: ${oneLine(c, 110)}`));
117
201
  }
118
202
  return lines;
119
203
  }
120
204
 
205
+ // costText is a run's cost beside its tokens: none when the estimate is
206
+ // zero (a local model, or one Pi has no price for), where "$0.0000" read
207
+ // as a figure, and a bound when it rounds to zero.
208
+ export function costText(cost: number): string {
209
+ if (!(cost > 0)) return "";
210
+ if (cost < 0.0001) return " (<$0.0001)";
211
+ return ` ($${cost.toFixed(cost < 0.01 ? 4 : 2)})`;
212
+ }
213
+
214
+ function tilde(p: string): string {
215
+ const home = homedir();
216
+ return home && p.startsWith(home + sep) ? `~${p.slice(home.length)}` : p;
217
+ }
218
+
219
+ // filesLines names a run's files. The paths share a long directory and a
220
+ // long name and differ in the extension: three of them in full filled three
221
+ // lines. Collapsed, the directory is named once and the files after it;
222
+ // expanded, each path in full, to copy.
223
+ export function filesLines(paths: string[], expanded: boolean, t: Theme): string[] {
224
+ if (!paths.length) return [];
225
+ if (expanded) return paths.map((p) => t.fg("dim", p));
226
+ const dir = dirname(paths[0]);
227
+ if (!paths.every((p) => dirname(p) === dir)) return paths.map((p) => t.fg("dim", p));
228
+ const names = paths.map((p) => basename(p));
229
+ const md = names.find((n) => n.endsWith(".md"));
230
+ const stem = md ? md.slice(0, -".md".length) : "";
231
+ const files =
232
+ stem && names.every((n) => n.startsWith(`${stem}.`))
233
+ ? `${stem} ${names.map((n) => n.slice(stem.length)).join(" ")}`
234
+ : names.join(" ");
235
+ return [t.fg("dim", `files in ${tilde(dir)}${sep}`), t.fg("dim", ` ${files}`)];
236
+ }
237
+
121
238
  function header(o: OutcomeDetails, model: string | undefined, t: Theme): string {
122
239
  const mark =
123
240
  o.status === "complete"
@@ -146,7 +263,9 @@ export function outcomeLines(d: ResearchDetails, expanded: boolean, t: Theme): s
146
263
  const g = o.digest;
147
264
  if (g?.factChecked) {
148
265
  const counts = Object.entries(g.verdicts).map(([k, n]) => `${n} ${k}`);
149
- lines.push(t.fg("muted", `fact-check: ${counts.join(", ") || "no claims checked"} · ${g.sources} sources, ${g.cited} cited`));
266
+ // The claims as the run concluded them: the fact-check's verdicts,
267
+ // the quote check after it, and the program's arithmetic.
268
+ lines.push(t.fg("muted", `claims: ${counts.join(", ") || "none checked"} · ${g.sources} sources, ${g.cited} cited`));
150
269
  const shown = expanded ? g.unconfirmed : g.unconfirmed.slice(0, 3);
151
270
  for (const u of shown) {
152
271
  lines.push(` ${t.fg("warning", u.status)} ${oneLine(u.claim, expanded ? 400 : 100)}`);
@@ -159,13 +278,14 @@ export function outcomeLines(d: ResearchDetails, expanded: boolean, t: Theme): s
159
278
  }
160
279
  }
161
280
  if (o.checkpoint) {
281
+ // The card is all a /research run shows after a stop (no agent turn
282
+ // follows one): it says how to go on, as the text did.
162
283
  lines.push(t.fg("muted", `checkpoint: ${o.checkpoint}`));
284
+ lines.push(t.fg("muted", "/research-resume continues it without repeating finished searches"));
163
285
  }
164
- const md = o.artifacts.find((p) => p.endsWith(".md"));
165
- if (md && !expanded) {
166
- lines.push(t.fg("dim", md));
167
- } else {
168
- for (const p of expanded ? o.artifacts : []) lines.push(t.fg("dim", p));
286
+ if (d.usage?.tokens) {
287
+ lines.push(t.fg("muted", `used ${count(d.usage.tokens)} tokens${costText(d.usage.cost)}`));
169
288
  }
289
+ lines.push(...filesLines(o.artifacts, expanded, t));
170
290
  return lines;
171
291
  }
package/src/research.ts CHANGED
@@ -73,8 +73,11 @@ async function stage(c: Call, details: ResearchDetails, args: string[]): Promise
73
73
 
74
74
  function stopped(details: ResearchDetails, why: string): Result {
75
75
  details.stage = "done";
76
- details.outcome = { status: "cancelled", detail: why, artifacts: [] };
77
- return { text: `deep-research run cancelled: ${why}. Nothing more was spent.`, details, isError: false };
76
+ details.outcome = { status: "cancelled", detail: `${why}; web research did not start`, artifacts: [] };
77
+ // Every stop here is before the run: the clarifier or the planner was
78
+ // paid for, the searches were not. "Nothing more was spent" read as
79
+ // nothing spent at all, beside the tokens the planning had used.
80
+ return { text: `deep-research run cancelled: ${why}. Web research did not start.`, details, isError: false };
78
81
  }
79
82
 
80
83
  // failedStage is a stage that ended without the output it exists for.
@@ -164,7 +167,7 @@ async function planned(c: Call, run: NewRun, review: boolean, details: ResearchD
164
167
  waiting(c, details);
165
168
  const plan = await c.hooks.review(r.plan);
166
169
  if (plan === "stop") {
167
- return stopped(details, "the plan was not confirmed");
170
+ return stopped(details, "the plan was declined");
168
171
  }
169
172
  run.plan = plan;
170
173
  return withPlan(c, run, plan);
package/src/result.ts CHANGED
@@ -80,24 +80,40 @@ function recText(r: Rec): string {
80
80
  return [r.choose, r.when && `when ${r.when}`].filter(Boolean).join(" ");
81
81
  }
82
82
 
83
+ // decided is each claim as the run concluded it: the claim's own status,
84
+ // which drsh sets after the fact-check, its governance included (a quote the
85
+ // checker gave that is not in the page makes a supported verdict
86
+ // insufficient; a computed claim is decided by the program). The verdicts
87
+ // are the checker's answers before that: counted, they called claims drsh
88
+ // had made insufficient supported, beside the conclusions they had failed. A claim with no status (an older run) takes its verdict's.
89
+ function decided(j: RunJSON): Unconfirmed[] {
90
+ const verdicts = j.fact_check?.verdicts ?? [];
91
+ const byId = new Map(verdicts.map((v) => [v.id, v]));
92
+ const claims = j.analysis?.claims ?? [];
93
+ if (!claims.length) {
94
+ return verdicts.map((v) => ({ id: v.id, claim: v.claim ?? "", status: v.status, reason: v.reason }));
95
+ }
96
+ const out: Unconfirmed[] = [];
97
+ for (const c of claims) {
98
+ const v = byId.get(c.id);
99
+ const status = c.status || v?.status;
100
+ if (status) out.push({ id: c.id, claim: c.claim || v?.claim || "", status, reason: c.note || v?.reason });
101
+ }
102
+ return out;
103
+ }
104
+
105
+ const statusOrder = ["supported", "partial", "disputed", "contradicted", "insufficient", "unsourced"];
106
+
83
107
  export function digest(raw: unknown): Digest {
84
108
  const j = (raw ?? {}) as RunJSON;
85
- const verdicts = j.fact_check?.verdicts ?? [];
109
+ const all = decided(j);
110
+ // In one order, supported first, so the count reads the same each run.
86
111
  const counts: Record<string, number> = {};
87
- for (const v of verdicts) {
88
- counts[v.status] = (counts[v.status] ?? 0) + 1;
89
- }
90
- const claims = new Map((j.analysis?.claims ?? []).map((c) => [c.id, c.claim]));
91
- const unconfirmed = verdicts
92
- .filter((v) => v.status !== "supported")
93
- .map((v) => ({ id: v.id, claim: v.claim || claims.get(v.id) || "", status: v.status, reason: v.reason }));
94
- // A computed claim has no verdict: the program decided it against its
95
- // computation, and its status and note say how.
96
- for (const c of j.analysis?.claims ?? []) {
97
- if (c.computed && c.status && c.status !== "supported") {
98
- unconfirmed.push({ id: c.id, claim: c.claim, status: c.status, reason: c.note });
99
- }
112
+ const rank = (s: string) => (statusOrder.indexOf(s) + statusOrder.length + 1) % (statusOrder.length + 1);
113
+ for (const c of [...all].sort((a, b) => rank(a.status) - rank(b.status))) {
114
+ counts[c.status] = (counts[c.status] ?? 0) + 1;
100
115
  }
116
+ const unconfirmed = all.filter((c) => c.status !== "supported");
101
117
  const figures = (j.analysis?.computations ?? []).map((m) =>
102
118
  m.valid
103
119
  ? { id: m.id, label: m.label ?? "", value: [m.result, m.unit].filter(Boolean).join(" "), formula: m.formula }
@@ -146,27 +162,43 @@ export interface Outcome {
146
162
  // maxReport bounds the report sent to the model; the whole of it is on disk.
147
163
  export const maxReport = 60_000;
148
164
 
165
+ const followUps = "I can also answer follow-ups from this run's saved files, though those answers aren't fact-checked.";
166
+
149
167
  // closingOffer is what the agent offers after a report, in the Pi user's
150
- // terms: the command for a deeper run, whose fact-check is a step it may
151
- // not finish, and follow-ups from the saved files, which are not checked.
152
- export const closingOffer =
153
- "For more depth, I can run a deeper research (`/research --mode deep`), which includes a fact-check step; I can also answer follow-ups from this run's saved files, though those answers aren't fact-checked.";
154
-
155
- const rules = [
156
- "Answer from this report and keep its citations.",
157
- "Say the confidence it gives.",
158
- "Say which claims the fact-check did not confirm, and do not present an unconfirmed claim or a blocked recommendation or conclusion as fact.",
159
- "State a figure only as the report or a COMPUTED line gives it; do no arithmetic of your own.",
160
- // Said to a Pi user, "a new deep_research" and "via research_ask" name
161
- // the agent's tools, which the user cannot call: a new run is the
162
- // /research command, and a follow-up is answered from the run's files,
163
- // which the agent can read. Told what not to say, the model still
164
- // offered "a fact-checked version", a check a run can end without;
165
- // given the sentence, it uses it.
166
- "Do not add facts the run did not establish.",
167
- "Give the user the artifact paths.",
168
- `End with this sentence, as written: "${closingOffer}"`,
169
- ];
168
+ // terms: the command for another run, and follow-ups from the saved files,
169
+ // which are not checked. The other run is what this one was not: a checked
170
+ // one after an instant lookup, a broader one after a quick or standard run.
171
+ // It once offered a deep run as the one that "includes a fact-check step",
172
+ // after a standard run that had been fact-checked.
173
+ export function closingOffer(d?: Digest): string {
174
+ if (d?.instant) {
175
+ return `For a fact-checked answer, I can run a standard research (\`/research --mode standard\`); ${followUps}`;
176
+ }
177
+ if (d?.depth === "deep") {
178
+ return `${followUps.replace(/^I can also/, "I can")} A new question is a new run (\`/research\`).`;
179
+ }
180
+ return `For a broader look, I can run a deep research (\`/research --mode deep\`), which plans more sub-topics and reads more pages; ${followUps}`;
181
+ }
182
+
183
+ function rules(d?: Digest): string[] {
184
+ return [
185
+ "Answer from this report and keep its citations.",
186
+ "Say the confidence it gives.",
187
+ "Say which claims the fact-check did not confirm, and do not present an unconfirmed claim or a blocked recommendation or conclusion as fact.",
188
+ "State a figure only as the report or a COMPUTED line gives it; do no arithmetic of your own.",
189
+ // Said to a Pi user, "a new deep_research" and "via research_ask"
190
+ // name the agent's tools, which the user cannot call: a new run is
191
+ // the /research command, and a follow-up is answered from the run's
192
+ // files, which the agent can read. Told what not to say, the model
193
+ // still offered "a fact-checked version", a check a run can end
194
+ // without; given the sentence, it uses it.
195
+ "Do not add facts the run did not establish.",
196
+ // The paths share a long directory and name: listed in full, the
197
+ // three of them took three wrapped lines of the answer.
198
+ "Give the user the folder the run's files are in, once, then the file names (the .md report first), not each full path.",
199
+ `End with this sentence, as written: "${closingOffer(d)}"`,
200
+ ];
201
+ }
170
202
 
171
203
  function digestLines(d: Digest): string[] {
172
204
  if (d.instant) {
@@ -175,7 +207,7 @@ function digestLines(d: Digest): string[] {
175
207
  const out = [`Confidence: ${d.confidence || "not stated"}.`];
176
208
  if (d.factChecked) {
177
209
  const counts = Object.entries(d.verdicts).map(([k, n]) => `${n} ${k}`);
178
- out.push(`Fact-check: ${counts.length ? counts.join(", ") : "no claims were checked"}.`);
210
+ out.push(`Claims, as the run concluded them after the fact-check: ${counts.length ? counts.join(", ") : "none were checked"}.`);
179
211
  } else {
180
212
  // A standard or deep run whose analysis or fact-check failed: it is
181
213
  // not an instant lookup, and what it did find is still worth saying.
@@ -245,7 +277,7 @@ export function content(o: Outcome): string {
245
277
  lines.push(`Artifacts: ${o.artifacts.join(", ")}`);
246
278
  }
247
279
  if (o.report) {
248
- lines.push("", "How to report it:", ...rules.map((r) => `- ${r}`));
280
+ lines.push("", "How to report it:", ...rules(o.digest).map((r) => `- ${r}`));
249
281
  }
250
282
  lines.push(...reportText(o));
251
283
  return lines.join("\n");