@botbuddy/cli 1.7.0 → 1.8.1

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.7.0",
3
+ "version": "1.8.1",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,5 +8,5 @@ export function createProfileCoordinator({ profile, identity, fetchImpl = fetch
8
8
  const json = await response.json(); if (json.error) throw new Error(json.error.message || "BotBuddy lock verification failed");
9
9
  const text = json.result?.content?.find((item) => item.type === "text")?.text; try { return text ? JSON.parse(text) : {}; } catch { throw new Error("BotBuddy lock verification returned invalid JSON"); }
10
10
  }
11
- return { kind: "profile", async status({ host, slot }) { const result = await call("list_resources", { host, subtype: "playwright_lane" }); const list = Array.isArray(result) ? result : result.resources ?? []; const resource = list.find((item) => item.name === `playwright_lane:${host}:${slot}` || String(item.slot) === String(slot)); return resource ? { held: resource.status !== "free", heldBy: resource.owner_agent_id ?? null } : { held: false, heldBy: null }; }, async emit(event) { await call("record_lane_event", event); }, agentId: identity.agentId };
11
+ return { kind: "profile", async status({ host, slot }) { const result = await call("list_resources", { host, subtype: "playwright_lane" }); const list = Array.isArray(result) ? result : result.resources ?? []; const resource = list.find((item) => item.name === `playwright_lane:${host}:${slot}` || String(item.slot) === String(slot)); return resource ? { held: resource.status !== "free", heldBy: resource.owner_agent_id ?? null, heldByName: resource.agents?.name ?? null, host: resource.host ?? null, name: resource.name ?? null, slot: resource.slot ?? null } : { held: false, heldBy: null, heldByName: null, host: null, name: null, slot: null }; }, async emit(event) { await call("record_lane_event", event); }, agentId: identity.agentId };
12
12
  }
@@ -0,0 +1,17 @@
1
+ // BOT-1488: name the Playwright lane the SAME way the lock kernel stores it.
2
+ // `acquire_resources` canonicalizes the host server-side (normalize_host_string /
3
+ // canonical_host in supabase/functions/_shared/state.ts), so a raw
4
+ // `os.hostname()` like "Jonos-MBP.localdomain" never string-matches the stored
5
+ // "jonos-mbp:<slot>" lane — the gate then refuses a lane the operator holds and
6
+ // prints a lane name that does not exist server-side.
7
+ //
8
+ // This mirrors the PURE string half of the server's normalizeHostString:
9
+ // lowercase + trim + strip a trailing `.local`/`.localdomain`. The server's
10
+ // alias map (canonical_host) is the authority for cross-alias merges; replicating
11
+ // that map here is out of scope for BOT-1488 (and would need invalidation to stay
12
+ // correct), so we fold exactly the case/suffix drift that bites local runs and
13
+ // otherwise defer to the canonical `host` field the server returns.
14
+ export function canonicalizeHostString(host) {
15
+ if (host === null || host === undefined) return host ?? null;
16
+ return String(host).trim().toLowerCase().replace(/\.(local|localdomain)$/, "");
17
+ }
package/src/pw/run.mjs CHANGED
@@ -3,22 +3,77 @@ import { planInvocation } from "./args.mjs";
3
3
  import { actionTypeFromMethod, NAV } from "./readiness.mjs";
4
4
  import { isStaleRefError, staleRefRemediation } from "./targets.mjs";
5
5
  import { createProfileCoordinator } from "./coordinator.mjs";
6
+ import { canonicalizeHostString } from "./host.mjs";
6
7
  import { resolveAgentProfile } from "../wait-profile.mjs";
7
8
  import { readProfileIdentity } from "../agent-credential-store.mjs";
8
- const hostFor = (env) => env.PLAYWRIGHT_MCP_HOST || env.HOSTNAME || os.hostname();
9
- function help(out) { out.write("Usage: botbuddy pw [--profile <name>] <lane> <verb> [args…]\n\nAlias: bb-pw <lane> <verb> [args…]\n"); }
9
+ import { loadConfig, getConfig } from "../config.mjs";
10
+ // BOT-1488: canonicalize the raw hostname the SAME way acquire_resources does
11
+ // server-side, so the lane name bb-pw builds/matches/prints is the one the lock
12
+ // kernel actually stored ("jonos-mbp:8", not "Jonos-MBP.localdomain:8").
13
+ const hostFor = (env) => canonicalizeHostString(env.PLAYWRIGHT_MCP_HOST || env.HOSTNAME || os.hostname());
14
+ function help(out) { out.write("Usage: botbuddy pw [--profile <name>] [--session-id <id>] <lane> <verb> [args…]\n\nAlias: bb-pw <lane> <verb> [args…]\n\n--session-id <id> accept a lane held by this arming-session agent id (from\n register_agent); defaults to $BOTBUDDY_SESSION_ID, then the\n id saved by `botbuddy register`.\n"); }
10
15
  function redact(value, secretValues = []) { return secretValues.reduce((text, secret) => secret ? text.split(secret).join("[redacted]") : text, String(value ?? "")); }
