probe-research 0.20.0 → 0.22.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.
@@ -25,7 +25,7 @@
25
25
  * one PostHog event so we hear who asked (plan R17).
26
26
  */
27
27
 
28
- const { spawnSync } = require("node:child_process");
28
+ const { spawn, spawnSync } = require("node:child_process");
29
29
  const crypto = require("node:crypto");
30
30
  const fs = require("node:fs");
31
31
  const os = require("node:os");
@@ -33,6 +33,7 @@ const path = require("node:path");
33
33
 
34
34
  const agentRun = require("../lib/agent-run");
35
35
  const download = require("../lib/background-download");
36
+ const setupCheck = require("../lib/setup-check");
36
37
  const signIn = require("../lib/sign-in");
37
38
 
38
39
  const DIST = "probe-research";
@@ -132,8 +133,10 @@ const FIX_MIN = "0.385.0";
132
133
  * `install --profile` and `status --repaste-choice`; 0.423.0 was cut from the commit before it merged.
133
134
  * 0.425.0 since PR15: past-work.md's `probe import folders|review|start|status|resume`; 0.424.0 was
134
135
  * cut before it merged.
136
+ * 0.432.0 since PR25: a set-up computer's agent calls run PR22's CLI (Recommended = on) and PR26's
137
+ * `update --json`; 0.431.0 was cut at PR22's merge, before PR26.
135
138
  */
136
- const AGENT_MIN_CLI = "0.425.0";
139
+ const AGENT_MIN_CLI = "0.432.0";
137
140
  /** `install` flags only AGENT_MIN_CLI knows (D36). */
138
141
  const AGENT_INSTALL_FLAGS = Object.freeze(["--recommended", "--who-records", "--session-default", "--profile",
139
142
  "--attempt"]);
@@ -296,11 +299,17 @@ const LauncherVerb = Object.freeze({
296
299
  INSTALL: "install",
297
300
  /** Launcher-only: the install prompt's sign-in (`runSignIn`), before any CLI exists. */
298
301
  SIGN_IN: "sign-in",
302
+ /** The wizard's Update (`probe update` is retired): `update --json` is the agent's (PR26). */
303
+ UPDATE: "update",
299
304
  });
300
305
  /** What `sign-in` takes (the hosted install.md names them; its test reads this list). */
301
- const SIGN_IN_FLAGS = Object.freeze(["--json", "--wait", "--no-browser"]);
306
+ const SIGN_IN_FLAGS = Object.freeze(["--json", "--wait", "--no-browser", "--if-needed"]);
307
+ /** `sign-in`'s flag for install.md's first call: on a computer already set up, status's answer and no tab. */
308
+ const IF_NEEDED_FLAG = "--if-needed";
302
309
  /** What `install` means -- exactly what `probe install` always ran (`main.py`). */
303
310
  const INSTALL_ACTION = Object.freeze(["--action", "configure"]);
311
+ /** What `update` means: the wizard's Update, which `probe update` became. */
312
+ const UPDATE_ACTION = Object.freeze(["--action", "update"]);
304
313
  /** The website's retired one-time sign-in code; the CLI ignores the same shape. */
305
314
  const SIGN_IN_CODE = /^[A-Z0-9]{10}$/;
306
315
  /** The CLI root's own options: a call that starts with one names its own
@@ -320,6 +329,7 @@ function signInCodeAt(args) {
320
329
  *
321
330
  * (nothing), CODE -> wizard
322
331
  * install [CODE] [flags] -> wizard --action configure [flags]
332
+ * update [flags] -> wizard --action update [flags]
323
333
  * CODE install [flags] -> wizard --action configure [flags]
324
334
  * --flag ... -> wizard --flag ... (the CLI root's own excepted)
325
335
  * anything else -> unchanged (`doctor`, `backfill`, `wizard ...`)
@@ -334,6 +344,7 @@ function cliArgs(args) {
334
344
  const [first, ...rest] = words;
335
345
  if (first === undefined) return [LauncherVerb.WIZARD];
336
346
  if (first === LauncherVerb.INSTALL) return [LauncherVerb.WIZARD, ...INSTALL_ACTION, ...rest];
347
+ if (first === LauncherVerb.UPDATE) return [LauncherVerb.WIZARD, ...UPDATE_ACTION, ...rest];
337
348
  // Flags alone (`npx probe-research --agent codex`) used to reach the CLI's
338
349
  // root as `probe --agent codex`, which is not a command at all.
339
350
  if (first.startsWith("-") && !ROOT_ONLY_FLAGS.includes(first.split("=")[0])) {
@@ -418,8 +429,68 @@ async function sendUnsupportedPlatform(env) {
418
429
  /** The install prompt's first funnel step (plan D14), sent by the launcher before any CLI exists. */
419
430
  const SIGN_IN_STARTED_EVENT = "agent_install.signin_started";
420
431
 
