From 822c8d2d0490a25bc2b1f7423c76cd4f22680240 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Thu, 26 Nov 2026 19:59:28 +0000 Subject: [PATCH 1/2] Wrap the paragraph on the boot and the sweep at 120 characters One line of the paragraph in the box documentation was longer than the line length of the documentation. --- doc/boxes.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/boxes.md b/doc/boxes.md index 6faced9..fb48482 100644 --- a/doc/boxes.md +++ b/doc/boxes.md @@ -166,10 +166,11 @@ tick. ### Boot and sweep At boot the orchestrator reconciles its rows with Docker by the `boxes.box` label: it adopts live containers, marks -missing ones as stopped, marks an interrupted create as an error, and repairs the isolation of every running box. The periodic sweep uses the same label in the opposite direction: it removes every labelled container, -network and box directory that has no live row, containers before networks. One guard: when the strays outnumber the -known boxes by a wide margin, the sweep refuses, because that pattern usually means a wrongly mounted data volume rather -than real garbage. The sweep removes login containers by age. +missing ones as stopped, marks an interrupted create as an error, and repairs the isolation of every running box. The +periodic sweep uses the same label in the opposite direction: it removes every labelled container, network and box +directory that has no live row, containers before networks. One guard: when the strays outnumber the known boxes by a +wide margin, the sweep refuses, because that pattern usually means a wrongly mounted data volume rather than real +garbage. The sweep removes login containers by age. ### The subnet pool From dac4905315e91d9ac09811dbaa559d946f5f75c6 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Thu, 26 Nov 2026 19:59:32 +0000 Subject: [PATCH 2/2] Let a box select an ordered list of agent sets and change it later A box selected one agent set when it was created, and the selection could not change. A box now has an ordered list of named sets, which the user selects in the create form and changes on the details page of the box. The orchestrator merges the sets over the global set in the order of the list, so a later set replaces skills and MCP servers with the same name from the global set or an earlier set. A change applies at the next start of the box, and the egress proxy allows the MCP hosts of a new set at once. The list cannot name the global set, because every box gets it. A migration moves the set of each box into the new table box_agent_sets. The API changed. POST /api/boxes takes agentSets instead of agentSet, PUT /api/boxes/:id/agent-sets is new, and BoxDetail has agentSets instead of agentSetId and agentSetName. --- dashboard/e2e/agents.test.ts | 81 ++++++++++-- dashboard/e2e/dialogs.test.ts | 2 +- dashboard/e2e/orchestrator.ts | 4 +- dashboard/src/api.ts | 12 ++ dashboard/src/components/AgentSetPicker.tsx | 88 +++++++++++++ dashboard/src/views/BoxCreate.tsx | 30 ++--- dashboard/src/views/BoxInfo.tsx | 50 +++++++- doc/agent-sets.md | 41 +++--- doc/boxes.md | 7 +- doc/glossary.md | 2 +- doc/rest.md | 15 ++- orchestrator/src/agents.test.ts | 109 ++++++++++------ orchestrator/src/agents.ts | 130 ++++++++++++-------- orchestrator/src/app.test.ts | 65 +++++++++- orchestrator/src/app.ts | 12 +- orchestrator/src/bodies.ts | 10 +- orchestrator/src/boxes.ts | 100 +++++++++------ orchestrator/src/db.test.ts | 42 +++++-- orchestrator/src/db.ts | 18 ++- orchestrator/src/gateway/upstream.test.ts | 2 +- shared/types.ts | 26 ++-- 21 files changed, 631 insertions(+), 215 deletions(-) create mode 100644 dashboard/src/components/AgentSetPicker.tsx diff --git a/dashboard/e2e/agents.test.ts b/dashboard/e2e/agents.test.ts index 4148c71..b0feda8 100644 --- a/dashboard/e2e/agents.test.ts +++ b/dashboard/e2e/agents.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeAll, beforeEach, expect, test } from 'vitest'; import { closeBrowser, openPage, shoot } from './browser.ts'; -import { startOrchestrator, type TestOrchestrator } from './orchestrator.ts'; +import { DEFAULT_BOX, startOrchestrator, type TestOrchestrator } from './orchestrator.ts'; /** The orchestrator that the tests in this file share. */ let stub: TestOrchestrator; @@ -144,17 +144,80 @@ test('a SKILL.md with no front matter is called out before it is saved', async ( } }); -test('a box is created against a named set, and the global one is not offered', async () => { - const { page, close } = await openPage(stub.url, '/new'); +test('a box is created with named sets, and the global one is not offered', async () => { + const { page, errors, close } = await openPage(stub.url, '/new'); try { - await expect.poll(() => page.getByLabel('Agent set').isVisible()).toBe(true); + const add = page.getByRole('combobox', { name: 'Add an agent set' }); + await expect.poll(() => add.isVisible()).toBe(true); await page.getByLabel('Name').fill('a new box'); - await page.getByLabel('Agent set').click(); + await add.click(); // The global set always applies, so it is not an option. - expect(await page.getByRole('option').allInnerTexts()).toEqual([ - 'Global set only', - 'Go projects', - ]); + expect(await page.getByRole('option').allInnerTexts()).toEqual(['Go projects']); + await page.getByRole('option', { name: 'Go projects' }).click(); + await expect.poll(() => page.getByRole('listitem').allInnerTexts()).toEqual(['Go projects']); + + await page.getByRole('button', { name: 'Create' }).click(); + await expect.poll(() => stub.boxCalls.length).toBe(1); + expect(stub.boxCalls[0]).toMatchObject({ name: 'a new box', agentSets: ['as1'] }); + expect(errors).toEqual([]); + } finally { + await close(); + } +}); + +test('the box details page adds and removes the agent sets of the box', async () => { + const res = await fetch(`${stub.url}/api/agent-sets`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ name: 'Web' }), + }); + const web = ((await res.json()) as { id: string }).id; + const { page, errors, close } = await openPage(stub.url, `/boxes/${DEFAULT_BOX.id}/info`); + try { + const add = page.getByRole('combobox', { name: 'Add an agent set' }); + await expect.poll(() => page.getByText('Global set only').isVisible()).toBe(true); + + /** + * Changes the sets with one action and gives the body of the request. + * + * @param action The action in the page. + * @returns The JSON body of the PUT request. + */ + const change = async (action: () => Promise): Promise => { + const put = page.waitForRequest( + (req) => + req.method() === 'PUT' && req.url().endsWith(`/api/boxes/${DEFAULT_BOX.id}/agent-sets`), + ); + await action(); + return (await put).postDataJSON(); + }; + + expect( + await change(async () => { + await add.click(); + await page.getByRole('option', { name: 'Go projects' }).click(); + }), + ).toEqual({ agentSets: ['as1'] }); + await expect.poll(() => page.getByRole('listitem').allInnerTexts()).toEqual(['Go projects']); + + // A new set goes to the end of the list. + expect( + await change(async () => { + await add.click(); + await page.getByRole('option', { name: 'Web' }).click(); + }), + ).toEqual({ agentSets: ['as1', web] }); + await expect + .poll(() => page.getByRole('listitem').allInnerTexts()) + .toEqual(['Go projects', 'Web']); + // Each set is in the list, so the page offers no more sets. + await expect.poll(() => add.count()).toBe(0); + + expect( + await change(() => page.getByRole('button', { name: 'Remove Go projects' }).click()), + ).toEqual({ agentSets: [web] }); + await expect.poll(() => page.getByRole('listitem').allInnerTexts()).toEqual(['Web']); + expect(errors).toEqual([]); } finally { await close(); } diff --git a/dashboard/e2e/dialogs.test.ts b/dashboard/e2e/dialogs.test.ts index 3206b54..f4e8473 100644 --- a/dashboard/e2e/dialogs.test.ts +++ b/dashboard/e2e/dialogs.test.ts @@ -104,7 +104,7 @@ test('the new-box form creates the box and its first thread in one request', asy await expect.poll(() => stub.boxCalls.length).toBe(1); expect(stub.boxCalls[0]).toEqual({ name: 'second box', - agentSet: null, + agentSets: [], // The form preselects the default profile. The orchestrator makes its id. egressProfile: expect.stringMatching(/^ep[0-9a-f]{10}$/), thread: { diff --git a/dashboard/e2e/orchestrator.ts b/dashboard/e2e/orchestrator.ts index 1608c19..9ccb3f8 100644 --- a/dashboard/e2e/orchestrator.ts +++ b/dashboard/e2e/orchestrator.ts @@ -824,9 +824,9 @@ function createBox( const now = Date.now(); // A set ready_at marks the setup as done, so a start of the box runs no setup. db.prepare( - `INSERT INTO boxes (id, name, profile, review_base_rev, status, agent_set_id, ws_token, + `INSERT INTO boxes (id, name, profile, review_base_rev, status, ws_token, created_at, last_active_at, ready_at) - VALUES (?, ?, 'DEFAULT', NULL, ?, NULL, ?, ?, ?, ?)`, + VALUES (?, ?, 'DEFAULT', NULL, ?, ?, ?, ?, ?)`, ).run(id, spec.name ?? DEFAULT_BOX.name, spec.status ?? 'running', WS_TOKEN, now, now, now); ws.createWorkspace(cfg.DATA_DIR, id); diff --git a/dashboard/src/api.ts b/dashboard/src/api.ts index 624b1d7..782123b 100644 --- a/dashboard/src/api.ts +++ b/dashboard/src/api.ts @@ -333,6 +333,18 @@ export const api = { */ deleteReview: (id: string) => request(`/api/boxes/${id}/review`, { method: 'DELETE' }), + /** + * Selects the agent sets of a box. + * + * @param id The id of the box. + * @param agentSets The ids of the sets in the order of the merge, or an empty list for the global set only. + * @returns The box after the change. + */ + setBoxAgentSets: (id: string, agentSets: string[]) => + request(`/api/boxes/${id}/agent-sets`, { + method: 'PUT', + body: JSON.stringify({ agentSets }), + }), /** * Selects the egress profile of a box. * diff --git a/dashboard/src/components/AgentSetPicker.tsx b/dashboard/src/components/AgentSetPicker.tsx new file mode 100644 index 0000000..bf7ff7a --- /dev/null +++ b/dashboard/src/components/AgentSetPicker.tsx @@ -0,0 +1,88 @@ +import { X } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import type { AgentSetSummary } from '../../../shared/types.ts'; + +/** + * Selects the agent sets of a box as a list in the order of selection. A new set goes to the end of the list, so the + * user changes the order by removing a set and adding it again. + * + * @param sets The named sets of the user, without the global set. + * @param value The ids of the selected sets, in the order of the merge. + * @param onChange Receives the new list of ids after each change. + * @param disabled Disables all controls, for example while a request runs. + * @param id The id of the select that adds a set, for a label. + */ +export function AgentSetPicker({ + sets, + value, + onChange, + disabled = false, + id, +}: { + sets: AgentSetSummary[]; + value: string[]; + onChange: (ids: string[]) => void; + disabled?: boolean; + id?: string; +}) { + const selected = value + .map((setId) => sets.find((s) => s.id === setId)) + .filter((s): s is AgentSetSummary => s !== undefined); + const available = sets.filter((s) => !value.includes(s.id)); + + return ( +
+ {selected.length === 0 ? ( +

Global set only

+ ) : ( +
    + {selected.map((s) => ( +
  1. + {s.name} + +
  2. + ))} +
+ )} + {available.length > 0 ? ( + // The empty value keeps the placeholder after each selection. + + ) : null} + {selected.length > 1 ? ( +

+ A later set replaces skills and MCP servers with the same name from an earlier set. +

+ ) : null} +
+ ); +} diff --git a/dashboard/src/views/BoxCreate.tsx b/dashboard/src/views/BoxCreate.tsx index e103b4a..343eea3 100644 --- a/dashboard/src/views/BoxCreate.tsx +++ b/dashboard/src/views/BoxCreate.tsx @@ -1,5 +1,6 @@ import { type FormEvent, useEffect, useState } from 'react'; import { Link, useNavigate } from 'react-router'; +import { AgentSetPicker } from '@/components/AgentSetPicker'; import { Notice } from '@/components/Notice'; import { ThreadOptions, useThreadOptions } from '@/components/ThreadOptions'; import { Button } from '@/components/ui/button'; @@ -17,9 +18,6 @@ import type { AgentSetSummary, EgressProfileSummary } from '../../../shared/type import { api } from '../api.ts'; import { refresh } from '../stores/boxes.ts'; -/** Picker value for no extra set. The form sends it as null. */ -const NO_SET = 'none'; - /** Form that creates a box and then opens its first thread. */ export function BoxCreate() { const navigate = useNavigate(); @@ -33,7 +31,8 @@ export function BoxCreate() { * Null while loading. The form hides the picker while the list is null or empty. */ const [agentSets, setAgentSets] = useState(null); - const [agentSet, setAgentSet] = useState(NO_SET); + /** The ids of the selected sets, in the order of the merge. */ + const [selectedSets, setSelectedSets] = useState([]); /** The egress profiles. Null while loading. The form hides the select while null. */ const [profiles, setProfiles] = useState(null); /** The id of the selected profile. The empty string sends null, so the box uses the default profile. */ @@ -70,7 +69,7 @@ export function BoxCreate() { try { const created = await api.createBox({ name: name.trim(), - agentSet: agentSet === NO_SET ? null : agentSet, + agentSets: selectedSets, egressProfile: profile === '' ? null : profile, ...(thread.value ? { thread: thread.value } : {}), }); @@ -105,20 +104,13 @@ export function BoxCreate() { {agentSets && agentSets.length > 0 ? (
- - + +