11
- async function gate({ env, host, lane, deps }) { if (env.BB_PW_NO_LOCK === "1") return { allowed: true }; let profile, identity; try { profile = await (deps.resolveProfile ?? resolveAgentProfile)({ cwd: deps.cwd ?? process.cwd(), env, explicitProfile: deps.profile ?? null }); identity = await (deps.readIdentity ?? readProfileIdentity)(profile.name); } catch (error) { return { allowed: false, message: `bb-pw: profile verification failed (${error.message}). Run botbuddy profile setup or set BB_PW_NO_LOCK=1 for local-only work.` }; } const coordinator = deps.coordinator ?? createProfileCoordinator({ profile, identity, fetchImpl: deps.fetch }); if (!profile.token || !identity || identity.tenant !== profile.tenant || coordinator.kind !== "profile") return { allowed: false, message: "bb-pw: profile identity is missing or tenant-mismatched. Run botbuddy profile setup or set BB_PW_NO_LOCK=1 for local-only work." }; try { const status = await coordinator.status({ host, slot: lane }); return status.held && status.heldBy === identity.agentId ? { allowed: true, coordinator } : { allowed: false, message: `bb-pw: lane lock playwright_lane:${host}:${lane} must be held by this profile. Acquire it first or set BB_PW_NO_LOCK=1 for local-only work.` }; } catch (error) { return { allowed: false, message: `bb-pw: could not verify lane lock (${error.message}). Set BB_PW_NO_LOCK=1 for local-only work.` }; } }
16
+ // BOT-1488: the register_agent identity for this machine, persisted by
17
+ // `botbuddy register` into ~/.botbuddy/config.json. This is the SESSION agent
18
+ // that acquire_resources binds a lane to — distinct from the tenant-bound
19
+ // profile agent the gate historically demanded. bb-pw is not always launched
20
+ // through the `botbuddy` entrypoint (bb-pw.mjs imports runPw directly), so load
21
+ // the config here rather than assuming it is already in memory.
22
+ function readRegisteredAgentId() { try { loadConfig(); const id = getConfig()?.agent_id; return typeof id === "string" && id ? id : null; } catch { return null; } }
23
+ async function gate({ env, host, lane, deps }) {
24
+ if (env.BB_PW_NO_LOCK === "1") return { allowed: true };
25
+ let profile, identity;
26
+ try {
27
+ profile = await (deps.resolveProfile ?? resolveAgentProfile)({ cwd: deps.cwd ?? process.cwd(), env, explicitProfile: deps.profile ?? null });
28
+ identity = await (deps.readIdentity ?? readProfileIdentity)(profile.name);
29
+ } catch (error) {
30
+ return { allowed: false, message: `bb-pw: profile verification failed (${error.message}). Run botbuddy profile setup or set BB_PW_NO_LOCK=1 for local-only work.` };
31
+ }
32
+ const coordinator = deps.coordinator ?? createProfileCoordinator({ profile, identity, fetchImpl: deps.fetch });
33
+ if (!profile.token || !identity || identity.tenant !== profile.tenant || coordinator.kind !== "profile") return { allowed: false, message: "bb-pw: profile identity is missing or tenant-mismatched. Run botbuddy profile setup or set BB_PW_NO_LOCK=1 for local-only work." };
34
+ const laneName = `playwright_lane:${host}:${lane}`;
35
+ // The operator's own holder identities: the tenant-bound profile agent (today's
36
+ // happy path) OR the arming session agent — named explicitly with --session-id /
37
+ // $BOTBUDDY_SESSION_ID (BOT-1467 precedent) or read from the local register_agent
38
+ // identity. A foreign operator's agent is in none of these, so the gate stays a
39
+ // real refusal (AC-3).
40
+ const sessionAgentId = deps.sessionId ?? env.BOTBUDDY_SESSION_ID ?? null;
41
+ const registeredAgentId = (deps.readSessionAgentId ?? readRegisteredAgentId)();
42
+ const selfAgentIds = new Set([identity.agentId, sessionAgentId, registeredAgentId].filter(Boolean));
43
+ try {
44
+ const status = await coordinator.status({ host, slot: lane });
45
+ // The server's alias map can collapse the locally-normalized host further
46
+ // (jonos-macbook-pro -> jonos-mbp). When the lock service returned the resource,
47
+ // prefer its canonical host + name so messages/telemetry match what it stored,
48
+ // rather than the string bb-pw built — the ticket's "match by the canonical host
49
+ // field the server returns" path, without replicating the alias map here.
50
+ const canonicalHost = status.host ?? host;
51
+ const foundLaneName = status.name ?? laneName;
52
+ if (status.held && selfAgentIds.has(status.heldBy)) return { allowed: true, coordinator, canonicalHost };
53
+ // Distinguish an expired/free lane from one another operator holds so the
54
+ // operator knows whether to re-acquire vs. wait for a handover (BOT-660).
55
+ if (!status.held) return { allowed: false, message: `bb-pw: lane lock ${laneName} is not held (caller ${identity.agentId}). Acquire it via BotBuddy first, or set BB_PW_NO_LOCK=1 for local-only work.` };
56
+ const holder = status.heldBy ?? "unknown";
57
+ const holderName = status.heldByName ? ` (${status.heldByName})` : "";
58
+ return { allowed: false, message: `bb-pw: lane lock ${foundLaneName} is held by ${holder}${holderName}, not you (caller ${identity.agentId}). Acquire it first or set BB_PW_NO_LOCK=1 for local-only work.` };
59
+ } catch (error) {
60
+ return { allowed: false, message: `bb-pw: could not verify lane lock ${laneName} (${error.message}). Set BB_PW_NO_LOCK=1 for local-only work.` };
61
+ }
62
+ }
12
63
  export async function runPw(argv, deps = {}) {
13
- const env = deps.env ?? process.env, stdout = deps.stdout ?? process.stdout, stderr = deps.stderr ?? process.stderr; let args = [...argv]; if (["--help", "-h"].includes(args[0])) { help(stdout); return 0; } if (args[0] === "--profile") { if (!args[1]) { stderr.write("bb-pw: --profile needs a name\n"); return 2; } deps = { ...deps, profile: args[1] }; args = args.slice(2); }
64
+ const env = deps.env ?? process.env, stdout = deps.stdout ?? process.stdout, stderr = deps.stderr ?? process.stderr; let args = [...argv]; if (["--help", "-h"].includes(args[0])) { help(stdout); return 0; }
65
+ while (args[0] === "--profile" || args[0] === "--session-id") { const flag = args[0]; if (!args[1]) { stderr.write(`bb-pw: ${flag} needs a value\n`); return 2; } deps = flag === "--profile" ? { ...deps, profile: args[1] } : { ...deps, sessionId: args[1] }; args = args.slice(2); }
14
66
  let plan; try { plan = planInvocation(args, env); } catch (error) { stderr.write(`${error.message}\n`); return 2; }
15
67
  const { spawnExec, socketRun } = deps.daemon ?? await import("./daemon.mjs");
16
68
  if (plan.scope === "global") { if (plan.mode === "reap") { await (deps.reap ?? (await import("./reap.mjs")).reap)({ env, stdout }); return 0; } if (env.BB_PW_NO_LOCK !== "1") { stderr.write("bb-pw: close-all and kill-all require BB_PW_NO_LOCK=1 because they can affect lanes you do not own.\n"); return 3; } return spawnExec(plan, env); }
17
69
  const telemetry = deps.telemetry ?? (await import("./telemetry.mjs")).makeTelemetry({ env }); const host = deps.host ?? hostFor(env);
18
70
  const auth = await gate({ env, host, lane: plan.lane, deps }); if (!auth.allowed) { stderr.write(`${auth.message}\n`); return 3; }
19
- if (plan.mode === "status") { const lock = auth.coordinator?.status ? await auth.coordinator.status({ host, slot: plan.lane }) : null; stdout.write(JSON.stringify({ lane: plan.lane, session: plan.session, host, lock, spooled_events: telemetry.count(plan.lane) }, null, 2) + "\n"); return 0; }
71
+ // Report the host the lock service actually stored (alias-collapsed), so the
72
+ // status view and lane telemetry match the server, not the local string (AC-4).
73
+ const effHost = auth.canonicalHost ?? host;
74
+ if (plan.mode === "status") { const lock = auth.coordinator?.status ? await auth.coordinator.status({ host: effHost, slot: plan.lane }) : null; stdout.write(JSON.stringify({ lane: plan.lane, session: plan.session, host: effHost, lock, spooled_events: telemetry.count(plan.lane) }, null, 2) + "\n"); return 0; }
20
75
  if (actionTypeFromMethod(plan.verb) !== "other") telemetry.append(plan.lane, { ts: Date.now(), method: plan.verb, url: actionTypeFromMethod(plan.verb) === NAV ? plan.telemetryUrl : null });
21
76
  const inspect = plan.mode === "socket" || (actionTypeFromMethod(plan.verb) === "interaction" && (plan.targetKind === "ref" || plan.fresh)); let code;
22
77
  if (inspect) { if (plan.fresh) await socketRun({ ...plan, socketArgs: ["snapshot"] }, env).catch(() => {}); const result = await socketRun({ ...plan, socketArgs: plan.socketArgs ?? plan.execArgv.slice(1) }, env); if (result.text) stdout.write(`${redact(result.text, plan.secretValues)}\n`); if (!result.ok) stderr.write(`${redact(plan.targetKind === "ref" && isStaleRefError(result.error) ? staleRefRemediation(plan.target) : result.error, plan.secretValues)}\n`); code = result.ok ? 0 : 1; } else code = await spawnExec(plan, env);
23
- if (plan.rollup && code === 0) await telemetry.rollup({ lane: plan.lane, coordinator: auth.coordinator, host }); return code;
78
+ if (plan.rollup && code === 0) await telemetry.rollup({ lane: plan.lane, coordinator: auth.coordinator, host: effHost }); return code;
24
79
  }