Public: anyone can read this; the crew can change it.

Agents on board in one link: an isolated forge of their own (own pod, own crew, their tokens), contributing back as one clean pull request #3709

Parked opened this in answer to
Closed without merging

torque/forge:torque/3687-agents-on-board-in-one-link-an-isolated → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +578 −3
docs/SPAWN.md +2
@@ -44,6 +44,8 @@ A claim link is a live secret, so it stays out of an agent's conversation (#839)
4444
4545 A claim is bound to a spawned forge: it is read only from the organisation `parent.json` names, so a forge without `parent.json` answers 404, a row under any other account is never consulted, and a forge that already has an admin cannot be claimed. `keepAccess` (default false) decides who can see the child afterwards, and the claim page says which before anyone submits. With false, claiming removes the spawner's account from the organisation's Owners (the new owner can invite them back); with true, the page names the spawner and where to remove them. An idempotent replay of `POST /api/v1/forges` never returns or stores the link: `claimUrl` is kept as "shown once, in the first answer".
4646
47 An agent claims with nothing but HTTP (#3687): `POST /api/v1/claim {token, username, password, email?}` takes the same code under the same rules (same-origin, single-use, refused once there is an admin, rate-limited per address; `src/actions/claim.ts`) and answers 201 with an admin-scope API token, shown once. With it the agent adds its own model key (`POST /settings/subscriptions`, `Accept: application/json` for a 200/422 answer) and names its crew (`POST /settings/crew`). Every forge serves the whole on-ramp as one page at `/agents.md` and as JSON at `/.well-known/forge.json` (`src/web/agents.ts`), both rendered from one object, and `/llms.txt` links to them. Still to come: the pod placement (#3702), the "Invite an agent" button (#3703) and per-repository "Let <forge> propose" grants (#3704).
48
4749 ## The child's own keys, domain and model key (#576)
4850
4951 Spawn makes the child's `secret.key` and SSH host key in the child's own directory, so they exist before its first boot and are never the parent's. The child's address is `<name>--<parent's host>`, from the placement (one label under the platform apex). It is recorded as `url` in `parent.json` and shown on the child's home ("Your forge: …"). Hosted by another forge, the child prints `FORGE_APP_SSH` verbatim wherever it says how to connect, and says the terminal is off when that is unset.
src/actions/claim.ts added +113
@@ -0,0 +1,113 @@
1 /**
2 * Claiming a spawned forge with nothing but HTTP (#3687): the same claim
3 * link a person opens in a browser (`web/pages/claim.ts`), for an agent
4 * that has no browser. It posts the code after the link's `#` with a
5 * username and a password; the first account is made, becomes the forge's
6 * admin and an owner of its organisation, the link burns, and the answer
7 * carries an admin-scope API token, shown once, so the agent can go on to
8 * add its own model key and name its crew (`/agents.md` says how).
9 *
10 * The rules are the page's: the link is single-use and burnt in the
11 * statement that checks it (`spawn/claim.ts`), a forge with an admin cannot
12 * be claimed, and an account that cannot be made puts the link back.
13 */
14
15 import type { App } from "../app.ts";
16 import { PASSWORD_TOO_LONG, withinPasswordCap } from "../core/hash-gate.ts";
17 import { createToken } from "../core/tokens.ts";
18 import { createUser, getUserByName, type User } from "../core/users.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20 import {
21 burnClaim,
22 handOver,
23 readClaim,
24 spawnedOrg,
25 unburnClaim,
26 type ClaimState,
27 } from "../spawn/claim.ts";
28 import { givenEmail, MIN_SIGNUP_PASSWORD, noEmail } from "./users.ts";
29
30 const USERNAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,38}$/;
31
32 /** The name the minted token carries on the account's token list. */
33 export const CLAIM_TOKEN_NAME = "claim";
34
35 export interface ClaimInput {
36 readonly token: string;
37 readonly username: string;
38 readonly email: string;
39 readonly password: string;
40 }
41
42 export interface Claimed {
43 readonly user: User;
44 /** The spawned organisation the account now owns. */
45 readonly org: string;
46 /** An admin-scope API token, the only copy. */
47 readonly token: string;
48 }
49
50 export type ClaimFailure =
51 | { readonly kind: "gone"; readonly state: Exclude<ClaimState["state"], "ok"> }
52 | {
53 readonly kind: "invalid";
54 readonly field: "username" | "email" | "password";
55 readonly message: string;
56 };
57
58 const invalid = (field: "username" | "email" | "password", message: string) =>
59 err<ClaimFailure>({ kind: "invalid", field, message });
60
61 /** Take a spawned forge by its claim code, with a password, and mint its first token. */
62 export async function claimWithPassword(
63 app: App,
64 input: ClaimInput,
65 ): Promise<Result<Claimed, ClaimFailure>> {
66 const spawned = await spawnedOrg(app);
67 if (spawned === undefined) return err({ kind: "gone", state: "unknown" });
68 const orgId = spawned.org.id;
69 const before = readClaim(app.db, orgId, input.token);
70 if (before.state !== "ok") return err({ kind: "gone", state: before.state });
71
72 const username = input.username.trim();
73 const email = input.email.trim();
74 if (!USERNAME.test(username))
75 return invalid("username", "a username is letters, digits, dots and dashes, at most 39");
76 if (getUserByName(app.db, username) !== undefined)
77 return invalid("username", "that username is taken");
78 if (email !== "" && !givenEmail(email))
79 return invalid("email", "that does not look like an email address");
80 if (input.password.length < MIN_SIGNUP_PASSWORD)
81 return invalid("password", `a password needs at least ${MIN_SIGNUP_PASSWORD} characters`);
82 if (!withinPasswordCap(input.password)) return invalid("password", PASSWORD_TOO_LONG);
83
84 // Spent first, in one statement: of two callers on one link, one wins.
85 const spent = burnClaim(app.db, orgId, input.token);
86 if (spent.state !== "ok") return err({ kind: "gone", state: spent.state });
87 const made = await createUser(app.db, {
88 username,
89 email: email === "" ? noEmail(username) : email,
90 password: input.password,
91 isAdmin: true,
92 // The one-time claim link the spawner handed out is the proof.
93 trusted: true,
94 origin: "claim",
95 });
96 if (!made.ok) {
97 unburnClaim(app.db, orgId, input.token);
98 return made.error === "email_taken"
99 ? invalid("email", "that email already has an account")
100 : made.error === "username_reserved"
101 ? invalid("username", "that name is reserved")
102 : invalid("username", "that username is taken");
103 }
104 handOver(app.db, spawned, made.value.id);
105 const minted = createToken(app.db, made.value.id, CLAIM_TOKEN_NAME, "admin");
106 app.log.info("forge claimed", {
107 org: spawned.org.username,
108 user: made.value.username,
109 spawnerKeeps: spawned.keepAccess,
110 by: "api",
111 });
112 return ok({ user: made.value, org: spawned.org.username, token: minted.token });
113 }
src/core/reserved.ts +1
@@ -92,6 +92,7 @@ export const SYSTEM_NAMES: readonly string[] = [
9292 "origins",
9393 "robots.txt",
9494 "llms.txt",
95 "agents.md",
9596 "runs",
9697 "search",
9798 "settings",
src/http/api.ts +43
@@ -40,6 +40,8 @@ import {
4040 signOutHere,
4141 } from "../actions/signins.ts";
4242 import { STRANGER_MAX } from "./limits.ts";
43 import { claimWithPassword } from "../actions/claim.ts";
44 import { signinWindow } from "../core/signin-window.ts";
4345 import {
4446 askedIn,
4547 askedJson,
@@ -4911,6 +4913,47 @@ export function apiRoutes(router: Router<Handler>): void {
49114913 return json(state);
49124914 });
49134915
4916 // A spawned forge claimed with nothing but HTTP (#3687): the code after
4917 // the claim link's `#`, a username and a password make the first admin;
4918 // the answer carries an admin token, shown once (`actions/claim.ts`).
4919 router.add("POST", "/api/v1/claim", async (ctx) => {
4920 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden();
4921 const wait = signinWindow(ctx.app.db, "claim", clientAddress(ctx.request));
4922 if (wait !== undefined)
4923 return json(
4924 { error: "rate_limited", message: `too many attempts; wait ${wait}s` },
4925 429,
4926 { "retry-after": String(wait) },
4927 );
4928 // Anyone may call this, so its body is a stranger's (`http/limits.ts`).
4929 const input = await boundedBody(ctx.request, STRANGER_MAX);
4930 if (input === "too_large")
4931 return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`);
4932 const claimed = await claimWithPassword(ctx.app, {
4933 token: str(input.token),
4934 username: str(input.username),
4935 email: str(input.email),
4936 password: str(input.password),
4937 });
4938 if (!claimed.ok) {
4939 const f = claimed.error;
4940 if (f.kind === "invalid") return apiError("invalid", 422, `${f.field}: ${f.message}`);
4941 return f.state === "unknown"
4942 ? apiError("not_found", 404, "not a claim code on this forge")
4943 : apiError("gone", 410, f.state === "owned" ? "this forge already has an admin" : `this claim link is ${f.state}`);
4944 }
4945 return json(
4946 {
4947 username: claimed.value.user.username,
4948 org: claimed.value.org,
4949 token: claimed.value.token,
4950 scope: "admin",
4951 guide: `${ctx.url.origin}/agents.md`,
4952 },
4953 201,
4954 );
4955 });
4956
49144957 // A child's signed heartbeat (docs/SPAWN.md): counts and version, never
49154958 // data. Every refusal is the same 404, so nothing says who is a child.
49164959 router.add("POST", "/api/v1/heartbeat", async (ctx) => {
src/http/server.ts +4
@@ -248,6 +248,7 @@ import {
248248 tellSubmit,
249249 } from "../web/studio/actions.ts";
250250 import { everydayCreate, everydayKeep, everydayOptions, everydaySwitch } from "../web/pages/everyday.ts";
251 import { agentsMd, forgeJson } from "../web/agents.ts";
251252 import { claimFragmentPage, claimOptions, claimSubmit } from "../web/pages/claim.ts";
252253 import { firstAdminOptions, firstAdminPage, firstAdminSubmit } from "../web/pages/first-admin.ts";
253254 import { familyPage } from "../web/pages/family.ts";
@@ -654,6 +655,9 @@ export function buildRouter(): Router<Handler> {
654655 // What the open web expects of a site, from the forge's own facts.
655656 router.add("GET", "/.well-known/security.txt", securityTxt);
656657 router.add("GET", "/llms.txt", llmsTxt);
658 // An agent's on-ramp (#3687): get a forge, pay for its crew, contribute.
659 router.add("GET", "/agents.md", agentsMd);
660 router.add("GET", "/.well-known/forge.json", forgeJson);
657661 router.add("GET", "/.well-known/change-password", changePassword);
658662 router.add("GET", "/robots.txt", robotsTxt);
659663 router.add("GET", "/releases.json", releasesJson);
src/web/agents.ts added +219
@@ -0,0 +1,219 @@
1 /**
2 * The on-ramp for an agent (#3687), as one page it can read and one file it
3 * can parse:
4 *
5 * /agents.md how an agent gets a forge of its own and builds
6 * on it with nothing but HTTP: claim, pay for its
7 * crew with its own model key, name its crew,
8 * contribute back as a pull
9 * /.well-known/forge.json the same facts as JSON: endpoints, auth, limits
10 *
11 * Both are rendered from one plain object (`agentGuide`), so they never
12 * disagree, and both say only what this forge already knows: its URL, its
13 * parent's, whether it was spawned and is still unclaimed, its own limits.
14 * Nobody's words but the forge's appear in either.
15 */
16
17 import { MIN_SIGNUP_PASSWORD } from "../actions/users.ts";
18 import { MODELS } from "../crew/models.ts";
19 import type { Ctx } from "../http/context.ts";
20 import { BODY_MAX, STRANGER_MAX } from "../http/limits.ts";
21 import { CLAIM_TTL_MS, hasAdmin, spawnedOrg } from "../spawn/claim.ts";
22
23 export interface AgentGuide {
24 readonly forge: string;
25 readonly url: string;
26 /** The forge this one was spawned from, where its pulls go; null for a root forge. */
27 readonly parent: string | null;
28 readonly guide: string;
29 readonly llms: string;
30 readonly api: string;
31 readonly mcp: string;
32 readonly auth: {
33 readonly header: string;
34 readonly scopes: readonly string[];
35 readonly oauth: string;
36 };
37 readonly claim: {
38 /** Whether this forge is spawned and still waits for its first admin. */
39 readonly open: boolean;
40 readonly method: "POST";
41 readonly url: string;
42 readonly body: Readonly<Record<string, string>>;
43 readonly returns: string;
44 readonly errors: Readonly<Record<string, string>>;
45 };
46 readonly crew: {
47 readonly models: readonly string[];
48 readonly modelKey: Step;
49 readonly agent: Step;
50 readonly onRepo: Step;
51 };
52 readonly contribute: {
53 readonly fork: string;
54 readonly pull: string;
55 readonly rule: string;
56 };
57 readonly limits: {
58 readonly claimLinkHours: number;
59 readonly passwordMin: number;
60 readonly anonymousBodyBytes: number;
61 readonly bodyBytes: number;
62 };
63 }
64
65 interface Step {
66 readonly method: string;
67 readonly url: string;
68 readonly as: string;
69 readonly fields: Readonly<Record<string, string>>;
70 }
71
72 /** What an agent needs to know about this forge, as plain data. */
73 export async function agentGuide(ctx: Ctx): Promise<AgentGuide> {
74 const o = ctx.url.origin;
75 const spawned = await spawnedOrg(ctx.app);
76 const form = "form (application/x-www-form-urlencoded), Authorization: Bearer <admin token>, Accept: application/json";
77 return {
78 forge: ctx.url.host,
79 url: o,
80 parent: ctx.app.config.parentUrl ?? null,
81 guide: `${o}/agents.md`,
82 llms: `${o}/llms.txt`,
83 api: `${o}/api/v1`,
84 mcp: `${o}/mcp`,
85 auth: {
86 header: "Authorization: Bearer <token>",
87 scopes: ["ro", "rw", "admin"],
88 oauth: `${o}/.well-known/oauth-protected-resource`,
89 },
90 claim: {
91 open: spawned !== undefined && !hasAdmin(ctx.app.db),
92 method: "POST",
93 url: `${o}/api/v1/claim`,
94 body: {
95 token: "the code after # in the claim link",
96 username: "letters, digits, dots and dashes",
97 password: `at least ${MIN_SIGNUP_PASSWORD} characters`,
98 email: "optional",
99 },
100 returns: '201 {"username", "org", "token", "scope": "admin", "guide"}; the token is shown once',
101 errors: {
102 "404": "not a claim code on this forge",
103 "410": "the link is used or expired, or the forge already has an admin",
104 "422": "a field is wrong; the message names it",
105 "429": "too many attempts; wait for Retry-After",
106 },
107 },
108 crew: {
109 models: MODELS.map((m) => m.id).filter((id) => id !== ""),
110 modelKey: {
111 method: "POST",
112 url: `${o}/settings/subscriptions`,
113 as: form,
114 fields: {
115 name: "a word or two",
116 token: "your model API key, or a Claude setup-token (sk-ant-oat…)",
117 apiBase: "optional: an https gateway base URL, e.g. https://openrouter.ai/api",
118 },
119 },
120 agent: {
121 method: "POST",
122 url: `${o}/settings/crew`,
123 as: form,
124 fields: {
125 username: "the crew member's name",
126 model: "one of models, or empty for the runner's default",
127 brief: "what it is for",
128 budgetUsd: "optional: its spend ceiling",
129 },
130 },
131 onRepo: {
132 method: "PUT",
133 url: `${o}/api/v1/repos/{owner}/{name}/crew/{agent}`,
134 as: "Authorization: Bearer <token>",
135 fields: {},
136 },
137 },
138 contribute: {
139 fork: "POST {forge}/api/v1/repos/{owner}/{name}/forks",
140 pull: 'POST {forge}/api/v1/repos/{owner}/{name}/pulls with {"title", "body", "base", "head", "headRepo"}',
141 rule: "A pull from outside never lands by itself: the repository's people decide. A crew member never merges and never moves a default branch.",
142 },
143 limits: {
144 claimLinkHours: CLAIM_TTL_MS / 3_600_000,
145 passwordMin: MIN_SIGNUP_PASSWORD,
146 anonymousBodyBytes: STRANGER_MAX,
147 bodyBytes: BODY_MAX,
148 },
149 };
150 }
151
152 const fieldsLine = (fields: Readonly<Record<string, string>>): string =>
153 Object.entries(fields)
154 .map(([k, v]) => `\`${k}\` (${v})`)
155 .join(", ");
156
157 /** The guide as one page of Markdown. */
158 export function agentsMarkdown(g: AgentGuide): string {
159 const c = g.crew;
160 return [
161 `# Agents on forge at ${g.forge}`,
162 "",
163 "> Get a forge of your own, pay for its crew with your own model key, and contribute back as one pull. Everything here is plain HTTP; the same facts as JSON are at /.well-known/forge.json.",
164 "",
165 "## 1. Claim your forge",
166 "",
167 `- You are handed a claim link: \`https://<your forge>/claim#<code>\`. It works once, for ${g.limits.claimLinkHours} hours.`,
168 `- ${g.claim.method} ${g.claim.url} with JSON ${fieldsLine(g.claim.body)}.`,
169 `- Answer: ${g.claim.returns}. Your account is the forge's admin and an owner of its organisation.`,
170 `- Errors: ${Object.entries(g.claim.errors).map(([k, v]) => `${k} ${v}`).join("; ")}.`,
171 `- This forge: ${g.claim.open ? "waiting to be claimed" : "not claimable (not spawned, or already has an admin)"}.`,
172 "",
173 "## 2. Pay for your crew with your own tokens",
174 "",
175 `- ${c.modelKey.method} ${c.modelKey.url} as a ${c.modelKey.as}: ${fieldsLine(c.modelKey.fields)}.`,
176 '- Answer: 200 {"ok": true} or 422 {"ok": false, "error"}. The key is stored sealed and never shown again.',
177 "",
178 "## 3. Name your crew",
179 "",
180 `- ${c.agent.method} ${c.agent.url} as a ${c.agent.as}: ${fieldsLine(c.agent.fields)}.`,
181 `- Models: ${c.models.map((m) => `\`${m}\``).join(", ")}.`,
182 `- Put a crew member on a repository: ${c.onRepo.method} ${c.onRepo.url}, ${c.onRepo.as}.`,
183 "",
184 "## 4. Contribute back",
185 "",
186 g.parent === null
187 ? "- This forge has no parent. Offer a change to any forge that lets you read a repository:"
188 : `- Your pulls go to the forge this one was spawned from: ${g.parent}. With read on a repository there:`,
189 `- Fork: ${g.contribute.fork}; push a branch to your fork over git; then ${g.contribute.pull}.`,
190 `- ${g.contribute.rule}`,
191 "",
192 "## Auth and limits",
193 "",
194 `- API: ${g.api}, \`${g.auth.header}\`, scopes ${g.auth.scopes.join(" < ")}. MCP: ${g.mcp} (OAuth discovery: ${g.auth.oauth}).`,
195 `- Bodies: at most ${g.limits.anonymousBodyBytes} bytes without a token, ${g.limits.bodyBytes} with one.`,
196 `- More: ${g.llms}`,
197 "",
198 ].join("\n");
199 }
200
201 const headers = (type: string) => ({
202 "content-type": type,
203 // Whether the forge is still claimable can change at any moment.
204 "cache-control": "public, max-age=60",
205 });
206
207 /** GET /agents.md */
208 export async function agentsMd(ctx: Ctx): Promise<Response> {
209 return new Response(agentsMarkdown(await agentGuide(ctx)), {
210 headers: headers("text/markdown; charset=utf-8"),
211 });
212 }
213
214 /** GET /.well-known/forge.json */
215 export async function forgeJson(ctx: Ctx): Promise<Response> {
216 return new Response(JSON.stringify(await agentGuide(ctx)), {
217 headers: headers("application/json"),
218 });
219 }
src/web/pages/subscriptions.ts +4 −3
@@ -39,7 +39,7 @@ import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
3939 import { field, readForm, type Form } from "../form.ts";
4040 import { html, when, type Html } from "../html.ts";
4141 import { icon } from "../icons.ts";
42 import { flashTo, page } from "../layout.ts";
42 import { flashOrJson, flashTo, page } from "../layout.ts";
4343 import {
4444 badge,
4545 btn,
@@ -424,12 +424,13 @@ export async function subscriptionAdd(ctx: Ctx): Promise<Response> {
424424 invalid_api_base:
425425 "The API base URL must be https, with no credentials, query, or hash. For OpenRouter use https://openrouter.ai/api (a Claude subscription token cannot use a gateway).",
426426 };
427 return flashTo(ctx, POOL, {
427 // An agent asking for JSON (`/agents.md`) is told plainly, not redirected.
428 return flashOrJson(ctx, POOL, {
428429 tone: "danger",
429430 message: messages[added.error],
430431 });
431432 }
432 return flashTo(ctx, POOL, {
433 return flashOrJson(ctx, POOL, {
433434 message: `${added.value.name} is in the pool. Grant it to a repository under its Settings → Crew, or to an organization on its page.`,
434435 });
435436 }
src/web/standards.ts +1
@@ -259,6 +259,7 @@ export function llmsTxt(ctx: Ctx): Response {
259259 "",
260260 `- MCP: ${o}/mcp (OAuth discovery: ${o}/.well-known/oauth-protected-resource)`,
261261 `- API: ${o}/api/v1, Authorization: Bearer <token>`,
262 `- A forge of your own, its crew on your own model key, and how to contribute back: ${o}/agents.md (JSON: ${o}/.well-known/forge.json)`,
262263 "",
263264 "## Public repositories",
264265 "",
test/agent-onramp.test.ts added +173
@@ -0,0 +1,173 @@
1 /**
2 * An agent on board with nothing but HTTP (#3687): it reads the guide at
3 * /agents.md or /.well-known/forge.json, claims its spawned forge with
4 * `POST /api/v1/claim`, and with the admin token it is handed adds its own
5 * model key and names its crew. The claim keeps the page's rules: one use,
6 * same-origin, every field checked, and a forge with an admin is not
7 * claimable.
8 */
9
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { createOrg, listTeamMembers, listTeams, OWNERS_TEAM } from "../src/core/orgs.ts";
16 import { createUser, getUserByName } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { mintClaim } from "../src/spawn/claim.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 describe("an agent claims its forge and staffs its crew over HTTP", () => {
24 let dir = "";
25 let app: App;
26 let servers: Servers;
27 let base = "";
28 let code = "";
29 let orgId = "";
30 let makerId = "";
31 let adminToken = "";
32
33 const claim = (body: Record<string, string>, headers: Record<string, string> = {}) =>
34 fetch(`${base}/api/v1/claim`, {
35 method: "POST",
36 headers: { "content-type": "application/json", ...headers },
37 body: JSON.stringify(body),
38 });
39 const guide = async () =>
40 (await (await fetch(`${base}/.well-known/forge.json`)).json()) as {
41 url: string;
42 parent: string | null;
43 claim: { open: boolean; url: string };
44 crew: { models: string[]; modelKey: { url: string }; agent: { url: string } };
45 limits: { claimLinkHours: number; passwordMin: number };
46 };
47
48 beforeAll(async () => {
49 dir = await mkdtemp(join(tmpdir(), "forge-agent-onramp-"));
50 app = createApp({
51 dataDir: dir,
52 port: 0,
53 parentUrl: "https://forge.example",
54 });
55 // The spawner's account on the child: an owner of the org, not an admin.
56 const maker = await createUser(app.db, {
57 origin: "seed",
58 trusted: true,
59 username: "maker",
60 email: "[email protected]",
61 password: "a-good-passphrase",
62 });
63 if (!maker.ok) throw new Error(maker.error);
64 makerId = maker.value.id;
65 const org = createOrg(app.db, "grokforge", maker.value.id);
66 if (!org.ok) throw new Error(org.error);
67 orgId = org.value.id;
68 await Bun.write(join(dir, "parent.json"), JSON.stringify({ org: "grokforge" }));
69 code = mintClaim(app.db, orgId);
70 servers = await serve(app);
71 base = servers.url;
72 });
73
74 afterAll(async () => {
75 servers.stop();
76 app.close();
77 await rm(dir, { recursive: true, force: true });
78 });
79
80 test("the guide says this forge is waiting, and how to claim it", async () => {
81 const g = await guide();
82 expect(g.url).toBe(base);
83 expect(g.parent).toBe("https://forge.example");
84 expect(g.claim.open).toBe(true);
85 expect(g.claim.url).toBe(`${base}/api/v1/claim`);
86 expect(g.crew.modelKey.url).toBe(`${base}/settings/subscriptions`);
87 expect(g.crew.models).toContain("sonnet");
88 expect(g.crew.models).not.toContain("");
89 expect(g.limits.claimLinkHours).toBe(24);
90 expect(g.limits.passwordMin).toBe(12);
91
92 const md = await fetch(`${base}/agents.md`);
93 expect(md.status).toBe(200);
94 expect(md.headers.get("content-type")).toContain("text/markdown");
95 // The security floor rides every response.
96 expect(md.headers.get("x-content-type-options")).toBe("nosniff");
97 const text = await md.text();
98 expect(text).toContain(`POST ${base}/api/v1/claim`);
99 expect(text).toContain("waiting to be claimed");
100 expect(text).toContain("https://forge.example");
101 // And llms.txt points an agent at it.
102 expect(await (await fetch(`${base}/llms.txt`)).text()).toContain(`${base}/agents.md`);
103 });
104
105 test("a made-up code, a cross-origin post, and a weak password are refused, and nothing is spent", async () => {
106 const wrong = await claim({ token: "x".repeat(43), username: "grokbot", password: "a-long-agent-passphrase" });
107 expect(wrong.status).toBe(404);
108 const foreign = await claim(
109 { token: code, username: "grokbot", password: "a-long-agent-passphrase" },
110 { origin: "https://evil.example" },
111 );
112 expect(foreign.status).toBe(403);
113 const weak = await claim({ token: code, username: "grokbot", password: "short" });
114 expect(weak.status).toBe(422);
115 expect(((await weak.json()) as { message: string }).message).toStartWith("password:");
116 const badName = await claim({ token: code, username: "-no", password: "a-long-agent-passphrase" });
117 expect(badName.status).toBe(422);
118 expect(getUserByName(app.db, "grokbot")).toBeUndefined();
119 expect((await guide()).claim.open).toBe(true);
120 });
121
122 test("the code makes the first admin and hands back an admin token, once", async () => {
123 const res = await claim({ token: code, username: "grokbot", password: "a-long-agent-passphrase" });
124 expect(res.status).toBe(201);
125 const body = (await res.json()) as { username: string; org: string; token: string; scope: string };
126 expect(body.username).toBe("grokbot");
127 expect(body.org).toBe("grokforge");
128 expect(body.scope).toBe("admin");
129 expect(body.token).toStartWith("forge_");
130 adminToken = body.token;
131
132 const user = getUserByName(app.db, "grokbot");
133 expect(user?.isAdmin).toBe(true);
134 // It owns the org now, and the spawner — who did not keep access — left.
135 const owners = listTeams(app.db, orgId).find((t) => t.name === OWNERS_TEAM)!;
136 const members = listTeamMembers(app.db, owners.id).map((m) => m.id);
137 expect(members).toContain(user!.id);
138 expect(members).not.toContain(makerId);
139
140 const me = await fetch(`${base}/api/v1/user`, { headers: { authorization: `Bearer ${adminToken}` } });
141 expect(((await me.json()) as { username: string }).username).toBe("grokbot");
142
143 // The link is spent, and the forge is no longer claimable by anyone.
144 const again = await claim({ token: code, username: "second", password: "a-long-agent-passphrase" });
145 expect(again.status).toBe(410);
146 expect(getUserByName(app.db, "second")).toBeUndefined();
147 expect((await guide()).claim.open).toBe(false);
148 });
149
150 test("with that token it adds its own model key and names its crew", async () => {
151 const post = (path: string, form: Record<string, string>, token = adminToken) =>
152 fetch(`${base}${path}`, {
153 method: "POST",
154 headers: { authorization: `Bearer ${token}`, accept: "application/json" },
155 body: new URLSearchParams(form),
156 redirect: "manual",
157 });
158 const bad = await post("/settings/subscriptions", { name: "mine", token: "has spaces in it" });
159 expect(bad.status).toBe(422);
160 expect(((await bad.json()) as { ok: boolean }).ok).toBe(false);
161 const good = await post("/settings/subscriptions", { name: "mine", token: "sk-ant-api03-agentsownkey" });
162 expect(good.status).toBe(200);
163 expect(((await good.json()) as { ok: boolean }).ok).toBe(true);
164 const row = app.db
165 .query<{ n: number }, []>("SELECT count(*) AS n FROM subscription WHERE name = 'mine'")
166 .get();
167 expect(row?.n).toBe(1);
168
169 const crew = await post("/settings/crew", { username: "grok-one", model: "sonnet", brief: "builds" });
170 expect(crew.status).toBeLessThan(400);
171 expect(getUserByName(app.db, "grok-one")?.kind).toBe("agent");
172 });
173 });
test/standards.test.ts +18
@@ -81,6 +81,24 @@ describe("what the open web expects", () => {
8181 }
8282 });
8383
84 test("a forge nobody spawned still guides an agent, and has nothing to claim", async () => {
85 const g = (await (await fetch(`${base}/.well-known/forge.json`)).json()) as {
86 parent: string | null;
87 claim: { open: boolean };
88 };
89 expect(g.parent).toBeNull();
90 expect(g.claim.open).toBe(false);
91 const md = await (await fetch(`${base}/agents.md`)).text();
92 expect(md).toContain("not claimable");
93 expect(md).toContain("This forge has no parent");
94 const claim = await fetch(`${base}/api/v1/claim`, {
95 method: "POST",
96 headers: { "content-type": "application/json" },
97 body: JSON.stringify({ token: "x".repeat(43), username: "bot", password: "a-long-agent-passphrase" }),
98 });
99 expect(claim.status).toBe(404);
100 });
101
84102 test("change-password sends a password manager to the right page", async () => {
85103 const res = await fetch(`${base}/.well-known/change-password`, {
86104 redirect: "manual",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs