@botbuddy/cli 1.6.2 → 1.6.4

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": "@botbuddy/cli",
3
- "version": "1.6.2",
3
+ "version": "1.6.4",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -27,9 +27,21 @@ function keychainService(profile) {
27
27
  return profileCredentialEnvironment(profile);
28
28
  }
29
29
 
30
- function writePasswordPrompt(command, args, password) {
30
+ // A keychain/credential-store write failed AFTER OAuth + registration already
31
+ // succeeded. It carries its own code so the CLI never mislabels a storage
32
+ // failure as an auth failure (which would tell the user to re-`login`).
33
+ export class ProfileCredentialStoreError extends Error {
34
+ constructor(message, { cause } = {}) {
35
+ super(message);
36
+ this.name = "ProfileCredentialStoreError";
37
+ this.code = "profile_credential_store_failed";
38
+ if (cause !== undefined) this.cause = cause;
39
+ }
40
+ }
41
+
42
+ function writePasswordPrompt(command, args, password, spawnProcess) {
31
43
  return new Promise((resolve, reject) => {
32
- const child = spawn(command, args, { stdio: ["pipe", "ignore", "pipe"] });
44
+ const child = spawnProcess(command, args, { stdio: ["pipe", "ignore", "pipe"] });
33
45
  let stderr = "";
34
46
  child.stderr.on("data", (chunk) => { stderr += chunk; });
35
47
  child.once("error", reject);
@@ -37,16 +49,37 @@ function writePasswordPrompt(command, args, password) {
37
49
  if (code === 0) resolve();
38
50
  else reject(new Error(`${command} exited ${code}${stderr ? `: ${stderr.trim()}` : ""}`));
39
51
  });
40
- // `security -w` prompts from standard input when it is the last option.
41
- // Keeping the password off argv prevents process-list disclosure.
42
- child.stdin.end(`${password}\n`);
52
+ // `security -w` prompt mode reads the secret from standard input TWICE (the
53
+ // value and a retype). A single piped line leaves the retype empty, so
54
+ // `security` exits with "passwords don't match" the moment there is no TTY.
55
+ // Feeding the same value twice satisfies both reads without an interactive
56
+ // terminal, and keeping it off argv prevents process-list disclosure.
57
+ child.stdin.end(`${password}\n${password}\n`);
43
58
  });
44
59
  }
45
60
 
46
- async function writeKeychain(profile, token) {
61
+ export async function writeKeychain(profile, token, { spawnProcess = spawn } = {}) {
47
62
  const service = keychainService(profile);
48
- if (!service) throw new Error("unknown profile keychain service");
49
- await writePasswordPrompt("security", ["add-generic-password", "-U", "-s", service, "-a", userInfo().username, "-w"], token);
63
+ if (!service) throw new ProfileCredentialStoreError(`unknown profile keychain service for "${profile}"`);
64
+ try {
65
+ await writePasswordPrompt(
66
+ "security",
67
+ ["add-generic-password", "-U", "-s", service, "-a", userInfo().username, "-w"],
68
+ token,
69
+ spawnProcess,
70
+ );
71
+ } catch (error) {
72
+ // `security` cancels its authorization when the login keychain is locked in
73
+ // a headless session; guide the user to unlock it rather than re-login.
74
+ const detail = String(error?.message ?? error);
75
+ if (/authorization was cancell?ed/i.test(detail)) {
76
+ throw new ProfileCredentialStoreError(
77
+ "macOS Keychain authorization was canceled — unlock your login keychain (`security unlock-keychain`) and retry; a headless session needs it already unlocked",
78
+ { cause: error },
79
+ );
80
+ }
81
+ throw new ProfileCredentialStoreError(`could not write the profile credential to the macOS Keychain: ${detail}`, { cause: error });
82
+ }
50
83
  }
51
84
 
52
85
  async function readKeychain(profile) {
@@ -1 +1 @@
1
- {"schema_version":1,"source_version":"1.6.1","source_identity":"9cc6a78baeb0da589214386daad729a2e8909936a2407da801777f9902e8667f"}
1
+ {"schema_version":1,"source_version":"1.6.3","source_identity":"2deb439f7afdbb1918d76fe15665ed6ca14c30bcfd5d65524083695cc939814c"}
package/src/commands.mjs CHANGED
@@ -10,7 +10,7 @@ import { cmdRun } from "./run.mjs";
10
10
  import { runWait } from "./wait.mjs";
11
11
  import { green, red, cyan, dim, bold, die } from "./utils.mjs";
12
12
  import { VERSION } from "./version.mjs";
13
- import { bootstrapProfile, ProfileBootstrapError, profileShellRefresh } from "./profile-bootstrap.mjs";
13
+ import { bootstrapProfile, ProfileBootstrapError, profileBootstrapRecovery, profileShellRefresh } from "./profile-bootstrap.mjs";
14
14
  import { runPw } from "./pw/run.mjs";
15
15
 
16
16
  export async function run(argv) {
@@ -325,7 +325,7 @@ async function cmdProfile(args) {
325
325
  schema_version: 1,
326
326
  outcome: "error",
327
327
  error: code,
328
- recovery: "botbuddy login && botbuddy profile setup " + args[1],
328
+ recovery: profileBootstrapRecovery(code, args[1]),
329
329
  }));
330
330
  process.exitCode = 3;
331
331
  }
