Watch
0
0
Fork
You've already forked hyperhive
0

swarm UI: log an agent into claude from its card; the credentials go to bao and the agent picks them up

A new swarm service, `swarm-claude-login`, in its own container on the host
that sets `deploy.claude-login.enable` (defaulted on by `allSwarmServices`
where the host has the minter's store leaf, like the review classifier).

- swarm-ui: an agent card showing "login needed" gets a "log in" button.
  Its dialog starts the login, shows the URL claude printed, and takes the
  pasted code.
- swarm-controller: `POST/DELETE /api/agents/{name}/claude-login` and
  `POST /api/agents/{name}/claude-login/code`, behind the swarm UI's
  authelia-gated `/api/`, relay the steps to the minter as requests on
  `$SWARM.claude-login.request`.
- swarm-claude-login: runs `claude auth login` over piped stdio with HOME
  and CLAUDE_CONFIG_DIR in a per-login scratch dir, scrapes the first
  https URL, writes the code to stdin, and stores the `.credentials.json`
  at `swarm/agents/<agent>/claude-credentials` with a KV v2 write, a new
  version over any earlier one. The scratch dir goes on every exit path; a
  login waits 15 minutes for its code.
- hive-agent: while parked in `wait_for_login`, reads that leaf every 30 s
  under the agent's own cert and installs it only when its KV version is
  newer than the one recorded in `<harness>/claude-credentials-version`.
  An equal or older version is never put back, because claude rotates the
  refresh token and the stored copy is stale after the first refresh.
- swarm-secret-client: `claude_login` paths and `SecretStore::read_versioned`.
- Credentials: a `claude-login` store leaf minted by glue-bao-tls, a
  `swarm-claude-login` policy (create/update on
  `swarm/agents/+/claude-credentials`, read on its own queue client
  secret), an authelia machine client, and a `--claude-login-client`
  grant in the queue's auth-callout responder. The unit runs as a static
  system user.

The hive's own web-UI login is unchanged.

Refs #5268
This commit is contained in:
atlas 2026-10-14 22:26:53 +02:00 • committed by mara
commit d5de1e4943
48 changed files with 2680 additions and 42 deletions

View file

@ -0,0 +1,13 @@
/* <ClaudeLoginDialog> — the code form's column, as
`LinkMatrixAccountForm.css` lays its form out. */
.claude-login-form {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75em;
margin-top: 1em;
}
.claude-login-ok {
margin-top: 1em;
color: var(--green);
}

View file

@ -0,0 +1,130 @@
// <ClaudeLoginDialog> — logs one agent in to claude through the swarm's
// login minter. Opening it starts the login (`POST …/claude-login`), which
// answers with the URL claude printed; the operator opens it and pastes the
// code back (`POST …/claude-login/code`). Closing it while the code is
// still awaited stops the login (`DELETE …/claude-login`).
//
// Mounted only while open, so each open is a fresh login.
import { useEffect, useState } from "preact/hooks";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { Button } from "../../ui/button/Button.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { Panel } from "../../ui/panel/Panel.js";
import { TextField } from "../../ui/text-field/TextField.js";
import {
afterCode,
afterStart,
claudeLoginPath,
leavesLoginRunning,
pastedCode,
type LoginStep,
} from "./ClaudeLoginSteps.js";
import "./ClaudeLoginDialog.css";
async function problemOf(r: Response): Promise<ProblemDetails | null> {
return r.ok ? null : await readApiError(r);
}
export function ClaudeLoginDialog({
agent,
onClose,
}: {
agent: string;
onClose: () => void;
}) {
const [step, setStep] = useState<LoginStep>({ step: "starting" });
const [code, setCode] = useState("");
useEffect(() => {
let live = true;
void (async () => {
try {
const r = await fetch(claudeLoginPath(agent), { method: "POST" });
const problem = await problemOf(r);
const next = afterStart(
problem ? { problem } : ((await r.json()) as { url: string }),
);
if (live) setStep(next);
} catch (err) {
if (live) setStep(afterStart({ problem: { detail: String(err) } }));
}
})();
return () => {
live = false;
};
}, [agent]);
function close() {
if (leavesLoginRunning(step)) {
void fetch(claudeLoginPath(agent), { method: "DELETE" });
}
onClose();
}
async function submit(e: Event) {
e.preventDefault();
const pasted = pastedCode(code);
if (step.step !== "code" || pasted === null) return;
const { url } = step;
setStep({ step: "submitting", url });
try {
const r = await fetch(claudeLoginPath(agent, true), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ code: pasted }),
});
setStep(afterCode(await problemOf(r)));
} catch (err) {
setStep(afterCode({ detail: String(err) }));
}
setCode("");
}
return (
<Dialog open onClose={close} label={`log ${agent} in to claude`} plain>
<Panel title={`log in to claude — ${agent}`} icon="🔑" onClose={close}>
{step.step === "starting" && <p>starting the login…</p>}
{(step.step === "code" || step.step === "submitting") && (
<>
<p>
Open{" "}
<a href={step.url} target="_blank" rel="noopener noreferrer">
the claude login page
</a>
, sign in with this agent's account, and paste the code it shows.
</p>
<form class="claude-login-form" onSubmit={submit}>
<TextField
id="claude-login-code"
label="code"
value={code}
required
onInput={setCode}
/>
<Button
variant="primary"
type="submit"
disabled={step.step === "submitting"}
>
{step.step === "submitting" ? "logging in…" : "log in"}
</Button>
</form>
</>
)}
{step.step === "stored" && (
<p class="claude-login-ok">
Stored. <strong>{agent}</strong> picks the login up within a minute
and resumes.
</p>
)}
{step.step === "failed" && (
<ApiErrorPanel
context="the claude login failed; close and start again"
problem={step.problem}
/>
)}
</Panel>
</Dialog>
);
}

