@juanhuttemann/pi-deep-research 0.1.2 → 0.1.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanhuttemann/pi-deep-research",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Fact-checked, cited web research inside Pi: runs the deep-research CLI (drsh) on Pi's own model, with live progress, clarifying questions and plan review",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/args.ts CHANGED
@@ -10,6 +10,31 @@ export interface Answer {
10
10
  answer: string;
11
11
  }
12
12
 
13
+ // maxAnswers and maxAnswerChars are drsh's bounds on --answers
14
+ // (ui.Clarified.Checked: agent.MaxQuestions, ui.maxAnswer). Past them the
15
+ // next stage fails after the questions were already answered, so they are
16
+ // held here first; the bridge tests run them against a real drsh.
17
+ export const maxAnswers = 3;
18
+ export const maxAnswerChars = 300;
19
+
20
+ // clip is a typed answer cut to maxAnswerChars, as the terminal cuts one.
21
+ export function clip(answer: string): string {
22
+ const chars = [...answer.trim()];
23
+ return chars.length > maxAnswerChars ? chars.slice(0, maxAnswerChars).join("") : chars.join("");
24
+ }
25
+
26
+ // checkAnswers refuses answers drsh would refuse, with drsh's reasons.
27
+ export function checkAnswers(answers: Answer[]): void {
28
+ if (answers.length > maxAnswers) {
29
+ throw new Error(`answers: at most ${maxAnswers}, one per clarifying question`);
30
+ }
31
+ for (const a of answers) {
32
+ if ([...a.answer.trim()].length > maxAnswerChars || [...a.question.trim()].length > maxAnswerChars) {
33
+ throw new Error(`answers: an answer is over ${maxAnswerChars} characters`);
34
+ }
35
+ }
36
+ }
37
+
13
38
  // Clarified is the --answers JSON: the questions asked and the reader's
14
39
  // answers, as ui.ParseAnswers reads it.
15
40
  export interface Clarified {
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@ import { StringEnum } from "@earendil-works/pi-ai";
12
12
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
13
13
  import { Text } from "@earendil-works/pi-tui";
14
14
  import { Type, type TSchema } from "typebox";
15
- import type { Answer } from "./args.ts";
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
18
  import { planLines, subTopicNames, withSubTopics, type Plan } from "./plan.ts";
@@ -213,7 +213,7 @@ export default function deepResearch(pi: ExtensionAPI) {
213
213
  if (pick === skip) continue;
214
214
  const answer = pick === other ? await ctx.ui.input(q.text, "your answer", { signal }) : pick;
215
215
  if (answer === undefined) return "stop";
216
- if (answer.trim()) out.push({ question: q.text, answer: answer.trim() });
216
+ if (answer.trim()) out.push({ question: q.text, answer: clip(answer) });
217
217
  }
218
218
  return out;
219
219
  }
@@ -274,8 +274,9 @@ export default function deepResearch(pi: ExtensionAPI) {
274
274
  Type.String({ description: "A checkpoint path a cancelled, failed or incomplete run reported: continues that run without repeating finished searches. Takes no other parameter." }),
275
275
  ),