Merged over the global AGENTS.md and skills, which every box gets.{' '} diff --git a/dashboard/src/views/BoxInfo.tsx b/dashboard/src/views/BoxInfo.tsx index 8b57099..2681dc2 100644 --- a/dashboard/src/views/BoxInfo.tsx +++ b/dashboard/src/views/BoxInfo.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useState } from 'react'; import { Link, useNavigate, useParams } from 'react-router'; +import { AgentSetPicker } from '@/components/AgentSetPicker'; import { BackLink } from '@/components/BackLink'; import { boxBadges } from '@/components/BoxCard'; import { BoxWorkList } from '@/components/BoxWorkList'; @@ -19,7 +20,12 @@ import { import { useUp } from '@/hooks/use-up'; import { pollWhileVisible } from '@/lib/poll'; import { shortSize } from '@/lib/rough'; -import type { BoxDetail, EgressDenial, EgressProfileSummary } from '../../../shared/types.ts'; +import type { + AgentSetSummary, + BoxDetail, + EgressDenial, + EgressProfileSummary, +} from '../../../shared/types.ts'; import { api } from '../api.ts'; import { refresh } from '../stores/boxes.ts'; @@ -56,6 +62,8 @@ export function BoxInfo() { const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [confirmDelete, setConfirmDelete] = useState(false); + /** The named agent sets, for the picker. Null while loading or when the request failed. */ + const [agentSets, setAgentSets] = useState(null); /** The egress profiles, for the select. Null while loading or when the request failed. */ const [profiles, setProfiles] = useState(null); /** The targets that the egress profile refused. Null while loading or when the request failed. */ @@ -87,6 +95,13 @@ export function BoxInfo() { }, [load]); useEffect(() => { + void (async () => { + try { + setAgentSets((await api.listAgentSets()).filter((s) => !s.global)); + } catch { + // Without the list, the page shows the names of the sets without the picker. + } + })(); void (async () => { try { setProfiles(await api.listEgressProfiles()); @@ -173,8 +188,6 @@ export function BoxInfo() { {box.runtimeDetails.map(([label, value]) => ( ))} - {/* Every box gets the global set, so a box without a named set shows "global only". */} - {/* Null before the first measurement. */} + + + Agent sets + + + {agentSets ? ( +

+ s.id)} + disabled={busy} + onChange={(ids) => void act(() => api.setBoxAgentSets(id, ids))} + /> +

+ A change applies at the next start of the box.{' '} + + Edit the sets + + . +

+
+ ) : ( +

+ {box.agentSets.length > 0 + ? box.agentSets.map((s) => s.name).join(', ') + : 'Global set only'} +

+ )} + + + Egress diff --git a/doc/agent-sets.md b/doc/agent-sets.md index f583c7e..43cf0c2 100644 --- a/doc/agent-sets.md +++ b/doc/agent-sets.md @@ -13,25 +13,24 @@ use. The global set applies to every box of its owner, and the user cannot delet More sets can be added in the dashboard. A set has a display name, an optional `AGENTS.md`, any number of skills, and up to 20 MCP servers. -A set is selected when a [box is created](boxes.md). The selection is stored with the box and cannot change later. A box -that selects no set gets the global set alone. Naming the global set is the same as naming nothing. +A box has an ordered list of named sets. The user selects the list when the [box is created](boxes.md), and can change +it on the details page of the box. A new set goes to the end of the list. To change the order, the user removes a set +and adds it again. The global set is never in the list, because every box gets it. A box with an empty list gets the +global set alone. ## Merging -A box always gets the global set. When another set is selected, the orchestrator merges the two. The two kinds of -content merge differently: +A box always gets the global set. The orchestrator merges the sets of the list over the global set, in the order of the +list. The kinds of content merge differently: -- The `AGENTS.md` files are concatenated: the global one first, the selected set's one after it, separated by a blank - line. -- A skill is addressed by its name. When two skills have the same name, one wins. The order, highest first: - 1. a skill of the selected set - 2. a skill from a repository of the selected set, in the order of the repository list - 3. a skill of the global set - 4. a skill from a repository of the global set, in the order of the repository list -- An MCP server is addressed by its name. An MCP server of the selected set replaces an MCP server of the global set - with the same name. +- The `AGENTS.md` files are joined in the order of the merge, with a blank line between two files. +- A skill is addressed by its name. A skill of a set replaces a skill with the same name of the global set or of an + earlier set. Inside one set, a skill of the set replaces a skill from its repositories. A skill from an earlier + repository of the set replaces a skill from a later repository. +- An MCP server is addressed by its name. An MCP server of a set replaces an MCP server with the same name of the global + set or of an earlier set. -The editor of a named set shows the merged result under "Merged result". +The editor of a named set shows the merge of the global set and this set under "Merged result". ## Skills @@ -102,12 +101,13 @@ At each box start, the [file service](files.md) in the box installs the merged s The practical effects: -- Changes to a set reach a box the next time the box starts. A running box keeps what it has. A new secret or a new - OAuth login of an MCP server applies without a restart of the box. +- Changes to a set and changes to the list of a box reach the box the next time the box starts. A running box keeps + what it has. A new secret or a new OAuth login of an MCP server applies without a restart of the box. The egress + proxy allows the hosts of the MCP servers of a newly selected set at once. - An item deleted from a set is removed from the box at the next start. A built-in skill whose condition no longer holds is removed in the same way. -- When a set is deleted, the boxes that selected it keep what is already installed, and get the global set alone at the - next start. +- When a set is deleted, the orchestrator removes it from the list of each box. A box keeps what is already installed, + and gets the other sets of its list at the next start. ## Managing sets @@ -155,8 +155,9 @@ managed file cannot name `.ssh` or all of `.claude`. ### Deleting a set -The box's `agent_set_id` column references the set with `ON DELETE SET NULL`, and the set's items and repositories are -deleted with it, together with the repository checkouts. +The `box_agent_sets` table holds the list of each box, with the position of each set. Its rows reference the box and +the set with `ON DELETE CASCADE`. The items and the repositories of a set are deleted with the set, together with the +repository checkouts. ### MCP servers diff --git a/doc/boxes.md b/doc/boxes.md index fb48482..d038146 100644 --- a/doc/boxes.md +++ b/doc/boxes.md @@ -8,7 +8,8 @@ network. The [glossary](glossary.md) defines these terms. Select **New** on the box list. The form asks for: - a name (100 characters or fewer), -- an optional agent set, merged over the global set (see [agent sets](agent-sets.md)), +- an optional list of agent sets, merged over the global set in the order of the list (see + [agent sets](agent-sets.md)), - the [egress profile](egress-profiles.md), with the default profile preselected, - the agent and settings of the first [thread](threads.md). @@ -39,8 +40,8 @@ The info icon on a card opens the box's details page. ## Box details The details page shows the box's identity and runtime state: the facts of the runtime (on Docker the container id, the -network name with its subnet, and the image id), agent set, last activity, disk use, and the ACP session id of the most -recently active thread. It shows the egress profile of the box, which the user can change there, and the +network name with its subnet, and the image id), last activity, disk use, and the ACP session id of the most recently +active thread. It shows the agent sets and the egress profile of the box, which the user can change there, and the [refused hosts](egress-profiles.md#refused-hosts). It lists the dev tunnels the box hosts and the processes the orchestrator last read in the box. For a running box whose network isolation is not complete, it shows a warning. diff --git a/doc/glossary.md b/doc/glossary.md index 435cb1a..84f35de 100644 --- a/doc/glossary.md +++ b/doc/glossary.md @@ -26,7 +26,7 @@ volume. **[Agent set](agent-sets.md)** -A named collection of agent instructions, skills, and remote MCP servers. The orchestrator gives the selected set to +A named collection of agent instructions, skills, and remote MCP servers. The orchestrator gives the selected sets to each box when the box starts. **Harness** diff --git a/doc/rest.md b/doc/rest.md index eb499f4..213e7db 100644 --- a/doc/rest.md +++ b/doc/rest.md @@ -38,6 +38,7 @@ adapter's last advertised modes and config options (when one has answered), and | POST | `/api/boxes/:id/start` | `BoxDetail` | | POST | `/api/boxes/:id/stop` | `BoxDetail` | | DELETE | `/api/boxes/:id` | 204 | +| PUT | `/api/boxes/:id/agent-sets` | `BoxDetail` | | PUT | `/api/boxes/:id/egress-profile` | `BoxDetail` | | GET | `/api/boxes/:id/denials` | `EgressDenial[]` | @@ -46,16 +47,20 @@ adapter's last advertised modes and config options (when one has answered), and ```json { "name": "my-box", - "agentSet": "set-id-or-null", + "agentSets": ["set-id"], "egressProfile": "profile-id-or-null", "thread": { "harness": "claude", "modeId": "…", "config": { } } } ``` Every [box](boxes.md) is created with one thread. `thread` selects its harness and its initial mode and config; absent, -it is Claude on its defaults. `profile` is accepted but ignored. An unknown `agentSet` or `egressProfile` gets a 400. +it is Claude on its defaults. `profile` is accepted but ignored. An unknown `egressProfile` gets a 400. -`PUT …/egress-profile` accepts `{ "egressProfile": "…" }`, or null for the default profile. `GET …/denials` answers the +`agentSets` lists the [agent sets](agent-sets.md) of the box in the order of the merge. An absent or empty list selects +the global set only. A list with the global set, an unknown set, or one set twice gets a 400. + +`PUT …/agent-sets` accepts `{ "agentSets": [...] }` with the same rules. `PUT …/egress-profile` accepts +`{ "egressProfile": "…" }`, or null for the default profile. `GET …/denials` answers the [refused hosts](egress-profiles.md#refused-hosts) from the proxy, and a 502 when the proxy does not answer. ## Threads @@ -172,8 +177,8 @@ one callback for each login, in the 10 minutes after the connect. `POST …/repos` accepts an `AgentRepoBody` with `url` and an optional `ref`, adds the repository, and pulls it. A failed pull is not an error of the request: the set's `repos` list shows it. `POST …/pull` pulls the repository again. -The preview answers what a box that selects this [agent set](agent-sets.md) receives: the global set, with this set laid -over it. Each skill in `skills` names the repository it comes from, or `null`. +The preview answers what a box that selects only this [agent set](agent-sets.md) receives: the global set, with this +set laid over it. Each skill in `skills` names the repository it comes from, or `null`. ## Egress profiles diff --git a/orchestrator/src/agents.test.ts b/orchestrator/src/agents.test.ts index b397f84..e006a9c 100644 --- a/orchestrator/src/agents.test.ts +++ b/orchestrator/src/agents.test.ts @@ -73,11 +73,11 @@ afterEach(() => { /** * Packs a set and reads the tar back. It fails when the tar holds a path more than once. * - * @param setId The id of the selected set, or null for only the global set. + * @param setIds The ids of the selected sets, in the order of the merge. * @returns The content and the mode of each file, by its path relative to the home. */ async function packed( - setId: string | null, + setIds: readonly string[], ): Promise> { const files = new Map(); const twice: string[] = []; @@ -97,7 +97,7 @@ async function packed( await new Promise((resolve, reject) => { entries.on('finish', resolve); entries.on('error', reject); - store.pack('', setId).pipe(entries); + store.pack('', setIds).pipe(entries); }); assert.deepEqual(twice, [], 'paths packed more than once'); return files; @@ -106,24 +106,25 @@ async function packed( /** * Packs a set and lists its paths. * - * @param setId The id of the selected set, or null for only the global set. + * @param setIds The ids of the selected sets, in the order of the merge. * @returns The paths relative to the home, sorted. */ -async function paths(setId: string | null): Promise { - return [...(await packed(setId)).keys()].sort(); +async function paths(setIds: readonly string[]): Promise { + return [...(await packed(setIds)).keys()].sort(); } /** * Inserts a running box row with the columns that the box count of a set reads. * * @param id The id of the box. - * @param agentSetId The id of the set that the box selected, or null. + * @param agentSetIds The ids of the sets that the box selected. */ -function insertBox(id: string, agentSetId: string | null): void { +function insertBox(id: string, agentSetIds: readonly string[]): void { db.prepare( - `INSERT INTO boxes (id, name, profile, status, agent_set_id, created_at, last_active_at) - VALUES (?, 'test', 'DEFAULT', 'running', ?, 0, 0)`, - ).run(id, agentSetId); + `INSERT INTO boxes (id, name, profile, status, created_at, last_active_at) + VALUES (?, 'test', 'DEFAULT', 'running', 0, 0)`, + ).run(id); + store.selectForBox(id, agentSetIds); } test('the global set exists from the first boot and cannot be deleted', () => { @@ -178,11 +179,52 @@ test('skills are a union, and the set wins a name clash', async () => { // `overrides` names the global skill that the set replaces. assert.deepEqual(bundle.overrides, ['review']); assert.equal( - (await packed(set.id)).get('.claude/skills/review/SKILL.md')?.content, + (await packed([set.id])).get('.claude/skills/review/SKILL.md')?.content, 'go review\n', ); }); +test('several sets merge in the order of the list, and a later set wins', async () => { + store.updateSet('', 'global', { agentsMd: 'House rules.' }); + store.putItem('', 'global', { name: 'review', content: 'global review' }); + const go = store.createSet('', 'go'); + store.updateSet('', go.id, { agentsMd: 'Go rules.' }); + store.putItem('', go.id, { name: 'review', content: 'go review' }); + store.putItem('', go.id, { name: 'bench', content: 'go bench' }); + const web = store.createSet('', 'web'); + store.updateSet('', web.id, { agentsMd: 'Web rules.' }); + store.putItem('', web.id, { name: 'bench', content: 'web bench' }); + + const files = await packed([go.id, web.id]); + assert.equal( + files.get('.claude/CLAUDE.md')?.content, + 'House rules.\n\nGo rules.\n\nWeb rules.\n', + ); + assert.equal(files.get('.claude/skills/review/SKILL.md')?.content, 'go review\n'); + assert.equal(files.get('.claude/skills/bench/SKILL.md')?.content, 'web bench\n'); + + const reversed = await packed([web.id, go.id]); + assert.equal( + reversed.get('.claude/CLAUDE.md')?.content, + 'House rules.\n\nWeb rules.\n\nGo rules.\n', + ); + assert.equal(reversed.get('.claude/skills/bench/SKILL.md')?.content, 'go bench\n'); +}); + +test('a box keeps its sets in the order of selection, and a new selection replaces it', () => { + const go = store.createSet('', 'go'); + const web = store.createSet('', 'web'); + insertBox('s1', [web.id, go.id]); + assert.deepEqual(store.setsOf('s1'), [ + { id: web.id, name: 'web' }, + { id: go.id, name: 'go' }, + ]); + + store.selectForBox('s1', [go.id]); + assert.deepEqual(store.setsOf('s1'), [{ id: go.id, name: 'go' }]); + assert.equal(store.getSet('', web.id).boxCount, 0); +}); + test('naming the global set as the extra one changes nothing', () => { store.putItem('', 'global', { name: 'review', content: 'x' }); assert.deepEqual(store.bundle('', 'global'), store.bundle('', null)); @@ -194,7 +236,7 @@ test('a merged set is packed in every harness layout', async () => { const set = store.createSet('', 'go'); store.putItem('', set.id, { name: 'bench', content: 'Run the benchmarks.' }); - const files = await packed(set.id); + const files = await packed([set.id]); assert.deepEqual([...files.keys()].sort(), [ '.agents/skills/bench/SKILL.md', @@ -221,7 +263,7 @@ test('every packed path is home-relative and inside a layout', async () => { store.updateSet('', 'global', { agentsMd: 'House rules.' }); store.putItem('', 'global', { name: 'review', content: 'x' }); - for (const rel of await paths(null)) { + for (const rel of await paths([])) { assert.match( rel, /^(\.claude\/(CLAUDE\.md|skills\/)|\.codex\/AGENTS\.md|\.config\/opencode\/AGENTS\.md|\.agents\/skills\/)/, @@ -231,7 +273,7 @@ test('every packed path is home-relative and inside a layout', async () => { }); test('a box with nothing configured gets an empty set', async () => { - assert.deepEqual(await paths(null), []); + assert.deepEqual(await paths([]), []); }); test('the skills of the orchestrator are packed, and a skill of the set wins', async () => { @@ -242,13 +284,13 @@ test('the skills of the orchestrator are packed, and a skill of the set wins', a store = new AgentStore(db, dir, undefined, () => builtins); store.putItem('', 'global', { name: 'diagrams', content: 'own diagrams' }); - const files = await packed(null); + const files = await packed([]); assert.equal(files.get('.claude/skills/diagrams/SKILL.md')?.content, 'own diagrams\n'); assert.equal(files.get('.agents/skills/share-app/SKILL.md')?.content, 'orchestrator share-app\n'); // The next tar holds only the skills of the set, so the next install removes the built-in skills. builtins = []; - assert.deepEqual(await paths(null), [ + assert.deepEqual(await paths([]), [ '.agents/skills/diagrams/SKILL.md', '.claude/skills/diagrams/SKILL.md', ]); @@ -315,7 +357,7 @@ test('a repository skill is copied with all its files, without its links', async chmodSync(join(tree, 'scripts', 'run.sh'), 0o755); symlinkSync('/etc/passwd', join(tree, 'passwd')); - const files = await packed(null); + const files = await packed([]); assert.deepEqual([...files.keys()].sort(), [ '.agents/skills/pdf/SKILL.md', @@ -336,10 +378,7 @@ test('a skill that changes source leaves no file of the old one behind', async ( await store.addRepo('', 'global', { url: 'https://example.com/skills' }); store.putItem('', 'global', { name: 'pdf', content: 'mine' }); - assert.deepEqual(await paths(null), [ - '.agents/skills/pdf/SKILL.md', - '.claude/skills/pdf/SKILL.md', - ]); + assert.deepEqual(await paths([]), ['.agents/skills/pdf/SKILL.md', '.claude/skills/pdf/SKILL.md']); }); test('a failed pull is recorded, and the skills of the last good pull stay', async () => { @@ -351,7 +390,7 @@ test('a failed pull is recorded, and the skills of the last good pull stay', asy assert.equal(after.repos[0]!.error, 'repository not found'); assert.deepEqual(after.repos[0]!.skills, ['pdf']); - assert.equal((await packed(null)).get('.claude/skills/pdf/SKILL.md')?.content, 'pdf'); + assert.equal((await packed([])).get('.claude/skills/pdf/SKILL.md')?.content, 'pdf'); }); test('a repository that cannot be pulled at all is still added', async () => { @@ -485,23 +524,21 @@ test('an unknown set is a 404 on every route into it', () => { test('a set counts the live boxes that selected it', () => { const set = store.createSet('', 'go'); - insertBox('s1', set.id); - insertBox('s2', null); + insertBox('s1', [set.id]); + insertBox('s2', []); assert.equal(store.getSet('', set.id).boxCount, 1); }); -test('deleting a set leaves its boxes alone and falls them back to global', () => { - const set = store.createSet('', 'go'); - insertBox('s1', set.id); +test('deleting a set leaves its boxes alone and removes it from their lists', () => { + const go = store.createSet('', 'go'); + const web = store.createSet('', 'web'); + insertBox('s1', [go.id, web.id]); - store.deleteSet('', set.id); + store.deleteSet('', go.id); - const row = db.prepare('SELECT agent_set_id, status FROM boxes WHERE id = ?').get('s1') as { - agent_set_id: string | null; - status: string; - }; + const row = db.prepare('SELECT status FROM boxes WHERE id = ?').get('s1') as { status: string }; assert.equal(row.status, 'running'); - assert.equal(row.agent_set_id, null); + assert.deepEqual(store.setsOf('s1'), [{ id: web.id, name: 'web' }]); }); test('a set going away takes its skills with it', () => { @@ -832,7 +869,7 @@ test('the MCP servers of a set replace the servers of the global set with the sa assert.deepEqual(preview.mcpOverrides, ['docs']); assert.deepEqual(mcp.bundle('', null).mcpOverrides, []); assert.deepEqual( - mcp.mcpSnapshot('', set.id).map((server) => [server.setId, server.url]), + mcp.mcpSnapshot('', [set.id]).map((server) => [server.setId, server.url]), [ [set.id, 'https://docs.example.org/mcp'], [globalId, GITHUB_MCP.url], @@ -868,7 +905,7 @@ test('the secrets of an MCP server become placeholders, and a server without a s */ const placeholder = (server: string, header: string): string => rowsOf(id, server)[header]?.[1] ?? ''; - const snapshot = mcp.mcpSnapshot('', null); + const snapshot = mcp.mcpSnapshot('', []); assert.deepEqual(mcp.mcpServersFor('', snapshot), [ { diff --git a/orchestrator/src/agents.ts b/orchestrator/src/agents.ts index e8fca95..2f5023a 100644 --- a/orchestrator/src/agents.ts +++ b/orchestrator/src/agents.ts @@ -92,11 +92,11 @@ interface Bundle { agentsMd: string; /** Every skill, sorted by name. */ skills: BundleSkill[]; - /** The names of the skills in the selected set that replace a skill of the global set. */ + /** The names of the skills in the selected sets that replace a skill of the global set or of an earlier set. */ overrides: string[]; /** Every MCP server, sorted by name. */ mcpServers: McpSnapshotEntry[]; - /** The names of the MCP servers in the selected set that replace a server of the global set. */ + /** The names of the MCP servers in the selected sets that replace a server of the global set or of an earlier set. */ mcpOverrides: string[]; } @@ -339,7 +339,10 @@ export class AgentStore { .prepare('SELECT COUNT(*) AS n FROM agent_repos WHERE set_id = ?') .get(row.id) as { n: number }; const used = this.db - .prepare("SELECT COUNT(*) AS n FROM boxes WHERE agent_set_id = ? AND status != 'deleted'") + .prepare( + `SELECT COUNT(*) AS n FROM box_agent_sets JOIN boxes ON boxes.id = box_agent_sets.box_id + WHERE box_agent_sets.set_id = ? AND boxes.status != 'deleted'`, + ) .get(row.id) as { n: number }; return { id: row.id, @@ -369,17 +372,35 @@ export class AgentStore { } /** - * Gives the display name of a set. + * Gives the agent sets that a box selected, in the order of the merge. * - * @param id The id of the set, or null. - * @returns The name, or null when the id is null or the set does not exist. + * @param boxId The id of the box. + * @returns The id and the name of each set. The list is empty for the global set only. */ - nameOf(id: string | null): string | null { - if (!id) return null; - const row = this.db.prepare('SELECT name FROM agent_sets WHERE id = ?').get(id) as - | { name: string } - | undefined; - return row?.name ?? null; + setsOf(boxId: string): Array<{ id: string; name: string }> { + return this.db + .prepare( + `SELECT agent_sets.id, agent_sets.name FROM box_agent_sets + JOIN agent_sets ON agent_sets.id = box_agent_sets.set_id + WHERE box_agent_sets.box_id = ? ORDER BY box_agent_sets.position`, + ) + .all(boxId) as Array<{ id: string; name: string }>; + } + + /** + * Stores the agent sets that a box selects, and replaces the earlier selection. + * + * @param boxId The id of the box. + * @param setIds The ids of the sets, in the order of the merge, without the global set. + */ + selectForBox(boxId: string, setIds: readonly string[]): void { + const insert = this.db.prepare( + 'INSERT INTO box_agent_sets (box_id, set_id, position) VALUES (?, ?, ?)', + ); + this.db.transaction(() => { + this.db.prepare('DELETE FROM box_agent_sets WHERE box_id = ?').run(boxId); + for (const [position, setId] of setIds.entries()) insert.run(boxId, setId, position); + })(); } /** @@ -760,14 +781,17 @@ export class AgentStore { } /** - * Gives the merged set for a box, in the form that the editor shows. + * Gives the merge of one set over the global set, in the form that the editor shows. * - * @param owner The owner of the box. - * @param setId The id of the set that the box selected, or null for only the global set. + * @param owner The owner of the set. + * @param setId The id of the set, or null for only the global set. * @returns The merged AGENTS.md, the skills with their sources, and the overridden skill names. */ bundle(owner: string, setId: string | null): AgentBundlePreview { - const { agentsMd, skills, overrides, mcpServers, mcpOverrides } = this.merge(owner, setId); + const { agentsMd, skills, overrides, mcpServers, mcpOverrides } = this.merge( + owner, + setId ? [setId] : [], + ); return { agentsMd, skills: skills.map((skill) => ({ name: skill.name, repo: skill.repo })), @@ -782,11 +806,11 @@ export class AgentStore { * list until its next start. * * @param owner The owner of the box. - * @param setId The id of the set that the box selected, or null for only the global set. + * @param setIds The ids of the sets that the box selected, in the order of the merge. * @returns The servers, sorted by name. */ - mcpSnapshot(owner: string, setId: string | null): McpSnapshotEntry[] { - return this.merge(owner, setId).mcpServers; + mcpSnapshot(owner: string, setIds: readonly string[]): McpSnapshotEntry[] { + return this.merge(owner, setIds).mcpServers; } /** @@ -815,49 +839,59 @@ export class AgentStore { } /** - * Merges the selected set over the global set of the owner. + * Merges the selected sets over the global set of the owner, in the order of + * the list. * - * The merged AGENTS.md is the global AGENTS.md, then a blank line, then the - * AGENTS.md of the selected set. A skill or an MCP server of the selected set - * replaces a skill or a server of the global set with the same name. A - * selected set of another user counts as no selection. + * The merged AGENTS.md is the global AGENTS.md and the AGENTS.md of each + * selected set, joined by blank lines. A skill or an MCP server of a selected + * set replaces a skill or a server with the same name of the global set or + * of an earlier set. A selected set of another user and the global set count + * as no selection. * * @param owner The owner of the box. - * @param setId The id of the selected set, or null for only the global set. + * @param setIds The ids of the selected sets, in the order of the merge. * @returns The merged set. */ - private merge(owner: string, setId: string | null): Bundle { + private merge(owner: string, setIds: readonly string[]): Bundle { const global = this.globalRow(owner); - const extra = setId - ? (this.db - .prepare('SELECT * FROM agent_sets WHERE id = ? AND owner = ? AND global = 0') - .get(setId, owner) as AgentSetRow | undefined) - : undefined; + const select = this.db.prepare( + 'SELECT * FROM agent_sets WHERE id = ? AND owner = ? AND global = 0', + ); + const extras = setIds + .map((id) => select.get(id, owner) as AgentSetRow | undefined) + .filter((row): row is AgentSetRow => row !== undefined); - const agentsMd = [global?.agents_md ?? '', extra?.agents_md ?? ''] + const agentsMd = [global?.agents_md ?? '', ...extras.map((extra) => extra.agents_md)] .map((part) => part.trim()) .filter((part) => part !== '') .join('\n\n'); const byName = global ? this.skillsOf(global.id) : new Map(); - const overrides: string[] = []; - for (const skill of extra ? this.skillsOf(extra.id).values() : []) { - if (byName.has(skill.name)) overrides.push(skill.name); - byName.set(skill.name, skill); - } - - const skills = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); - + const overrides = new Set(); const servers = new Map( (global ? this.mcpServers(global.id) : []).map((server) => [server.name, server]), ); - const mcpOverrides: string[] = []; - for (const server of extra ? this.mcpServers(extra.id) : []) { - if (servers.has(server.name)) mcpOverrides.push(server.name); - servers.set(server.name, server); + const mcpOverrides = new Set(); + for (const extra of extras) { + for (const skill of this.skillsOf(extra.id).values()) { + if (byName.has(skill.name)) overrides.add(skill.name); + byName.set(skill.name, skill); + } + for (const server of this.mcpServers(extra.id)) { + if (servers.has(server.name)) mcpOverrides.add(server.name); + servers.set(server.name, server); + } } + + const skills = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); const mcpServers = [...servers.values()].sort((a, b) => a.name.localeCompare(b.name)); - return { agentsMd, skills, overrides, mcpServers, mcpOverrides }; + return { + agentsMd, + skills, + overrides: [...overrides], + mcpServers, + mcpOverrides: [...mcpOverrides], + }; } /** @@ -894,11 +928,11 @@ export class AgentStore { * skill with the same name. * * @param owner The owner of the box. - * @param setId The id of the set that the box selected, or null for only the global set. + * @param setIds The ids of the sets that the box selected, in the order of the merge. * @returns The tar stream. */ - pack(owner: string, setId: string | null): Readable { - const bundle = this.merge(owner, setId); + pack(owner: string, setIds: readonly string[]): Readable { + const bundle = this.merge(owner, setIds); const names = new Set(bundle.skills.map((skill) => skill.name)); for (const skill of this.builtins(owner)) { if (!names.has(skill.name)) diff --git a/orchestrator/src/app.test.ts b/orchestrator/src/app.test.ts index 01d3a3e..197a8a2 100644 --- a/orchestrator/src/app.test.ts +++ b/orchestrator/src/app.test.ts @@ -829,6 +829,69 @@ test('a set is created, filled and read back over the API', async () => { ); }); +test('a box changes its agent sets over the API', async () => { + insertBox('abc123'); + fakeDocker(); + /** + * Creates a named set. + * + * @param name The name of the set. + * @returns The id of the set. + */ + const create = async (name: string): Promise => + ( + ( + await orchestrator.app.inject({ method: 'POST', url: '/api/agent-sets', payload: { name } }) + ).json() as { id: string } + ).id; + const go = await create('Go projects'); + const web = await create('Web'); + /** + * Selects the agent sets of the box. + * + * @param agentSets The ids of the sets. + * @param box The id of the box. + * @returns The response. + */ + const select = (agentSets: string[], box = 'abc123') => + orchestrator.app.inject({ + method: 'PUT', + url: `/api/boxes/${box}/agent-sets`, + payload: { agentSets }, + }); + + const selected = await select([web, go]); + assert.equal(selected.statusCode, 200); + assert.deepEqual(selected.json().agentSets, [ + { id: web, name: 'Web' }, + { id: go, name: 'Go projects' }, + ]); + const listed = await orchestrator.app.inject({ url: '/api/agent-sets' }); + assert.deepEqual( + (listed.json() as Array<{ id: string; boxCount: number }>).map((s) => [s.id, s.boxCount]), + [ + ['global', 0], + [go, 1], + [web, 1], + ], + ); + + const none = await select([]); + assert.equal(none.statusCode, 200); + assert.deepEqual(none.json().agentSets, []); + + const unknown = await select(['nope']); + assert.equal(unknown.statusCode, 400); + assert.match((unknown.json() as { error: string }).error, /Unknown agent set/); + const global = await select(['global']); + assert.equal(global.statusCode, 400); + assert.match((global.json() as { error: string }).error, /global set/); + const twice = await select([go, go]); + assert.equal(twice.statusCode, 400); + assert.match((twice.json() as { error: string }).error, /selected twice/); + assert.equal((await select([], 'nope')).statusCode, 404); +}); + test('the preview shows the merge, overrides named', async () => { await orchestrator.app.inject({ method: 'PATCH', @@ -942,7 +1005,7 @@ test('creating a box against an unknown set is refused before anything is built' const res = await orchestrator.app.inject({ method: 'POST', url: '/api/boxes', - payload: { name: 'a box', agentSet: 'nope' }, + payload: { name: 'a box', agentSets: ['nope'] }, }); assert.equal(res.statusCode, 400); assert.match((res.json() as { error: string }).error, /Unknown agent set/); diff --git a/orchestrator/src/app.ts b/orchestrator/src/app.ts index ad86c63..fb28e71 100644 --- a/orchestrator/src/app.ts +++ b/orchestrator/src/app.ts @@ -30,6 +30,7 @@ import { agentMcpServerBody, agentRepoBody, backgroundStopBody, + boxAgentSetsBody, boxEgressProfileBody, createAgentSetBody, createBoxBody, @@ -375,7 +376,10 @@ export function buildApp(cfg: Config, db: Db, opts: BuildOptions = {}): Orchestr const rows = db.prepare("SELECT * FROM boxes WHERE status != 'deleted'").all() as BoxRow[]; return rows.map((row) => { const profile = profiles.forBox(row.owner, row.egress_profile_id); - const servers = agents.mcpSnapshot(row.owner, row.agent_set_id); + const servers = agents.mcpSnapshot( + row.owner, + agents.setsOf(row.id).map((set) => set.id), + ); return { id: row.id, owner: row.owner, @@ -717,6 +721,12 @@ export function buildApp(cfg: Config, db: Db, opts: BuildOptions = {}): Orchestr return reply.code(204).send(); }); + app.put('/api/boxes/:id/agent-sets', async (req) => { + const { id } = req.params as { id: string }; + const body = parseBody(boxAgentSetsBody, req.body); + return manager.setAgentSets(id, body.agentSets); + }); + app.put('/api/boxes/:id/egress-profile', async (req) => { const { id } = req.params as { id: string }; const body = parseBody(boxEgressProfileBody, req.body); diff --git a/orchestrator/src/bodies.ts b/orchestrator/src/bodies.ts index 97f23ca..ba09554 100644 --- a/orchestrator/src/bodies.ts +++ b/orchestrator/src/bodies.ts @@ -48,7 +48,7 @@ const threadOptions = z.object({ export const createBoxBody = z.object({ name: z.string(), profile: z.string().optional(), - agentSet: z.string().nullable().optional(), + agentSets: z.array(z.string()).optional(), egressProfile: z.string().nullable().optional(), thread: threadOptions.optional(), }); @@ -61,6 +61,14 @@ export const boxEgressProfileBody = z.object({ egressProfile: z.string().nullable(), }); +/** + * The body of PUT /api/boxes/:id/agent-sets, with the agent sets of the box in + * the order of the merge. An empty list selects the global set only. + */ +export const boxAgentSetsBody = z.object({ + agentSets: z.array(z.string()), +}); + /** The body of POST /api/boxes/:id/threads, with the thread to add. */ export const createThreadBody = z.object({ from: z.string().optional(), diff --git a/orchestrator/src/boxes.ts b/orchestrator/src/boxes.ts index 7187efe..966550b 100644 --- a/orchestrator/src/boxes.ts +++ b/orchestrator/src/boxes.ts @@ -1,15 +1,14 @@ import { randomBytes } from 'node:crypto'; import type { McpServer } from '@agentclientprotocol/sdk'; -import { - type BoxDetail, - type BoxSummary, - type BoxTunnel, - type CreateBoxBody, - type CreateThreadBody, - GLOBAL_AGENT_SET, - type HarnessId, - type ThreadOptions, - type ThreadSummary, +import type { + BoxDetail, + BoxSummary, + BoxTunnel, + CreateBoxBody, + CreateThreadBody, + HarnessId, + ThreadOptions, + ThreadSummary, } from '../../shared/types.ts'; import type { AgentStore } from './agents.ts'; import { boxEnv } from './boxenv.ts'; @@ -468,18 +467,7 @@ export class BoxManager { if (!name) throw new HttpError(400, 'name is required'); if (name.length > 100) throw new HttpError(400, 'name must be 100 characters or fewer'); - // Each box gets the global set of its owner, so a request that names it is - // the same as a request without a set, and the row stores null. - const requested = body.agentSet?.trim() ?? ''; - const agentSetId = - requested === '' || - requested === GLOBAL_AGENT_SET || - requested === this.agents.globalId(owner) - ? null - : requested; - if (agentSetId && !this.agents.has(owner, agentSetId)) { - throw new HttpError(400, `Unknown agent set: ${agentSetId}`); - } + const agentSetIds = this.selectedAgentSets(owner, body.agentSets); const egressProfileId = this.selectedProfile(owner, body.egressProfile); // The check comes before any allocation, so an unknown harness gets a 400 @@ -510,7 +498,6 @@ export class BoxManager { // compares each repository with its own HEAD. review_base_rev: null, status: 'creating', - agent_set_id: agentSetId, // The box has its own token, which opens only the WebSocket of this box. ws_token: generateWsToken(), egress_profile_id: egressProfileId, @@ -523,14 +510,17 @@ export class BoxManager { mcp_servers: '[]', }; - this.db - .prepare( - `INSERT INTO boxes (id, name, owner, profile, status, agent_set_id, - ws_token, egress_profile_id, proxy_token, created_at, last_active_at) - VALUES (@id, @name, @owner, @profile, @status, @agent_set_id, - @ws_token, @egress_profile_id, @proxy_token, @created_at, @last_active_at)`, - ) - .run(row); + this.db.transaction(() => { + this.db + .prepare( + `INSERT INTO boxes (id, name, owner, profile, status, + ws_token, egress_profile_id, proxy_token, created_at, last_active_at) + VALUES (@id, @name, @owner, @profile, @status, + @ws_token, @egress_profile_id, @proxy_token, @created_at, @last_active_at)`, + ) + .run(row); + this.agents.selectForBox(id, agentSetIds); + })(); // The proxy must know the box before the box makes its first request. await this.syncEgress(); @@ -557,6 +547,46 @@ export class BoxManager { return this.detail(id); } + /** + * Checks the agent sets that a request selects for a box of a user. Each box + * gets the global set of its owner, so the list cannot name it. + * + * @param owner The owner of the box. + * @param requested The ids of the sets in the order of the merge, or undefined for the global set only. + * @returns The ids to store. + * @throws {HttpError} A 400 when an id names the global set, when the user has no set with an id, or when an id is in + * the list twice. + */ + private selectedAgentSets(owner: string, requested: readonly string[] | undefined): string[] { + const ids: string[] = []; + for (const id of requested ?? []) { + if (id === this.agents.globalId(owner)) { + throw new HttpError(400, 'The global set applies to every box and cannot be selected'); + } + if (!this.agents.has(owner, id)) throw new HttpError(400, `Unknown agent set: ${id}`); + if (ids.includes(id)) throw new HttpError(400, `Agent set selected twice: ${id}`); + ids.push(id); + } + return ids; + } + + /** + * Selects the agent sets of a box. The box gets the files and the MCP + * servers of the sets at its next start. The egress proxy allows the hosts + * of the MCP servers of the sets at once. + * + * @param id The id of the box. + * @param requested The ids of the sets in the order of the merge. An empty list selects the global set only. + * @returns The detail of the box. + * @throws {HttpError} A 404 when the box does not exist, or a 400 when the list is not valid. + */ + async setAgentSets(id: string, requested: readonly string[]): Promise { + const row = this.mustGet(id); + this.agents.selectForBox(id, this.selectedAgentSets(row.owner, requested)); + void this.syncEgress(); + return this.detail(id); + } + /** * Checks the egress profile that a request selects for a box of a user. * @@ -718,14 +748,15 @@ export class BoxManager { const slog = log.box(row.id); const settings = readSettings(this.db, row.owner); // The adapters read the row, so a change to a set applies at the next start. - const mcpServers = this.agents.mcpSnapshot(row.owner, row.agent_set_id); + const agentSetIds = this.agents.setsOf(row.id).map((set) => set.id); + const mcpServers = this.agents.mcpSnapshot(row.owner, agentSetIds); try { await setUpBox( row.id, { caCertificate: this.egress.caCertificate(), identity: { gitName: settings.gitName, gitEmail: settings.gitEmail }, - agentSet: this.agents.pack(row.owner, row.agent_set_id), + agentSet: this.agents.pack(row.owner, agentSetIds), }, slog, ); @@ -1054,8 +1085,7 @@ export class BoxManager { upstream?.forkableHarnesses ?? new Set(), ), ), - agentSetId: row.agent_set_id, - agentSetName: this.agents.nameOf(row.agent_set_id), + agentSets: this.agents.setsOf(row.id), // The last measurement, or null until there is one. diskBytes: row.disk_bytes, diskMeasuredAt: row.disk_measured_at, diff --git a/orchestrator/src/db.test.ts b/orchestrator/src/db.test.ts index a11b2e3..7a49254 100644 --- a/orchestrator/src/db.test.ts +++ b/orchestrator/src/db.test.ts @@ -289,13 +289,9 @@ test('the agent tables arrive with a global set, and existing boxes select none' const sets = upgraded.prepare('SELECT id, name FROM agent_sets').all(); assert.deepEqual(sets, [{ id: 'global', name: 'Global' }]); - // A box that predates the feature gets the global set and nothing - // else, which is what a null column means. - assert.ok(columns(upgraded, 'boxes').includes('agent_set_id')); - const row = upgraded.prepare("SELECT agent_set_id FROM boxes WHERE id = 'live'").get() as { - agent_set_id: string | null; - }; - assert.equal(row.agent_set_id, null); + // A box that predates the feature gets the global set and nothing else. + const rows = upgraded.prepare("SELECT set_id FROM box_agent_sets WHERE box_id = 'live'").all(); + assert.deepEqual(rows, []); } finally { upgraded.close(); } @@ -806,3 +802,35 @@ test('the MCP servers from before the secret rows are deleted, also from the box upgraded.close(); } }); + +test('the agent set of each box moves into the ordered list of the box', () => { + const before = MIGRATIONS.findIndex((sql) => sql.includes('CREATE TABLE box_agent_sets')); + const db = new Database(join(dir, 'boxes.db')); + for (const sql of MIGRATIONS.slice(0, before)) db.exec(sql); + db.pragma(`user_version = ${before}`); + db.prepare( + `INSERT INTO agent_sets (id, name, agents_md, created_at, updated_at) + VALUES ('go', 'Go', '', 1, 1)`, + ).run(); + for (const [id, setId] of [ + ['b1', 'go'], + ['b2', null], + ]) { + db.prepare( + `INSERT INTO boxes (id, name, owner, status, ws_token, agent_set_id, created_at, last_active_at) + VALUES (?, 'box', '', 'stopped', 'ws', ?, 1, 1)`, + ).run(id, setId); + } + db.close(); + + const upgraded = openDb(dir); + try { + assert.deepEqual( + upgraded.prepare('SELECT box_id, set_id, position FROM box_agent_sets').all(), + [{ box_id: 'b1', set_id: 'go', position: 0 }], + ); + assert.ok(!columns(upgraded, 'boxes').includes('agent_set_id')); + } finally { + upgraded.close(); + } +}); diff --git a/orchestrator/src/db.ts b/orchestrator/src/db.ts index c9531dc..ea404a5 100644 --- a/orchestrator/src/db.ts +++ b/orchestrator/src/db.ts @@ -38,11 +38,6 @@ export interface BoxRow { review_base_rev: string | null; /** The lifecycle state. A deleted box keeps its row as a tombstone. */ status: BoxStatus; - /** - * The extra agent set of this box, or null for only the global set. The - * database clears it when the set is deleted. - */ - agent_set_id: string | null; /** The bearer token that a WebSocket upgrade must give. It opens only this box. */ ws_token: string; /** @@ -787,6 +782,19 @@ export const MIGRATIONS: string[] = [ PRIMARY KEY (owner, host) ); `, + // Replaces the one agent set of each box with an ordered list of sets. + ` + CREATE TABLE box_agent_sets ( + box_id TEXT NOT NULL REFERENCES boxes(id) ON DELETE CASCADE, + set_id TEXT NOT NULL REFERENCES agent_sets(id) ON DELETE CASCADE, + position INTEGER NOT NULL, + PRIMARY KEY (box_id, set_id) + ); + CREATE INDEX idx_box_agent_sets_set ON box_agent_sets(set_id); + INSERT INTO box_agent_sets (box_id, set_id, position) + SELECT id, agent_set_id, 0 FROM boxes WHERE agent_set_id IS NOT NULL; + ALTER TABLE boxes DROP COLUMN agent_set_id; + `, ]; /** An open database handle. */ diff --git a/orchestrator/src/gateway/upstream.test.ts b/orchestrator/src/gateway/upstream.test.ts index 033b338..5ccbab5 100644 --- a/orchestrator/src/gateway/upstream.test.ts +++ b/orchestrator/src/gateway/upstream.test.ts @@ -3332,7 +3332,7 @@ function boxMcpServers(servers: AgentMcpServer[]): void { const id = agents.globalId(''); for (const server of servers) agents.putMcpServer('', id, server); db.prepare("UPDATE boxes SET mcp_servers = ? WHERE id = 's1'").run( - JSON.stringify(agents.mcpSnapshot('', null)), + JSON.stringify(agents.mcpSnapshot('', [])), ); } diff --git a/shared/types.ts b/shared/types.ts index 83a1ba9..a8a9e42 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -392,13 +392,11 @@ export interface BoxSummary { /** All threads of the box, oldest first. */ threads: ThreadSummary[]; /** - * The agent set that the user selected when the box was created, or null - * for the global set only. The value is also null when the set was deleted - * later. + * The agent sets that the user selected for the box, in the order of the + * merge. The list is empty for the global set only. A deleted set leaves the + * list. */ - agentSetId: string | null; - /** The current name of the agent set, for the UI. Null when `agentSetId` is null. */ - agentSetName: string | null; + agentSets: Array<{ id: string; name: string }>; /** * The disk space of the box in bytes: its workspace, its home and its Nix * store together. Null before the first measurement. @@ -490,11 +488,11 @@ export interface CreateBoxBody { */ profile?: string; /** - * The id of the agent set whose AGENTS.md and skills are merged over the - * global ones for this box. Absent, empty or the id of the global set means - * the global set only. + * The ids of the agent sets that are merged over the global set for this + * box, in the order of the merge. A later set wins. Absent or empty means the + * global set only. */ - agentSet?: string | null; + agentSets?: string[]; /** The id of the egress profile of the box. Absent or null means the default profile of the user. */ egressProfile?: string | null; /** @@ -1106,12 +1104,6 @@ export interface ReviewBaseResponse { repos: ReviewRepo[]; } -/** - * The name for the global agent set in a request that creates a box. Such a - * request is the same as a request without an agent set. - */ -export const GLOBAL_AGENT_SET = 'global'; - /** One skill of an agent set, as stored and as the API reports it. */ export interface AgentItem { /** @@ -1140,7 +1132,7 @@ export interface AgentSetSummary { skillCount: number; /** The number of repositories that the set takes skills from. */ repoCount: number; - /** The number of live boxes that were created with this set. */ + /** The number of live boxes that use this set. */ boxCount: number; /** The creation time of the set, in epoch milliseconds. */ createdAt: number;