Watch
0
0
Fork
You've already forked hyperhive
0

add a default archetype, preselected by the clients

This commit is contained in:
atlas 2026-11-27 17:41:52 +01:00 • committed by mara
commit 8f7c45d40f
15 changed files with 253 additions and 47 deletions

View file

@ -239,21 +239,23 @@ message box under her terminal. She is the manager agent: her MCP surface is the
privileged one that configures agents, and she can recover the others. Changes to privileged one that configures agents, and she can recover the others. Changes to
an agent's config arrive as PRs you merge. → [`2-handbook/agents/agent-permissions.md`](../2-handbook/agents/agent-permissions.md) an agent's config arrive as PRs you merge. → [`2-handbook/agents/agent-permissions.md`](../2-handbook/agents/agent-permissions.md)
To create an agent yourself instead, use the swarm UI, or: To create an agent yourself instead, use the swarm UI, the optional last step of `swarmctl setup` (it asks whether the agent should be custom), or:
```bash ```bash
swarmctl agent create <name> --hive firsthive swarmctl agent create <name> --hive firsthive
``` ```
The name is yours to choose; it has no meaning to the swarm. The controller provisions the agent's identity, forge user and config repo The name is yours to choose; it has no meaning to the swarm. The controller provisions the agent's identity and forge user, then has the hive build
(`agent-configs/<name>`, from the default template), then has the hive build and start the container. The swarm builds the agent from the `default` archetype, which has
and start the container. The hive builds from a copy of hyperhive on the swarm's own forge: the no config repo; pass `--custom` for a custom agent, whose repo
(`agent-configs/<name>`) the controller seeds from the default template, or
`--archetype <name>` for another archetype. The hive builds from a copy of hyperhive on the swarm's own forge: the
controller mirrors it there as `hyperhive/hyperhive` on a fresh swarm, so the controller mirrors it there as `hyperhive/hyperhive` on a fresh swarm, so the
first agent needs no extra step (see first agent needs no extra step (see
[`nixos.md`](nixos.md#the-hyperhive-mirror)). It returns once the scheduler queues the job — watch the [`nixos.md`](nixos.md#the-hyperhive-mirror)). It returns once the scheduler queues the job — watch the
swarm UI's job view for progress. swarm UI's job view for progress.
Later config changes are PRs on `agent-configs/<name>`; you merge them on the Later config changes to a custom agent are PRs on `agent-configs/<name>`; you merge them on the
forge, and the merge deploys them. → forge, and the merge deploys them. →
[`2-handbook/agents/persistence.md`](../2-handbook/agents/persistence.md#config-changes) [`2-handbook/agents/persistence.md`](../2-handbook/agents/persistence.md#config-changes)

View file

@ -9,9 +9,14 @@ change each field before you create the agent.
An agent created from an archetype has no `agent-configs/<name>` repo of its An agent created from an archetype has no `agent-configs/<name>` repo of its
own. The swarm's `internal/meta` flake builds it from the archetype's module, own. The swarm's `internal/meta` flake builds it from the archetype's module,
so every agent of that archetype runs the same configuration. To change what it runs, change the so every agent of that archetype runs the same configuration. To change what it runs, change the
archetype. Picking "none" creates a custom agent, with its own config repo. The archetype. The create form opens on `default`, an archetype with the default
swarm can also turn an archetype agent into a custom one later config, so an agent that needs no config repo has none. Picking "none"
([below](#turn-into-custom)). creates a custom agent, with its own config repo. The swarm can also turn an
archetype agent, `default` included, into a custom one later
([below](#turn-into-custom)). The API stays as it was: a request with no
`archetype` still creates a custom agent, and `swarmctl agent create` sends
`default` unless you pass `--custom`. A swarm whose controller or builder
lists no `default` opens the form on "none."
## The built-in archetypes ## The built-in archetypes
@ -19,6 +24,7 @@ The hyperhive flake ships these:
| archetype | what it sets | | archetype | what it sets |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `default` | the default config: its module is empty, so it builds what an unedited custom agent builds, and it holds the default permissions. It has no prompt, caps or inference settings. The create form preselects it. |
| `reviewer` | permissions `messaging`, `inbox`, `execution`: the default set without `meta`. With `execution` it can run `hive-forge`, `git` and other commands. | | `reviewer` | permissions `messaging`, `inbox`, `execution`: the default set without `meta`. With `execution` it can run `hive-forge`, `git` and other commands. |
| `android-dev` | installs `android-tools` (`adb`, `fastboot`), Gradle, a JDK, the Android SDK (build-tools 36.1.0, platform 35) and nix-ld, and sets `ANDROID_HOME`, `ANDROID_SDK_ROOT` and `JAVA_HOME`, so the `aapt2` Gradle downloads runs; default permissions. | | `android-dev` | installs `android-tools` (`adb`, `fastboot`), Gradle, a JDK, the Android SDK (build-tools 36.1.0, platform 35) and nix-ld, and sets `ANDROID_HOME`, `ANDROID_SDK_ROOT` and `JAVA_HOME`, so the `aapt2` Gradle downloads runs; default permissions. |
| `reverse-engineer` | sets `services.hyperhive.agent.rea.enable`: installs REA, Ghidra 12.1 and procps, and allows all REA MCP tools; default permissions and the agent's normal memory cap. | | `reverse-engineer` | sets `services.hyperhive.agent.rea.enable`: installs REA, Ghidra 12.1 and procps, and allows all REA MCP tools; default permissions and the agent's normal memory cap. |
@ -44,7 +50,7 @@ agent gets every new item, and two of them would both label and assign it.
An existing ruth, created before this archetype, keeps her own config repo and An existing ruth, created before this archetype, keeps her own config repo and
model. Set `sonnet` in the swarm UI's inference settings for her if wanted. model. Set `sonnet` in the swarm UI's inference settings for her if wanted.
Each built-in archetype also sets `services.hyperhive.agent.icon`, so its agents Each built-in archetype except `default` also sets `services.hyperhive.agent.icon`, so its agents
show an icon in the swarm UI until their config sets another. show an icon in the swarm UI until their config sets another.
## Where an archetype comes from ## Where an archetype comes from

View file

@ -112,6 +112,12 @@ No approval gate guards this: the caller is root on the controller's host, or lo
* `--hive <HIVE>` — Hive in this swarm to deploy the agent to. * `--hive <HIVE>` — Hive in this swarm to deploy the agent to.
Required, and deliberately not defaulted: it's an *address* — the hive that gets the deploy message — and only the operator knows which one they mean. The controller checks it against the swarm's hive roster and names the known hives if it misses. Required, and deliberately not defaulted: it's an *address* — the hive that gets the deploy message — and only the operator knows which one they mean. The controller checks it against the swarm's hive roster and names the known hives if it misses.
* `--archetype <NAME>` — Archetype of the `hyperhive` source to build the agent from.
`default` is the default config with no config repo; turn the agent into a custom one later when it needs a repo. The hive's `hyperhive` input must know the archetype, or the agent's build fails.
Default value: `default`
* `--custom` — Create a custom agent: it gets an `agent-configs/<name>` repo and no archetype
* `--agents-md <FILE>` — A text file the agent's `AGENTS.md` starts with. * `--agents-md <FILE>` — A text file the agent's `AGENTS.md` starts with.
The agent writes it on its first start, and only when it has no `AGENTS.md` yet: re-creating an agent never replaces an existing file. The controller refuses a file over 64 KiB. The agent writes it on its first start, and only when it has no `AGENTS.md` yet: re-creating an agent never replaces an existing file. The controller refuses a file over 64 KiB.

View file

@ -36,6 +36,12 @@ stored list and logs a warning on each pass. A swarm whose
builder connects after the controller has no list until a retry succeeds. A swarm with no builder enabled shows no builder connects after the controller has no list until a retry succeeds. A swarm with no builder enabled shows no
archetype select. archetype select.
The create form preselects the `default` archetype once the list has loaded and
lists it, then "none" (a custom agent), then the rest. A list without `default`,
from a controller or builder that predates it, leaves "none" preselected. The
server still reads no `archetype` in `POST /api/agents` as a custom
agent, the only way the request says custom.
The stored value: The stored value:
```json ```json

View file

@ -1,10 +1,11 @@
// <ArchetypePicker> — the create form's archetype choice, drawn like the // <ArchetypePicker> — the create form's archetype choice, drawn like the
// broadcast screen's agent picker: one tile per choice with its icon and name, // broadcast screen's agent picker: one tile per choice with its icon and name,
// where the broadcast screen has one per agent. One choice at a time, so each // where the broadcast screen has one per agent. One choice at a time, so each
// tile is a radio button. The first tile is "none", an agent with no archetype. // tile is a radio button. The first tiles are `default` (when the swarm lists
// it) and "none", an agent with no archetype.
import { import {
archetypeKey,
iconSrc, iconSrc,
pickerTiles,
type Archetype, type Archetype,
} from "./CreateAgentArchetype.js"; } from "./CreateAgentArchetype.js";
import { FormField } from "../ui/form-field/FormField.js"; import { FormField } from "../ui/form-field/FormField.js";
@ -35,14 +36,7 @@ export function ArchetypePicker({
onChange: (key: string) => void; onChange: (key: string) => void;
disabled?: boolean; disabled?: boolean;
}) { }) {
const tiles: { key: string; name: string; svg?: string }[] = [ const tiles = pickerTiles(archetypes);
{ key: "", name: "none" },
...archetypes.map((a) => ({
key: archetypeKey(a),
name: a.name,
svg: a.icon,
})),
];
return ( return (
<FormField label="archetype" labelId={`${id}-label`}> <FormField label="archetype" labelId={`${id}-label`}>
<div <div

View file

@ -101,3 +101,43 @@ export function iconSrc(svg: string | undefined): string | null {
if (svg === undefined || svg.trim() === "") return null; if (svg === undefined || svg.trim() === "") return null;
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
} }
/** The archetype with the default config and no config repo. */
export const DEFAULT_ARCHETYPE = { source: "hyperhive", name: "default" };
/**
* The `archetypeKey` the form opens on: `default` when the list has it, else
* `""`, a custom agent, which is what a controller or builder that predates
* `default` gets.
* `null` until the list has loaded.
*/
export function openingKey(list: Archetype[] | null): string | null {
if (list === null) return null;
const def = findArchetype(list, DEFAULT_ARCHETYPE);
return def ? archetypeKey(def) : "";
}
/** One picker tile: `key` is the `archetypeKey`, `""` for a custom agent. */
export interface Tile {
key: string;
name: string;
svg?: string;
}
/**
* The picker's tiles: `default` first when the list has it, then `none` (a
* custom agent), then the rest in list order.
*/
export function pickerTiles(list: Archetype[]): Tile[] {
const def = findArchetype(list, DEFAULT_ARCHETYPE);
const tile = (a: Archetype): Tile => ({
key: archetypeKey(a),
name: a.name,
svg: a.icon,
});
return [
...(def ? [tile(def)] : []),
{ key: "", name: "none" },
...list.filter((a) => a !== def).map(tile),
];
}

View file

@ -24,8 +24,9 @@
// page-scoped input/button chrome — see that kit's own comments for why. // page-scoped input/button chrome — see that kit's own comments for why.
// //
// Permissions: checkboxes from `GET /api/permissions`, on the default set or the // Permissions: checkboxes from `GET /api/permissions`, on the default set or the
// picked archetype's; sent only when that differs from the default. A caller can // picked archetype's; sent only when that differs from the default. The form opens
// open the form on an archetype with `initialArchetype`. // on the `default` archetype when the swarm lists it, else on none (a custom
// agent); a caller can open it on another archetype with `initialArchetype`.
import { useEffect, useRef, useState } from "preact/hooks"; import { useEffect, useRef, useState } from "preact/hooks";
import { Link } from "wouter-preact"; import { Link } from "wouter-preact";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js"; import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
@ -60,6 +61,7 @@ import {
import { import {
archetypeKey, archetypeKey,
findArchetype, findArchetype,
openingKey,
prefill, prefill,
requestArchetype, requestArchetype,
type ArchetypeList, type ArchetypeList,
@ -143,7 +145,7 @@ export function CreateAgentForm({
// Unticked: the server writes `false`, so the agent starts restricted. // Unticked: the server writes `false`, so the agent starts restricted.
const [internet, setInternet] = useState(false); const [internet, setInternet] = useState(false);
// `null` until `/api/archetypes` answers; `archetype` is the picked one's // `null` until `/api/archetypes` answers; `archetype` is the picked one's
// `archetypeKey`, `""` for none. // `archetypeKey`, `""` for none (a custom agent).
const [archetypes, setArchetypes] = useState<ArchetypeList | null>(null); const [archetypes, setArchetypes] = useState<ArchetypeList | null>(null);
const [archetypesError, setArchetypesError] = useState<ProblemDetails | null>( const [archetypesError, setArchetypesError] = useState<ProblemDetails | null>(
null, null,
@ -214,15 +216,20 @@ export function CreateAgentForm({
setInference(p.inference); setInference(p.inference);
} }
// Opens on `initialArchetype` once the list and the permission catalogue are // Opens on `initialArchetype`, else on `default` when the list has it, once
// both in, and only once, so a later pick of "none" stays. // the list and the permission catalogue are both in, and only once, so a
// later pick of "none" stays.
const seeded = useRef(false); const seeded = useRef(false);
useEffect(() => { useEffect(() => {
if (seeded.current || !initialArchetype || !archetypes || !catalogue) if (seeded.current || !archetypes || !catalogue) return;
return;
seeded.current = true; seeded.current = true;
const found = findArchetype(archetypes.archetypes, initialArchetype); if (initialArchetype) {
if (found) pickArchetype(archetypeKey(found)); const found = findArchetype(archetypes.archetypes, initialArchetype);
if (found) pickArchetype(archetypeKey(found));
return;
}
const key = openingKey(archetypes.archetypes);
if (key) pickArchetype(key);
}, [archetypes, catalogue]); }, [archetypes, catalogue]);
const unlisted = const unlisted =
initialArchetype !== undefined && initialArchetype !== undefined &&

View file

@ -5,6 +5,8 @@ import { test } from "node:test";
import { import {
archetypeKey, archetypeKey,
iconSrc, iconSrc,
openingKey,
pickerTiles,
prefill, prefill,
requestArchetype, requestArchetype,
} from "../src/pages/CreateAgentArchetype.ts"; } from "../src/pages/CreateAgentArchetype.ts";
@ -81,7 +83,7 @@ test("the key tells sources apart", () => {
); );
}); });
test("a picked archetype is sent by source and name, none is left out", () => { test("a picked archetype is sent by source and name, none (a custom agent) is left out", () => {
const reviewer = { const reviewer = {
source: "hyperhive", source: "hyperhive",
name: "reviewer", name: "reviewer",
@ -102,3 +104,38 @@ test("an icon is a data URL of the SVG text, and none without text", () => {
assert.ok(src.startsWith("data:image/svg+xml;charset=utf-8,%3Csvg"), src); assert.ok(src.startsWith("data:image/svg+xml;charset=utf-8,%3Csvg"), src);
assert.ok(!src.includes("<"), "the markup is percent-encoded"); assert.ok(!src.includes("<"), "the markup is percent-encoded");
}); });
const listed = (...names) =>
names.map((name) => ({ source: "hyperhive", name, description: "d" }));
test("the form opens on default once the list has it, and on none otherwise", () => {
assert.equal(openingKey(null), null);
assert.equal(
openingKey(listed("reviewer", "default")),
archetypeKey({ source: "hyperhive", name: "default", description: "d" }),
);
// An older controller or builder lists no default: a custom agent, as before.
assert.equal(openingKey(listed("reviewer", "ruth")), "");
assert.equal(openingKey([]), "");
// A `default` from another source is not the built-in one.
assert.equal(
openingKey([{ source: "other", name: "default", description: "d" }]),
"",
);
});
test("the tiles are default, then none, then the rest in list order", () => {
const names = (list) => pickerTiles(list).map((t) => t.name);
assert.deepEqual(names(listed("reviewer", "default", "ruth")), [
"default",
"none",
"reviewer",
"ruth",
]);
assert.deepEqual(names(listed("reviewer", "ruth")), [
"none",
"reviewer",
"ruth",
]);
assert.equal(pickerTiles(listed("default"))[1].key, "");
});

View file

@ -7,9 +7,17 @@
# the create form shows beside the archetype, and `prompt`, the text the create # the create form shows beside the archetype, and `prompt`, the text the create
# form prefills the new agent's AGENTS.md with (the built-ins read theirs from # form prefills the new agent's AGENTS.md with (the built-ins read theirs from
# ./prompts/<name>.md); see docs/2-handbook/swarm/archetypes.md. Every archetype # ./prompts/<name>.md); see docs/2-handbook/swarm/archetypes.md. Every archetype
# sets `services.hyperhive.agent.icon` (with `mkDefault`) to an SVG in `icons/`, # but `default`, whose module is empty, sets `services.hyperhive.agent.icon`
# so its agents show one until their config sets another. # (with `mkDefault`) to an SVG in `icons/`, so its agents show one until their
# config sets another.
{ {
default = {
module = { };
meta = {
icon = builtins.readFile ./icons/default.svg;
description = "The default config, no config repo; turn it into a custom agent when you need one. It holds the default permissions.";
};
};
reviewer = { reviewer = {
module = module =
{ lib, ... }: { lib, ... }:

View file

@ -0,0 +1,12 @@
<svg width="300" height="300" viewBox="0 0 300 300" role="img" xmlns="http://www.w3.org/2000/svg">
<title>default</title>
<desc>Default archetype icon: an empty hive cell, a hexagon outline with nothing in it, amber on dark</desc>
<defs>
<clipPath id="clip"><circle cx="150" cy="150" r="140"/></clipPath>
</defs>
<g clip-path="url(#clip)">
<rect width="300" height="300" fill="#0a0600"/>
<polygon points="150,66 222.7,108 222.7,192 150,234 77.3,192 77.3,108" fill="none" stroke="#ffb300" stroke-width="12" stroke-linejoin="round"/>
</g>
<circle cx="150" cy="150" r="140" fill="none" stroke="#ffb300" stroke-width="3" opacity="0.6"/>
</svg>

After

Width:  |  Height:  |  Size: 666 B

View file

@ -299,7 +299,7 @@ let
# output and prints it as JSON. A derivation or a path in `meta` would # output and prints it as JSON. A derivation or a path in `meta` would
# make that evaluation build or copy something; a function would not # make that evaluation build or copy something; a function would not
# print at all. # print at all.
name = "the built-in archetypes carry a module and a meta of plain data, and reviewer can run commands and android-dev installs its toolchain and reverse-engineer turns rea on, and each sets an svg icon as a default, and each has a non-empty prompt under the 64 KiB cap, and ruth runs sonnet with manage_root_agent, logs and metrics, and triage runs haiku with three flows that send to members"; name = "the built-in archetypes carry a module and a meta of plain data, and reviewer can run commands and android-dev installs its toolchain and reverse-engineer turns rea on, and each but default sets an svg icon as a default, and each but default has a non-empty prompt under the 64 KiB cap, and default is an empty module with no prompt, permissions or inference and an svg icon in its meta, and ruth runs sonnet with manage_root_agent, logs and metrics, and triage runs haiku with three flows that send to members";
ok = ok =
let let
plain = plain =
@ -319,8 +319,11 @@ let
lib.all (a: a ? module && a.meta.description != "") (lib.attrValues archetypes) lib.all (a: a ? module && a.meta.description != "") (lib.attrValues archetypes)
&& plain metas && plain metas
&& lib.all (m: (m.prompt or "") != "" && builtins.stringLength m.prompt <= 65536) ( && lib.all (m: (m.prompt or "") != "" && builtins.stringLength m.prompt <= 65536) (
lib.attrValues metas lib.attrValues (builtins.removeAttrs metas [ "default" ])
) )
&& archetypes.default.module == { }
&& !(metas.default ? prompt || metas.default ? permissions || metas.default ? inference)
&& lib.hasPrefix "<svg" metas.default.icon
&& lib.elem "messaging" reviewer && lib.elem "messaging" reviewer
&& lib.elem "inbox" reviewer && lib.elem "inbox" reviewer
&& lib.elem "execution" reviewer && lib.elem "execution" reviewer

View file

@ -42,6 +42,7 @@ pub(crate) fn create(
target: &Target, target: &Target,
name: &str, name: &str,
hive: &str, hive: &str,
archetype: Option<&str>,
agents_md: Option<&Path>, agents_md: Option<&Path>,
) -> Result<()> { ) -> Result<()> {
// Client-side before the round trip, so a typo is an immediate local // Client-side before the round trip, so a typo is an immediate local
@ -57,7 +58,7 @@ pub(crate) fn create(
}) })
.transpose()?; .transpose()?;
let resp = request_create(target, &name, &hive, agents_md.as_deref())?; let resp = request_create(target, &name, &hive, archetype, agents_md.as_deref())?;
println!("queued: job node {}", resp.node_id); println!("queued: job node {}", resp.node_id);
println!( println!(
@ -73,18 +74,20 @@ pub(crate) fn create(
} }
/// The round trip of [`create`] for an already validated `name` and `hive`, /// The round trip of [`create`] for an already validated `name` and `hive`,
/// printing nothing. /// printing nothing. `archetype` names an archetype of the `hyperhive` source;
/// `None` creates a custom agent with a config repo.
pub(crate) fn request_create( pub(crate) fn request_create(
target: &Target, target: &Target,
name: &str, name: &str,
hive: &str, hive: &str,
archetype: Option<&str>,
agents_md: Option<&str>, agents_md: Option<&str>,
) -> Result<CreateAgentResponse> { ) -> Result<CreateAgentResponse> {
let rt = tokio::runtime::Builder::new_current_thread() let rt = tokio::runtime::Builder::new_current_thread()
.enable_all() .enable_all()
.build() .build()
.context("starting a tokio runtime for the controller request")?; .context("starting a tokio runtime for the controller request")?;
rt.block_on(post_create(target, name, hive, agents_md)) rt.block_on(post_create(target, name, hive, archetype, agents_md))
} }
/// Parse a CLI-supplied name into a validated identifier, naming which /// Parse a CLI-supplied name into a validated identifier, naming which
@ -184,6 +187,7 @@ async fn post_create(
target: &Target, target: &Target,
name: &str, name: &str,
hive: &str, hive: &str,
archetype: Option<&str>,
agents_md: Option<&str>, agents_md: Option<&str>,
) -> Result<CreateAgentResponse> { ) -> Result<CreateAgentResponse> {
post( post(
@ -196,7 +200,10 @@ async fn post_create(
inference: None, inference: None,
permissions: None, permissions: None,
unrestricted_internet: None, unrestricted_internet: None,
archetype: None, archetype: archetype.map(|name| swarm_wire::agent_archetype::ArchetypeRef {
source: "hyperhive".to_owned(),
name: name.to_owned(),
}),
agents_md: agents_md.map(str::to_owned), agents_md: agents_md.map(str::to_owned),
}, },
"create-agent", "create-agent",

View file

@ -281,7 +281,9 @@ pub(crate) trait Actions {
fn make_admin(&mut self, name: &str) -> Result<String>; fn make_admin(&mut self, name: &str) -> Result<String>;
/// `ruth`, with the permissions of a manager, declared `up`. /// `ruth`, with the permissions of a manager, declared `up`.
fn declare_ruth(&mut self, hive: &str, exists: bool) -> Result<String>; fn declare_ruth(&mut self, hive: &str, exists: bool) -> Result<String>;
fn create_agent(&mut self, name: &str, hive: &str) -> Result<String>; /// An agent of the `default` archetype, or a custom one with its own config
/// repo when `custom`.
fn create_agent(&mut self, name: &str, hive: &str, custom: bool) -> Result<String>;
} }
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
@ -748,7 +750,12 @@ fn other_agent(ui: &mut impl Ui, actions: &mut impl Actions, session: &mut Sessi
let hive = ask_valid(ui, "Hive", session.hive.as_deref(), |h| { let hive = ask_valid(ui, "Hive", session.hive.as_deref(), |h| {
crate::agent::parse_ident(h, "hive").map(drop) crate::agent::parse_ident(h, "hive").map(drop)
})?; })?;
let said = ui.working("creating the agent", || actions.create_agent(&name, &hive))?; let custom =
ui.ask("Custom agent with its own config repo, instead of the default archetype? [y/N]: ")?;
let custom = matches!(custom.trim().to_lowercase().as_str(), "y" | "yes");
let said = ui.working("creating the agent", || {
actions.create_agent(&name, &hive, custom)
})?;
session.hive = Some(hive); session.hive = Some(hive);
ui.say(Tone::Good, &format!("✔ {said}")); ui.say(Tone::Good, &format!("✔ {said}"));
Ok(()) Ok(())
@ -944,8 +951,8 @@ mod tests {
Ok("ruth is declared up".to_owned()) Ok("ruth is declared up".to_owned())
} }
fn create_agent(&mut self, name: &str, hive: &str) -> Result<String> { fn create_agent(&mut self, name: &str, hive: &str, custom: bool) -> Result<String> {
self.note(&format!("create_agent:{name}:{hive}")); self.note(&format!("create_agent:{name}:{hive}:custom={custom}"));
self.world.others += 1; self.world.others += 1;
Ok("queued".to_owned()) Ok("queued".to_owned())
} }
@ -982,8 +989,8 @@ mod tests {
fn declare_ruth(&mut self, _: &str, _: bool) -> Result<String> { fn declare_ruth(&mut self, _: &str, _: bool) -> Result<String> {
Ok("declared".to_owned()) Ok("declared".to_owned())
} }
fn create_agent(&mut self, name: &str, hive: &str) -> Result<String> { fn create_agent(&mut self, name: &str, hive: &str, custom: bool) -> Result<String> {
self.0.create_agent(name, hive) self.0.create_agent(name, hive, custom)
} }
} }
@ -1445,6 +1452,22 @@ mod tests {
})); }));
} }
#[test]
fn another_agent_is_a_default_archetype_agent_unless_asked_custom() {
let created = |custom_answer: &'static str| {
let log = log();
let mut actions = Fake::new(World::fresh(), &log);
let mut script: Vec<&str> = FULL_RUN[..FULL_RUN.len() - 1].to_vec();
script.extend(["y", "scribe", "", custom_answer]);
let mut ui = Script::new(&script, &log);
run(&mut ui, &mut actions).expect("the run finishes");
calls(&log, "create_agent")
};
assert_eq!(created(""), ["create_agent:scribe:firsthive:custom=false"]);
assert_eq!(created("n"), ["create_agent:scribe:firsthive:custom=false"]);
assert_eq!(created("y"), ["create_agent:scribe:firsthive:custom=true"]);
}
#[test] #[test]
fn a_step_that_the_check_still_finds_open_is_not_taken_as_done() { fn a_step_that_the_check_still_finds_open_is_not_taken_as_done() {
let log = log(); let log = log();

View file

@ -590,6 +590,22 @@ struct AgentCreateArgs {
/// hive roster and names the known hives if it misses. /// hive roster and names the known hives if it misses.
#[arg(long, value_name = "HIVE")] #[arg(long, value_name = "HIVE")]
hive: String, hive: String,
/// Archetype of the `hyperhive` source to build the agent from.
///
/// `default` is the default config with no config repo; turn the agent
/// into a custom one later when it needs a repo. The hive's `hyperhive`
/// input must know the archetype, or the agent's build fails.
#[arg(
long,
value_name = "NAME",
default_value = "default",
conflicts_with = "custom"
)]
archetype: String,
/// Create a custom agent: it gets an `agent-configs/<name>` repo and no
/// archetype.
#[arg(long)]
custom: bool,
/// A text file the agent's `AGENTS.md` starts with. /// A text file the agent's `AGENTS.md` starts with.
/// ///
/// The agent writes it on its first start, and only when it has no /// The agent writes it on its first start, and only when it has no
@ -606,6 +622,13 @@ struct AgentCreateArgs {
controller_socket: Option<PathBuf>, controller_socket: Option<PathBuf>,
} }
impl AgentCreateArgs {
/// The archetype to send: `--archetype`, or none for `--custom`.
fn requested_archetype(&self) -> Option<&str> {
(!self.custom).then_some(self.archetype.as_str())
}
}
#[derive(Args)] #[derive(Args)]
struct AgentMintForgeTokenArgs { struct AgentMintForgeTokenArgs {
/// Name of an agent that already exists. /// Name of an agent that already exists.
@ -838,8 +861,15 @@ fn main() -> Result<()> {
Verb::Agent { Verb::Agent {
command: AgentVerb::Create(args), command: AgentVerb::Create(args),
} => { } => {
let archetype = args.requested_archetype().map(str::to_owned);
let target = remote.target(args.controller_socket)?; let target = remote.target(args.controller_socket)?;
agent::create(&target, &args.name, &args.hive, args.agents_md.as_deref()) agent::create(
&target,
&args.name,
&args.hive,
archetype.as_deref(),
args.agents_md.as_deref(),
)
} }
// Same socket-resolution reasoning as `Create` above. // Same socket-resolution reasoning as `Create` above.
Verb::Agent { Verb::Agent {
@ -1729,6 +1759,30 @@ mod tests {
); );
} }
#[test]
fn agent_create_defaults_to_the_default_archetype_and_custom_sends_none() {
let args = |extra: &[&str]| {
let base = ["swarmctl", "agent", "create", "scribe", "--hive", "alpha"];
Cli::try_parse_from(base.iter().chain(extra))
};
let archetype_of = |cli: Cli| {
let Verb::Agent {
command: AgentVerb::Create(args),
} = cli.command
else {
panic!("expected `agent create`");
};
args.requested_archetype().map(str::to_owned)
};
assert_eq!(archetype_of(args(&[]).unwrap()).as_deref(), Some("default"));
assert_eq!(
archetype_of(args(&["--archetype", "reviewer"]).unwrap()).as_deref(),
Some("reviewer")
);
assert_eq!(archetype_of(args(&["--custom"]).unwrap()), None);
assert!(args(&["--custom", "--archetype", "reviewer"]).is_err());
}
/// The socket is optional on the command line because the nix wrapper /// The socket is optional on the command line because the nix wrapper
/// sets `SWARM_CONTROLLER_SOCKET`; `path_from` is what turns an absent /// sets `SWARM_CONTROLLER_SOCKET`; `path_from` is what turns an absent
/// pair into an error rather than a guess. /// pair into an error rather than a guess.

View file

@ -322,7 +322,7 @@ impl Actions for Live {
let target = self.target()?; let target = self.target()?;
let hive = agent::parse_ident(hive, "hive")?; let hive = agent::parse_ident(hive, "hive")?;
if !exists { if !exists {
agent::request_create(target, RUTH, &hive, None)?; agent::request_create(target, RUTH, &hive, None, None)?;
} }
let every = Duration::from_secs(2); let every = Duration::from_secs(2);
ensure_manager_permission( ensure_manager_permission(
@ -339,10 +339,11 @@ impl Actions for Live {
)) ))
} }
fn create_agent(&mut self, name: &str, hive: &str) -> Result<String> { fn create_agent(&mut self, name: &str, hive: &str, custom: bool) -> Result<String> {
let name = agent::parse_ident(name, "agent name")?; let name = agent::parse_ident(name, "agent name")?;
let hive = agent::parse_ident(hive, "hive")?; let hive = agent::parse_ident(hive, "hive")?;
let resp = agent::request_create(self.target()?, &name, &hive, None)?; let archetype = (!custom).then_some("default");
let resp = agent::request_create(self.target()?, &name, &hive, archetype, None)?;
let mut said = format!( let mut said = format!(
"queued job node {} to deploy {name:?} to hive {hive:?}", "queued job node {} to deploy {name:?} to hive {hive:?}",
resp.node_id resp.node_id