@juanhuttemann/pi-deep-research 0.2.0 → 0.3.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
@@ -33,10 +33,13 @@ setup, while Exa, Tavily and Firecrawl use their keys from `drsh setup`.
33
33
 
34
34
  - **`deep_research` tool.** Ask Pi to research something.
35
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.
36
+ long it has taken, what the model is doing, each sub-agent (follow-ups
37
+ marked), and the searches, pages and sources so far. Once the search
38
+ is over, its sub-agents fold into one line, and the fact-check's tally
39
+ shows when it has one.
38
40
  - 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.
41
+ the claims it did not confirm, and the folder the run's files are in;
42
+ Ctrl+O expands it to every claim and each file's full path.
40
43
  - Esc stops a run. It keeps a checkpoint, and resuming from it skips the
41
44
  searches already done.
42
45
  - When the question leaves something open, the clarifying questions open
@@ -54,15 +57,21 @@ setup, while Exa, Tavily and Firecrawl use their keys from `drsh setup`.
54
57
  - **`/research [--topics 3 --follow-ups off --domains a,b …] question`**
55
58
  runs a research yourself.
56
59
  - 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.
60
+ setting under the cursor through its values, Enter lists them all, and
61
+ the line under the list says what the setting does.
62
+ - You answer the clarifying questions and review the plan: its depth,
63
+ pages per topic, follow-ups, and the search each sub-topic starts
64
+ from. An edit past drsh's sub-topic limit is refused there. Then the
65
+ run starts, ends in a card like the tool's (with the tokens it used),
66
+ and the agent reports what it found. An instant run has no plan
67
+ review: it searches the question as asked.
60
68
  - `/research-stop` ends the run, keeping a checkpoint.
61
69
  - `/research-resume` continues the last stopped, failed or incomplete
62
70
  run from its checkpoint without repeating finished searches;