276
276
  answers: Type.Optional(
277
- Type.Array(Type.Object({ question: Type.String(), answer: Type.String() }), {
278
- description: "The user's answers to the clarifying questions an earlier call returned. Given, no questions are asked.",
277
+ Type.Array(Type.Object({ question: Type.String(), answer: Type.String({ maxLength: maxAnswerChars }) }), {
278
+ maxItems: maxAnswers,
279
+ description: `The user's answers to the clarifying questions an earlier call returned, at most ${maxAnswers}, each at most ${maxAnswerChars} characters. Given, no questions are asked.`,
279
280
  }),
280
281
  ),
281
282
  domains: Type.Optional(
@@ -309,6 +310,7 @@ export default function deepResearch(pi: ExtensionAPI) {
309
310
  throw new Error("deep_research needs a question (or resume with a checkpoint path)");
310
311
  }
311
312
  const answers = Array.isArray(p.answers) ? (p.answers as Answer[]) : undefined;
313
+ if (answers) checkAnswers(answers);
312
314
  return {
313
315
  kind: "new",
314
316
  run: {
@@ -403,8 +405,11 @@ export default function deepResearch(pi: ExtensionAPI) {
403
405
  const { value: r, bridge } = await withEndpoint(ctx, model, signal, (env) =>
404
406
  runPlain(bin, ["ask", runFile, "-p", params.question], { env, signal }),
405
407
  );
408
+ if (r.aborted) {
409
+ throw new Error("research_ask was cancelled");
410
+ }
406
411
  if (r.code !== 0) {
407
- throw new Error(`drsh ask failed: ${(r.stderr || r.stdout).trim().slice(-2000)}`);
412
+ throw new Error(`drsh ask failed: ${(r.stderr || r.stdout).trim().slice(-2000) || `exit ${r.code}`}`);
408
413
  }
409
414
  return {
410
415
  content: [
@@ -483,69 +488,83 @@ export default function deepResearch(pi: ExtensionAPI) {
483
488
  ctx.ui.notify("A research run is already going; /research-stop ends it", "warning");
484
489
  return;
485
490
  }
486
- let s: Setting[];
487
- try {
488
- s = await ensureSettings();
489
- } catch (err) {
490
- ctx.ui.notify((err as Error).message, "error");
491
- return;
492
- }
493
- let parsed;
494
- try {
495
- parsed = parseCommandArgs(s, args);
496
- } catch (err) {
497
- ctx.ui.notify((err as Error).message, "error");
498
- return;
499
- }
500
- if (!ctx.hasUI) {
501
- ctx.ui.notify("/research needs the interactive UI; ask the agent to use deep_research instead", "error");
502
- return;
503
- }
504
- const question = parsed.question || (await ctx.ui.input("Research question", "what should the run find out?"))?.trim();
505
- if (!question) return;
506
- let values = parsed.values;
507
- if (Object.keys(values).length === 0 && parsed.domains.length === 0) {
508
- const chosen = await settingsScreen(ctx, s, values);
509
- if (!chosen) return;
510
- values = chosen;
511
- }
491
+ // Taken before the first await: the settings and the prompts wait
492
+ // on the user, and a second /research in that time passed the
493
+ // check above and started a run of its own; the first to end then
494
+ // cleared this while the other went on, past /research-stop.
512
495
  const abort = new AbortController();
513
496
  commandRun = abort;
514
- const status = throttle(() => {
515
- if (!latest) return;
516
- const lines = progressLines(latest, ctx.ui.theme);
517
- ctx.ui.setWidget("deep-research", lines);
518
- ctx.ui.setStatus("deep-research", `research: ${latest.state?.phase || latest.stage}`);
519
- }, 250);
520
- let latest: ResearchDetails | undefined;
521
497
  try {
522
- const req: Request = { kind: "new", run: { question, values, domains: parsed.domains }, review: true };
523
- const { result, bridge } = await run(ctx, req, undefined, abort.signal, {
524
- update: (d) => {
525
- latest = d;
526
- status.call();
527
- },
528
- ask: (qs) => askQuestions(ctx, qs, abort.signal),
529
- review: (plan) => reviewPlan(ctx, plan, abort.signal),
530
- });
531
- pi.sendMessage(
532
- { customType: "deep-research", content: result.text, display: true, details: result.details },
533
- { triggerTurn: result.details.outcome !== undefined && result.details.outcome.status !== "cancelled" },
534
- );
535
- if (bridge?.usage.totalTokens) {
536
- ctx.ui.notify(`research used ${bridge.usage.totalTokens} tokens ($${bridge.usage.cost.total.toFixed(4)}) on ${bridge.modelName}`, "info");
537
- }
538
- } catch (err) {
539
- ctx.ui.notify(`research failed: ${(err as Error).message}`, "error");
498
+ await researchCommand(args, ctx, abort);
540
499
  } finally {
541
- status.cancel();
542
500
  commandRun = undefined;
543
- ctx.ui.setWidget("deep-research", undefined);
544
- ctx.ui.setStatus("deep-research", undefined);
545
501
  }
546
502
  },
547
503
  });
548
504
 
505
+ // researchCommand is /research once it holds commandRun.
506
+ async function researchCommand(args: string, ctx: ExtensionContext, abort: AbortController): Promise<void> {
507
+ let s: Setting[];
508
+ try {
509
+ s = await ensureSettings();
510
+ } catch (err) {
511
+ ctx.ui.notify((err as Error).message, "error");
512
+ return;
513
+ }
514
+ let parsed;
515
+ try {
516
+ parsed = parseCommandArgs(s, args);
517
+ } catch (err) {
518
+ ctx.ui.notify((err as Error).message, "error");
519
+ return;
520
+ }
521
+ if (!ctx.hasUI) {
522
+ ctx.ui.notify("/research needs the interactive UI; ask the agent to use deep_research instead", "error");
523
+ return;
524
+ }
525
+ const question = parsed.question || (await ctx.ui.input("Research question", "what should the run find out?", { signal: abort.signal }))?.trim();
526
+ if (!question) return;
527
+ let values = parsed.values;
528
+ if (Object.keys(values).length === 0 && parsed.domains.length === 0) {
529
+ const chosen = await settingsScreen(ctx, s, values);
530
+ if (!chosen) return;
531
+ values = chosen;
532
+ }
533
+ // /research-stop while the prompts were open.
534
+ if (abort.signal.aborted) return;
535
+ const status = throttle(() => {
536
+ if (!latest) return;
537
+ const lines = progressLines(latest, ctx.ui.theme);
538
+ ctx.ui.setWidget("deep-research", lines);
539
+ ctx.ui.setStatus("deep-research", `research: ${latest.state?.phase || latest.stage}`);
540
+ }, 250);
541
+ let latest: ResearchDetails | undefined;
542
+ try {
543
+ const req: Request = { kind: "new", run: { question, values, domains: parsed.domains }, review: true };
544
+ const { result, bridge } = await run(ctx, req, undefined, abort.signal, {
545
+ update: (d) => {
546
+ latest = d;
547
+ status.call();
548
+ },
549
+ ask: (qs) => askQuestions(ctx, qs, abort.signal),
550
+ review: (plan) => reviewPlan(ctx, plan, abort.signal),
551
+ });
552
+ pi.sendMessage(
553
+ { customType: "deep-research", content: result.text, display: true, details: result.details },
554
+ { triggerTurn: result.details.outcome !== undefined && result.details.outcome.status !== "cancelled" },
555
+ );
556
+ if (bridge?.usage.totalTokens) {
557
+ ctx.ui.notify(`research used ${bridge.usage.totalTokens} tokens ($${bridge.usage.cost.total.toFixed(4)}) on ${bridge.modelName}`, "info");
558
+ }
559
+ } catch (err) {
560
+ ctx.ui.notify(`research failed: ${(err as Error).message}`, "error");
561
+ } finally {
562
+ status.cancel();
563
+ ctx.ui.setWidget("deep-research", undefined);
564
+ ctx.ui.setStatus("deep-research", undefined);
565
+ }
566
+ }
567
+
549
568
  pi.registerCommand("research-stop", {
550
569
  description: "Stop the research run /research started; it keeps a checkpoint to resume from",
551
570
  handler: async (_args, ctx) => {
package/src/plan.ts CHANGED
@@ -23,12 +23,15 @@ export function subTopicNames(plan: Plan): string[] {
23
23
  // each. An unchanged line keeps its sub-topic, the planner's query and
24
24
  // terms included; a changed or new one is a sub-topic of that name alone,
25
25
  // whose query the run derives, since the old query searched for something
26
- // else.
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".
27
29
  export function withSubTopics(plan: Plan, text: string): Plan {
28
30
  const old = new Map((plan.sub_topics ?? []).map((t) => [t.name.trim(), t]));
29
31
  const names = text
30
32
  .split("\n")
31
- .map((l) => l.replace(/^\s*(?:\d+[.)]|[-*•])\s*/, "").trim())
33
+ .map((l) => l.trim())
34
+ .map((l) => (old.has(l) ? l : l.replace(/^(?:\d+[.)]|[-*•])\s*/, "").trim()))
32
35
  .filter(Boolean);
33
36
  return { ...plan, sub_topics: names.map((n) => old.get(n) ?? { name: n }) };
34
37
  }
package/src/research.ts CHANGED
@@ -168,8 +168,11 @@ async function checkpointLeft(c: Call): Promise<string | undefined> {
168
168
  }
169
169
  const valid: { path: string; mtime: number }[] = [];
170
170
  for (const path of candidates) {
171
- if (resumable(await readJSON(path))) {
172
- valid.push({ path, mtime: (await stat(path)).mtimeMs });
171
+ // A file can go between the read and the stat (a cleanup, an
172
+ // antivirus on Windows): it is then not one to offer.
173
+ const mtime = await stat(path).then((st) => st.mtimeMs, () => undefined);
174
+ if (mtime !== undefined && resumable(await readJSON(path))) {
175
+ valid.push({ path, mtime });
173
176
  }
174
177
  }
175
178
  return valid.sort((a, b) => b.mtime - a.mtime)[0]?.path;
package/src/result.ts CHANGED
@@ -20,8 +20,10 @@ export interface Digest {
20
20
  question: string;
21
21
  depth: string;
22
22
  confidence: string;
23
- // factChecked is false for an instant run, which answers in one call
24
- // with no fact-check at all.
23
+ // instant is a run that answers in one call with no fact-check at all.
24
+ instant: boolean;
25
+ // factChecked is false for an instant run, and for any run that ended
26
+ // before its fact-check did (a late phase failed: incomplete).
25
27
  factChecked: boolean;
26
28
  verdicts: Record<string, number>;
27
29
  unconfirmed: Unconfirmed[];
@@ -87,6 +89,7 @@ export function digest(raw: unknown): Digest {
87
89
  question: j.question ?? "",
88
90
  depth: j.depth ?? "",
89
91
  confidence: j.confidence ?? "",
92
+ instant: j.depth === "instant",
90
93
  factChecked: j.depth !== "instant" && j.fact_check != null,
91
94
  verdicts: counts,
92
95
  unconfirmed,
@@ -122,12 +125,18 @@ const rules = [
122
125
  ];
123
126
 
124
127
  function digestLines(d: Digest): string[] {
125
- if (!d.factChecked) {
128
+ if (d.instant) {
126
129
  return ["NOT FACT-CHECKED: this was an instant run, one search and one answer with no fact-check. Tell the user so."];
127
130
  }
128
131
  const out = [`Confidence: ${d.confidence || "not stated"}.`];
129
- const counts = Object.entries(d.verdicts).map(([k, n]) => `${n} ${k}`);
130
- out.push(`Fact-check: ${counts.length ? counts.join(", ") : "no claims were checked"}.`);
132
+ if (d.factChecked) {
133
+ const counts = Object.entries(d.verdicts).map(([k, n]) => `${n} ${k}`);
134
+ out.push(`Fact-check: ${counts.length ? counts.join(", ") : "no claims were checked"}.`);
135
+ } else {
136
+ // A standard or deep run whose analysis or fact-check failed: it is
137
+ // not an instant lookup, and what it did find is still worth saying.
138
+ out.push(`NOT FACT-CHECKED: the run (${d.depth || "not instant"}) ended before its fact-check finished, so none of its claims were checked. Tell the user so.`);
139
+ }
131
140
  for (const u of d.unconfirmed) {
132
141
  out.push(`- ${u.id} ${u.status}: ${u.claim}${u.reason ? ` (${u.reason})` : ""}`);
133
142
  }
@@ -153,7 +162,11 @@ function reportText(o: Outcome): string[] {
153
162
 
154
163
  function recovery(o: Outcome): string[] {
155
164
  if (!o.checkpoint) {
156
- return o.status === "cancelled" ? ["It stopped before its plan was made, so there is no checkpoint: run it again."] : [];
165
+ // No checkpoint is either a run stopped before its plan, or one whose
166
+ // checkpoint could not be saved or read back: which, drsh does not say.
167
+ return o.status === "cancelled"
168
+ ? ["There is no checkpoint to resume from (the run stopped before its plan was made, or its checkpoint could not be saved): run it again."]
169
+ : [];
157
170
  }
158
171
  const limited = /rate.?limit|challenge/i.test(o.detail ?? "");
159
172
  return [
package/src/settings.ts CHANGED
@@ -148,6 +148,11 @@ export function parseCommandArgs(settings: Setting[], input: string): CommandArg
148
148
  const eq = w.indexOf("=");
149
149
  const name = eq < 0 ? w.slice(2) : w.slice(2, eq);
150
150
  let v: string | undefined = eq < 0 ? undefined : w.slice(eq + 1);
151
+ const byFlag = settings.find((x) => x.flag === name && x.key !== name);
152
+ if (byFlag) {
153
+ out.values[byFlag.key] = flagValue(byFlag, v, words[i + 1]);
154
+ continue;
155
+ }
151
156
  if (v === undefined) {
152
157
  v = words[++i];
153
158
  if (v === undefined) {
@@ -172,14 +177,38 @@ export function parseCommandArgs(settings: Setting[], input: string): CommandArg
172
177
  return out;
173
178
  }
174
179
 
180
+ // flagValue is the value a setting named by its CLI flag (--no-follow-ups,
181
+ // where the setting is follow-ups) takes: the flag means what it means to
182
+ // drsh, so --no-follow-ups=true is follow-ups off, and alone, like any bool
183
+ // flag, it takes no value. The setting's own on and off after it read the
184
+ // other way round from what they say, so they are refused, not guessed at.
185
+ function flagValue(s: Setting, v: string | undefined, next: string | undefined): string {
186
+ const own = `use --${s.key} ${s.choices.map((c) => c.label).join("|")}`;
187
+ if (v === undefined && next !== undefined && s.choices.some((c) => c.label === next || c.value === next)) {
188
+ throw new Error(`--${s.flag} takes no value; ${own}`);
189
+ }
190
+ const b = v === undefined ? "true" : parseBool(v);
191
+ const o = b === undefined ? undefined : s.choices.find((c) => c.arg === `--${s.flag}=${b}`);
192
+ if (!o) {
193
+ throw new Error(`--${s.flag}: ${JSON.stringify(v)} is not true or false; ${own}`);
194
+ }
195
+ return o.value;
196
+ }
197
+
198
+ // parseBool reads a bool as drsh's flags do (Go's strconv.ParseBool).
199
+ function parseBool(v: string): string | undefined {
200
+ if (["1", "t", "T", "true", "TRUE", "True"].includes(v)) return "true";
201
+ if (["0", "f", "F", "false", "FALSE", "False"].includes(v)) return "false";
202
+ return undefined;
203
+ }
204
+
175
205
  export interface Completion {
176
206
  value: string;
177
207
  label: string;
178
208
  description?: string;
179
209
  }
180
210
 
181
- // completions offers the option names, then a named option's choices; an
182
- // option is named by its key or its CLI flag, as parseCommandArgs reads it.
211
+ // completions offers the option names, then a named option's choices.
183
212
  export function completions(settings: Setting[], prefix: string): Completion[] {
184
213
  const words = prefix.split(/\s+/);
185
214
  const last = words[words.length - 1] ?? "";
@@ -187,7 +216,9 @@ export function completions(settings: Setting[], prefix: string): Completion[] {
187
216
  const head = before ? `${before} ` : "";
188
217
  const prev = words[words.length - 2] ?? "";
189
218
  if (prev.startsWith("--")) {
190
- const s = settings.find((x) => x.key === prev.slice(2) || x.flag === prev.slice(2));
219
+ // Named by its flag, a setting takes no value to complete: its choices
220
+ // there would read inverted (see flagValue).
221
+ const s = settings.find((x) => x.key === prev.slice(2));
191
222
  if (s) {
192
223
  return s.choices
193
224
  .filter((o) => o.label.startsWith(last))