View file

@ -0,0 +1,42 @@
// The claude login dialog's steps, kept out of the component so `npm test`
// runs them. The routes are swarm-controller's `claude_login` module.
import type { ProblemDetails } from "@hive/shared/api-error.js";
export type LoginStep =
| { step: "starting" }
| { step: "code"; url: string }
| { step: "submitting"; url: string }
| { step: "stored" }
| { step: "failed"; problem: ProblemDetails };
export function claudeLoginPath(agent: string, code = false): string {
return `/api/agents/${encodeURIComponent(agent)}/claude-login${code ? "/code" : ""}`;
}
// The step after the start answered: its URL, or why there is none.
export function afterStart(
answer: { url: string } | { problem: ProblemDetails },
): LoginStep {
return "url" in answer
? { step: "code", url: answer.url }
: { step: "failed", problem: answer.problem };
}
// The step after the code was posted. The minter ends the login on a
// refused code, so the next attempt is a fresh start.
export function afterCode(problem: ProblemDetails | null): LoginStep {
return problem === null ? { step: "stored" } : { step: "failed", problem };
}
// Whether closing the dialog leaves a login running that should be
// stopped.
export function leavesLoginRunning(s: LoginStep): boolean {
return s.step === "code";
}
// What the code form may submit: the pasted code without surrounding
// whitespace, or nothing.
export function pastedCode(raw: string): string | null {
const code = raw.trim();
return code === "" ? null : code;
}

View file

