@botbuddy/cli 1.9.1 → 1.9.2

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.9.1",
3
+ "version": "1.9.2",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
package/src/api.mjs CHANGED
@@ -53,20 +53,30 @@ export async function callTool(toolName, args = {}) {
53
53
  // * { ok:true, data } — tool result JSON (data.success may still be false)
54
54
  // * { ok:false, auth:true } — not authenticated / token expired
55
55
  // * { ok:false, status } — HTTP/JSON-RPC/transport error (status may be null)
56
- export async function callToolJson(toolName, args = {}, { fetchImpl = fetch, signal } = {}) {
56
+ // BOT-1487: resolve the auth header ONCE so a caller that issues several tool
57
+ // calls (e.g. `profile setup` does whoami → register_agent) can pin the SAME
58
+ // credential across all of them. Without this, each callToolJson independently
59
+ // re-reads the owner token, so a concurrent `botbuddy login` could swap the
60
+ // bound tenant mid-sequence (a TOCTOU that would register in the wrong tenant).
61
+ // Returns { auth } with the header object, or { error } with the structured
62
+ // not-authenticated / token-expired receipt to return verbatim.
63
+ export async function resolveCallAuth() {
57
64
  const owner = await resolveOwnerToken({ getConfig });
58
- let auth;
59
65
  if (owner && !(owner.expiresAt && Date.now() >= owner.expiresAt)) {
60
- auth = { Authorization: `Bearer ${owner.token}` };
61
- } else {
62
- const agentKey = await resolveAgentKey();
63
- if (agentKey) {
64
- auth = { "x-agent-api-key": agentKey };
65
- } else if (owner) {
66
- return { ok: false, auth: true, error: "token_expired" };
67
- } else {
68
- return { ok: false, auth: true, error: "not_authenticated" };
69
- }
66
+ return { auth: { Authorization: `Bearer ${owner.token}` } };
67
+ }
68
+ const agentKey = await resolveAgentKey();
69
+ if (agentKey) return { auth: { "x-agent-api-key": agentKey } };
70
+ if (owner) return { error: { ok: false, auth: true, error: "token_expired" } };
71
+ return { error: { ok: false, auth: true, error: "not_authenticated" } };
72
+ }
73
+
74
+ export async function callToolJson(toolName, args = {}, { fetchImpl = fetch, signal, auth: pinnedAuth = null } = {}) {
75
+ let auth = pinnedAuth;
76
+ if (!auth) {
77
+ const resolved = await resolveCallAuth();
78
+ if (resolved.error) return resolved.error;
79
+ auth = resolved.auth;
70
80
  }
71
81
  const body = { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: toolName, arguments: args } };
72
82
  let res;
@@ -1 +1 @@
1
- {"schema_version":1,"source_version":"1.9.0","source_identity":"70b96a360d9dd5bd637dc6378a4cae6542cb0a508990f28d26c842946e6fb694"}
1
+ {"schema_version":1,"source_version":"1.9.0","source_identity":"8bc02282f116b4857951c61a187ad7894c3153b36559b46cd171df24b0af98c4"}
@@ -2,7 +2,7 @@ import { hostname } from "node:os";
2
2
  import { randomUUID } from "node:crypto";
3
3
 
4
4
  import { ensureProfileCredentialBackend, readProfileIdentity, readProfileRetryIdentity, recordProfileRetryIdentity, installProfileCredential, profileCredentialEnvironment, ProfileCredentialStoreError } from "./agent-credential-store.mjs";
5
- import { callToolJson } from "./api.mjs";
5
+ import { callToolJson, resolveCallAuth } from "./api.mjs";
6
6
  import { latestPublicCliCommand } from "./public-invocation.mjs";
7
7
 
8
8
  const PROFILES = Object.freeze({
@@ -38,6 +38,7 @@ function registrationCredential(data) {
38
38
  export async function bootstrapProfile(profileName, {
39
39
  name = null,
40
40
  call = callToolJson,
41
+ resolveAuth = resolveCallAuth,
41
42
  readIdentity = readProfileIdentity,
42
43
  readRetryIdentity = readProfileRetryIdentity,
43
44
  recordRetryIdentity = recordProfileRetryIdentity,
@@ -55,14 +56,60 @@ export async function bootstrapProfile(profileName, {
55
56
  // cannot loop forever on stale metadata.
56
57
  const reusableIdentity = existing?.tenant === profile.tenant ? existing.agentId : retryIdentity?.agentId ?? null;
57
58
  const agentName = name ?? (existing?.tenant === profile.tenant ? existing.name : retryIdentity?.name ?? defaultProfileAgentName(profileName));
59
+ // BOT-1487: tenancy is auth-bound after BOT-1416 — register_agent selects the
60
+ // tenant from the OAuth session / agent key and rejects a runtime tenant_id
61
+ // with MCP_TENANT_CONTEXT_IS_AUTH_ONLY. So we no longer send tenant_id; the
62
+ // returned tenant_id is attested against the profile's tenant below instead.
63
+ //
64
+ // register_agent is a MUTATING call (it persists the agent, its credential
65
+ // hash, and tenant membership). If the session is logged into another tenant,
66
+ // registering first and rejecting the response afterwards would leave a stray,
67
+ // unreachable agent in the wrong tenant on every attempt (names are randomized
68
+ // and the wrong-tenant path records no retry identity). So resolve the bound
69
+ // tenant with the read-only `whoami` FIRST and gate registration on it.
70
+ //
71
+ // Fail CLOSED (AGENTS.md — no fallbacks; non-determinism is worse than
72
+ // failure): the mutating register_agent runs ONLY on a positively attested
73
+ // tenant that matches the profile. A missing/erroring/malformed whoami never
74
+ // silently proceeds, because the later attestation cannot undo an agent that
75
+ // registration already persisted in the wrong tenant.
76
+ //
77
+ // Snapshot the credential ONCE and pin it to both whoami and register_agent.
78
+ // Otherwise each call re-reads the owner token, so a concurrent `botbuddy
79
+ // login` could swap the bound tenant between the attesting whoami and the
80
+ // mutating register (a TOCTOU that would register in the second tenant).
81
+ const pinned = await resolveAuth();
82
+ if (pinned?.error) throw new ProfileBootstrapError("profile_agent_required");
83
+ const auth = pinned?.auth ?? null;
84
+ const identity = await call("whoami", {}, { auth });
85
+ const identityCode = typeof identity?.data?.code === "string" ? identity.data.code : null;
86
+ if (identityCode === "MCP_TENANT_SELECTION_REQUIRED" || identityCode === "MCP_TENANT_CONTEXT_IS_AUTH_ONLY") {
87
+ throw new ProfileBootstrapError("profile_tenant_selection_required");
88
+ }
89
+ const boundTenant = typeof identity?.data?.tenant_id === "string" ? identity.data.tenant_id : null;
90
+ if (!boundTenant) {
91
+ // whoami did not positively attest a tenant (transport/server error or a
92
+ // response without a string tenant_id) — refuse rather than register blind.
93
+ throw new ProfileBootstrapError("profile_tenant_unverified");
94
+ }
95
+ if (boundTenant !== profile.tenant) {
96
+ throw new ProfileBootstrapError("profile_credential_wrong_tenant");
97
+ }
58
98
  const args = {
59
99
  name: agentName,
60
100
  type: "codex",
61
- tenant_id: profile.tenant,
62
101
  ...(reusableIdentity ? { agent_id: reusableIdentity } : {}),
63
102
  };
64
- const response = await call("register_agent", args);
103
+ const response = await call("register_agent", args, { auth });
65
104
  const data = response?.data;
105
+ // Defense-in-depth: whoami above already gated on the tenant, so register_agent
106
+ // should not return a tenant-context error here — but if the contract drifts,
107
+ // surface its own actionable recovery, not the misleading
108
+ // `profile_agent_required` → `botbuddy login` loop that keeps failing because
109
+ // login itself is fine.
110
+ if (data?.code === "MCP_TENANT_CONTEXT_IS_AUTH_ONLY" || data?.code === "MCP_TENANT_SELECTION_REQUIRED") {
111
+ throw new ProfileBootstrapError("profile_tenant_selection_required");
112
+ }
66
113
  if (!response?.ok || (response.isError && data?.code !== "FRESH_CONNECTION_REQUIRED")) {
67
114
  throw new ProfileBootstrapError("profile_agent_required");
68
115
  }
@@ -126,6 +173,20 @@ export function profileBootstrapRecovery(code, profileName) {
126
173
  if (code === "profile_credential_persist_failed") {
127
174
  return `ensure ~/.botbuddy is writable and no other setup is running, then re-run: botbuddy profile setup ${profileName}`;
128
175
  }
176
+ if (code === "profile_tenant_unverified") {
177
+ // whoami could not confirm the bound tenant, so registration was refused
178
+ // before any mutation. Usually transient — retry; login only if it persists.
179
+ return `could not confirm your tenant with the server — retry: botbuddy profile setup ${profileName} (if it persists, run botbuddy login, then re-run setup)`;
180
+ }
181
+ if (code === "profile_tenant_selection_required") {
182
+ // Tenancy is chosen at MCP authentication (BOT-1416), not passed to
183
+ // register_agent. Point the user at selecting the profile's tenant when
184
+ // they sign in — never the bare login loop that implies login is broken.
185
+ const tenant = getAgentProfile(profileName)?.tenant;
186
+ return tenant
187
+ ? `sign in and select the "${tenant}" tenant during authentication, then re-run: botbuddy profile setup ${profileName}`
188
+ : `sign in and select the matching tenant during authentication, then re-run: botbuddy profile setup ${profileName}`;
189
+ }
129
190
  return `botbuddy login && botbuddy profile setup ${profileName}`;
130
191
  }
131
192