@@ -1,7 +1,7 @@
1
1
  import { hostname } from "node:os";
2
2
  import { randomUUID } from "node:crypto";
3
3
 
4
- import { ensureProfileCredentialBackend, readProfileIdentity, readProfileRetryIdentity, recordProfileRetryIdentity, installProfileCredential, profileCredentialEnvironment } from "./agent-credential-store.mjs";
4
+ import { ensureProfileCredentialBackend, readProfileIdentity, readProfileRetryIdentity, recordProfileRetryIdentity, installProfileCredential, profileCredentialEnvironment, ProfileCredentialStoreError } from "./agent-credential-store.mjs";
5
5
  import { callToolJson } from "./api.mjs";
6
6
  import { latestPublicCliCommand } from "./public-invocation.mjs";
7
7
 
@@ -79,13 +79,31 @@ export async function bootstrapProfile(profileName, {
79
79
  const token = registrationCredential(data);
80
80
  if (!token) throw new ProfileBootstrapError("profile_agent_required");
81
81
 
82
- await store({
83
- profile: profileName,
84
- tenant: profile.tenant,
85
- agentId: data.agent_id,
86
- name: agentName,
87
- token,
88
- });
82
+ try {
83
+ await store({
84
+ profile: profileName,
85
+ tenant: profile.tenant,
86
+ agentId: data.agent_id,
87
+ name: agentName,
88
+ token,
89
+ });
90
+ } catch (error) {
91
+ // OAuth + registration + tenant attestation all succeeded; only persisting
92
+ // the credential failed. Give the two persistence failures accurate,
93
+ // distinct recoveries — never the `botbuddy login` OAuth recovery:
94
+ // • a Keychain write failure (ProfileCredentialStoreError) is resolved by
95
+ // unlocking the login keychain;
96
+ // • a filesystem/lock failure writing ~/.botbuddy/agent-profiles.json
97
+ // (EACCES/ENOSPC/busy store lock) is NOT — unlocking the keychain would
98
+ // not help, so it gets its own code.
99
+ if (error instanceof ProfileBootstrapError) throw error;
100
+ const code = error instanceof ProfileCredentialStoreError
101
+ ? "profile_credential_store_failed"
102
+ : "profile_credential_persist_failed";
103
+ const failure = new ProfileBootstrapError(code);
104
+ failure.cause = error;
105
+ throw failure;
106
+ }
89
107
  return {
90
108
  schema_version: 1,
91
109
  outcome: "installed",
@@ -98,6 +116,19 @@ export async function bootstrapProfile(profileName, {
98
116
  };
99
117
  }
100
118
 
119
+ // Maps a bootstrap error code to the recovery hint shown in the CLI receipt.
120
+ // A credential-store/Keychain failure gets its own actionable recovery; every
121
+ // other failure keeps the historical login-first recovery verbatim.
122
+ export function profileBootstrapRecovery(code, profileName) {
123
+ if (code === "profile_credential_store_failed") {
124
+ return `unlock your login keychain (security unlock-keychain), then re-run: botbuddy profile setup ${profileName}`;
125
+ }
126
+ if (code === "profile_credential_persist_failed") {
127
+ return `ensure ~/.botbuddy is writable and no other setup is running, then re-run: botbuddy profile setup ${profileName}`;
128
+ }
129
+ return `botbuddy login && botbuddy profile setup ${profileName}`;
130
+ }
131
+
101
132
  export function profileShellRefresh(profileName) {
102
133
  const tokenEnv = profileCredentialEnvironment(profileName);
103
134
  if (!tokenEnv) throw new ProfileBootstrapError("profile_required");
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ // BOT-1400: plan a lossless multi-version reconciliation for the CLI publish
3
+ // workflow.
4
+ //
5
+ // The publish workflow serializes all runs through one static concurrency
6
+ // group so its dist-tag backward-move guard is correct (only one run publishes
7
+ // at a time). GitHub keeps at most one running + one pending run per group, so
8
+ // if 3+ CLI version bumps land inside a single ~2-minute publish window the
9
+ // *middle* version's queued run is dropped and that version never publishes.
10
+ //
11
+ // This module closes that gap without weakening the serialization: the single
12
+ // surviving run (always the newest push, which becomes the pending run) walks
13
+ // main's recent first-parent history, collects every distinct CLI version
14
+ // between the most recently *published* version and HEAD, and orders them
15
+ // ascending. The workflow then publishes each intermediate from its own
16
+ // historical tree — in ascending order, so every stable publish moves `latest`
17
+ // forward and every prerelease moves `next` forward — before its existing
18
+ // single-version logic handles HEAD. No version is lost; no dist-tag moves
19
+ // backward under any interleaving.
20
+ //
21
+ // The git walk is bounded (recent commits touching cli/package.json) and stops
22
+ // at the first already-published version, so an ancient, deliberately
23
+ // superseded version is never resurrected. Per-version publish-vs-skip against
24
+ // the live dist-tag is still decided in the workflow (it reflects live registry
25
+ // state as the loop advances); this module only orders the candidates.
26
+
27
+ import { execFileSync } from "node:child_process";
28
+ import { readFileSync } from "node:fs";
29
+
30
+ import { compareSemver, isPrerelease } from "./publish-equal.mjs";
31
+
32
+ // How far back to walk commits that touched the `cli/` tree. The loss window is
33
+ // a handful of rapid bumps (each a few commits); 60 is comfortably generous
34
+ // while bounding the git work and guaranteeing termination. planReconciliation
35
+ // stops at the first already-published version, so this only bounds pathological
36
+ // cases — and even an over-broad tail is caught by the workflow's per-version
37
+ // already-published check before anything is republished.
38
+ const DEFAULT_LIMIT = 60;
39
+
40
+ // Reduce a newest→oldest history of { version, commit } to the ascending list
41
+ // of distinct versions that must be reconciled: everything strictly newer than
42
+ // the most recently published version in that history, excluding anything
43
+ // already on npm. Each version keeps its NEWEST commit so the published tarball
44
+ // carries every change shipped under that version.
45
+ export function planReconciliation(history, published) {
46
+ const publishedSet = new Set((published ?? []).map(String));
47
+ const tail = [];
48
+ const seen = new Set();
49
+ for (const entry of history) {
50
+ const version = String(entry.version);
51
+ if (seen.has(version)) continue; // dedupe; the newest commit was seen first
52
+ seen.add(version);
53
+ // Stop at the first already-published version: everything older than it was
54
+ // reconciled when it (or a later version) published. This is what prevents
55
+ // resurrecting an old, superseded version.
56
+ if (publishedSet.has(version)) break;
57
+ tail.push({ version, commit: entry.commit });
58
+ }
59
+ return tail
60
+ .sort((a, b) => compareSemver(a.version, b.version))
61
+ .map((e) => ({ version: e.version, commit: e.commit, prerelease: isPrerelease(e.version) }));
62
+ }
63
+
64
+ // Accepts the raw `npm view <pkg> versions --json` payload (an array, or a bare
65
+ // string when only one version exists) and returns the reconciliation plan.
66
+ export function planFromHistory(history, publishedRaw) {
67
+ const published = Array.isArray(publishedRaw) ? publishedRaw : [publishedRaw];
68
+ return planReconciliation(history, published);
69
+ }
70
+
71
+ function git(args, cwd) {
72
+ // Strip the location-override git env vars so `cwd` always selects the repo.
73
+ // Git sets GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE while running a hook; if we
74
+ // inherited them, a git command here would silently target the hook's repo
75
+ // instead of `cwd` (e.g. a reconcile invoked from a pre-push hook, or a test
76
+ // exercising a scratch repo under one). Everything else is inherited.
77
+ const env = { ...process.env };
78
+ delete env.GIT_DIR;
79
+ delete env.GIT_WORK_TREE;
80
+ delete env.GIT_INDEX_FILE;
81
+ return execFileSync("git", args, { cwd, env, encoding: "utf8" });
82
+ }
83
+
84
+ // Walk main's first-parent history from `headSha` over commits that touched the
85
+ // publishable CLI tree (`cli/`), reading the package version at each, newest →
86
+ // oldest. Walking the whole `cli/` tree — not just `cli/package.json` — is what
87
+ // lets a CLI-only fix committed AFTER a version bump (same version, no
88
+ // package.json change) be the newest commit for that version, so the archived
89
+ // tree carries that fix rather than the older bump commit's tree. First-parent
90
+ // keeps us on the mainline (side-branch commits from a merge never inject a
91
+ // version). Returns [{ version, commit }].
92
+ export function buildHistory(headSha, { limit = DEFAULT_LIMIT, cwd = process.cwd() } = {}) {
93
+ const raw = git(
94
+ ["log", "--first-parent", "-n", String(limit), "--format=%H", headSha, "--", "cli"],
95
+ cwd,
96
+ );
97
+ const commits = raw.split("\n").map((l) => l.trim()).filter(Boolean);
98
+ const history = [];
99
+ for (const commit of commits) {
100
+ let version;
101
+ try {
102
+ const pkg = JSON.parse(git(["show", `${commit}:cli/package.json`], cwd));
103
+ version = pkg?.version;
104
+ } catch {
105
+ // cli/package.json did not exist / was unparseable at this commit — we
106
+ // have walked past the package's introduction; stop.
107
+ break;
108
+ }
109
+ if (typeof version !== "string" || version.length === 0) break;
110
+ history.push({ version, commit });
111
+ }
112
+ return history;
113
+ }
114
+
115
+ if (import.meta.url === `file://${process.argv[1]}`) {
116
+ const args = process.argv.slice(2);
117
+ // `--plan <headSha>`: read the registry versions JSON on stdin, print the
118
+ // ascending reconciliation plan as `<version>\t<commit>\t<stable|prerelease>`
119
+ // (one row per version to publish, newest last). Prints nothing when there is
120
+ // nothing to reconcile.
121
+ if (args[0] === "--plan") {
122
+ const headSha = args[1];
123
+ if (!headSha) {
124
+ console.error("usage: reconcile.mjs --plan <headSha> (registry versions JSON on stdin)");
125
+ process.exit(2);
126
+ }
127
+ try {
128
+ const publishedRaw = JSON.parse(readFileSync(0, "utf8"));
129
+ const history = buildHistory(headSha, { cwd: process.cwd() });
130
+ for (const entry of planFromHistory(history, publishedRaw)) {
131
+ process.stdout.write(`${entry.version}\t${entry.commit}\t${entry.prerelease ? "prerelease" : "stable"}\n`);
132
+ }
133
+ process.exit(0);
134
+ } catch (err) {
135
+ console.error(String(err?.message ?? err));
136
+ process.exit(2);
137
+ }
138
+ }
139
+ console.error("usage: reconcile.mjs --plan <headSha>");
140
+ process.exit(2);
141
+ }