421
- /** POST one anonymous launcher event, awaited and bounded (TELEMETRY_TIMEOUT_MS); never throws. */
422
- async function sendLauncherEvent(env, event) {
432
+ /** The launcher's own refusal of an agent's command (PR24); the CLI's ride on its step's event. */
433
+ const REFUSED_EVENT = "agent_install.refused";
434
+ /** `agent_install.refused`'s `step`: the install prompt's command the launcher refused. */
435
+ const AgentStep = Object.freeze({
436
+ SIGN_IN: "sign_in",
437
+ SIGN_IN_WAIT: "sign_in_wait",
438
+ INSTALL: "install",
439
+ STATUS: "status",
440
+ IMPORT: "import",
441
+ EXAMPLE: "example",
442
+ OTHER: "other",
443
+ });
444
+ /** The `probe` shim's exits the agent reads as a reason (`vocabularies.ShimReason.BY_EXIT`). */
445
+ const SHIM_REASONS = Object.freeze({ 69: "no_service", 70: "service_lost" });
446
+
447
+ /** The step an agent's `probe` arguments are (`AgentStep`). */
448
+ function getAgentStep(forwarded) {
449
+ if (forwarded[0] === LauncherVerb.WIZARD) {
450
+ return forwarded.includes("--pending") ? AgentStep.SIGN_IN_WAIT : AgentStep.INSTALL;
451
+ }
452
+ return [AgentStep.STATUS, AgentStep.IMPORT, AgentStep.EXAMPLE].includes(forwarded[0]) ? forwarded[0] : AgentStep.OTHER;
453
+ }
454
+
455
+ /** One bounded `agent_install.refused` for `step`, then the refusal itself (`agentRun.refuse`). */
456
+ async function refuseAgent(step, reason, message, code) {
457
+ await sendLauncherEvent(process.env, REFUSED_EVENT, {
458
+ step, reason, outcome: code === agentRun.EXIT_AGAIN ? "run_again" : "failed",
459
+ chat_agent: signIn.detectAgent(process.env),
460
+ });
461
+ agentRun.refuse(reason, message, code);
462
+ }
463
+
464
+ /** The hidden word the launcher re-runs itself with, detached, to send one of these events after it exits. */
465
+ const EVENT_VERB = "--probe-launcher-event";
466
+ const BACKGROUND_EVENTS = Object.freeze([SIGN_IN_STARTED_EVENT]);
467
+
468
+ /**
469
+ * Send one launcher event from a detached copy of the launcher, so the answer never waits on PostHog
470
+ * (~0.2 s from a fresh connection, up to TELEMETRY_TIMEOUT_MS; PR25). `props` ride as JSON. Never throws.
471
+ */
472
+ function sendEventInBackground(env, event, props = {}) {
473
+ if (!maySendTelemetry(env)) return;
474
+ try {
475
+ const child = spawn(process.execPath, [__filename, EVENT_VERB, event, JSON.stringify(props)],
476
+ { detached: true, stdio: "ignore", env });
477
+ child.on("error", () => {});
478
+ child.unref();
479
+ } catch {}
480
+ }
481
+
482
+ /** The detached copy's work: one event from BACKGROUND_EVENTS, its JSON `props` (`sendEventInBackground`). */
483
+ async function sendBackgroundEvent(args) {
484
+ if (!BACKGROUND_EVENTS.includes(args[0])) return;
485
+ let props = {};
486
+ try {
487
+ props = JSON.parse(args[1] || "{}");
488
+ } catch {}
489
+ await sendLauncherEvent(process.env, args[0], props && typeof props === "object" ? props : {});
490
+ }
491
+
492
+ /** POST one anonymous launcher event with `props`, awaited and bounded (TELEMETRY_TIMEOUT_MS); never throws. */
493
+ async function sendLauncherEvent(env, event, props = {}) {
423
494
  if (!maySendTelemetry(env)) return;
424
495
  try {
425
496
  const machine = machineId(env);
@@ -436,6 +507,7 @@ async function sendLauncherEvent(env, event) {
436
507
  distinct_id: `machine:${machine}`,
437
508
  timestamp: new Date().toISOString(),
438
509
  properties: {
510
+ ...props,
439
511
  surface: "launcher",
440
512
  os: OS_NAMES[process.platform] || process.platform,
441
513
  arch: process.arch,
@@ -512,6 +584,7 @@ async function main() {
512
584
  const startedMs = Date.now();
513
585
  const args = process.argv.slice(2);
514
586
  if (args[0] === download.DOWNLOAD_VERB) return runBackgroundDownload();
587
+ if (args[0] === EVENT_VERB) return sendBackgroundEvent(args.slice(1));
515
588
  if (args[0] === LauncherVerb.SIGN_IN) return runSignIn(args.slice(1), startedMs);
516
589
  // `npx probe-research` with no arguments runs the wizard — that is the entire
517
590
  // reason this package exists, so it should not require remembering a verb.
@@ -527,15 +600,20 @@ async function main() {
527
600
  if (isStatusJson(forwarded) && getProbeCommands().length === 0) {
528
601
  // No Probe here: the install prompt's first read (step 1b) answers at once, with no download (D37).
529
602
  // A `probe` that does not answer (its service restarting) is Probe here: its status runs (P1b).
530
- agentRun.answer({ v: 1, setup: NONE_SETUP }, 0);
603
+ // A saved sign-in with no CLI is Probe here too: the CLI first, then its status, never `none` (F4).
604
+ // Windows has no CLI build: a sign-in the SDK saved there is no install to read.
605
+ if (process.platform === "win32" || !signIn.hasSavedSignIn(process.env)) {
606
+ agentRun.answer({ v: 1, setup: NONE_SETUP }, 0);
607
+ }
608
+ return runAgentCall(await getAgentProbe(startedMs, AgentStep.STATUS), forwarded, startedMs, AgentStep.STATUS);
531
609
  }
532
610
  const agentCli = needsAgentCli(forwarded);
533
611
  // An agent's call with --json: inside its 110 s, its process group stopped at the deadline (D67).
534
612
  const launch = isAgentCall(forwarded)
535
- ? (cmd, cmdArgs) => runAgentCall(cmd, cmdArgs, startedMs) : run;
613
+ ? (cmd, cmdArgs) => runAgentCall(cmd, cmdArgs, startedMs, getAgentStep(forwarded)) : run;
536
614
  if (agentCli) {
537
615
  // The first download is still installing the CLI: wait for it within the budget (D41).
538
- if (isAgentCall(forwarded)) await waitForRunningDownload(startedMs);
616
+ if (isAgentCall(forwarded)) await waitForRunningDownload(startedMs, getAgentStep(forwarded));
539
617
  const installed = findProbe(AGENT_MIN_CLI);
540
618
  if (installed) return launch(installed, forwarded);
541
619
  }
@@ -639,8 +717,8 @@ const DOWNLOAD_POLL_MS = 1000;
639
717
  /** The uninstall barrier (`probe.shared.updates.uninstall_barrier.path`). */
640
718
  const BARRIER_FILE = [".local", "state", "probe", "uninstall", "barrier.json"];
641
719
 
642
- /** `status` flags only AGENT_MIN_CLI knows: the re-paste menu's answer (D84). */
643
- const AGENT_STATUS_FLAGS = Object.freeze(["--repaste-choice"]);
720
+ /** `status` flags only AGENT_MIN_CLI knows: the re-paste menu's answer (D84), the past-work offer's (PR24). */
721
+ const AGENT_STATUS_FLAGS = Object.freeze(["--repaste-choice", "--past-work-choice"]);
644
722
  /** `import` verbs only AGENT_MIN_CLI has: bringing in past work (D49, D74). `import wandb` is older. */
645
723
  const AGENT_IMPORT_VERBS = Object.freeze(["folders", "review", "start", "status", "resume"]);
646
724
 
@@ -671,14 +749,20 @@ function sleep(ms) {
671
749
  return new Promise((resolve) => setTimeout(resolve, ms));
672
750
  }
673
751
 
674
- /** Run an agent's call under the backstop; a call it had to stop answers `run_again` (75). */
675
- async function runAgentCall(cmd, cmdArgs, startedMs) {
752
+ /** Run an agent's call (`step`) under the backstop; a call it had to stop answers `run_again` (75). */
753
+ async function runAgentCall(cmd, cmdArgs, startedMs, step) {
676
754
  const ran = await agentRun.runWithBackstop(cmd, cmdArgs, { deadlineMs: startedMs + agentRun.AGENT_BUDGET_MS });
677
755
  if (ran.stopped) {
678
- agentRun.refuse(agentRun.Reason.RUN_AGAIN, "Stopped at the agent's time limit: run the same command again.",
756
+ await refuseAgent(step, agentRun.Reason.RUN_AGAIN, "Stopped at the agent's time limit: run the same command again.",
679
757
  agentRun.EXIT_AGAIN);
680
758
  }
681
- if (ran.error) agentRun.refuse(agentRun.Reason.INCOMPLETE, `could not run ${cmd}: ${ran.error}`, 1);
759
+ if (ran.error) await refuseAgent(step, agentRun.Reason.INCOMPLETE, `could not run ${cmd}: ${ran.error}`, 1);
760
+ if (SHIM_REASONS[ran.code]) {
761
+ // The shim answered the agent itself (no service, or it went away): the CLI never said.
762
+ await sendLauncherEvent(process.env, REFUSED_EVENT, {
763
+ step, reason: SHIM_REASONS[ran.code], outcome: "failed", chat_agent: signIn.detectAgent(process.env),
764
+ });
765
+ }
682
766
  process.exit(ran.code);
683
767
  }
684
768
 
@@ -720,20 +804,20 @@ async function finishStoppedUninstall(deadlineMs) {
720
804
  "repair", "--json"],
721
805
  { stdio: ["ignore", 2, 2], timeout: Math.max(1000, deadlineMs - WAIT_RESERVE_MS - Date.now()) });
722
806
  if (hasBarrier()) {
723
- agentRun.refuse(agentRun.Reason.UNINSTALL_RUNNING,
807
+ await refuseAgent(AgentStep.SIGN_IN, agentRun.Reason.UNINSTALL_RUNNING,
724
808
  "An uninstall of Probe stopped halfway and is being finished first: run the same command again.",
725
809
  agentRun.EXIT_AGAIN);
726
810
  }
727
811
  }
728
812
 
729
- /** An agent's call while the first download runs: wait within the budget, else `downloading` (75). */
730
- async function waitForRunningDownload(startedMs) {
813
+ /** An agent's call (`step`) while the first download runs: wait within the budget, else `downloading` (75). */
814
+ async function waitForRunningDownload(startedMs, step) {
731
815
  const until = startedMs + agentRun.AGENT_BUDGET_MS - WAIT_RESERVE_MS;
732
816
  for (;;) {
733
817
  const record = download.loadDownload();
734
818
  if (!record || record.state !== download.DownloadState.RUNNING) return record;
735
819
  if (Date.now() >= until) {
736
- agentRun.refuse(agentRun.Reason.DOWNLOADING, "Probe is still downloading: run the same command again.",
820
+ await refuseAgent(step, agentRun.Reason.DOWNLOADING, "Probe is still downloading: run the same command again.",
737
821
  agentRun.EXIT_AGAIN);
738
822
  }
739
823
  await sleep(DOWNLOAD_POLL_MS);
@@ -744,7 +828,7 @@ async function waitForRunningDownload(startedMs) {
744
828
  async function runSignIn(rest, startedMs) {
745
829
  const deadlineMs = startedMs + agentRun.AGENT_BUDGET_MS;
746
830
  const unknown = rest.find((word) => !SIGN_IN_FLAGS.includes(word));
747
- if (unknown) agentRun.refuse(agentRun.Reason.INCOMPLETE, `sign-in takes ${SIGN_IN_FLAGS.join(", ")}, not ${unknown}`, 2);
831
+ if (unknown) await refuseAgent(AgentStep.SIGN_IN, agentRun.Reason.INCOMPLETE, `sign-in takes ${SIGN_IN_FLAGS.join(", ")}, not ${unknown}`, 2);
748
832
  if (process.platform === "win32") {
749
833
  console.error(UNSUPPORTED_PLATFORM);
750
834
  await sendUnsupportedPlatform(process.env);
@@ -752,15 +836,16 @@ async function runSignIn(rest, startedMs) {
752
836
  }
753
837
  const hosted = signIn.findHostedAgent(process.env);
754
838
  if (hosted) {
755
- agentRun.refuse(agentRun.Reason.HOSTED_AGENT, `This chat runs in ${hosted}, not on your computer, so Probe `
756
- + "cannot be set up from it. Paste this into an agent on your own computer.", 1);
839
+ await refuseAgent(AgentStep.SIGN_IN, agentRun.Reason.HOSTED_AGENT, `This chat runs in ${hosted}, not on your `
840
+ + "computer, so Probe cannot be set up from it. Paste this into an agent on your own computer.", 1);
757
841
  }
758
842
  if (rest.includes("--wait")) return waitForSignIn(rest.includes("--json"), startedMs);
759
843
  if (hasBarrier()) await finishStoppedUninstall(deadlineMs);
844
+ if (rest.includes(IF_NEEDED_FLAG)) await answerIfSetUp(deadlineMs);
760
845
  const started = await signIn.startSignIn({ noBrowser: rest.includes("--no-browser") });
761
- if (!started.ok) agentRun.refuse(agentRun.Reason.INCOMPLETE, started.message, 1);
846
+ if (!started.ok) await refuseAgent(AgentStep.SIGN_IN, agentRun.Reason.INCOMPLETE, started.message, 1);
762
847
  const downloading = findProbe(AGENT_MIN_CLI) ? "not_needed" : startBackgroundDownload();
763
- await sendLauncherEvent(process.env, SIGN_IN_STARTED_EVENT);
848
+ sendEventInBackground(process.env, SIGN_IN_STARTED_EVENT, { chat_agent: signIn.detectAgent(process.env) });
764
849
  if (!rest.includes("--json")) {
765
850
  agentRun.writeLine(`Approve this computer in the browser: ${started.verification_uri_complete}`);
766
851
  agentRun.writeLine(`The page shows the code ${started.user_code}. Then run: ${SIGN_IN_WAIT.replace(" --json", "")}`);
@@ -770,6 +855,21 @@ async function runSignIn(rest, startedMs) {
770
855
  next: SIGN_IN_WAIT }, 0);
771
856
  }
772
857
 
858
+ /**
859
+ * `sign-in --if-needed`: this computer's status first (install.md's old step 1, in one call). Set up: its
860
+ * answer, and no tab (D48). Refused: its answer, for its `reason`. Otherwise this returns and the sign-in starts.
861
+ */
862
+ async function answerIfSetUp(deadlineMs) {
863
+ const ran = setupCheck.runSetupCheck({ launcher: __filename, deadlineMs: deadlineMs - WAIT_RESERVE_MS });
864
+ if (ran.check === setupCheck.SetupCheck.TIMED_OUT) {
865
+ await refuseAgent(AgentStep.SIGN_IN, agentRun.Reason.RUN_AGAIN,
866
+ "Stopped at the agent's time limit: run the same command again.", agentRun.EXIT_AGAIN);
867
+ }
868
+ if (ran.check === setupCheck.SetupCheck.NOT_SET_UP) return;
869
+ agentRun.writeLine(ran.stdout.trim());
870
+ process.exit(ran.code);
871
+ }
872
+
773
873
  /** The downloaded `probe`, asked again while the budget lasts when the download finished (`done`). */
774
874
  async function findDownloadedProbe(done, startedMs) {
775
875
  const until = startedMs + agentRun.AGENT_BUDGET_MS - WAIT_RESERVE_MS;
@@ -783,33 +883,53 @@ async function findDownloadedProbe(done, startedMs) {
783
883
  /** `sign-in --wait`: the download first (within the budget), then the CLI polls for the approval. */
784
884
  async function waitForSignIn(json, startedMs) {
785
885
  if (!signIn.loadPending()) {
786
- agentRun.refuse(agentRun.Reason.SIGN_IN_EXPIRED,
886
+ await refuseAgent(AgentStep.SIGN_IN_WAIT, agentRun.Reason.SIGN_IN_EXPIRED,
787
887
  "No sign-in is waiting (or it expired): run `npx -y probe-research sign-in --json` for a new one.", 1);
788
888
  }
789
889
  if (hasBarrier()) {
790
- agentRun.refuse(agentRun.Reason.UNINSTALL_RUNNING,
890
+ await refuseAgent(AgentStep.SIGN_IN_WAIT, agentRun.Reason.UNINSTALL_RUNNING,
791
891
  "An uninstall of Probe stopped halfway: run `npx -y probe-research sign-in --json` again to finish it.",
792
892
  agentRun.EXIT_AGAIN);
793
893
  }
794
- let probe = findProbe(AGENT_MIN_CLI);
894
+ const probe = await getAgentProbe(startedMs, AgentStep.SIGN_IN_WAIT);
895
+ return runAgentCall(probe, ["wizard", "--action", "login", "--pending", ...(json ? ["--json"] : [])], startedMs,
896
+ AgentStep.SIGN_IN_WAIT);
897
+ }
898
+
899
+ /** A `probe` at the agent floor: the one here, else the first download's (started if none runs), waited
900
+ * for within the budget; else `downloading` (75, run it again), the service's reason when the download
901
+ * ended on one (`no_service`, `service_lost`, `updating`), or `incomplete` with the download's log. */
902
+ async function getAgentProbe(startedMs, step) {
903
+ const found = findProbe(AGENT_MIN_CLI);
904
+ if (found) return found;
905
+ const record = download.loadDownload();
906
+ // A finished download whose `probe` is gone (removed since) is downloaded again, never waited on.
907
+ const isGone = record && record.state === download.DownloadState.DONE && getProbeCommands().length === 0;
908
+ if (!record || record.state === download.DownloadState.FAILED || isGone) startBackgroundDownload();
909
+ const done = await waitForRunningDownload(startedMs, step);
910
+ const probe = await findDownloadedProbe(done, startedMs);
911
+ if (!probe && done && done.state === download.DownloadState.DONE) {
912
+ // Installed, but its `probe` did not answer yet: the Probe service it just started restarts
913
+ // once for its first update, and `probe --version` goes through it (PR3b dry run, 1 in 4).
914
+ await refuseAgent(step, agentRun.Reason.DOWNLOADING, "Probe is finishing its install: run the same command again.",
915
+ agentRun.EXIT_AGAIN);
916
+ }
917
+ const serviceExit = !probe && done && done.state === download.DownloadState.FAILED
918
+ ? download.getServiceExit(done.reason) : null;
919
+ if (serviceExit !== null) {
920
+ // Downloaded, but the Probe service did not take the install (PR29): its reason, so install.md's
921
+ // row for it applies (repair, or run it again), never "did not download".
922
+ await refuseAgent(step, done.reason, serviceExit === agentRun.EXIT_AGAIN
923
+ ? `Probe is finishing an update (${done.error}): run the same command again.`
924
+ : `Probe downloaded, but its service did not answer, so its install did not finish (${done.error}); ` +
925
+ `its log: ${download.getFile(download.LOG_NAME)}`, serviceExit);
926
+ }
795
927
  if (!probe) {
796
- const record = download.loadDownload();
797
- if (!record || record.state === download.DownloadState.FAILED) startBackgroundDownload();
798
- const done = await waitForRunningDownload(startedMs);
799
- probe = await findDownloadedProbe(done, startedMs);
800
- if (!probe && done && done.state === download.DownloadState.DONE) {
801
- // Installed, but its `probe` did not answer yet: the Probe service it just started restarts
802
- // once for its first update, and `probe --version` goes through it (PR3b dry run, 1 in 4).
803
- agentRun.refuse(agentRun.Reason.DOWNLOADING, "Probe is finishing its install: run the same command again.",
804
- agentRun.EXIT_AGAIN);
805
- }
806
- if (!probe) {
807
- agentRun.refuse(agentRun.Reason.INCOMPLETE,
808
- `Probe did not download (${(done && done.error) || "no probe command after it"}); ` +
809
- `its log: ${download.getFile(download.LOG_NAME)}`, 1);
810
- }
928
+ await refuseAgent(step, agentRun.Reason.INCOMPLETE,
929
+ `Probe did not download (${(done && done.error) || "no probe command after it"}); ` +
930
+ `its log: ${download.getFile(download.LOG_NAME)}`, 1);
811
931
  }
812
- return runAgentCall(probe, ["wizard", "--action", "login", "--pending", ...(json ? ["--json"] : [])], startedMs);
932
+ return probe;
813
933
  }
814
934
 
815
935
  /**
@@ -6,14 +6,16 @@
6
6
  * Its own process, in its own session (`detached`), so an agent's 110 s kill of the command that
7
7
  * started it never takes it; it ends by itself after DOWNLOAD_CAP_MS. One at a time
8
8
  * (`download.lock`, the holder's pid), one log (`download.log`), one record the later commands read
9
- * (`download.json`: running | done | failed). A machine with an uninstall stopped halfway runs
10
- * `probe repair` instead: it finishes that uninstall before anything is signed in (D47).
9
+ * (`download.json`: running | done | failed, a failed one the service's `reason` when its exit is one).
10
+ * A machine with an uninstall stopped halfway runs `probe repair` instead: it finishes that uninstall
11
+ * before anything is signed in (D47).
11
12
  */
12
13
 
13
14
  const fs = require("node:fs");
14
15
  const path = require("node:path");
15
16
  const { spawn, spawnSync } = require("node:child_process");
16
17
 
18
+ const { AGENT_BUDGET_MS, DEADLINE_ENV } = require("./agent-run");
17
19
  const { getStateFolder } = require("./sign-in");
18
20
 
19
21
  const RECORD_NAME = "download.json";
@@ -25,6 +27,16 @@ const DOWNLOAD_CAP_MS = 10 * 60 * 1000;
25
27
  const DOWNLOAD_VERB = "--probe-background-download";
26
28
 
27
29
  const DownloadState = Object.freeze({ RUNNING: "running", DONE: "done", FAILED: "failed" });
30
+ /**
31
+ * A step's exit that is the Probe service's answer, not the download's (PR29): the `probe` shim's own
32
+ * (`ShimReason.BY_EXIT`: no service answered, it went away mid-command, an update held it) and
33
+ * `service start`'s busy (75). The record keeps the reason; the agent's call answers it with this exit.
34
+ */
35
+ const SERVICE_EXITS = Object.freeze({ 69: "no_service", 70: "service_lost", 75: "updating" });
36
+ /** The step's exits it runs again after, once: no service answered, or it went away mid-command. */
37
+ const RETRIED_EXITS = Object.freeze([69, 70]);
38
+ /** How much of the log's end a failed step's own answer is looked for in. */
39
+ const ANSWER_TAIL_BYTES = 64 * 1024;
28
40
 
29
41
  function getFile(name) {
30
42
  return path.join(getStateFolder(), name);
@@ -138,13 +150,14 @@ function runDownload(steps) {
138
150
  const started = Date.now();
139
151
  saveDownload({ state: DownloadState.RUNNING, pid: process.pid, started_at: started / 1000 });
140
152
  try {
141
- for (const [cmd, ...args] of steps) {
142
- const left = DOWNLOAD_CAP_MS - (Date.now() - started);
143
- const ran = left > 0 ? spawnSync(cmd, args, { stdio: "inherit", timeout: left, killSignal: "SIGKILL" }) : null;
153
+ for (const step of steps) {
154
+ let { ran, logged } = runStep(step, started);
155
+ // Once more with a fresh deadline when its service never answered: uv's own download may have used up
156
+ // the first one before `probe` started, and uv's copy is ready by now (PR29).
157
+ if (ran && !ran.error && RETRIED_EXITS.includes(ran.status)) ({ ran, logged } = runStep(step, started));
144
158
  if (!ran || ran.error || ran.status !== 0) {
145
- const why = !ran ? "the download ran out of time"
146
- : ran.error ? `${cmd}: ${ran.error.message}` : `${path.basename(cmd)} exited ${ran.status}`;
147
- saveDownload({ state: DownloadState.FAILED, pid: process.pid, error: why, finished_at: Date.now() / 1000 });
159
+ saveDownload({ state: DownloadState.FAILED, pid: process.pid, ...getFailure(step[0], ran, logged),
160
+ finished_at: Date.now() / 1000 });
148
161
  return 1;
149
162
  }
150
163
  }
@@ -155,12 +168,78 @@ function runDownload(steps) {
155
168
  }
156
169
  }
157
170
 
171
+ /** One step (`[cmd, ...args]`) within what is left of DOWNLOAD_CAP_MS: `{ran}` (null: no time left) and
172
+ * where its output starts in the log (`logged`). */
173
+ function runStep([cmd, ...args], started) {
174
+ const left = DOWNLOAD_CAP_MS - (Date.now() - started);
175
+ const logged = getLogSize();
176
+ // As an agent's call: the CLI's `probe` waits for a first service still starting until this deadline
177
+ // (a fresh Mac's outlasted its own 10 s, so the install that runs inside it never ran: PR29).
178
+ const env = { ...process.env, [DEADLINE_ENV]: String((Date.now() + AGENT_BUDGET_MS) / 1000) };
179
+ const ran = left > 0 ? spawnSync(cmd, args, { stdio: "inherit", env, timeout: left, killSignal: "SIGKILL" }) : null;
180
+ return { ran, logged };
181
+ }
182
+
183
+ /** How a step failed: `{error}`, with the service's `reason` when its exit is one (SERVICE_EXITS). */
184
+ function getFailure(cmd, ran, logged) {
185
+ if (!ran) return { error: "the download ran out of time" };
186
+ if (ran.error) return { error: `${cmd}: ${ran.error.message}` };
187
+ const exited = `${path.basename(cmd)} exited ${ran.status}`;
188
+ const reason = SERVICE_EXITS[ran.status];
189
+ if (!reason) return { error: exited };
190
+ return { reason, error: loadStepMessage(logged) || `the Probe service did not answer (${exited})` };
191
+ }
192
+
193
+ /** The exit an agent's call answers a failed download's service `reason` with, or null: not one. */
194
+ function getServiceExit(reason) {
195
+ const found = Object.keys(SERVICE_EXITS).find((code) => SERVICE_EXITS[code] === reason);
196
+ return found === undefined ? null : Number(found);
197
+ }
198
+
199
+ function getLogSize() {
200
+ try {
201
+ return fs.statSync(getFile(LOG_NAME)).size;
202
+ } catch {
203
+ return 0;
204
+ }
205
+ }
206
+
207
+ /** The first line of the last `message` a step's `--json` answer put in the log past `offset`, or null. */
208
+ function loadStepMessage(offset) {
209
+ let text = "";
210
+ try {
211
+ const fd = fs.openSync(getFile(LOG_NAME), "r");
212
+ try {
213
+ const size = fs.fstatSync(fd).size;
214
+ const length = Math.max(0, Math.min(size - offset, ANSWER_TAIL_BYTES));
215
+ const buffer = Buffer.alloc(length);
216
+ fs.readSync(fd, buffer, 0, length, size - length);
217
+ text = buffer.toString("utf8");
218
+ } finally {
219
+ fs.closeSync(fd);
220
+ }
221
+ } catch {
222
+ return null;
223
+ }
224
+ for (const line of text.split("\n").reverse()) {
225
+ try {
226
+ const answer = JSON.parse(line);
227
+ if (answer && typeof answer.message === "string" && answer.message.trim()) {
228
+ return answer.message.trim().split("\n")[0].slice(0, 300);
229
+ }
230
+ } catch {}
231
+ }
232
+ return null;
233
+ }
234
+
158
235
  module.exports = {
159
236
  DOWNLOAD_CAP_MS,
160
237
  DOWNLOAD_VERB,
161
238
  DownloadState,
162
239
  LOG_NAME,
240
+ SERVICE_EXITS,
163
241
  getFile,
242
+ getServiceExit,
164
243
  loadDownload,
165
244
  runDownload,
166
245
  startDownload,
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `sign-in --if-needed`: this computer's own status first, so a set-up computer opens no tab (D48) and the
3
+ * agent's first call is the sign-in itself, one model turn sooner (PR25: the link reached the chat 12.5-18.6 s
4
+ * after the paste, ~2.5 s of it the turn between `status` and `sign-in`).
5
+ */
6
+
7
+ const { spawnSync } = require("node:child_process");
8
+
9
+ /** What install.md's first step ran before: the same status, with the same flags. */
10
+ const STATUS_ARGS = Object.freeze(["status", "--json", "--refresh"]);
11
+ /** Status's answer is ~25 KB on a computer with every agent set up; past spawnSync's 1 MB default it would be cut. */
12
+ const MAX_ANSWER_BYTES = 16 * 1024 * 1024;
13
+
14
+ /** `setup.why`'s word for "no saved sign-in" (the CLI's `SetupGap.SIGNED_OUT`). */
15
+ const SIGNED_OUT_GAP = "signed_out";
16
+
17
+ /** What the status said about signing in here. */
18
+ const SetupCheck = Object.freeze({
19
+ /** Set up (`isSetUp`): answer the status itself, no tab. */
20
+ SET_UP: "set_up",
21
+ /** The status refused (`ok: false` with a `reason`): answer it, so the agent acts on its reason. */
22
+ REFUSED: "refused",
23
+ /** Anything else (none, partial signed out, unknown, an older CLI with no `setup`): sign in. */
24
+ NOT_SET_UP: "not_set_up",
25
+ /** The status did not answer before `deadlineMs`. */
26
+ TIMED_OUT: "timed_out",
27
+ });
28
+
29
+ /** install.md's rule for the re-paste menu: `done`, or `partial` still signed in (PR23b, P3: a plugin off). */
30
+ function isSetUp(setup) {
31
+ if (!setup || typeof setup !== "object") return false;
32
+ if (setup.state === "done") return true;
33
+ return setup.state === "partial" && !(Array.isArray(setup.why) && setup.why.includes(SIGNED_OUT_GAP));
34
+ }
35
+
36
+ /** The last stdout line as an object, or null. */
37
+ function getLastAnswer(stdout) {
38
+ const lines = String(stdout || "").trim().split("\n");
39
+ try {
40
+ const answer = JSON.parse(lines[lines.length - 1]);
41
+ return answer && typeof answer === "object" ? answer : null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Run the launcher's own `status --json --refresh` (whatever it does on this computer: answer `none` at once
49
+ * with no Probe here, or run the installed CLI's status) until `deadlineMs`: `{check, stdout, code}`.
50
+ */
51
+ function runSetupCheck({ launcher, deadlineMs, env = process.env }) {
52
+ const ran = spawnSync(process.execPath, [launcher, ...STATUS_ARGS], {
53
+ encoding: "utf8",
54
+ env,
55
+ maxBuffer: MAX_ANSWER_BYTES,
56
+ stdio: ["ignore", "pipe", "inherit"],
57
+ timeout: Math.max(1000, deadlineMs - Date.now()),
58
+ });
59
+ if (ran.error || ran.signal) return { check: SetupCheck.TIMED_OUT, stdout: "", code: 1 };
60
+ const answer = getLastAnswer(ran.stdout);
61
+ const code = ran.status === null ? 1 : ran.status;
62
+ if (answer && isSetUp(answer.setup)) return { check: SetupCheck.SET_UP, stdout: ran.stdout, code };
63
+ if (answer && answer.ok === false && typeof answer.reason === "string") {
64
+ return { check: SetupCheck.REFUSED, stdout: ran.stdout, code };
65
+ }
66
+ return { check: SetupCheck.NOT_SET_UP, stdout: ran.stdout, code };
67
+ }
68
+
69
+ module.exports = { SIGNED_OUT_GAP, SetupCheck, isSetUp, runSetupCheck };
package/lib/sign-in.js CHANGED
@@ -117,6 +117,18 @@ function getConfigFile(env) {
117
117
  return path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "probe", "config.json");
118
118
  }
119
119
 
120
+ /** The CLI config's active account (`settings.load_context`), or null. Callers read one field each. */
121
+ function loadActiveContext(env) {
122
+ try {
123
+ const data = JSON.parse(fs.readFileSync(getConfigFile(env), "utf8"));
124
+ const contexts = data && typeof data.contexts === "object" ? data.contexts : null;
125
+ const active = contexts ? contexts[data.current_context || "default"] : data;
126
+ return active && typeof active === "object" ? active : null;
127
+ } catch {
128
+ return null;
129
+ }
130
+ }
131
+
120
132
  /**
121
133
  * The API this computer signs in to: `PROBE_BASE_URL`, else the saved account's, else Probe's.
122
134
  * Never a key: only `base_url` is read from the config.
@@ -124,16 +136,18 @@ function getConfigFile(env) {
124
136
  function getSignInBase(env) {
125
137
  const fromEnv = env.PROBE_BASE_URL;
126
138
  if (fromEnv && /^https?:\/\//.test(fromEnv)) return fromEnv.replace(/\/+$/, "");
127
- try {
128
- const data = JSON.parse(fs.readFileSync(getConfigFile(env), "utf8"));
129
- const contexts = data && typeof data.contexts === "object" ? data.contexts : null;
130
- const active = contexts ? contexts[data.current_context || "default"] : data;
131
- const saved = active && typeof active.base_url === "string" ? active.base_url : null;
132
- if (saved && /^https?:\/\//.test(saved)) return saved.replace(/\/+$/, "");
133
- } catch {}
139
+ const active = loadActiveContext(env);
140
+ const saved = active && typeof active.base_url === "string" ? active.base_url : null;
141
+ if (saved && /^https?:\/\//.test(saved)) return saved.replace(/\/+$/, "");
134
142
  return DEFAULT_BASE;
135
143
  }
136
144
 
145
+ /** Is a sign-in saved here (the active account holds a key)? Only whether: the key itself is never read out. */
146
+ function hasSavedSignIn(env) {
147
+ const active = loadActiveContext(env);
148
+ return Boolean(active && typeof active.token === "string" && active.token);
149
+ }
150
+
137
151
  /** `content` written whole into `file`, readable by this user only. */
138
152
  function savePrivate(file, content) {
139
153
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
@@ -236,6 +250,7 @@ module.exports = {
236
250
  getSayLine,
237
251
  getSignInBase,
238
252
  getStateFolder,
253
+ hasSavedSignIn,
239
254
  loadPending,
240
255
  makePkcePair,
241
256
  startSignIn,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "probe-research",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "Setup wizard for Probe Research in your coding agents. Runs from zero with npx.",
5
5
  "bin": {
6
6
  "probe-research": "bin/probe-research.js"