probe-research 0.15.0 → 0.17.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.
@@ -11,7 +11,7 @@
11
11
  * there is nothing here that can drift from the CLI's behaviour.
12
12
  *
13
13
  * Resolution order, best first:
14
- * 1. `probe` on PATH AND new enough -> exec it (the common re-run case)
14
+ * 1. `probe` on PATH at or above FIX_MIN -> exec it at once (the common re-run case)
15
15
  * 2. `uv` -> uvx, no install, no state left behind
16
16
  * 3. bootstrap uv, then uvx -> the from-zero path: uv at the Mac app's pin,
17
17
  * its installer checked by sha256 before it runs
@@ -31,7 +31,13 @@ const fs = require("node:fs");
31
31
  const os = require("node:os");
32
32
  const path = require("node:path");
33
33
 
34
+ const agentRun = require("../lib/agent-run");
35
+ const download = require("../lib/background-download");
36
+ const signIn = require("../lib/sign-in");
37
+
34
38
  const DIST = "probe-research";
39
+ /** The compiled CLI `probe-research[all]` pins to its own version since the split (the CLI's `_entry.CLI_DIST`). */
40
+ const CLI_DIST = "probe-research-cli";
35
41
 
36
42
  /**
37
43
  * Where the published-version manifest lives. The SessionStart hook already
@@ -103,6 +109,26 @@ const MANIFEST_TIMEOUT_MS = 1500;
103
109
  * entry point, so the floor only ever names a release already on PyPI.
104
110
  */
105
111
  const MIN_CLI = "0.374.0";
112
+ /**
113
+ * The first CLI whose wizard opens the browser at once (instant sign-in, plan S8): its sign-in asks for
114
+ * the code before sending queued writes, and its setup runs behind the screens. An installed `probe` at
115
+ * or above it runs at once, with no manifest read: its own updater moves it forward. Below it (0.374.0
116
+ * to the release before this one still carry the slow wizard), the launcher runs that release's newest
117
+ * instead, downloaded once. Same rule as MIN_CLI: only ever a release already on PyPI.
118
+ */
119
+ const FIX_MIN = "0.385.0";
120
+ /**
121
+ * The first CLI with the install prompt's half (plan D36): `sign-in --wait` (`wizard --action login
122
+ * --pending`), `install --attempt` / `--recommended` / `--session-default`, and status's `setup`
123
+ * block. An installed `probe` below it runs none of the agent's calls: the newest release does
124
+ * (downloaded once), as below FIX_MIN. Same rule as the floors above: a release already on PyPI
125
+ * when this launcher publishes (release.yml publishes the launcher after PyPI, in the same run).
126
+ * 0.418.0, not 0.417.0: 0.417.0 was cut from a commit before the agent install merged (#4350).
127
+ */
128
+ const AGENT_MIN_CLI = "0.418.0";
129
+ /** `install` flags only AGENT_MIN_CLI knows (D36). */
130
+ const AGENT_INSTALL_FLAGS = Object.freeze(["--recommended", "--who-records", "--session-default", "--profile",
131
+ "--attempt"]);
106
132
  /**
107
133
  * The floor where Probe's compiled CLI has no build (`getMissingBuild`): no release past
108
134
  * the split installs there, so the newest that does is run as it is (plan R15, T22).
@@ -163,13 +189,33 @@ function getUvVersion() {
163
189
  * whatever ancient build happens to be on PATH gives them a CLI with none of
164
190
  * the wizard in it, which is precisely the bug this check exists to stop.
165
191
  */
