@juanhuttemann/pi-deep-research 0.1.1 → 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.1",
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";
@@ -120,7 +120,10 @@ export default function deepResearch(pi: ExtensionAPI) {
120
120
  let settings: Setting[] = [];
121
121
  let loadError = "";
122
122
  let choice: ModelChoice = { kind: "pi" };
123
- let lastRun: RunRecord | undefined;
123
+ // lastReport is the last run that wrote a .json, what research_ask reads
124
+ // by default: a run stopped or failed after it leaves none, and must not
125
+ // hide the one before.
126
+ let lastReport: RunRecord | undefined;
124
127
  let commandRun: AbortController | undefined;
125
128
 
126
129
  async function loadSettings(): Promise<Setting[]> {
@@ -132,6 +135,10 @@ export default function deepResearch(pi: ExtensionAPI) {
132
135
  }
133
136
  settings = parseSettings(r.stdout);
134
137
  loadError = "";
138
+ // Wherever drsh first answers (the session's start, /research,
139
+ // /research-doctor, the stand-in), the real tools replace the
140
+ // stand-in: drsh installed mid-session is usable from then on.
141
+ registerTools(settings);
135
142
  } catch (err) {
136
143
  const e = err as NodeJS.ErrnoException;
137
144
  loadError = e.code === "ENOENT" ? `drsh was not found (${bin}).\n${installHelp}` : e.message;
@@ -189,7 +196,7 @@ export default function deepResearch(pi: ExtensionAPI) {
189
196
 
190
197
  function remember(rec: RunRecord | undefined): void {
191
198
  if (!rec) return;
192
- lastRun = rec;
199
+ if (rec.json) lastReport = rec;
193
200
  pi.appendEntry(runEntry, rec);
194
201
  }
195
202
 
@@ -206,7 +213,7 @@ export default function deepResearch(pi: ExtensionAPI) {
206
213
  if (pick === skip) continue;
207
214
  const answer = pick === other ? await ctx.ui.input(q.text, "your answer", { signal }) : pick;
208
215
  if (answer === undefined) return "stop";
209
- if (answer.trim()) out.push({ question: q.text, answer: answer.trim() });
216
+ if (answer.trim()) out.push({ question: q.text, answer: clip(answer) });
210
217
  }
211
218
  return out;
212
219
  }
@@ -267,8 +274,9 @@ export default function deepResearch(pi: ExtensionAPI) {
267
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." }),
268
275
  ),
269
276
  answers: Type.Optional(
270
- Type.Array(Type.Object({ question: Type.String(), answer: Type.String() }), {
271
- 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.`,
272
280
  }),
273
281
  ),
274
282
  domains: Type.Optional(
@@ -302,6 +310,7 @@ export default function deepResearch(pi: ExtensionAPI) {
302
310
  throw new Error("deep_research needs a question (or resume with a checkpoint path)");
303
311
  }
304
312
  const answers = Array.isArray(p.answers) ? (p.answers as Answer[]) : undefined;
313
+ if (answers) checkAnswers(answers);
305
314
  return {
306
315
  kind: "new",
307
316
  run: {
@@ -388,16 +397,19 @@ export default function deepResearch(pi: ExtensionAPI) {
388
397
  model: Type.Optional(Type.String({ description: "provider/id of a Pi model to answer with; default as for deep_research." })),
389
398
  }),
390
399
  async execute(_id, params, signal, _onUpdate, ctx) {
391
- const runFile = params.run || lastRun?.json;
400
+ const runFile = params.run || lastReport?.json;
392
401
  if (!runFile) {
393
- throw new Error("no research run in this session yet: pass run with a run's .json path, or run deep_research first");
402
+ throw new Error("no research run in this session has written a report yet: pass run with a run's .json path, or run deep_research first");
394
403
  }
395
404
  const { model, label } = resolveModel(ctx, params.model);
396
405
  const { value: r, bridge } = await withEndpoint(ctx, model, signal, (env) =>
397
406
  runPlain(bin, ["ask", runFile, "-p", params.question], { env, signal }),
398
407
  );
408
+ if (r.aborted) {
409
+ throw new Error("research_ask was cancelled");
410
+ }
399
411
  if (r.code !== 0) {
400
- 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}`}`);
401
413
  }
402
414
  return {
403
415
  content: [
@@ -422,8 +434,7 @@ export default function deepResearch(pi: ExtensionAPI) {
422
434
  description: "Fact-checked, cited web research with the deep-research CLI (drsh). Unavailable until drsh is installed.",
423
435
  parameters: Type.Object({ question: Type.Optional(Type.String()) }),
424
436
  async execute() {
425
- const s = await loadSettings();
426
- registerTools(s);
437
+ await loadSettings();
427
438
  throw new Error("drsh is available now; call deep_research again");
428
439
  },
429
440
  });
@@ -431,14 +442,14 @@ export default function deepResearch(pi: ExtensionAPI) {
431
442
 
432
443
  pi.on("session_start", async (_event, ctx) => {
433
444
  choice = { kind: "pi" };
434
- lastRun = undefined;
445
+ lastReport = undefined;
435
446
  for (const e of ctx.sessionManager.getBranch()) {
436
447
  if (e.type !== "custom") continue;
437
448
  if (e.customType === modelEntry && e.data) choice = e.data as ModelChoice;
438
- if (e.customType === runEntry && e.data) lastRun = e.data as RunRecord;
449
+ if (e.customType === runEntry && (e.data as RunRecord | undefined)?.json) lastReport = e.data as RunRecord;
439
450
  }
440
451
  try {
441
- registerTools(await loadSettings());
452
+ await loadSettings();
442
453
  } catch {
443
454
  registerStandIn();
444
455
  }
@@ -477,69 +488,83 @@ export default function deepResearch(pi: ExtensionAPI) {
477
488
  ctx.ui.notify("A research run is already going; /research-stop ends it", "warning");
478
489
  return;
479
490
  }
480
- let s: Setting[];
481
- try {
482
- s = await ensureSettings();
483
- } catch (err) {
484
- ctx.ui.notify((err as Error).message, "error");
485
- return;
486
- }
487
- let parsed;
488
- try {
489
- parsed = parseCommandArgs(s, args);
490
- } catch (err) {
491
- ctx.ui.notify((err as Error).message, "error");
492
- return;
493
- }
494
- if (!ctx.hasUI) {
495
- ctx.ui.notify("/research needs the interactive UI; ask the agent to use deep_research instead", "error");
496
- return;
497
- }
498
- const question = parsed.question || (await ctx.ui.input("Research question", "what should the run find out?"))?.trim();
499
- if (!question) return;
500
- let values = parsed.values;
501
- if (Object.keys(values).length === 0 && parsed.domains.length === 0) {
502
- const chosen = await settingsScreen(ctx, s, values);
503
- if (!chosen) return;
504
- values = chosen;
505
- }
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.
506
495
  const abort = new AbortController();
507
496
  commandRun = abort;
508
- const status = throttle(() => {
509
- if (!latest) return;
510
- const lines = progressLines(latest, ctx.ui.theme);
511
- ctx.ui.setWidget("deep-research", lines);
512
- ctx.ui.setStatus("deep-research", `research: ${latest.state?.phase || latest.stage}`);
513
- }, 250);
514
- let latest: ResearchDetails | undefined;
515
497
  try {
516
- const req: Request = { kind: "new", run: { question, values, domains: parsed.domains }, review: true };
517
- const { result, bridge } = await run(ctx, req, undefined, abort.signal, {
518
- update: (d) => {
519
- latest = d;
520
- status.call();
521
- },
522
- ask: (qs) => askQuestions(ctx, qs, abort.signal),
523
- review: (plan) => reviewPlan(ctx, plan, abort.signal),
524
- });
525
- pi.sendMessage(
526
- { customType: "deep-research", content: result.text, display: true, details: result.details },
527
- { triggerTurn: result.details.outcome !== undefined && result.details.outcome.status !== "cancelled" },
528
- );
529
- if (bridge?.usage.totalTokens) {
530
- ctx.ui.notify(`research used ${bridge.usage.totalTokens} tokens ($${bridge.usage.cost.total.toFixed(4)}) on ${bridge.modelName}`, "info");
531
- }
532
- } catch (err) {
533
- ctx.ui.notify(`research failed: ${(err as Error).message}`, "error");
498
+ await researchCommand(args, ctx, abort);
534
499
  } finally {
535
- status.cancel();
536
500
  commandRun = undefined;
537
- ctx.ui.setWidget("deep-research", undefined);
538
- ctx.ui.setStatus("deep-research", undefined);
539
501
  }
540
502
  },
541
503
  });
542
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
+
543
568
  pi.registerCommand("research-stop", {
544
569
  description: "Stop the research run /research started; it keeps a checkpoint to resume from",
545
570
  handler: async (_args, ctx) => {
@@ -581,6 +606,10 @@ export default function deepResearch(pi: ExtensionAPI) {
581
606
  return;
582
607
  }
583
608
  ctx.ui.setStatus("deep-research", "checking drsh…");
609
+ // The check a user runs after installing drsh: loading its settings
610
+ // brings in the real tools. A drsh that cannot load them is
611
+ // reported by the doctor run below.
612
+ await ensureSettings().catch(() => undefined);
584
613
  try {
585
614
  const { value: r } = await withEndpoint(ctx, model, undefined, (env) => runPlain(bin, ["doctor"], { env }));
586
615
  const verdict = r.code === 0 ? "drsh doctor: ready" : "drsh doctor: something is broken (✗ lines)";
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
@@ -4,7 +4,7 @@
4
4
  // to ask (clarify off, instant), so this knows no setting by name.
5
5
 
6
6
  import { existsSync } from "node:fs";
7
- import { readFile, writeFile } from "node:fs/promises";
7
+ import { readdir, readFile, stat, writeFile } from "node:fs/promises";
8
8
  import { join } from "node:path";
9
9
  import { newRunArgs, planRunArgs, resumeArgs, type Answer, type NewRun } from "./args.ts";
10
10
  import { initialState, reduce, type Question } from "./events.ts";
@@ -150,14 +150,49 @@ async function readJSON(path: string | undefined): Promise<unknown> {
150
150
  }
151
151
  }
152
152
 
153
+ // checkpointLeft is the checkpoint a run that ended with no done line left
154
+ // on disk. drsh saves it after each step, as <reports>/*.partial.json, and
155
+ // names it only in the done line, which a killed run never writes: on
156
+ // Windows, where stopping a child process kills it outright, that is every
157
+ // stopped run. Each run has a reports directory of its own, so a checkpoint
158
+ // there is this run's; a resumed run saves to the checkpoint it resumed. A
159
+ // file that is not one drsh can resume from (no question or no plan, as
160
+ // replay.Load refuses) is not offered.
161
+ async function checkpointLeft(c: Call): Promise<string | undefined> {
162
+ let candidates: string[];
163
+ if (c.req.kind === "resume") {
164
+ candidates = [c.req.checkpoint];
165
+ } else {
166
+ const names = await readdir(c.reports).catch(() => [] as string[]);
167
+ candidates = names.filter((n) => n.endsWith(".partial.json")).map((n) => join(c.reports, n));
168
+ }
169
+ const valid: { path: string; mtime: number }[] = [];
170
+ for (const path of candidates) {
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 });
176
+ }
177
+ }
178
+ return valid.sort((a, b) => b.mtime - a.mtime)[0]?.path;
179
+ }
180
+
181
+ function resumable(raw: unknown): boolean {
182
+ const t = raw as { question?: unknown; plan?: unknown } | null | undefined;
183
+ return typeof t?.question === "string" && t.question.trim() !== "" && Array.isArray(t.plan) && t.plan.length > 0;
184
+ }
185
+
153
186
  // outcome reads what a run's done line says it wrote.
154
- async function outcome(r: JsonlResult, model?: string): Promise<{ o: Outcome; isError: boolean }> {
187
+ async function outcome(c: Call, r: JsonlResult): Promise<{ o: Outcome; isError: boolean }> {
188
+ const model = c.model;
155
189
  if (!r.done) {
156
190
  const status = r.aborted ? "cancelled" : "failed";
157
191
  const detail = r.aborted
158
192
  ? "the run was stopped before it could end cleanly"
159
193
  : `drsh exited (code ${r.code}) without a done line, so it was killed or crashed${r.stderr ? `: ${r.stderr.trim().slice(-1500)}` : ""}`;
160
- return { o: { status, detail, artifacts: [], model }, isError: !r.aborted };
194
+ const checkpoint = await checkpointLeft(c);
195
+ return { o: { status, detail, artifacts: [], model, checkpoint }, isError: !r.aborted };
161
196
  }
162
197
  const artifacts = r.done.artifacts ?? [];
163
198
  const md = artifacts.find((p) => p.endsWith(".md"));
@@ -210,6 +245,6 @@ export async function research(c: Call): Promise<Result> {
210
245
  details.state = initialState();
211
246
  c.hooks.update(details);
212
247
  const r = await stage(c, details, args);
213
- const { o, isError } = await outcome(r, c.model);
248
+ const { o, isError } = await outcome(c, r);
214
249
  return { text: content(o), isError, ...finish(details, o, details.question) };
215
250
  }
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
@@ -144,7 +144,15 @@ export function parseCommandArgs(settings: Setting[], input: string): CommandArg
144
144
  rest.push(w);
145
145
  continue;
146
146
  }
147
- let [name, v] = w.slice(2).split("=", 2) as [string, string | undefined];
147
+ // Split at the first "=" only: a value may hold one.
148
+ const eq = w.indexOf("=");
149
+ const name = eq < 0 ? w.slice(2) : w.slice(2, eq);
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
+ }
148
156
  if (v === undefined) {
149
157
  v = words[++i];
150
158
  if (v === undefined) {
@@ -169,6 +177,31 @@ export function parseCommandArgs(settings: Setting[], input: string): CommandArg
169
177
  return out;
170
178
  }
171
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
+
172
205
  export interface Completion {
173
206
  value: string;
174
207
  label: string;
@@ -183,6 +216,8 @@ export function completions(settings: Setting[], prefix: string): Completion[] {
183
216
  const head = before ? `${before} ` : "";
184
217
  const prev = words[words.length - 2] ?? "";
185
218
  if (prev.startsWith("--")) {
219
+ // Named by its flag, a setting takes no value to complete: its choices
220
+ // there would read inverted (see flagValue).
186
221
  const s = settings.find((x) => x.key === prev.slice(2));
187
222
  if (s) {
188
223
  return s.choices