@ -17,6 +17,13 @@
gap: 0.4em;
margin-left: auto;
}
/* The "login needed" badge and its "log in" button, kept together; the
wrapper also keeps their clicks, and the dialog's, off the card. */
.ui-agent-card-login {
display: inline-flex;
align-items: center;
gap: 0.4em;
}
.ui-agent-card-message {
color: var(--muted);
white-space: normal;

View file

@ -12,11 +12,13 @@
// `WantedMenu` below keeps its own clicks (mouse or keyboard-synthesized,
// `WantedMenu` hosts real `<button>`s) from also firing `Card`'s
// `onClick` and opening the detail panel.
import { useState } from "preact/hooks";
import { Badge } from "@hive/shared/badge.js";
import type { ProblemDetails } from "@hive/shared/api-error.js";
import { Card } from "../../ui/card/Card.js";
import { RelativeTime } from "../../ui/relative-time/RelativeTime.js";
import { AgentIcon } from "../AgentIcon.js";
import { ClaudeLoginDialog } from "../claude-login/ClaudeLoginDialog.js";
import { FRESHNESS, showsLoginNeeded, type AgentRow } from "../AgentTypes.js";
import { WantedMenu } from "./WantedMenu.js";
import "./AgentCard.css";
@ -45,6 +47,7 @@ export function AgentCard({
onOpenDetail: (row: AgentRow) => void;
}) {
const { tone, label } = FRESHNESS[row.freshness];
const [loggingIn, setLoggingIn] = useState(false);
return (
<Card selected={selected} onClick={() => onOpenDetail(row)}>
<div class="ui-agent-card-row">
@ -72,11 +75,28 @@ export function AgentCard({
}
/>
{showsLoginNeeded(row) ? (
<Badge
tone="warning"
value="login needed"
title="the agent's claude has no session; its turns wait until it is logged in"
/>
<span
class="ui-agent-card-login"
onClick={(e) => e.stopPropagation()}
>
<Badge
tone="warning"
value="login needed"
title="the agent's claude has no session; its turns wait until it is logged in"
/>
<Badge
variant="quiet"
value="log in"
title={`log ${row.name} in to claude from here`}
onClick={() => setLoggingIn(true)}
/>
{loggingIn ? (
<ClaudeLoginDialog
agent={row.name}
onClose={() => setLoggingIn(false)}
/>
) : null}
</span>
) : null}
<span
class="ui-agent-card-wanted"

View file

@ -0,0 +1,54 @@
// The claude login dialog's step logic. Run by `npm test`, which Node runs
// with its built-in test runner and type stripping, so the `.ts` module is
// imported as it is.
import assert from "node:assert/strict";
import { test } from "node:test";
import {
afterCode,
afterStart,
claudeLoginPath,
leavesLoginRunning,
pastedCode,
} from "../src/agent/claude-login/ClaudeLoginSteps.ts";
test("the routes name the agent, escaped", () => {
assert.equal(claudeLoginPath("atlas"), "/api/agents/atlas/claude-login");
assert.equal(
claudeLoginPath("atlas", true),
"/api/agents/atlas/claude-login/code",
);
assert.equal(claudeLoginPath("a/b"), "/api/agents/a%2Fb/claude-login");
});
test("a started login asks for the code at its URL", () => {
assert.deepEqual(afterStart({ url: "https://claude.ai/oauth/x" }), {
step: "code",
url: "https://claude.ai/oauth/x",
});
});
test("a start that failed shows why and has no URL", () => {
const problem = { detail: "no claude login minter is listening" };
assert.deepEqual(afterStart({ problem }), { step: "failed", problem });
});
test("an accepted code is stored; a refused one is a failure", () => {
assert.deepEqual(afterCode(null), { step: "stored" });
const problem = { detail: "OAuth error: invalid code" };
assert.deepEqual(afterCode(problem), { step: "failed", problem });
});
test("only a login waiting for its code is stopped on close", () => {
assert.equal(leavesLoginRunning({ step: "code", url: "https://u" }), true);
assert.equal(leavesLoginRunning({ step: "starting" }), false);
assert.equal(
leavesLoginRunning({ step: "submitting", url: "https://u" }),
false,
);
assert.equal(leavesLoginRunning({ step: "stored" }), false);
});
test("a pasted code is trimmed, and a blank one is nothing", () => {
assert.equal(pastedCode(" abc-def \n"), "abc-def");
assert.equal(pastedCode(" \n "), null);
});