166
- function installedVersion() {
167
- const r = spawnSync("probe", ["--version"], { encoding: "utf8", shell: false, timeout: VERSION_TIMEOUT_MS });
192
+ function installedVersion(command = "probe") {
193
+ const r = spawnSync(command, ["--version"], { encoding: "utf8", shell: false, timeout: VERSION_TIMEOUT_MS });
168
194
  if (r.status !== 0 || !r.stdout) return null;
169
195
  const m = r.stdout.match(/(\d+\.\d+\.\d+(?:\.\d+)?)/);
170
196
  return m ? m[1] : null;
171
197
  }
172
198
 
199
+ /**
200
+ * An installed `probe` at or above `min`: the one on PATH, else the one uv's tool install put in
201
+ * its bin folder (a first download's, before the agent's shell PATH knows that folder); null.
202
+ */
203
+ function findProbe(min) {
204
+ const candidates = [has("probe") ? "probe" : null, ...getUvBinFolders(process.env).map((d) => path.join(d, "probe"))];
205
+ for (const candidate of candidates.filter(Boolean)) {
206
+ if (candidate !== "probe") {
207
+ try {
208
+ fs.accessSync(candidate, fs.constants.X_OK);
209
+ } catch {
210
+ continue;
211
+ }
212
+ }
213
+ const found = installedVersion(candidate);
214
+ if (found && atLeast(found, min)) return candidate;
215
+ }
216
+ return null;
217
+ }
218
+
173
219
  function baseUrl() {
174
220
  const env = process.env.PROBE_BASE_URL;
175
221
  if (env && /^https?:\/\//.test(env)) return env.replace(/\/+$/, "");
@@ -235,7 +281,11 @@ const LauncherVerb = Object.freeze({
235
281
  WIZARD: "wizard",
236
282
  /** Launcher-only: "straight into the guided install", skipping the menu. */
237
283
  INSTALL: "install",
284
+ /** Launcher-only: the install prompt's sign-in (`runSignIn`), before any CLI exists. */
285
+ SIGN_IN: "sign-in",
238
286
  });
287
+ /** What `sign-in` takes (the hosted install.md names them; its test reads this list). */
288
+ const SIGN_IN_FLAGS = Object.freeze(["--json", "--wait", "--no-browser"]);
239
289
  /** What `install` means -- exactly what `probe install` always ran (`main.py`). */
240
290
  const INSTALL_ACTION = Object.freeze(["--action", "configure"]);
241
291
  /** The website's retired one-time sign-in code; the CLI ignores the same shape. */
@@ -349,6 +399,14 @@ function machineId(env) {
349
399
 
350
400
  /** POST one `install.unsupported_platform`, awaited and bounded; never throws. */
351
401
  async function sendUnsupportedPlatform(env) {
402
+ await sendLauncherEvent(env, UNSUPPORTED_EVENT);
403
+ }
404
+
405
+ /** The install prompt's first funnel step (plan D14), sent by the launcher before any CLI exists. */
406
+ const SIGN_IN_STARTED_EVENT = "agent_install.signin_started";
407
+
408
+ /** POST one anonymous launcher event, awaited and bounded (TELEMETRY_TIMEOUT_MS); never throws. */
409
+ async function sendLauncherEvent(env, event) {
352
410
  if (!maySendTelemetry(env)) return;
353
411
  try {
354
412
  const machine = machineId(env);
@@ -361,7 +419,7 @@ async function sendUnsupportedPlatform(env) {
361
419
  body: JSON.stringify({
362
420
  api_key: POSTHOG_KEY,
363
421
  batch: [{
364
- event: UNSUPPORTED_EVENT,
422
+ event,
365
423
  distinct_id: `machine:${machine}`,
366
424
  timestamp: new Date().toISOString(),
367
425
  properties: {
@@ -438,7 +496,10 @@ function readGlibc() {
438
496
  const REPAIR_NEEDS_NETWORK = "probe repair needs the network to fetch a working CLI";
439
497
 
440
498
  async function main() {
499
+ const startedMs = Date.now();
441
500
  const args = process.argv.slice(2);
501
+ if (args[0] === download.DOWNLOAD_VERB) return runBackgroundDownload();
502
+ if (args[0] === LauncherVerb.SIGN_IN) return runSignIn(args.slice(1), startedMs);
442
503
  // `npx probe-research` with no arguments runs the wizard — that is the entire
443
504
  // reason this package exists, so it should not require remembering a verb.
444
505
  const forwarded = cliArgs(args);
@@ -450,16 +511,26 @@ async function main() {
450
511
  process.exit(1);
451
512
  }
452
513
  if (signInCodeAt(args) >= 0) console.error(SIGN_IN_CODE_NOTE);
514
+ if (isStatusJson(forwarded) && !has("probe") && !findProbe("0")) {
515
+ // No Probe here: the install prompt's first read (step 1b) answers at once, with no download (D37).
516
+ agentRun.answer({ v: 1, setup: NONE_SETUP }, 0);
517
+ }
518
+ const agentCli = needsAgentCli(forwarded);
519
+ // An agent's call with --json: inside its 110 s, its process group stopped at the deadline (D67).
520
+ const launch = isAgentCall(forwarded)
521
+ ? (cmd, cmdArgs) => runAgentCall(cmd, cmdArgs, startedMs) : run;
522
+ if (agentCli) {
523
+ // The first download is still installing the CLI: wait for it within the budget (D41).
524
+ if (isAgentCall(forwarded)) await waitForRunningDownload(startedMs);
525
+ const installed = findProbe(AGENT_MIN_CLI);
526
+ if (installed) return launch(installed, forwarded);
527
+ }
528
+ const fixMin = agentCli ? AGENT_MIN_CLI : FIX_MIN;
453
529
 
454
- // Hand off to an existing install only when it is BOTH above the floor and
455
- // current. The floor alone is not enough, and that was the bug: `npx <tool>`
456
- // means "run the latest", but a floor is satisfied forever, so anyone who had
457
- // ever installed the CLI was frozen on it and npx silently never delivered
458
- // another update.
459
- //
460
- // That is the same failure the `--refresh` flag below exists to fix -- uv
461
- // serving whatever it resolved on day one -- in the other branch. It was
462
- // fixed there and left standing here.
530
+ // Hand off to an installed CLI at or above FIX_MIN at once, with no manifest
531
+ // read before the wizard: such a CLI keeps itself current (its updater), so a
532
+ // floor no longer freezes anyone on an old release the way it did before the
533
+ // CLI updated itself. Below FIX_MIN, the published latest is fetched instead.
463
534
  // No compiled CLI build for this computer: no release after the split installs here, so an
464
535
  // installed probe is never "behind" one; run it as long as it is above the floor.
465
536
  const missingBuild = getMissingBuild(process.platform, process.arch,
@@ -468,7 +539,7 @@ async function main() {
468
539
  let latest = null;
469
540
  if (missingBuild && mayUseInstalled(forwarded) && has("probe")) {
470
541
  const found = installedVersion();
471
- if (found && atLeast(found, wanted)) return run("probe", forwarded);
542
+ if (found && atLeast(found, agentCli ? AGENT_MIN_CLI : wanted)) return launch("probe", forwarded);
472
543
  }
473
544
  if (!mayUseInstalled(forwarded)) {
474
545
  // A repair runs the NEWEST release, never the floor: the floor predates
@@ -480,29 +551,23 @@ async function main() {
480
551
  }
481
552
  } else if (has("probe")) {
482
553
  const found = installedVersion();
483
- if (found && atLeast(found, wanted)) {
484
- latest = await latestVersion();
485
- // Unknown latest means run what we have: see latestVersion's contract.
486
- if (!latest || atLeast(found, latest)) return run("probe", forwarded);
487
- console.error(
488
- `probe-research: probe ${found} is behind ${latest}; fetching the latest…`,
489
- );
490
- } else {
491
- console.error(
492
- `probe-research: installed probe ${found || "(unknown version)"} is older than ` +
493
- `${wanted}; fetching the latest…`,
494
- );
495
- }
554
+ // A fixed CLI runs at once (plan S8): no manifest read on the way to the browser.
555
+ if (found && atLeast(found, fixMin)) return launch("probe", forwarded);
556
+ latest = await latestVersion();
557
+ // Unknown latest (offline, no route) means run what we have: see latestVersion's contract.
558
+ if (!latest && !agentCli && found && atLeast(found, wanted)) return launch("probe", forwarded);
559
+ console.error(
560
+ `probe-research: installed probe ${found || "(unknown version)"} is older than ` +
561
+ `${fixMin}; fetching ${latest || "the latest"}…`,
562
+ );
563
+ } else {
564
+ latest = await latestVersion();
496
565
  }
497
- // A FLOOR, not an exact pin. Unpinned, `uv tool run --from probe-research`
498
- // reuses an already-installed 0.8.2 tool; pinned exactly, it demands a PyPI
499
- // version that may not exist. `>=` fixes both.
500
- // Resolve to the newest version we actually know about, not merely the floor.
501
- // `uv tool run` reuses an installed tool that satisfies the constraint, so a
502
- // stale 0.46.0 satisfies `>=0.36.0` and uv hands back the very version we
503
- // just decided was out of date -- the currency check above would print
504
- // "fetching the latest" and then change nothing. Measured exactly that before
505
- // this line existed.
566
+ // The published latest, pinned exactly (plan S8): the manifest names it only once it is on PyPI, and
567
+ // uv reuses the env it built for that version, so it is downloaded once, ever. A range let uv hand back
568
+ // the stale tool it already had (a 0.46.0 satisfied `>=0.36.0`: measured). Unknown latest (offline, no
569
+ // route): any fixed CLI uv already has, `>=FIX_MIN`. A repair still asks for the newest, `>=`.
570
+ const pinned = !missingBuild && latest && atLeast(latest, fixMin) ? latest : null;
506
571
  const target = latest && atLeast(latest, wanted) ? latest : wanted;
507
572
  // `[all]`: the CLI's dependencies are an extra from the release after
508
573
  // 0.188 (plan 2.11); asking for it is harmless while core still has them.
@@ -514,24 +579,17 @@ async function main() {
514
579
  "(the probe-research package without [all]) installs at every version.",
515
580
  );
516
581
  }
517
- const spec = missingBuild ? `${DIST}[all]` : `${DIST}[all]>=${target}`;
518
- // REFRESH. uv caches the ENVIRONMENT it built for a requirement, so a range
519
- // like `>=0.10.0` keeps serving whatever it resolved the FIRST time — every
520
- // user frozen on the version they happened to run on day one, with the
521
- // launcher silently never delivering another update.
522
- //
523
- // It has to be the full `--refresh`: `--refresh-package` only refreshes
524
- // package METADATA and still reuses the built environment (measured — it
525
- // kept returning 0.10.0 after 0.10.1 was published). The full refresh costs
526
- // ~100ms, which is nothing for a command that only runs when there is no
527
- // usable local install.
582
+ const spec = missingBuild ? `${DIST}[all]`
583
+ : !mayUseInstalled(forwarded) ? `${DIST}[all]>=${target}`
584
+ : pinned ? `${DIST}[all]==${pinned}` : `${DIST}[all]>=${fixMin}`;
528
585
  // No pipx: the CLI installs itself for good with uv only, so a pipx run ended
529
- // in that refusal anyway (install redesign R11).
586
+ // in that refusal anyway (install redesign R11). Cache flags: getRefreshFlags.
530
587
  const isolated = uvRunFlags(forwarded);
588
+ const refresh = getRefreshFlags({ repair: !mayUseInstalled(forwarded), missingBuild, pinned });
531
589
  const uvOnPath = has("uv");
532
590
  const uvVersion = uvOnPath ? getUvVersion() : null;
533
591
  if (uvVersion && atLeast(uvVersion, UV_MIN)) {
534
- return run("uv", ["tool", "run", ...isolated, "--python", PYTHON_REQUEST, "--refresh", "--from", spec, "probe",
592
+ return launch("uv", ["tool", "run", ...isolated, "--python", PYTHON_REQUEST, ...refresh, "--from", spec, "probe",
535
593
  ...forwarded]);
536
594
  }
537
595
 
@@ -547,16 +605,196 @@ async function main() {
547
605
  console.error(`probe-research: ${uvVersion ? `uv ${uvVersion} is older than ${UV_MIN}` : "uv on PATH did not say its version"}.`);
548
606
  }
549
607
  const uv = installUv(process.env, forwarded);
550
- return run(uv, [
551
- "tool", "run", ...isolated, "--python", PYTHON_REQUEST, "--refresh", "--from", spec, "probe", ...forwarded,
608
+ return launch(uv, [
609
+ "tool", "run", ...isolated, "--python", PYTHON_REQUEST, ...refresh, "--from", spec, "probe", ...forwarded,
552
610
  ]);
553
611
  }
554
612
 
613
+ // --- the install prompt: `sign-in`, the background download, the agent's calls (plan D1, D3, D36) ---
614
+
615
+ /** What the agent runs after `sign-in`. */
616
+ const SIGN_IN_WAIT = "npx -y probe-research sign-in --wait --json";
617
+ /** `status --json` on a machine with no Probe (D37): what a CLI's `setup` block says there. */
618
+ const NONE_SETUP = Object.freeze({
619
+ state: "none", why: [], profile: null, account: null, team: null, this_chat: null,
620
+ });
621
+ /** Kept back from the budget for the CLI's own work once the download is in. */
622
+ const WAIT_RESERVE_MS = 20 * 1000;
623
+ /** How often a running download is looked at again. */
624
+ const DOWNLOAD_POLL_MS = 1000;
625
+ /** The uninstall barrier (`probe.shared.updates.uninstall_barrier.path`). */
626
+ const BARRIER_FILE = [".local", "state", "probe", "uninstall", "barrier.json"];
627
+
628
+ /** `probe` arguments only AGENT_MIN_CLI runs (D36). */
629
+ function needsAgentCli(forwarded) {
630
+ if (forwarded[0] === "example") return true;
631
+ if (forwarded[0] !== LauncherVerb.WIZARD) return false;
632
+ return forwarded.includes("--pending")
633
+ || forwarded.some((word) => AGENT_INSTALL_FLAGS.includes(word.split("=")[0]));
634
+ }
635
+
636
+ /** An agent's call: one of those, answered as JSON, so it runs under the 110 s backstop. */
637
+ function isAgentCall(forwarded) {
638
+ return needsAgentCli(forwarded) && forwarded.includes("--json");
639
+ }
640
+
641
+ function isStatusJson(forwarded) {
642
+ return forwarded[0] === "status" && forwarded.includes("--json");
643
+ }
644
+
645
+ function hasBarrier() {
646
+ return fs.existsSync(path.join(os.homedir(), ...BARRIER_FILE));
647
+ }
648
+
649
+ function sleep(ms) {
650
+ return new Promise((resolve) => setTimeout(resolve, ms));
651
+ }
652
+
653
+ /** Run an agent's call under the backstop; a call it had to stop answers `run_again` (75). */
654
+ async function runAgentCall(cmd, cmdArgs, startedMs) {
655
+ const ran = await agentRun.runWithBackstop(cmd, cmdArgs, { deadlineMs: startedMs + agentRun.AGENT_BUDGET_MS });
656
+ if (ran.stopped) {
657
+ agentRun.refuse(agentRun.Reason.RUN_AGAIN, "Stopped at the agent's time limit: run the same command again.",
658
+ agentRun.EXIT_AGAIN);
659
+ }
660
+ if (ran.error) agentRun.refuse(agentRun.Reason.INCOMPLETE, `could not run ${cmd}: ${ran.error}`, 1);
661
+ process.exit(ran.code);
662
+ }
663
+
664
+ /** The newest release's `probe` arguments for uv, pinned when the manifest names it. */
665
+ async function getLatestSpec() {
666
+ const latest = await latestVersion();
667
+ const missingBuild = getMissingBuild(process.platform, process.arch,
668
+ process.platform === "linux" ? readGlibc() : null);
669
+ const pinned = !missingBuild && latest && atLeast(latest, AGENT_MIN_CLI) ? latest : null;
670
+ return { pinned, spec: pinned ? `${DIST}[all]==${pinned}` : `${DIST}[all]>=${AGENT_MIN_CLI}`, missingBuild };
671
+ }
672
+
673
+ /** A uv this launcher runs: the one on PATH when it is new enough, else the pinned one installed. */
674
+ function getUv() {
675
+ const version = has("uv") ? getUvVersion() : null;
676
+ return version && atLeast(version, UV_MIN) ? "uv" : installUv(process.env, ["--json"]);
677
+ }
678
+
679
+ /** Start the first download in its own session (`background-download.js`): "started" | "running". */
680
+ function startBackgroundDownload() {
681
+ return download.startDownload({ launcher: __filename, args: [] });
682
+ }
683
+
684
+ /** The detached download itself: the newest CLI, installed for good by its own bootstrap. */
685
+ async function runBackgroundDownload() {
686
+ const { pinned, spec, missingBuild } = await getLatestSpec();
687
+ const refresh = getRefreshFlags({ repair: false, missingBuild, pinned });
688
+ const uv = getUv();
689
+ process.exit(download.runDownload([[uv, "tool", "run", "--python", PYTHON_REQUEST, ...refresh, "--from", spec,
690
+ "probe", "service", "start", "--min-version", pinned || AGENT_MIN_CLI, "--json"]]));
691
+ }
692
+
693
+ /** An uninstall stopped halfway is finished (`probe repair`) before the tab opens (D47). */
694
+ async function finishStoppedUninstall(deadlineMs) {
695
+ const { spec } = await getLatestSpec();
696
+ const uv = getUv();
697
+ const refresh = getRefreshFlags({ repair: true });
698
+ spawnSync(uv, ["tool", "run", "--isolated", "--python", PYTHON_REQUEST, ...refresh, "--from", spec, "probe",
699
+ "repair", "--json"],
700
+ { stdio: ["ignore", 2, 2], timeout: Math.max(1000, deadlineMs - WAIT_RESERVE_MS - Date.now()) });
701
+ if (hasBarrier()) {
702
+ agentRun.refuse(agentRun.Reason.UNINSTALL_RUNNING,
703
+ "An uninstall of Probe stopped halfway and is being finished first: run the same command again.",
704
+ agentRun.EXIT_AGAIN);
705
+ }
706
+ }
707
+
708
+ /** An agent's call while the first download runs: wait within the budget, else `downloading` (75). */
709
+ async function waitForRunningDownload(startedMs) {
710
+ const until = startedMs + agentRun.AGENT_BUDGET_MS - WAIT_RESERVE_MS;
711
+ for (;;) {
712
+ const record = download.loadDownload();
713
+ if (!record || record.state !== download.DownloadState.RUNNING) return record;
714
+ if (Date.now() >= until) {
715
+ agentRun.refuse(agentRun.Reason.DOWNLOADING, "Probe is still downloading: run the same command again.",
716
+ agentRun.EXIT_AGAIN);
717
+ }
718
+ await sleep(DOWNLOAD_POLL_MS);
719
+ }
720
+ }
721
+
722
+ /** `sign-in`: the tab within seconds, the download behind it; `sign-in --wait`: the CLI finishes it. */
723
+ async function runSignIn(rest, startedMs) {
724
+ const deadlineMs = startedMs + agentRun.AGENT_BUDGET_MS;
725
+ const unknown = rest.find((word) => !SIGN_IN_FLAGS.includes(word));
726
+ if (unknown) agentRun.refuse(agentRun.Reason.INCOMPLETE, `sign-in takes ${SIGN_IN_FLAGS.join(", ")}, not ${unknown}`, 2);
727
+ if (process.platform === "win32") {
728
+ console.error(UNSUPPORTED_PLATFORM);
729
+ await sendUnsupportedPlatform(process.env);
730
+ process.exit(1);
731
+ }
732
+ if (rest.includes("--wait")) return waitForSignIn(rest.includes("--json"), startedMs);
733
+ if (hasBarrier()) await finishStoppedUninstall(deadlineMs);
734
+ const started = await signIn.startSignIn({ noBrowser: rest.includes("--no-browser") });
735
+ if (!started.ok) agentRun.refuse(agentRun.Reason.INCOMPLETE, started.message, 1);
736
+ const downloading = findProbe(AGENT_MIN_CLI) ? "not_needed" : startBackgroundDownload();
737
+ await sendLauncherEvent(process.env, SIGN_IN_STARTED_EVENT);
738
+ if (!rest.includes("--json")) {
739
+ agentRun.writeLine(`Approve this computer in the browser: ${started.verification_uri_complete}`);
740
+ agentRun.writeLine(`The page shows the code ${started.user_code}. Then run: ${SIGN_IN_WAIT.replace(" --json", "")}`);
741
+ process.exit(0);
742
+ }
743
+ agentRun.answer({ ...started, reason: agentRun.Reason.WAITING_FOR_APPROVAL, download: downloading,
744
+ next: SIGN_IN_WAIT }, 0);
745
+ }
746
+
747
+ /** `sign-in --wait`: the download first (within the budget), then the CLI polls for the approval. */
748
+ async function waitForSignIn(json, startedMs) {
749
+ if (!signIn.loadPending()) {
750
+ agentRun.refuse(agentRun.Reason.SIGN_IN_EXPIRED,
751
+ "No sign-in is waiting (or it expired): run `npx -y probe-research sign-in --json` for a new one.", 1);
752
+ }
753
+ if (hasBarrier()) {
754
+ agentRun.refuse(agentRun.Reason.UNINSTALL_RUNNING,
755
+ "An uninstall of Probe stopped halfway: run `npx -y probe-research sign-in --json` again to finish it.",
756
+ agentRun.EXIT_AGAIN);
757
+ }
758
+ let probe = findProbe(AGENT_MIN_CLI);
759
+ if (!probe) {
760
+ const record = download.loadDownload();
761
+ if (!record || record.state === download.DownloadState.FAILED) startBackgroundDownload();
762
+ const done = await waitForRunningDownload(startedMs);
763
+ probe = findProbe(AGENT_MIN_CLI);
764
+ if (!probe) {
765
+ agentRun.refuse(agentRun.Reason.INCOMPLETE,
766
+ `Probe did not download (${(done && done.error) || "no probe command after it"}); ` +
767
+ `its log: ${download.getFile(download.LOG_NAME)}`, 1);
768
+ }
769
+ }
770
+ return runAgentCall(probe, ["wizard", "--action", "login", "--pending", ...(json ? ["--json"] : [])], startedMs);
771
+ }
772
+
773
+ /**
774
+ * uv's cache flags for a throwaway run. A pinned release builds once and is reused from uv's cache:
775
+ * `--refresh-package` reads only probe-research's index again (and the compiled CLI's, which `[all]` pins
776
+ * to the same version), so a release newer than uv's 10-minute copy still resolves, and no cached wheel
777
+ * or env is fetched again. A range (a repair's newest,
778
+ * a computer with no compiled build) needs the full `--refresh`: uv reuses the env it built for a range,
779
+ * so `--refresh-package` alone kept serving 0.10.0 after 0.10.1 shipped (measured).
780
+ */
781
+ function getRefreshFlags({ repair, missingBuild, pinned }) {
782
+ if (repair || missingBuild) return ["--refresh"];
783
+ return pinned ? ["--refresh-package", DIST, "--refresh-package", CLI_DIST] : [];
784
+ }
785
+
555
786
  /** The hex sha256 of a file's bytes. */
556
787
  function hashFile(file) {
557
788
  return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
558
789
  }
559
790
 
791
+ /** Where `uv tool install` links a tool's commands (`UV_TOOL_BIN_DIR`, then uv's own order). */
792
+ function getUvBinFolders(env) {
793
+ return [env.UV_TOOL_BIN_DIR, env.XDG_BIN_HOME,
794
+ env.XDG_DATA_HOME ? path.join(env.XDG_DATA_HOME, "..", "bin") : null,
795
+ path.join(os.homedir(), ".local", "bin")].filter(Boolean);
796
+ }
797
+
560
798
  /**
561
799
  * Where uv's installer puts uv, in its own order (UV_INSTALL_DIR, XDG_BIN_HOME,
562
800
  * XDG_DATA_HOME/../bin, ~/.local/bin): none of them is on THIS process's PATH,
@@ -0,0 +1,109 @@
1
+ /**
2
+ * An agent's command, kept inside its 110 s (plan D3, D67): the CLI stops itself between steps
3
+ * at the deadline it is handed (`PROBE_AGENT_DEADLINE`); this is only the backstop for a step that
4
+ * hangs. The child runs in its own process group so the whole group can be stopped: SIGTERM at the
5
+ * deadline, SIGKILL 5 s later, then one JSON line saying to run it again. Never the interactive
6
+ * wizard: a detached group loses the terminal.
7
+ *
8
+ * Every answer the launcher gives itself is one JSON line, `{ok, reason, message?}`, with a reason
9
+ * from the CLI's closed list (`probe.core.events.AgentInstallReason`): the agent branches on it.
10
+ */
11
+
12
+ const fs = require("node:fs");
13
+ const { spawn } = require("node:child_process");
14
+
15
+ /** The whole command's time, the download wait included. */
16
+ const AGENT_BUDGET_MS = 110 * 1000;
17
+ /** After SIGTERM, this long before SIGKILL. */
18
+ const KILL_GRACE_MS = 5 * 1000;
19
+ /** The variable the CLI reads its deadline from (epoch seconds; `agent_install.budget.DEADLINE_ENV`). */
20
+ const DEADLINE_ENV = "PROBE_AGENT_DEADLINE";
21
+ /** The CLI's own reserve: it is told a deadline this much before the backstop's. */
22
+ const CLI_MARGIN_MS = 3 * 1000;
23
+
24
+ /** The reasons the launcher answers itself (each is an `AgentInstallReason`). */
25
+ const Reason = Object.freeze({
26
+ WAITING_FOR_APPROVAL: "waiting_for_approval",
27
+ DOWNLOADING: "downloading",
28
+ UNINSTALL_RUNNING: "uninstall_running",
29
+ SIGN_IN_EXPIRED: "sign_in_expired",
30
+ INCOMPLETE: "incomplete",
31
+ RUN_AGAIN: "run_again",
32
+ });
33
+ /** Exit statuses: 75 means "run the same command again" (the CLI's `AGENT_EXIT_CODES`). */
34
+ const EXIT_AGAIN = 75;
35
+
36
+ /** One JSON answer on stdout, then exit `code`. Written synchronously: on a macOS pipe
37
+ * `process.stdout` is asynchronous, and `process.exit` would drop the line it still queues. */
38
+ function answer(fields, code) {
39
+ writeLine(JSON.stringify(fields));
40
+ process.exit(code);
41
+ }
42
+
43
+ /** One line on stdout, written before this returns (a full pipe falls back to the stream). */
44
+ function writeLine(text) {
45
+ try {
46
+ fs.writeSync(1, `${text}\n`);
47
+ } catch {
48
+ process.stdout.write(`${text}\n`);
49
+ }
50
+ }
51
+
52
+ /** Exit with `code` after one `{ok: false, reason, message}` line. */
53
+ function refuse(reason, message, code, extra = {}) {
54
+ answer({ ok: false, reason, message, ...extra }, code);
55
+ }
56
+
57
+ /**
58
+ * Run `cmd args` with the terminal's stdio, in its own process group, until `deadlineMs` (epoch
59
+ * ms): the child's own exit status, or the backstop's `run_again` when it had to be stopped.
60
+ */
61
+ function runWithBackstop(cmd, args, { deadlineMs, env = process.env } = {}) {
62
+ return new Promise((resolve) => {
63
+ const child = spawn(cmd, args, {
64
+ stdio: "inherit",
65
+ detached: true,
66
+ env: { ...env, [DEADLINE_ENV]: String((deadlineMs - CLI_MARGIN_MS) / 1000) },
67
+ });
68
+ let stopped = false;
69
+ const signalGroup = (signal) => {
70
+ try {
71
+ process.kill(-child.pid, signal);
72
+ } catch {}
73
+ };
74
+ // The agent's own Ctrl-C or kill reaches the launcher only: pass it on to the group.
75
+ const forward = (signal) => () => signalGroup(signal);
76
+ const handlers = { SIGINT: forward("SIGINT"), SIGTERM: forward("SIGTERM"), SIGHUP: forward("SIGHUP") };
77
+ for (const [signal, handler] of Object.entries(handlers)) process.on(signal, handler);
78
+ let killTimer = null;
79
+ const stopTimer = setTimeout(() => {
80
+ stopped = true;
81
+ signalGroup("SIGTERM");
82
+ killTimer = setTimeout(() => signalGroup("SIGKILL"), KILL_GRACE_MS);
83
+ }, Math.max(0, deadlineMs - Date.now()));
84
+ child.on("error", (err) => {
85
+ clearTimeout(stopTimer);
86
+ for (const [signal, handler] of Object.entries(handlers)) process.off(signal, handler);
87
+ resolve({ code: 1, error: err.message });
88
+ });
89
+ child.on("exit", (code, signal) => {
90
+ clearTimeout(stopTimer);
91
+ if (killTimer) clearTimeout(killTimer);
92
+ for (const [name, handler] of Object.entries(handlers)) process.off(name, handler);
93
+ resolve({ code: code === null ? 128 + (signal === "SIGKILL" ? 9 : 15) : code, stopped });
94
+ });
95
+ });
96
+ }
97
+
98
+ module.exports = {
99
+ AGENT_BUDGET_MS,
100
+ CLI_MARGIN_MS,
101
+ DEADLINE_ENV,
102
+ EXIT_AGAIN,
103
+ KILL_GRACE_MS,
104
+ Reason,
105
+ answer,
106
+ refuse,
107
+ runWithBackstop,
108
+ writeLine,
109
+ };
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The first download, behind the sign-in (plan D3): uv, Python 3.13 and the CLI, installed for good
3
+ * by the CLI's own bootstrap (`probe service start --min-version`, the Mac app's), while the person
4
+ * is in the browser tab.
5
+ *
6
+ * Its own process, in its own session (`detached`), so an agent's 110 s kill of the command that
7
+ * started it never takes it; it ends by itself after DOWNLOAD_CAP_MS. One at a time
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).
11
+ */
12
+
13
+ const fs = require("node:fs");
14
+ const path = require("node:path");
15
+ const { spawn, spawnSync } = require("node:child_process");
16
+
17
+ const { getStateFolder } = require("./sign-in");
18
+
19
+ const RECORD_NAME = "download.json";
20
+ const LOG_NAME = "download.log";
21
+ const LOCK_NAME = "download.lock";
22
+ /** The whole download, every step: past it the process stops (its children too). */
23
+ const DOWNLOAD_CAP_MS = 10 * 60 * 1000;
24
+ /** The hidden word the launcher re-runs itself with, detached, to do the download. */
25
+ const DOWNLOAD_VERB = "--probe-background-download";
26
+
27
+ const DownloadState = Object.freeze({ RUNNING: "running", DONE: "done", FAILED: "failed" });
28
+
29
+ function getFile(name) {
30
+ return path.join(getStateFolder(), name);
31
+ }
32
+
33
+ /** The download's record, or null (none yet). A running one whose process is gone reads failed. */
34
+ function loadDownload() {
35
+ let record;
36
+ try {
37
+ record = JSON.parse(fs.readFileSync(getFile(RECORD_NAME), "utf8"));
38
+ } catch {
39
+ return null;
40
+ }
41
+ if (!record || typeof record !== "object") return null;
42
+ if (record.state === DownloadState.RUNNING && !isAlive(record.pid)) {
43
+ return { ...record, state: DownloadState.FAILED, error: "the download stopped before it finished" };
44
+ }
45
+ return record;
46
+ }
47
+
48
+ function saveDownload(record) {
49
+ fs.mkdirSync(getStateFolder(), { recursive: true, mode: 0o700 });
50
+ const file = getFile(RECORD_NAME);
51
+ const temp = `${file}.${process.pid}`;
52
+ fs.writeFileSync(temp, JSON.stringify(record), { mode: 0o600 });
53
+ fs.renameSync(temp, file);
54
+ }
55
+
56
+ function isAlive(pid) {
57
+ if (!Number.isInteger(pid) || pid <= 1) return false;
58
+ try {
59
+ process.kill(pid, 0);
60
+ return true;
61
+ } catch (err) {
62
+ return err && err.code === "EPERM";
63
+ }
64
+ }
65
+
66
+ /** Take the one download's lock; false while a live download holds it (a stale one is broken). */
67
+ function takeLock() {
68
+ const lock = getFile(LOCK_NAME);
69
+ fs.mkdirSync(getStateFolder(), { recursive: true, mode: 0o700 });
70
+ for (let tries = 0; tries < 2; tries++) {
71
+ try {
72
+ const fd = fs.openSync(lock, "wx", 0o600);
73
+ fs.writeSync(fd, String(process.pid));
74
+ fs.closeSync(fd);
75
+ return true;
76
+ } catch {
77
+ let holder = NaN;
78
+ let age = Infinity;
79
+ try {
80
+ holder = parseInt(fs.readFileSync(lock, "utf8"), 10);
81
+ age = Date.now() - fs.statSync(lock).mtimeMs;
82
+ } catch {}
83
+ if (isAlive(holder) && age < DOWNLOAD_CAP_MS) return false;
84
+ try {
85
+ fs.unlinkSync(lock);
86
+ } catch {}
87
+ }
88
+ }
89
+ return false;
90
+ }
91
+
92
+ function readLockHolder() {
93
+ try {
94
+ return fs.readFileSync(getFile(LOCK_NAME), "utf8");
95
+ } catch {
96
+ return "";
97
+ }
98
+ }
99
+
100
+ function releaseLock() {
101
+ try {
102
+ if (parseInt(fs.readFileSync(getFile(LOCK_NAME), "utf8"), 10) === process.pid) fs.unlinkSync(getFile(LOCK_NAME));
103
+ } catch {}
104
+ }
105
+
106
+ /**
107
+ * Start the download in its own session, unless one runs: `"started" | "running"`. `args` are what
108
+ * the detached launcher runs (`downloadArgs`), `launcher` its own file.
109
+ */
110
+ function startDownload({ launcher, args, env = process.env }) {
111
+ const record = loadDownload();
112
+ if (record && record.state === DownloadState.RUNNING) return "running";
113
+ fs.mkdirSync(getStateFolder(), { recursive: true, mode: 0o700 });
114
+ const log = fs.openSync(getFile(LOG_NAME), "a", 0o600);
115
+ const child = spawn(process.execPath, [launcher, DOWNLOAD_VERB, ...args], {
116
+ detached: true,
117
+ stdio: ["ignore", log, log],
118
+ env,
119
+ });
120
+ child.on("error", () => {});
121
+ saveDownload({ state: DownloadState.RUNNING, pid: child.pid, started_at: Date.now() / 1000 });
122
+ child.unref();
123
+ fs.closeSync(log);
124
+ return "started";
125
+ }
126
+
127
+ /**
128
+ * The detached process's work: each step (`[cmd, ...args]`) in turn within DOWNLOAD_CAP_MS, its
129
+ * output in the log, its end in the record. Returns the exit status.
130
+ */
131
+ function runDownload(steps) {
132
+ if (!takeLock()) {
133
+ // Another download runs: the record names it (the starter wrote this process's pid there).
134
+ const holder = parseInt(readLockHolder(), 10);
135
+ if (isAlive(holder)) saveDownload({ state: DownloadState.RUNNING, pid: holder, started_at: Date.now() / 1000 });
136
+ return 0;
137
+ }
138
+ const started = Date.now();
139
+ saveDownload({ state: DownloadState.RUNNING, pid: process.pid, started_at: started / 1000 });
140
+ 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;
144
+ 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 });
148
+ return 1;
149
+ }
150
+ }
151
+ saveDownload({ state: DownloadState.DONE, pid: process.pid, finished_at: Date.now() / 1000 });
152
+ return 0;
153
+ } finally {
154
+ releaseLock();
155
+ }
156
+ }
157
+
158
+ module.exports = {
159
+ DOWNLOAD_CAP_MS,
160
+ DOWNLOAD_VERB,
161
+ DownloadState,
162
+ LOG_NAME,
163
+ getFile,
164
+ loadDownload,
165
+ runDownload,
166
+ startDownload,
167
+ };
@@ -0,0 +1,175 @@
1
+ /**
2
+ * This machine's device id, read (or minted) exactly as the CLI does: a port of
3
+ * `probe.sdk.settings.device_identity.device_instance_id`.
4
+ *
5
+ * The agent's sign-in starts before any CLI exists (D1), and the server binds the key it mints
6
+ * to the device the request names: a key with no device cannot mint the capture and daemon keys
7
+ * an install adds, so the install would open a second tab. Both languages must therefore land on
8
+ * ONE id. The rules kept: `PROBE_DEVICE_ID_PATH` / `PROBE_CONFIG_PATH` overrides, the stable
9
+ * machine witness (`m1:` + sha256 of `<machine id>:<home>`), a namespaced file for a second
10
+ * machine on a shared home, the legacy `<host>:<home>` witness, and an `O_EXCL` lock on the first
11
+ * mint. agent/tests/test_launcher_device_identity.py reads a file this wrote with the CLI's code.
12
+ */
13
+
14
+ const crypto = require("node:crypto");
15
+ const fs = require("node:fs");
16
+ const os = require("node:os");
17
+ const path = require("node:path");
18
+ const { spawnSync } = require("node:child_process");
19
+
20
+ const FILENAME = "device.json";
21
+ const ID_RE = /^[A-Za-z0-9_-]{16,128}$/;
22
+ const MACHINE_ID_RE = /^[0-9a-f]{32}$/;
23
+ const MAX_FILE_BYTES = 64 * 1024;
24
+ const WITNESS_HEX_LEN = 32;
25
+ const LOCK_WAIT_MS = 2000;
26
+
27
+ function getDeviceFile(env) {
28
+ if (env.PROBE_DEVICE_ID_PATH) return env.PROBE_DEVICE_ID_PATH;
29
+ if (env.PROBE_CONFIG_PATH) return path.join(path.dirname(env.PROBE_CONFIG_PATH), FILENAME);
30
+ const base = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state");
31
+ return path.join(base, "probe", FILENAME);
32
+ }
33
+
34
+ /** `<host>:<home>`, the CLI's `_home_fingerprint`. */
35
+ function getHomeFingerprint() {
36
+ let host = "";
37
+ try {
38
+ host = os.hostname().split(".")[0].trim();
39
+ } catch {}
40
+ return `${host || "unknown-host"}:${os.homedir()}`;
41
+ }
42
+
43
+ function isInContainer() {
44
+ if (fs.existsSync("/.dockerenv")) return true;
45
+ try {
46
+ const cgroup = fs.readFileSync("/proc/self/cgroup", "utf8");
47
+ return ["docker", "kubepods", "containerd", "lxc"].some((marker) => cgroup.includes(marker));
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ function isUsableMachineId(value) {
54
+ return MACHINE_ID_RE.test(value) && value !== "0".repeat(32);
55
+ }
56
+
57
+ /** `/etc/machine-id` on Linux (never in a container), the hardware UUID on macOS, else "". */
58
+ function getMachineId() {
59
+ if (process.platform === "linux" && !isInContainer()) {
60
+ for (const candidate of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
61
+ try {
62
+ const value = fs.readFileSync(candidate, "utf8").trim();
63
+ if (isUsableMachineId(value)) return value;
64
+ } catch {}
65
+ }
66
+ }
67
+ if (process.platform === "darwin") {
68
+ const ran = spawnSync("/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"],
69
+ { encoding: "utf8", timeout: 2000 });
70
+ const found = ran.status === 0 ? (ran.stdout.match(/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]+)"/) || [])[1] : null;
71
+ const value = found ? found.replace(/-/g, "").toLowerCase() : "";
72
+ if (isUsableMachineId(value)) return value;
73
+ }
74
+ return "";
75
+ }
76
+
77
+ /** `m1:<sha256(machine:home)[:32]>`, or null where no stable machine id exists. */
78
+ function getMachineWitness() {
79
+ const machine = getMachineId();
80
+ if (!machine) return null;
81
+ return `m1:${crypto.createHash("sha256").update(`${machine}:${os.homedir()}`).digest("hex").slice(0, WITNESS_HEX_LEN)}`;
82
+ }
83
+
84
+ /** The file as an object, or {} (absent, a link, not a regular file, too big, not JSON). */
85
+ function readFile(file) {
86
+ try {
87
+ const stat = fs.lstatSync(file);
88
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return {};
89
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
90
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
91
+ } catch {
92
+ return {};
93
+ }
94
+ }
95
+
96
+ function writeFile(file, payload) {
97
+ fs.mkdirSync(path.dirname(file), { recursive: true });
98
+ const temp = path.join(path.dirname(file), `.device-${process.pid}-${Date.now()}.json`);
99
+ fs.writeFileSync(temp, JSON.stringify(payload, Object.keys(payload).sort(), 2), { mode: 0o600 });
100
+ fs.renameSync(temp, file);
101
+ }
102
+
103
+ function getNamespaced(file, witness) {
104
+ const digest = crypto.createHash("sha256").update(witness).digest("hex").slice(0, 12);
105
+ const ext = path.extname(file);
106
+ return path.join(path.dirname(file), `${path.basename(file, ext)}-${digest}${ext}`);
107
+ }
108
+
109
+ function validId(value) {
110
+ return typeof value === "string" && ID_RE.test(value) ? value : null;
111
+ }
112
+
113
+ /**
114
+ * This machine's id, minted on first use; null when it cannot be kept (the request then names no
115
+ * device, as an unpersistable CLI's does).
116
+ */
117
+ function getDeviceInstanceId(env = process.env) {
118
+ let file = getDeviceFile(env);
119
+ const fingerprint = getHomeFingerprint();
120
+ const witness = getMachineWitness();
121
+ const claimed = (payload) => {
122
+ const value = validId(payload.device_instance_id);
123
+ return value && witness && payload.machine === witness ? value : null;
124
+ };
125
+ const ours = (payload) => {
126
+ const value = validId(payload.device_instance_id);
127
+ if (!value) return null;
128
+ if (witness && payload.machine) return claimed(payload);
129
+ if (payload.home !== undefined && payload.home !== null && payload.home !== fingerprint) return null;
130
+ return value;
131
+ };
132
+ const canonical = readFile(file);
133
+ const namespaced = witness ? getNamespaced(file, witness) : null;
134
+ const found = claimed(canonical) || (namespaced && claimed(readFile(namespaced))) || ours(canonical);
135
+ if (found) return found;
136
+ if (validId(canonical.device_instance_id)) {
137
+ // Another machine's file on a shared home: this one gets its own beside it.
138
+ file = namespaced || getNamespaced(file, fingerprint);
139
+ const mine = ours(readFile(file));
140
+ if (mine) return mine;
141
+ }
142
+ const lock = file.replace(/\.json$/, "") + ".lock";
143
+ let held = null;
144
+ try {
145
+ fs.mkdirSync(path.dirname(file), { recursive: true });
146
+ held = fs.openSync(lock, "wx");
147
+ } catch {
148
+ // Someone else is minting: read theirs once they are done.
149
+ const until = Date.now() + LOCK_WAIT_MS;
150
+ while (Date.now() < until) {
151
+ const theirs = ours(readFile(file));
152
+ if (theirs) return theirs;
153
+ spawnSync(process.execPath, ["-e", "setTimeout(() => {}, 50)"]);
154
+ }
155
+ return null;
156
+ }
157
+ try {
158
+ const again = ours(readFile(file));
159
+ if (again) return again;
160
+ const minted = crypto.randomBytes(16).toString("hex");
161
+ const payload = { device_instance_id: minted, created_at: Math.floor(Date.now() / 1000), home: fingerprint };
162
+ if (witness) payload.machine = witness;
163
+ writeFile(file, payload);
164
+ return minted;
165
+ } catch {
166
+ return null;
167
+ } finally {
168
+ try {
169
+ fs.closeSync(held);
170
+ fs.unlinkSync(lock);
171
+ } catch {}
172
+ }
173
+ }
174
+
175
+ module.exports = { getDeviceInstanceId, getDeviceFile, getMachineWitness };
package/lib/sign-in.js ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * `npx probe-research sign-in`: the agent's sign-in, asked for before anything downloads (plan D1).
3
+ *
4
+ * One POST for a device code (PKCE S256, the request the CLI sends for an agent: see
5
+ * tests/fixtures/device_code_request.json), the tab opened, and the secret half -- the device code
6
+ * and the PKCE verifier -- kept in a 0600 file for the CLI's `--action login --pending`, which
7
+ * polls for the approval. Nothing secret is printed: the answer names the code to read and the
8
+ * link, as the tab shows them.
9
+ */
10
+
11
+ const crypto = require("node:crypto");
12
+ const fs = require("node:fs");
13
+ const os = require("node:os");
14
+ const path = require("node:path");
15
+ const { spawn } = require("node:child_process");
16
+
17
+ const { getDeviceInstanceId } = require("./device-identity");
18
+
19
+ /** The folder the launcher and the CLI share (`probe.cli.install.attempt.get_folder`). */
20
+ const STATE_FOLDER = [".local", "state", "probe", "agent-install"];
21
+ const PENDING_NAME = "sign-in.json";
22
+ const PENDING_VERSION = 1;
23
+ const START_PATH = "/auth/device/code";
24
+ /** The request, as the CLI's `AGENT_CLIENT_CONTEXT` / `AGENT_GRANTS` spell it. */
25
+ const AGENT_CLIENT_CONTEXT = Object.freeze({ install: true, surface: "agent" });
26
+ const AGENT_GRANTS = Object.freeze(["api", "mcp"]);
27
+ const TOKEN_NAME_PREFIX = "Probe Research CLI · ";
28
+ /**
29
+ * Each coding agent's markers, in the harness registry's order (`harnesses.json`: id, detect_env,
30
+ * session_env): the agent this sign-in runs in, named on the approval page (`client_context.agent`,
31
+ * display only, D79). agent/tests/test_launcher_matches_cli.py holds this table to the registry.
32
+ */
33
+ const AGENT_MARKERS = Object.freeze([
34
+ ["claude_code", ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"], "CLAUDE_CODE_SESSION_ID"],
35
+ ["codex", ["CODEX_SANDBOX", "CODEX_THREAD_ID"], "CODEX_THREAD_ID"],
36
+ ["pi", ["PI_CODING_AGENT"], "PI_SESSION_ID"],
37
+ ["kimi_code", ["PROBE_KIMI_SESSION_ID"], "PROBE_KIMI_SESSION_ID"],
38
+ ["cursor_agent", ["CURSOR_AGENT"], "CURSOR_CONVERSATION_ID"],
39
+ ]);
40
+ /** How long the code request may take before the sign-in says it could not start. */
41
+ const START_TIMEOUT_MS = 10000;
42
+ const DEFAULT_BASE = "https://api.research.prbe.ai";
43
+
44
+ function getStateFolder() {
45
+ return path.join(os.homedir(), ...STATE_FOLDER);
46
+ }
47
+
48
+ /** A PKCE pair: a 43-character verifier from 32 random bytes, and its unpadded base64url S256. */
49
+ function makePkcePair() {
50
+ const verifier = crypto.randomBytes(32).toString("base64url");
51
+ const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
52
+ return { verifier, challenge };
53
+ }
54
+
55
+ /** The machine's short name, as the CLI labels a key (`device.hostname`, without its macOS read). */
56
+ function getHostname() {
57
+ try {
58
+ return os.hostname().split(".")[0].trim() || "unknown-host";
59
+ } catch {
60
+ return "unknown-host";
61
+ }
62
+ }
63
+
64
+ /**
65
+ * The coding agent this runs in, or null: a marker that is only a marker first, then any (the CLI's
66
+ * `agent_session.session_agent_from_env`: a stale Codex id in a pi shell is no Codex).
67
+ */
68
+ function detectAgent(env) {
69
+ for (const [id, markers, sessionEnv] of AGENT_MARKERS) {
70
+ if (markers.some((name) => name !== sessionEnv && env[name])) return id;
71
+ }
72
+ for (const [id, markers] of AGENT_MARKERS) {
73
+ if (markers.some((name) => env[name])) return id;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /** The body of the agent's device request (the fixture's keys, nothing else). */
79
+ function buildRequestBody({ challenge, deviceInstanceId, agent = null }) {
80
+ const body = {
81
+ token_name: `${TOKEN_NAME_PREFIX}${getHostname()}`,
82
+ scopes: null,
83
+ code_challenge: challenge,
84
+ grants: [...AGENT_GRANTS],
85
+ client_context: { ...AGENT_CLIENT_CONTEXT, ...(agent ? { agent } : {}) },
86
+ };
87
+ if (deviceInstanceId) body.device_instance_id = deviceInstanceId;
88
+ return body;
89
+ }
90
+
91
+ /** The CLI config's file (`settings.config_path`). */
92
+ function getConfigFile(env) {
93
+ if (env.PROBE_CONFIG_PATH) return env.PROBE_CONFIG_PATH;
94
+ return path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "probe", "config.json");
95
+ }
96
+
97
+ /**
98
+ * The API this computer signs in to: `PROBE_BASE_URL`, else the saved account's, else Probe's.
99
+ * Never a key: only `base_url` is read from the config.
100
+ */
101
+ function getSignInBase(env) {
102
+ const fromEnv = env.PROBE_BASE_URL;
103
+ if (fromEnv && /^https?:\/\//.test(fromEnv)) return fromEnv.replace(/\/+$/, "");
104
+ try {
105
+ const data = JSON.parse(fs.readFileSync(getConfigFile(env), "utf8"));
106
+ const contexts = data && typeof data.contexts === "object" ? data.contexts : null;
107
+ const active = contexts ? contexts[data.current_context || "default"] : data;
108
+ const saved = active && typeof active.base_url === "string" ? active.base_url : null;
109
+ if (saved && /^https?:\/\//.test(saved)) return saved.replace(/\/+$/, "");
110
+ } catch {}
111
+ return DEFAULT_BASE;
112
+ }
113
+
114
+ /** `content` written whole into `file`, readable by this user only. */
115
+ function savePrivate(file, content) {
116
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
117
+ const temp = `${file}.${process.pid}.${Date.now()}`;
118
+ fs.writeFileSync(temp, content, { mode: 0o600, flag: "wx" });
119
+ fs.renameSync(temp, file);
120
+ }
121
+
122
+ /** Open the link where a browser can open (never where PROBE_NO_BROWSER is set). True if tried. */
123
+ function openBrowser(url, env) {
124
+ if (env.PROBE_NO_BROWSER) return false;
125
+ const opener = process.platform === "darwin" ? "open"
126
+ : process.platform === "linux" && (env.DISPLAY || env.WAYLAND_DISPLAY) ? "xdg-open" : null;
127
+ if (!opener) return false;
128
+ try {
129
+ const child = spawn(opener, [url], { detached: true, stdio: "ignore" });
130
+ child.on("error", () => {});
131
+ child.unref();
132
+ return true;
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Ask for a code, keep the secret half, open the tab: `{ok, attempt, user_code,
140
+ * verification_uri_complete, expires_in, browser_opened}`, or `{ok: false, message}`.
141
+ */
142
+ async function startSignIn({ env = process.env, fetchImpl = fetch, noBrowser = false } = {}) {
143
+ const base = getSignInBase(env);
144
+ const { verifier, challenge } = makePkcePair();
145
+ const body = buildRequestBody({ challenge, deviceInstanceId: getDeviceInstanceId(env), agent: detectAgent(env) });
146
+ let data;
147
+ try {
148
+ const response = await fetchImpl(`${base}${START_PATH}`, {
149
+ method: "POST",
150
+ headers: { "content-type": "application/json", accept: "application/json" },
151
+ body: JSON.stringify(body),
152
+ signal: AbortSignal.timeout(START_TIMEOUT_MS),
153
+ });
154
+ data = await response.json().catch(() => null);
155
+ if (response.status !== 201 || !data || typeof data.device_code !== "string") {
156
+ const detail = data && data.detail && (data.detail.error_description || data.detail.error);
157
+ return { ok: false, message: `could not start the sign-in at ${base} (${detail || response.status})` };
158
+ }
159
+ } catch (err) {
160
+ return { ok: false, message: `could not reach ${base} (${err && err.message ? err.message : err})` };
161
+ }
162
+ const attempt = crypto.randomUUID();
163
+ const expiresIn = Number(data.expires_in) || 600;
164
+ const pending = {
165
+ v: PENDING_VERSION,
166
+ attempt,
167
+ base_url: base,
168
+ device_code: data.device_code,
169
+ code_verifier: verifier,
170
+ user_code: data.user_code,
171
+ verification_uri: data.verification_uri,
172
+ verification_uri_complete: data.verification_uri_complete,
173
+ interval: Number(data.interval) || 5,
174
+ expires_at: Date.now() / 1000 + expiresIn,
175
+ };
176
+ savePrivate(path.join(getStateFolder(), PENDING_NAME), JSON.stringify(pending));
177
+ const opened = noBrowser ? false : openBrowser(data.verification_uri_complete, env);
178
+ return {
179
+ ok: true,
180
+ attempt,
181
+ user_code: data.user_code,
182
+ verification_uri_complete: data.verification_uri_complete,
183
+ expires_in: expiresIn,
184
+ browser_opened: opened,
185
+ };
186
+ }
187
+
188
+ /** The request `startSignIn` left, or null (none, unreadable, expired). Its secret is never printed. */
189
+ function loadPending(now = Date.now() / 1000) {
190
+ try {
191
+ const data = JSON.parse(fs.readFileSync(path.join(getStateFolder(), PENDING_NAME), "utf8"));
192
+ if (!data || data.v !== PENDING_VERSION || typeof data.expires_at !== "number") return null;
193
+ return data.expires_at > now ? data : null;
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+
199
+ module.exports = {
200
+ AGENT_CLIENT_CONTEXT,
201
+ AGENT_MARKERS,
202
+ AGENT_GRANTS,
203
+ PENDING_NAME,
204
+ STATE_FOLDER,
205
+ START_PATH,
206
+ TOKEN_NAME_PREFIX,
207
+ buildRequestBody,
208
+ detectAgent,
209
+ getSignInBase,
210
+ getStateFolder,
211
+ loadPending,
212
+ makePkcePair,
213
+ startSignIn,
214
+ };
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "probe-research",
3
- "version": "0.15.0",
3
+ "version": "0.17.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"
7
7
  },
8
8
  "files": [
9
- "bin"
9
+ "bin",
10
+ "lib"
10
11
  ],
11
12
  "engines": {
12
13
  "node": ">=18"
@@ -25,6 +26,6 @@
25
26
  "probe-research"
26
27
  ],
27
28
  "scripts": {
28
- "test": "node --test test/resolve.test.js"
29
+ "test": "node --test test/resolve.test.js test/sign-in.test.js"
29
30
  }
30
31
  }