63
71
  `/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.
72
+ before drsh's first checkpoint has nothing searched: it starts again
73
+ with the same question, settings and answers, and with the plan you
74
+ approved, edits included, when you had approved one.
66
75
  - **`/research-model`** picks the model research runs use:
67
76
  - Pi's current model, the default.
68
77
  - 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.2.0",
3
+ "version": "0.3.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",
@@ -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/args.ts CHANGED
@@ -48,6 +48,10 @@ export interface NewRun {
48
48
  domains?: string[];
49
49
  answers?: Clarified;
50
50
  trace?: boolean;
51
+ // plan is the plan the user approved, kept when the run ended before
52
+ // drsh's first checkpoint: run again, it is run as approved, edits
53
+ // included, with no questions or review.
54
+ plan?: unknown;
51
55
  }
52
56
 
53
57
  export type Stage = "clarify" | "plan" | "run";
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, Text } 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 {
@@ -116,6 +116,20 @@ 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.
124
+ function showLines(ctx: ExtensionContext, key: string, lines: string[] | undefined): void {
125
+ if (lines === undefined || ctx.mode !== "tui") {
126
+ ctx.ui.setWidget(key, lines);
127
+ return;
128
+ }
129
+ const text = lines.join("\n");
130
+ ctx.ui.setWidget(key, () => new Text(text, 1, 0));
131
+ }
132
+
119
133
  export default function deepResearch(pi: ExtensionAPI) {
120
134
  const bin = process.env.DRSH_BIN || "drsh";
121
135
  let settings: Setting[] = [];
@@ -236,11 +250,13 @@ export default function deepResearch(pi: ExtensionAPI) {
236
250
  const edit = "Edit sub-topics";
237
251
  const stop = "Cancel";
238
252
  let plan = (raw ?? {}) as Plan;
253
+ const planned = subTopicNames(plan).length;
254
+ const max = settings.find((x) => x.key === "topics")?.max;
239
255
  // notice is why the last edit was not taken, shown under the options.
240
256
  let notice: string | undefined;
241
257
  try {
242
258
  for (;;) {
243
- ctx.ui.setWidget("deep-research-plan", planLines(plan));
259
+ showLines(ctx, "deep-research-plan", planLines(plan, planned));
244
260
  const pick = await pickWithNotice(ctx, "Review the plan", [run, edit, stop], { notice, signal });
245
261
  notice = undefined;
246
262
  if (pick === undefined || pick === stop) return "stop";
@@ -255,10 +271,12 @@ export default function deepResearch(pi: ExtensionAPI) {
255
271
  notice = "A plan needs at least one sub-topic";
256
272
  continue;
257
273
  }
274
+ notice = tooMany(edited, max);
275
+ if (notice) continue;
258
276
  plan = edited;
259
277
  }
260
278
  } finally {
261
- ctx.ui.setWidget("deep-research-plan", undefined);
279
+ showLines(ctx, "deep-research-plan", undefined);
262
280
  }
263
281
  }
264
282
 
@@ -455,8 +473,10 @@ export default function deepResearch(pi: ExtensionAPI) {
455
473
  });
456
474
  }
457
475
 
458
- pi.on("session_start", async (_event, ctx) => {
459
- session++;
476
+ // restoreBranch reads the model chosen and the last run and report from
477
+ // the branch now in effect: entries on another branch are not this
478
+ // conversation's.
479
+ function restoreBranch(ctx: ExtensionContext): void {
460
480
  choice = { kind: "pi" };
461
481
  lastReport = undefined;
462
482
  lastRun = undefined;
@@ -466,6 +486,26 @@ export default function deepResearch(pi: ExtensionAPI) {
466
486
  if (e.customType === runEntry && e.data) lastRun = e.data as RunRecord;
467
487
  if (e.customType === runEntry && (e.data as RunRecord | undefined)?.json) lastReport = e.data as RunRecord;
468
488
  }
489
+ }
490
+
491
+ // A /research run's message is drawn as its card: what it found,
492
+ // collapsed to the confidence, the claims the fact-check did not confirm
493
+ // and where the files are. Drawn as its text, it was the model's
494
+ // instructions and the whole report, which the agent's answer then said
495
+ // again. The text still goes to the model as it was.
496
+ pi.registerMessageRenderer<ResearchDetails>("deep-research", (message, { expanded, keyHint }, theme) => {
497
+ const d = message.details;
498
+ if (!d?.outcome) return undefined;
499
+ const lines = [theme.fg("toolTitle", theme.bold("deep research ")) + theme.fg("accent", d.question), ...outcomeLines(d, expanded, theme)];
500
+ lines.push(keyHint("app.tools.expand", expanded ? "to collapse" : "to expand"));
501
+ const box = new Box(1, 1, (t) => theme.bg("customMessageBg", t));
502
+ box.addChild(new Text(lines.join("\n"), 0, 0));
503
+ return box;
504
+ });
505
+
506
+ pi.on("session_start", async (_event, ctx) => {
507
+ session++;
508
+ restoreBranch(ctx);
469
509
  try {
470
510
  await loadSettings();
471
511
  } catch {
@@ -473,6 +513,13 @@ export default function deepResearch(pi: ExtensionAPI) {
473
513
  }
474
514
  });
475
515
 
516
+ // /tree moves to another branch of the same session file: the branch
517
+ // left behind kept its report, run and model in force, so research_ask
518
+ // and /research-resume went on with a run that branch never had.
519
+ pi.on("session_tree", async (_event, ctx) => {
520
+ restoreBranch(ctx);
521
+ });
522
+
476
523
  pi.on("session_shutdown", async () => {
477
524
  commandRun?.abort();
478
525
  });
@@ -498,6 +545,13 @@ export default function deepResearch(pi: ExtensionAPI) {
498
545
  const depth = by ? `${valueLabel(by, values[by.key] ?? by.value)} ${name}` : "the depth";
499
546
  return `${depth} holds every option at its least: pick another ${name} to change ${x.label}`;
500
547
  };
548
+ // describe is the row's help and the note on its value ("≤3").
549
+ const describe = (row: number) => {
550
+ const x = s[row];
551
+ const v = effective(s, values)[x.key];
552
+ const note = x.choices.find((o) => o.value === v)?.note;
553
+ return note ? `${x.help} (${valueLabel(x, v)}: ${note})` : x.help;
554
+ };
501
555
  // The menu checks heldWhy before stepping; this is the select's guard.
502
556
  const stepRow = (row: number, dir: 1 | -1) => {
503
557
  const x = s[row];
@@ -515,7 +569,7 @@ export default function deepResearch(pi: ExtensionAPI) {
515
569
  const viaMenu = () =>
516
570
  ctx.ui.custom<MenuResult | undefined>((_tui, theme, kb, done) => {
517
571
  const held = (row: number) => heldWhy(s[row]);
518
- const menu = new SettingsMenu(theme, kb, { title, rows, step: stepRow, held, selected }, (r) => {
572
+ const menu = new SettingsMenu(theme, kb, { title, rows, step: stepRow, held, describe, selected }, (r) => {
519
573
  selected = menu.selectedLine;
520
574
  done(r);
521
575
  });
@@ -540,13 +594,13 @@ export default function deepResearch(pi: ExtensionAPI) {
540
594
  }
541
595
 
542
596
  pi.registerCommand("research", {
543
- description: "Research a question: settings, clarifying questions and plan review, then a live run",
597
+ description: "Research a question, with settings and plan review",
544
598
  getArgumentCompletions: (prefix) => (settings.length ? completions(settings, prefix) : null),
545
599
  handler: (args, ctx) => commandRunWith(ctx, (abort) => researchCommand(args, ctx, abort)),
546
600
  });
547
601
 
548
602
  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",
603
+ description: "Resume the last stopped research run, or the checkpoint given",
550
604
  handler: (args, ctx) =>
551
605
  commandRunWith(ctx, async (abort) => {
552
606
  const checkpoint = args.trim() || lastRun?.checkpoint;
@@ -646,9 +700,8 @@ export default function deepResearch(pi: ExtensionAPI) {
646
700
  async function backgroundRun(ctx: ExtensionContext, abort: AbortController, req: Request): Promise<void> {
647
701
  const status = ticker(() => {
648
702
  if (!latest) return;
649
- const lines = progressLines(latest, ctx.ui.theme);
650
- ctx.ui.setWidget("deep-research", lines);
651
- ctx.ui.setStatus("deep-research", `research: ${latest.state?.phase || latest.stage}`);
703
+ showLines(ctx, "deep-research", progressLines(latest, ctx.ui.theme));
704
+ ctx.ui.setStatus("deep-research", `research: ${statusLabel(latest)}`);
652
705
  }, tickMs, () => latest?.started !== undefined);
653
706
  let latest: ResearchDetails | undefined;
654
707
  try {
@@ -660,24 +713,26 @@ export default function deepResearch(pi: ExtensionAPI) {
660
713
  ask: (qs) => askQuestions(ctx, qs, abort.signal),
661
714
  review: (plan) => reviewPlan(ctx, plan, abort.signal),
662
715
  });
716
+ // The usage goes on the run's card: a notice of it passed in a
717
+ // moment, apart from the run it was for.
718
+ if (bridge?.usage.totalTokens) {
719
+ result.details.usage = { tokens: bridge.usage.totalTokens, cost: bridge.usage.cost.total };
720
+ }
663
721
  pi.sendMessage(
664
722
  { customType: "deep-research", content: result.text, display: true, details: result.details },
665
723
  { triggerTurn: result.details.outcome !== undefined && result.details.outcome.status !== "cancelled" },
666
724
  );
667
- if (bridge?.usage.totalTokens) {
668
- ctx.ui.notify(`research used ${count(bridge.usage.totalTokens)} tokens ($${bridge.usage.cost.total.toFixed(4)}) on ${bridge.modelName}`, "info");
669
- }
670
725
  } catch (err) {
671
726
  ctx.ui.notify(`research failed: ${(err as Error).message}`, "error");
672
727
  } finally {
673
728
  status.cancel();
674
- ctx.ui.setWidget("deep-research", undefined);
729
+ showLines(ctx, "deep-research", undefined);
675
730
  ctx.ui.setStatus("deep-research", undefined);
676
731
  }
677
732
  }
678
733
 
679
734
  pi.registerCommand("research-stop", {
680
- description: "Stop the research run /research started; it keeps a checkpoint /research-resume continues from",
735
+ description: "Stop the /research run, keeping a checkpoint to resume from",
681
736
  handler: async (_args, ctx) => {
682
737
  if (!commandRun) {
683
738
  ctx.ui.notify("No /research run is going (a run the agent started stops with Esc)", "info");
@@ -688,7 +743,7 @@ export default function deepResearch(pi: ExtensionAPI) {
688
743
  });
689
744
 
690
745
  pi.registerCommand("research-model", {
691
- description: "Choose the model research runs use: Pi's current model, another of Pi's models, or drsh's own",
746
+ description: "Choose the model research runs use",
692
747
  handler: async (_args, ctx) => {
693
748
  const current = "Pi's current model (follows /model)";
694
749
  const own = "drsh's own configured model (drsh setup)";
@@ -707,7 +762,7 @@ export default function deepResearch(pi: ExtensionAPI) {
707
762
  });
708
763
 
709
764
  pi.registerCommand("research-doctor", {
710
- description: "Check what a research run depends on: the model (through Pi), search and the scraper",
765
+ description: "Check the model, search and scraper a run needs",
711
766
  handler: async (_args, ctx) => {
712
767
  let model: Model<Api> | undefined;
713
768
  try {
package/src/menu.ts CHANGED
@@ -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.
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
  }
@@ -23,24 +27,50 @@ export function subTopicNames(plan: Plan): string[] {
23
27
  // each. An unchanged line keeps its sub-topic, the planner's query and
24
28
  // terms included; a changed or new one is a sub-topic of that name alone,
25
29
  // whose query the run derives, since the old query searched for something
26
- // else. A list marker a reader typed (1., -, •) is dropped, but not from a
27
- // line that is a sub-topic's name as it stands: "3.5 vs 4 throughput" or
28
- // "-O2 vs -O3 builds" left alone is that sub-topic, not a new "5 vs 4".
30
+ // else. A list marker a reader typed ("1. ", "- ", "•") is dropped, but not
31
+ // from a line that is a sub-topic's name as it stands; and a number or a
32
+ // dash is a marker only with a space after it: "3.5 vs 4 throughput" or
33
+ // "-O2 builds", typed new, is that sub-topic, not "5 vs 4" or "O2 builds".
29
34
  export function withSubTopics(plan: Plan, text: string): Plan {
30
35
  const old = new Map((plan.sub_topics ?? []).map((t) => [t.name.trim(), t]));
31
36
  const names = text
32
37
  .split("\n")
33
38
  .map((l) => l.trim())
34
- .map((l) => (old.has(l) ? l : l.replace(/^(?:\d+[.)]|[-*•])\s*/, "").trim()))
39
+ .map((l) => (old.has(l) ? l : l.replace(/^(?:(?:\d+[.)]|[-*])\s+|•\s*)/, "").trim()))
35
40
  .filter(Boolean);
36
41
  return { ...plan, sub_topics: names.map((n) => old.get(n) ?? { name: n }) };
37
42
  }
38
43
 
39
- // planLines is the plan as the review shows it.
40
- 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[] {
41
59
  const names = subTopicNames(plan);
42
- return [
43
- `Plan: ${names.length} sub-topic${names.length === 1 ? "" : "s"}${plan.question ? ` for "${plan.question}"` : ""}`,
44
- ...names.map((n, i) => ` ${i + 1}. ${n}`),
45
- ];
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;
46
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
@@ -42,9 +42,9 @@ 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.
45
+ // request is a run that ended before drsh's first checkpoint, which it
46
+ // writes once the plan is taken: nothing was searched, so resuming it is
47
+ // asking it again, with the settings, answers and approved plan it had.
48
48
  request?: NewRun;
49
49
  }
50
50
 
@@ -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.
@@ -105,7 +108,7 @@ function waiting(c: Call, details: ResearchDetails): void {
105
108
  }
106
109
 
107
110
  async function clarify(c: Call, run: NewRun, details: ResearchDetails): Promise<Result | undefined> {
108
- if (run.answers) {
111
+ if (run.answers || run.plan) {
109
112
  return undefined;
110
113
  }
111
114
  enter(details, "clarify");
@@ -142,8 +145,11 @@ async function clarify(c: Call, run: NewRun, details: ResearchDetails): Promise<
142
145
  }
143
146
 
144
147
  // planned is the command line for the run itself: as asked, or the plan the
145
- // user reviewed and maybe edited.
148
+ // user reviewed and maybe edited, which is kept on run.plan.
146
149
  async function planned(c: Call, run: NewRun, review: boolean, details: ResearchDetails): Promise<string[] | Result> {
150
+ if (run.plan !== undefined) {
151
+ return withPlan(c, run, run.plan);
152
+ }
147
153
  if (!review || !c.hooks.review) {
148
154
  return newRunArgs(c.settings, run, c.reports, "run");
149
155
  }
@@ -152,11 +158,22 @@ async function planned(c: Call, run: NewRun, review: boolean, details: ResearchD
152
158
  const r = await stage(c, details, newRunArgs(c.settings, run, c.reports, "plan"));
153
159
  const failed = failedStage(details, r, "planning");
154
160
  if (failed) return failed;
161
+ // An instant plan is not reviewed, as drsh's own brief does not ask: it
162
+ // searches the question as asked, and drsh puts any plan marked instant
163
+ // back to that, so an edited sub-topic did nothing.
164
+ if ((r.plan as { instant?: unknown } | undefined)?.instant === true) {
165
+ return withPlan(c, run, r.plan);
166
+ }
155
167
  waiting(c, details);
156
168
  const plan = await c.hooks.review(r.plan);
157
169
  if (plan === "stop") {
158
- return stopped(details, "the plan was not confirmed");
170
+ return stopped(details, "the plan was declined");
159
171
  }
172
+ run.plan = plan;
173
+ return withPlan(c, run, plan);
174
+ }
175
+
176
+ async function withPlan(c: Call, run: NewRun, plan: unknown): Promise<string[]> {
160
177
  const file = join(c.reports, "plan.json");
161
178
  await writeFile(file, JSON.stringify(plan, null, 2));
162
179
  return planRunArgs(file, c.reports, run.trace);
@@ -277,5 +294,14 @@ export async function research(c: Call): Promise<Result> {
277
294
  c.hooks.update(details);
278
295
  const r = await stage(c, details, args);
279
296
  const { o, isError } = await outcome(c, r);
280
- return { text: content(o), isError, ...finish(details, o, details.question) };
297
+ const done = finish(details, o, details.question);
298
+ // Ended before drsh's first checkpoint, at the step into the run: a
299
+ // plan approved here was only in plan.json, and /research-resume found
300
+ // neither a checkpoint nor a request and said nothing was left. drsh's
301
+ // own status, not the outcome's: a run that searched to the end and
302
+ // failed only to write its report is not one to search again.
303
+ if (c.req.kind === "new" && done.record && !o.checkpoint && r.done?.status !== "complete") {
304
+ done.record.request = structuredClone(c.req.run);
305
+ }
306
+ return { text: content(o), isError, ...done };
281
307
  }
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,14 +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
 
149
- const rules = [
150
- "Answer from this report and keep its citations.",
151
- "Say the confidence it gives.",
152
- "Say which claims the fact-check did not confirm, and do not present an unconfirmed claim or a blocked recommendation or conclusion as fact.",
153
- "State a figure only as the report or a COMPUTED line gives it; do no arithmetic of your own.",
154
- "Do not add facts the run did not establish; offer research_ask for a question its pages may answer, or a new run.",
155
- "Give the user the artifact paths.",
156
- ];
165
+ const followUps = "I can also answer follow-ups from this run's saved files, though those answers aren't fact-checked.";
166
+
167
+ // closingOffer is what the agent offers after a report, in the Pi user's
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
+ }
157
202
 
158
203
  function digestLines(d: Digest): string[] {
159
204
  if (d.instant) {
@@ -162,7 +207,7 @@ function digestLines(d: Digest): string[] {
162
207
  const out = [`Confidence: ${d.confidence || "not stated"}.`];
163
208
  if (d.factChecked) {
164
209
  const counts = Object.entries(d.verdicts).map(([k, n]) => `${n} ${k}`);
165
- 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"}.`);
166
211
  } else {
167
212
  // A standard or deep run whose analysis or fact-check failed: it is
168
213
  // not an instant lookup, and what it did find is still worth saying.
@@ -232,7 +277,7 @@ export function content(o: Outcome): string {
232
277
  lines.push(`Artifacts: ${o.artifacts.join(", ")}`);
233
278
  }
234
279
  if (o.report) {
235
- lines.push("", "How to report it:", ...rules.map((r) => `- ${r}`));
280
+ lines.push("", "How to report it:", ...rules(o.digest).map((r) => `- ${r}`));
236
281
  }
237
282
  lines.push(...reportText(o));
238
283
  return lines.join("\n");