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

Spawn with config: a forge from a declarative recipe (apps and their modes, budget, admin, domain), saved and reusable #13222

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/649-spawn-with-config-a-forge-from-a-declara → main 15 commits fork 2 threads · 2 unresolved

  • Merged. mason/649-spawn-with-config-a-forge-from-a-declara was merged into main as e55511e.

Review

Sign in to review this change.
20 files changed +903 −33
docs/MCP.md +2 −2
@@ -212,7 +212,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
212212 | `signup` | — | Sign-ups: open (default); invite lets in only a person with an open invite link; closed refuses every new account | 324 |
213213 | `sizes` | — | A child forge's sizes: small, medium and large, each with CPU, memory and disk | 196 |
214214 | `snapshot_now` | — | Take a snapshot now, as Backups does (admin) | 133 |
215 | `spawn` | — | Spawn a child forge | 1066 |
215 | `spawn` | — | Spawn a child forge | 1203 |
216216 | `spend` | — | Report what your session spent outside forge runs: who, model, tokens or dollars, issue | 470 |
217217 | `ssh_keys` | `list`, `add`, `remove` | Your SSH keys; add: key, remove: id | 250 |
218218 | `steer` | — | Say a word to one crew run by its id | 224 |
@@ -420,7 +420,7 @@ longer sentences:
420420 - `dryRun`: plans unless it is `false`; anything else changes nothing. `limb` applying takes an admin token.
421421 - `signup`: the terminal's Invite links screen does the same: `s` picks a mode, shows the plan (from → to) and changes it after a confirm, for a forge admin who is a person.
422422 - `tell.from`: a path on this forge the issue links to, like `/alice/notes/pulls/3`. `tell.context`: where this was told from, for the builder.
423 - `spawn.reveal`, `claim_link.reveal`: put the live claim link in the answer (default false); it is a secret, only when its person reads it. `spawn.fresh`: a fresh app beside the copied ones. `spawn.followMode`: `tell-me` (default) tells the owner in their inbox when this forge's code moves; `take-updates` opens a pull with the new code, and a person merges it. `spawn.size`: recorded only, not enforced. `spawn.keepAccess`: stay an owner once claimed.
423 - `spawn.reveal`, `claim_link.reveal`: put the live claim link in the answer (default false); it is a secret, only when its person reads it. `spawn.fresh`: a fresh app beside the copied ones. `spawn.followMode`: `tell-me` (default) tells the owner in their inbox when this forge's code moves; `take-updates` opens a pull with the new code, and a person merges it. `spawn.size`: recorded only, not enforced. `spawn.keepAccess`: stay an owner once claimed. `spawn.config` `{apps:[{repo, mode: fork|autonomous|migration}], budgetUsd?, admin?, domain?}` or `spawn.recipe` (a name saved on the New forge page or `PUT /api/v1/forges/recipes/<name>`) in place of `apps`; a budget applies only beside a model key, which never travels through an agent.
424424 - `commits.ref`: branch, tag or commit; the default branch when absent. `report.page`: the http(s) address where the problem was seen. `plan.issues.pillar`: the pillar served, as `"P0"` or `"P0 Trust"`; `later: true` means no pillar and needs `why`.
425425 - `here.url`: none means the forge's own page. On `/` or `/settings` this forge's admin also gets `plan: { text, manage? }`, the Plan row's words and its manage-billing address; no plan notice or not an admin, no `plan` key.
426426 - `explore.q`: words, plus `kind:app|person|forge` and `sort:score|forks|ships|likes|use|fresh|name`, `updated:1d|7d|30d` (only what moved in that window), `owner:name` and `archived:yes`. `since` is another name for `updated`. `query` is the same argument; `q` wins when both are given. Each of `kind`, `sort`, `updated`, `owner`, `archived` is also its own argument (and a query parameter on `/explore` and `/api/v1/explore`); it wins over the same key in `q`.
docs/SPAWN.md +10
@@ -219,6 +219,16 @@ When the order turns paid (the `checkout.session.completed` webhook, or `/pricin
219219
220220 A paid order whose spawn fails (no capacity, a name taken in a race) becomes `failed`: a `billing.order_failed` event, the `paid_order` flow alarm, and a plain page to the buyer. On Settings → Billing an admin sees "Paid, not made" with **Retry** and a link to the provider's dashboard to refund. With no provider connected the paid plans show their size and say "ask the operator". Agents are refused as buyers.
221221
222 ## A forge from a config, saved as a recipe (#649)
223
224 A forge is described by a config: `{apps: [{repo, mode}], budgetUsd?, admin?, domain?}`, accepted as `config` on `POST /api/v1/forges` and the MCP `spawn` (at the top level of the body the door reads `apps`, `admin`, `domain` and `budgetUsd` only). A stranger's apps are forks only: `autonomous` and `migration` are refused (422) unless the spawner is signed in. `apps` may still be plain `owner/name` strings, which are forks. `mode` is `fork` (the default: a copy with its history that follows its upstream, as before), `autonomous` (the same copy, with the crew set to `go`: it plans, decides and ships on its own from the first tick) or `migration` (autonomous, and the app's first direction is `MIGRATION_DIRECTION`, the spawner's words after it). The plan names a mode only when it is not `fork`, so a plan of forks hashes as it always did. A bad mode, admin (a username), domain (a hostname) or budget is a 422 on its field; the dry run (the default) comes first.
225
226 `admin` and `domain` are **recorded** (API only: the page and the terminal do not ask for them) in the plan, the dry run and the ledger, and acted on by nothing yet: whoever opens the claim link still becomes the admin, and the child answers at `<name>--<host>`. The dry run says so. A budget needs a model key, which a config never carries: with none beside it the budget is left out of the plan and the answer says `budgetNote`.
227
228 A recipe is a config saved under a name (`src/spawn/recipes.ts`, `<data>/recipes/<person>.json`, at most 20 a person): no name for the child, no key, no brief. On `/forges/new`, a name under "Keep this setup as a recipe" keeps the form's apps, modes and budget when you press See the plan or Spawn; "Your recipes" lists them, each with a name field and **Spawn** (a recipe with a budget asks for its key again). The same door takes `recipe: "<name>"` (MCP `spawn {recipe}`); `GET /api/v1/forges/recipes`, `PUT` and `DELETE …/recipes/<name>` manage them.
229
230 On the page, the free-form app picker keeps its ticks; each ticked app now gets a mode select ("How each app goes in") after See the plan.
231
222232 ## Migration mode at spawn
223233
224234 `migration: true` (page checkbox "Migration mode", terminal field "Mode of the forked apps", API/MCP `spawn.migration`) puts each forked app in migration mode (`apps/migration_mode.ts`): the child gets the `app_migration` row with the parent's copy as its origin (open when that repository is public) and the direction `run natively here with parity to <origin>`, followed by the spawner's own words. It needs at least one app to fork. The crew's brief is not changed: only the direction and the origin row are set.
docs/features/README.md +1
@@ -40,6 +40,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
4040 - [Template mark](repo-template.md)
4141 - [Who changed a setting, and when](setting-history.md)
4242 - [A new forge can start from a template repository](new-forge-template.md)
43 - [Spawn a forge from a config, and keep it as a recipe](spawn-recipes.md)
4344 - [Made from: the template a forge came from](made-from.md)
4445 - [The explorer's sorts](explore.md)
4546 - [The feed pages by cursor](feed-cursor.md)
docs/features/spawn-recipes.md added +17
@@ -0,0 +1,17 @@
1 # Spawn a forge from a config, and keep it as a recipe
2
3 A forge is described by a config: apps, each started as a `fork`, `autonomous` or `migration`, and optionally a budget. Keep one under a name (a recipe) and spawn it again. Three doors, one rule set (`spawnDoor`).
4
5 - **Web, `/forges/new`:** tick the apps; each ticked app gets a mode after **See the plan**. Under "Keep this setup as a recipe" give a name: it is saved when you press **See the plan** or **Spawn**. "Your recipes" lists them, each with a name for the new forge and **Spawn** (a recipe with a budget asks for its key again).
6 - **Terminal, New forge (`:forge new`, or the home's New forge):** the Apps field takes `owner/name:autonomous` or `owner/name:migration`; **Save as recipe** keeps the apps and budget under a name when you press Ctrl+P or spawn; **Spawn from recipe** appears once you have one and cycles them with left and right (its apps and budget replace the fields above).
7 - **API and MCP:** `POST /api/v1/forges` and `spawn` take `config: {apps, budgetUsd?, admin?, domain?}` or `recipe: "<name>"`; `GET /api/v1/forges/recipes`, `PUT` and `DELETE /api/v1/forges/recipes/<name>` manage them.
8
9 Who may: a signed-in person. A stranger's apps are forks only; `autonomous` and `migration` hand the crew the wheel and take the spawner's words as the direction, so a stranger asking for either is refused (422). A guest has no recipes.
10
11 Modes: `autonomous` sets the app's autonomy to `go` (no plan nod, decisions by the decider) from the child's first tick; `migration` is that plus `MIGRATION_DIRECTION` as the first direction, the spawner's words after it.
12
13 `admin` and `domain` are recorded in the plan and the child's ledger and acted on by nothing yet, so only the API takes them; the page and the terminal leave them off.
14
15 A recipe is one file per person, `<data>/recipes/<person>.json`, at most 20, with no name for the child, no key and no brief. Saves are one synchronous read-change-write into a renamed file, so two at once do not lose one.
16
17 Code: `src/spawn/recipes.ts`, `src/spawn/door.ts`, `src/spawn/plan.ts`, `src/web/pages/new-forge.ts`, `src/tui/screens/newforge.ts`.
src/actions/spawn.ts +21 −4
@@ -33,6 +33,7 @@ import {
3333 canRead,
3434 createRepo,
3535 getRepo,
36 isGo,
3637 updateRepoSettings,
3738 type Repo,
3839 } from "../core/repos.ts";
@@ -145,6 +146,9 @@ interface Ledger {
145146 readonly ownerId?: string;
146147 /** Absent on a ledger written before sizes; reads as small. */
147148 readonly size?: Size;
149 /** The admin and the domain the spawner named; recorded only, nothing acts on them yet. */
150 readonly admin?: string;
151 readonly domain?: string;
148152 /** The template chosen (`spawn/templates.ts`); absent means `blank`. */
149153 readonly template?: string;
150154 /** The plan chosen (`settings/plans.ts`); absent means the free plan. */
@@ -174,6 +178,12 @@ interface Ledger {
174178 }
175179
outdated

This doc comment belongs to STARTER_KEY below; the new MIGRATION_DIRECTION block was inserted between them. Move it back.

176180 const SAFE_ID = /^[A-Za-z0-9_-]{1,80}$/;
181 /** The first direction of an app that arrives to be migrated: the spawner's words follow it. */
182 export const MIGRATION_DIRECTION =
183 "Migrate this app into the forge's shape: small modules, tests that pass, a forge.json that runs it, and the behaviour it had.";
184 const migrationDirection = (words: string): string =>
185 words === "" ? MIGRATION_DIRECTION : `${MIGRATION_DIRECTION}\n\n${words}`;
186
177187 /** The name the child's sealed model key goes by. */
178188 export const STARTER_KEY = "starter";
179189 const inFlight = new Set<string>();
@@ -394,6 +404,8 @@ async function make(
394404 createdAt: new Date().toISOString(),
395405 ...(owner === undefined ? {} : { ownerId: owner.id }),
396406 size: plan.size ?? DEFAULT_SIZE,
407 ...(plan.admin === undefined ? {} : { admin: plan.admin }),
408 ...(plan.domain === undefined ? {} : { domain: plan.domain }),
397409 ...(plan.template === undefined ? {} : { template: plan.template }),
398410 ...(plan.plan === undefined ? {} : { plan: plan.plan }),
399411 placement: placed.value.kind ?? "hosted",
@@ -563,19 +575,24 @@ async function copyInto(
563575 if (!fetched.ok) return err(inStep(step, `could not copy ${a.ref}: ${fetched.error.stderr}`));
564576 // The spawner's words are each app's direction; the child's first
565577 // boot opens the direction issue from them (`spawn/first-boot.ts`).
566 // Migration mode: the app answers to its parent's copy, and its direction says so
567 // (`apps/migration_mode.ts`); the spawner's own words follow.
568 let direction = plan.direction;
578 // A migrating app (`mode: "migration"`) is told to come into the forge's shape first.
579 // Migration mode (`plan.migration`): the app answers to its parent's copy, and its
580 // direction says so (`apps/migration_mode.ts`); the spawner's own words follow.
581 let direction = a.mode === "migration" ? migrationDirection(plan.direction) : plan.direction;
569582 if (plan.migration) {
570583 const mode = {
571584 origin: cleanOrigin(`${app.config.url ?? `http://${app.config.host ?? "localhost"}`}/${o}/${n}`),
572585 open: parent.visibility === "public",
573586 };
574587 setMigration(child.db, repo.id, mode.origin, mode.open);
575 direction = [migrationDirectionFor(mode), plan.direction].filter((s) => s !== "").join(". ");
588 direction = [migrationDirectionFor(mode), direction].filter((s) => s !== "").join(". ");
576589 }
577590 if (direction !== "" && repo.autonomyDirection !== direction)
578591 repo = updateRepoSettings(child.db, repo, { autonomyDirection: direction });
592 // An autonomous or migrating app is on the knob's `go` from the first tick: the crew plans,
593 // decides and ships on its own. A fork keeps what the starter crew gives it.
594 if (a.mode !== undefined && !isGo(repo))
595 repo = updateRepoSettings(child.db, repo, { autonomy: "autonomous", autonomyBy: founder.id, plansNeedNod: false, decisionsBy: "decider" });
579596 appEntries.push(
580597 await linkAppAtBirth(app, child, dir, {
581598 org: org.username,
src/contract/openapi/routes/deleteApiV1ForgesRecipesName.ts added +10
@@ -0,0 +1,10 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: "/api/v1/forges/recipes/{name}",
6 summary: "Delete one of the person's saved forge recipes by name (a person, write scope)",
7 auth: true,
8 role: "member",
9 refusals: { not_found: "no recipe has this name (404)" },
10 };
src/contract/openapi/routes/getApiV1ForgesRecipes.ts added +10
@@ -0,0 +1,10 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: "/api/v1/forges/recipes",
6 summary: "List the saved forge recipes of the person the token belongs to (read scope): each name with the config it spawns again",
7 auth: true,
8 role: "member",
9 refusals: { forbidden: "the token is not a person (403)" },
10 };
src/contract/openapi/routes/index.ts +3
@@ -8,6 +8,7 @@ export { route as deleteApiV1CodesId } from "./deleteApiV1CodesId.ts";
88 export { route as deleteApiV1ConversationFilesId } from "./deleteApiV1ConversationFilesId.ts";
99 export { route as deleteApiV1ConversationQueueId } from "./deleteApiV1ConversationQueueId.ts";
1010 export { route as deleteApiV1FeaturesSlug } from "./deleteApiV1FeaturesSlug.ts";
11 export { route as deleteApiV1ForgesRecipesName } from "./deleteApiV1ForgesRecipesName.ts";
1112 export { route as deleteApiV1OrgsOrgTeamsTeam } from "./deleteApiV1OrgsOrgTeamsTeam.ts";
1213 export { route as deleteApiV1OrgsOrgTeamsTeamMembersUsername } from "./deleteApiV1OrgsOrgTeamsTeamMembersUsername.ts";
1314 export { route as deleteApiV1ReposOwnerName } from "./deleteApiV1ReposOwnerName.ts";
@@ -103,6 +104,7 @@ export { route as getApiV1Forges } from "./getApiV1Forges.ts";
103104 export { route as getApiV1ForgesNameBill } from "./getApiV1ForgesNameBill.ts";
104105 export { route as getApiV1ForgesNamePlan } from "./getApiV1ForgesNamePlan.ts";
105106 export { route as getApiV1ForgesNameSandbox } from "./getApiV1ForgesNameSandbox.ts";
107 export { route as getApiV1ForgesRecipes } from "./getApiV1ForgesRecipes.ts";
106108 export { route as getApiV1ForgesSizes } from "./getApiV1ForgesSizes.ts";
107109 export { route as getApiV1ForgesTemplates } from "./getApiV1ForgesTemplates.ts";
108110 export { route as getApiV1Front } from "./getApiV1Front.ts";
@@ -431,6 +433,7 @@ export { route as putApiV1FeaturesSlug } from "./putApiV1FeaturesSlug.ts";
431433 export { route as putApiV1ForgeEconomics } from "./putApiV1ForgeEconomics.ts";
432434 export { route as putApiV1ForgesNameCredit } from "./putApiV1ForgesNameCredit.ts";
433435 export { route as putApiV1ForgesNamePlan } from "./putApiV1ForgesNamePlan.ts";
436 export { route as putApiV1ForgesRecipesName } from "./putApiV1ForgesRecipesName.ts";
434437 export { route as putApiV1Front } from "./putApiV1Front.ts";
435438 export { route as putApiV1PacksName } from "./putApiV1PacksName.ts";
436439 export { route as putApiV1ReposOwnerNameAppDomainsHostOldRecords } from "./putApiV1ReposOwnerNameAppDomainsHostOldRecords.ts";
src/contract/openapi/routes/putApiV1ForgesRecipesName.ts added +10
@@ -0,0 +1,10 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: "/api/v1/forges/recipes/{name}",
6 summary: "Save a forge recipe under a name (a person, write scope): the apps, how each starts, admin and domain; never the forge name, a key or a brief",
7 auth: true,
8 role: "member",
9 refusals: { invalid: "the config does not validate (422)" },
10 };
src/http/api/forges.ts +39
@@ -15,6 +15,7 @@ import { clientRows, listed } from "../../spawn/clients.ts";
1515 import { previewDoor, reissueDoor, spawnDoor } from "../../spawn/door.ts";
1616 import { checkMove } from "../../spawn/move_check.ts";
1717 import { moveToCell } from "../../spawn/move_cell.ts";
18 import { deleteRecipe, listRecipes, saveRecipe } from "../../spawn/recipes.ts";
1819 import { sizesView } from "../../spawn/sizes.ts";
1920 import { templatesView } from "../../spawn/templates.ts";
2021 import { billDownload } from "./forge_bill.ts";
@@ -48,6 +49,12 @@ function plansAnswer(ctx: Ctx): Response {
4849 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
4950 }
5051
52 /**
53 * A recipe name from the path: the router has already percent-decoded it, so it is not decoded
54 * again.
55 */
56 const recipeNameOf = (raw: string | undefined): string => (raw ?? "").trim();
57
5158 export function forgeRoutes(router: Router<Handler>): void {
5259 router.add("GET", "/api/v1/plans", plansAnswer);
5360 // What small, medium and large mean, and which templates a child may
@@ -97,6 +104,38 @@ export function forgeRoutes(router: Router<Handler>): void {
97104 return json(door.body, door.status);
98105 });
99106
107 // A person's saved recipes (`spawn/recipes.ts`): the forge configs they spawn again.
108 router.add("GET", "/api/v1/forges/recipes", (ctx) => {
109 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
110 const denied = requireScope(ctx, "ro");
111 if (denied) return denied;
112 const user = ctx.auth.user;
113 if (user === undefined) return forbidden();
114 return json({ items: listRecipes(ctx.app.config.dataDir, user.id) });
115 });
116 router.add("PUT", "/api/v1/forges/recipes/:name", async (ctx) => {
117 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden();
118 const denied = requireScope(ctx, "rw");
119 if (denied) return denied;
120 const user = ctx.auth.user;
121 if (user === undefined || user.kind !== "user") return forbidden();
122 const name = recipeNameOf(ctx.params["name"]);
123 const input = await body(ctx.request);
124 const saved = saveRecipe(ctx.app.config.dataDir, user.id, name, input["config"]);
125 return saved.ok ? json(saved.value) : apiError("invalid", 422, `${saved.error.field}: ${saved.error.reason}`);
126 });
127 router.add("DELETE", "/api/v1/forges/recipes/:name", (ctx) => {
128 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden();
129 const denied = requireScope(ctx, "rw");
130 if (denied) return denied;
131 const user = ctx.auth.user;
132 if (user === undefined || user.kind !== "user") return forbidden();
133 const name = recipeNameOf(ctx.params["name"]);
134 return deleteRecipe(ctx.app.config.dataDir, user.id, name)
135 ? json({ deleted: true })
136 : apiError("not_found", 404, "no such recipe");
137 });
138
100139 // The dollars this forge lends a child on its own model credential (#10484): a site admin sets
101140 // the cap.
102141 router.add("PUT", "/api/v1/forges/:name/credit", async (ctx) => {
src/http/mcp/tools/spawn.ts +3 −1
@@ -5,7 +5,7 @@ import { good, bad, type Tool, APP_ARG, REVEAL_ARG, LINK_KEPT, LINK_REVEALED } f
55
66 export const tool: Tool = {
77 name: "spawn",
8 doc: "`{ name, apps?, crew?, direction?, fresh?, purpose?, followMode?, size?, plan?, template?, keepAccess?, migration?, dryRun?, reveal? }`: a child forge to keep (`purpose: \"contribute\"` makes none: it answers the fork path), planned first (`dryRun` is true unless `false`); an admin's, and an `ro` token may plan but not make; `reveal: true` shows the claim link",
8 doc: "`{ name, config? | recipe?, apps?, crew?, direction?, fresh?, purpose?, followMode?, size?, plan?, template?, keepAccess?, migration?, dryRun?, reveal? }`: a child forge to keep (`purpose: \"contribute\"` makes none: it answers the fork path), planned first (`dryRun` is true unless `false`); an admin's, and an `ro` token may plan but not make; `reveal: true` shows the claim link",
99 description:
1010 "Spawn a child forge. Plans first.",
1111 inputSchema: {
@@ -47,6 +47,8 @@ export const tool: Tool = {
4747 type: "string",
4848 description: "From `templates`, or owner/name of a template repo.",
4949 },
50 config: { type: "object", description: "{apps:[{repo,mode}],budgetUsd?}" },
51 recipe: { type: "string", description: "Saved recipe name." },
5052 keepAccess: {
5153 type: "boolean",
5254 description: "Stay an owner.",
src/spawn/claim.ts +5 −3
@@ -388,8 +388,8 @@ export function becomeOrg(
388388 db.query("DELETE FROM session WHERE user_id = ?1").run(orgId);
389389 if (input.credential !== undefined && !addPasskey(db, orgId, "Passkey", input.credential).ok) throw new PasskeyRefused();
390390 // The one-time claim link is the proof, as it is for an account made beside the organisation
391 // (`createUser` with `trusted`). An organisation needed no proof; the person it becomes does, or
392 // the crew answers their first ask with "Verify your email first."
391 // (`createUser` with `trusted`). An organisation needed no proof; the person it becomes does,
392 // or the crew answers their first ask with "Verify your email first."
393393 markVerified(db, orgId, new Date().toISOString());
394394 return true;
395395 });
@@ -435,7 +435,9 @@ export interface LinkInfo {
435435 readonly expiresAt?: string;
436436 }
437437
438 /** True while an ended link can still be brought back: revoked in the last minute, in date, unspent. */
438 /**
439 * True while an ended link can still be brought back: revoked in the last minute, in date, unspent.
440 */
439441 export const undoable = (link: LinkInfo, now = Date.now()): boolean =>
440442 link.state === "ended" && link.revokedAt !== null && now - Date.parse(link.revokedAt) <= REVOKE_UNDO_MS;
441443
src/spawn/door.ts +43 −4
@@ -40,7 +40,8 @@ import {
4040 type BodyStore,
4141 type Placement,
4242 } from "./placement.ts";
43 import { dryRun, planSpawn, KEY_BUDGET_NOTE, MAX_APPS, type CatalogApp, type CrewBrief, type SpawnSource } from "./plan.ts";
43 import { parseConfig, recipeNamed, type ForgeConfig } from "./recipes.ts";
44 import { appEntry, dryRun, planSpawn, KEY_BUDGET_NOTE, MAX_APPS, type CatalogApp, type CrewBrief, type SpawnSource } from "./plan.ts";
4445 import { bootHostedChild } from "./host.ts";
4546 import { cellChildren, cellPlacement, ownsBody } from "./cell.ts";
4647 import { cellsAvailable } from "../apps/contain.ts";
@@ -233,8 +234,43 @@ export async function spawnDoor(
233234 if (raw["dryRun"] !== undefined && typeof raw["dryRun"] !== "boolean")
234235 return invalid("dryRun", "must be true or false");
235236 const dry = raw["dryRun"] !== false;
236 const apps = names(raw["apps"], "apps", MAX_APPS);
237 if (!Array.isArray(apps)) return apps;
237 // A config (or a saved recipe) is the same four fields the request may carry at top level.
238 let budgetWaits: number | undefined;
239 if (raw["config"] !== undefined || raw["recipe"] !== undefined) {
240 if (raw["config"] !== undefined && raw["recipe"] !== undefined) return invalid("config", "send a config or a recipe, not both");
241 let cfg: ForgeConfig;
242 if (raw["recipe"] !== undefined) {
243 if (user === undefined || typeof raw["recipe"] !== "string") return invalid("recipe", "name one of your saved recipes");
244 const kept = recipeNamed(ctx.app.config.dataDir, user.id, raw["recipe"]);
245 if (kept === undefined) return invalid("recipe", `you have no recipe named ${raw["recipe"].slice(0, 40)}`);
246 cfg = kept.config;
247 } else {
248 const parsed = parseConfig(raw["config"]);
249 if (!parsed.ok) return spawnWords({ kind: "invalid", ...parsed.error });
250 cfg = parsed.value;
251 }
252 // A key never travels in a config, so its budget applies only when one is given beside it.
253 if (raw["modelKey"] === undefined && raw["budgetUsd"] === undefined) budgetWaits = cfg.budgetUsd;
254 const rest = Object.fromEntries(Object.entries(raw).filter(([k]) => k !== "config" && k !== "recipe"));
255 raw = {
256 ...rest,
257 apps: cfg.apps,
258 ...(cfg.budgetUsd === undefined || budgetWaits !== undefined ? {} : { budgetUsd: cfg.budgetUsd }),
259 ...(cfg.admin === undefined ? {} : { admin: cfg.admin }),
260 ...(cfg.domain === undefined ? {} : { domain: cfg.domain }),
261 };
262 }
263 const appsIn = raw["apps"] ?? [];
264 if (!Array.isArray(appsIn) || appsIn.length > MAX_APPS) return invalid("apps", `must be a list of at most ${MAX_APPS} apps`);
265 const apps: string[] = [];
266 for (const item of appsIn) {
267 const e = appEntry(item);
268 if (!e.ok) return invalid("apps", e.error);
269 // An autonomous or migrating app hands the crew the wheel and takes the spawner's words as
270 // its direction: only a signed-in person may ask for that.
271 if (anon && e.value.mode !== "fork") return invalid("apps", `${e.value.ref}: sign in to start an app as ${e.value.mode}; a stranger's apps are forks`);
272 apps.push(e.value.ref);
273 }
238274 const crew = names(raw["crew"], "crew", MAX_CREW);
239275 if (!Array.isArray(crew)) return crew;
240276 if (anon && crew.length > 0)
@@ -335,7 +371,7 @@ export async function spawnDoor(
335371 const input = {
336372 name: raw["name"],
337373 org: raw["name"],
338 apps,
374 apps: appsIn,
339375 carryBriefs: briefs.length > 0,
340376 carrySubscriptions: false,
341377 direction: raw["direction"],
@@ -343,6 +379,8 @@ export async function spawnDoor(
343379 // by whoever opens the link.
344380 keepAccess: anon ? false : raw["keepAccess"],
345381 budgetUsd: raw["budgetUsd"],
382 admin: raw["admin"],
383 domain: raw["domain"],
346384 fresh: raw["fresh"],
347385 followMode: raw["followMode"],
348386 size,
@@ -367,6 +405,7 @@ export async function spawnDoor(
367405 firstAdmin: user?.username ?? null,
368406 ...(giftSeen === undefined ? {} : { gift: giftSeen }),
369407 ...dryRun(planned.value, source),
408 ...(budgetWaits === undefined ? {} : { budgetNote: `the $${budgetWaits} budget applies when a model key is given with it; none is, so this forge gets no key` }),
370409 ...(planned.value.budgetUsd === null ? {} : { keyNote: KEY_BUDGET_NOTE }),
371410 },
372411 };
src/spawn/plan.ts +60 −6
@@ -38,6 +38,13 @@ export const MAX_FRESH_CHARS = 200;
3838 export const NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/;
3939 const PLAN_KEY = /^[a-z][a-z0-9-]{0,19}$/;
4040 const APP_REF = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
41 /**
42 * How an app goes into the child: a `fork` (the default, never named in the plan), or one the crew
43 * works on its own.
44 */
45 export const APP_MODES = ["fork", "autonomous", "migration"] as const;
46 export type AppMode = (typeof APP_MODES)[number];
47 const HOSTNAME = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
4148
4249 /** An app the viewer can see, as the caller found it. */
4350 export interface CatalogApp {
@@ -69,6 +76,13 @@ export interface SpawnInput {
6976 * The key itself never enters the plan: only that there is one, capped.
7077 */
7178 readonly budgetUsd?: unknown;
79 /**
80 * The username meant to administer the child once it is taken over; optional, recorded in the
81 * plan.
82 */
83 readonly admin?: unknown;
84 /** The domain the child is meant to be reached at; optional, recorded in the plan. */
85 readonly domain?: unknown;
7286 /** One line describing a fresh app to start in the child, beside the forked ones; optional. */
7387 readonly fresh?: unknown;
7488 /** How the child follows the forge's code: `take-updates` (default) or `tell-me`. */
@@ -101,6 +115,8 @@ export interface PlannedApp {
101115 readonly history: "full";
102116 readonly forgeJson: true;
103117 readonly bytes: number;
118 /** Present only when not a plain fork, so a plan of forks hashes as it always did. */
119 readonly mode?: Exclude<AppMode, "fork">;
104120 }
105121
106122 /** An app begun from a sentence, not forked from anything. */
@@ -123,6 +139,10 @@ export interface SpawnPlan {
123139 readonly budgetUsd: number | null;
124140 /** Whom the child is for, for the parent's client list; absent when unsaid. */
125141 readonly forWhom?: string;
142 /** Who administers the child once taken over, present only when named. */
143 readonly admin?: string;
144 /** The domain the child is meant to answer at, present only when named. */
145 readonly domain?: string;
126146 /** A fresh app, present only when asked for. */
127147 readonly fresh?: PlannedFresh;
128148 /** How the child follows its parent's forge code; absent means `take-updates`. */
@@ -162,6 +182,12 @@ export const LEFT_BEHIND: readonly string[] = [
162182 "user accounts",
163183 ];
164184
185 /** What a mode does, in the words the dry run uses. */
186 export const MODE_SAID: Readonly<Record<Exclude<AppMode, "fork">, string>> = {
187 autonomous: "the crew works it on its own",
188 migration: "the crew migrates it on its own",
189 };
190
165191 const refuse = (field: string, reason: string) => err<Refusal>({ field, reason });
166192 const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
167193
@@ -179,6 +205,17 @@ export function freshName(description: string, taken: ReadonlySet<string>): stri
179205 return name;
180206 }
181207
208 /** One entry of `apps`: `owner/name` (a fork) or `{repo, mode}`. */
209 export function appEntry(item: unknown): Result<{ ref: string; mode: AppMode }, string> {
210 const looks = "an app is owner/name, or {repo, mode} with a mode of fork, autonomous or migration";
211 if (typeof item === "string") return APP_REF.test(item) ? ok({ ref: item, mode: "fork" }) : err("an app reference must look like owner/name");
212 if (typeof item !== "object" || item === null || Array.isArray(item)) return err(looks);
213 const { repo, mode = "fork" } = item as { repo?: unknown; mode?: unknown };
214 if (typeof repo !== "string" || !APP_REF.test(repo)) return err("an app reference must look like owner/name");
215 if (typeof mode !== "string" || !(APP_MODES as readonly string[]).includes(mode)) return err(`${repo}: mode must be fork, autonomous or migration`);
216 return ok({ ref: repo, mode: mode as AppMode });
217 }
218
182219 export function planSpawn(
183220 input: SpawnInput,
184221 source: SpawnSource,
@@ -200,17 +237,17 @@ export function planSpawn(
200237 const known = new Map(source.catalog.map((a) => [a.ref, a] as const));
201238 const seen = new Set<string>();
202239 const apps: PlannedApp[] = [];
203 for (const ref of input.apps as unknown[]) {
204 if (typeof ref !== "string" || !APP_REF.test(ref)) {
205 return refuse("apps", "an app reference must look like owner/name");
206 }
240 for (const item of input.apps as unknown[]) {
241 const entry = appEntry(item);
242 if (!entry.ok) return refuse("apps", entry.error);
243 const { ref, mode } = entry.value;
207244 if (seen.has(ref)) return refuse("apps", `${ref} is listed twice`);
208245 seen.add(ref);
209246 const app = known.get(ref);
210247 if (!app) return refuse("apps", `${ref} is not a known app`);
211248 if (!app.readable) return refuse("apps", `${ref} is not readable by you`);
212249 const bytes = Number.isFinite(app.bytes) && app.bytes >= 0 ? Math.floor(app.bytes) : 0;
213 apps.push({ ref, history: "full", forgeJson: true, bytes });
250 apps.push({ ref, history: "full", forgeJson: true, bytes, ...(mode === "fork" ? {} : { mode }) });
214251 }
215252 apps.sort((a, b) => byText(a.ref, b.ref));
216253
@@ -260,6 +297,19 @@ export function planSpawn(
260297 if (forWhom.length > MAX_FOR_CHARS) return refuse("for", `at most ${MAX_FOR_CHARS} characters`);
261298 }
262299
300 let admin: string | undefined;
301 if (input.admin !== undefined && input.admin !== null && input.admin !== "") {
302 if (typeof input.admin !== "string" || !NAME.test(input.admin)) return refuse("admin", "an admin is a username: 1-39 characters of a-z, 0-9 and \"-\"");
303 admin = input.admin;
304 }
305
306 let domain: string | undefined;
307 if (input.domain !== undefined && input.domain !== null && input.domain !== "") {
308 const d = typeof input.domain === "string" ? input.domain.trim().toLowerCase() : "";
309 if (!HOSTNAME.test(d)) return refuse("domain", "a domain looks like clients.example.com: letters, digits and dashes between dots");
310 domain = d;
311 }
312
263313 let fresh: PlannedFresh | undefined;
264314 if (input.fresh !== undefined && input.fresh !== null && input.fresh !== "") {
265315 if (typeof input.fresh !== "string") return refuse("fresh", "must be text");
@@ -326,6 +376,8 @@ export function planSpawn(
326376 keepAccess,
327377 budgetUsd,
328378 ...(forWhom === "" ? {} : { forWhom }),
379 ...(admin === undefined ? {} : { admin }),
380 ...(domain === undefined ? {} : { domain }),
329381 ...(fresh === undefined ? {} : { fresh }),
330382 ...(followMode === undefined ? {} : { followMode }),
331383 ...(size === undefined ? {} : { size }),
@@ -340,7 +392,7 @@ const enc = new TextEncoder();
340392 /** The studio's preview: what is copied, what stays, and how many bytes. */
341393 export function dryRun(plan: SpawnPlan, source: SpawnSource): DryRun {
342394 const copied = [
343 ...plan.apps.map((a) => `app ${a.ref} (full history, forge.json)`),
395 ...plan.apps.map((a) => `app ${a.ref} (full history, forge.json${a.mode === undefined ? "" : `, ${MODE_SAID[a.mode]}`})`),
344396 ...(plan.fresh === undefined
345397 ? []
346398 : [`a fresh app ${plan.fresh.name}: ${plan.fresh.description}`]),
@@ -348,6 +400,8 @@ export function dryRun(plan: SpawnPlan, source: SpawnSource): DryRun {
348400 ...plan.subscriptions.map((s) => `subscription ${s} (name only)`),
349401 ...(plan.migration ? ["migration mode: each app's direction is to run natively there with parity to its copy here"] : []),
350402 ...(plan.direction === "" ? [] : ["your words, as the child's direction"]),
403 ...(plan.admin === undefined ? [] : [`${plan.admin}, named as its admin (recorded; whoever opens the claim link still becomes the admin)`]),
404 ...(plan.domain === undefined ? [] : [`${plan.domain}, named as its domain (recorded; it is reached at its forge address until a domain is pointed here)`]),
351405 ...(plan.keepAccess ? ["your owner access, kept after the forge is taken over"] : []),
352406 ...(plan.budgetUsd === null
353407 ? []
src/spawn/recipes.ts added +140
@@ -0,0 +1,140 @@
1 /**
2 * Recipes: a forge's config (apps and their modes, budget, admin, domain),
3 * saved under a name to spawn again. One small JSON file per person under
4 * `<data>/recipes/`, plain data in and out. A recipe holds no name for the
5 * child, no key and no brief: only what `parseConfig` validated.
6 */
7
8 import { mkdirSync, readFileSync, unlinkSync } from "node:fs";
9 import { join } from "node:path";
10 import { writePrivate } from "../kernel/file_modes.ts";
11 import { err, ok, type Result } from "../kernel/result.ts";
12 import { appEntry, MAX_APPS, planSpawn, type AppMode } from "./plan.ts";
13
14 export const MAX_RECIPES = 20;
15 const RECIPE_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,39}$/;
16 const PERSON = /^[A-Za-z0-9_-]{1,64}$/;
17
18 export interface ConfigApp {
19 readonly repo: string;
20 readonly mode: AppMode;
21 }
22
23 /** What a forge is made of, as the owner says it. */
24 export interface ForgeConfig {
25 readonly apps: readonly ConfigApp[];
26 readonly budgetUsd?: number;
27 readonly admin?: string;
28 readonly domain?: string;
29 }
30
31 export interface Recipe {
32 readonly name: string;
33 readonly config: ForgeConfig;
34 }
35
36 /**
37 * The config in a request, checked and copied: only the four fields it names, each through the
38 * plan's own rules.
39 */
40 export function parseConfig(raw: unknown): Result<ForgeConfig, { field: string; reason: string }> {
41 if (typeof raw !== "object" || raw === null || Array.isArray(raw))
42 return err({ field: "config", reason: "must be {apps: [{repo, mode}], budgetUsd?, admin?, domain?}" });
43 const c = raw as Record<string, unknown>;
44 if (!Array.isArray(c["apps"])) return err({ field: "apps", reason: "apps must be a list" });
45 if (c["apps"].length > MAX_APPS) return err({ field: "apps", reason: `at most ${MAX_APPS} apps` });
46 const apps: ConfigApp[] = [];
47 for (const item of c["apps"] as unknown[]) {
48 const e = appEntry(item);
49 if (!e.ok) return err({ field: "apps", reason: e.error });
50 apps.push({ repo: e.value.ref, mode: e.value.mode });
51 }
52 // Every other field is checked by the plan itself, so a recipe can never hold what a spawn would
53 // refuse.
54 const planned = planSpawn(
55 {
56 name: "recipe",
57 org: "recipe",
58 apps: apps.map((a) => ({ ...a })),
59 carryBriefs: false,
60 carrySubscriptions: false,
61 budgetUsd: c["budgetUsd"],
62 admin: c["admin"],
63 domain: c["domain"],
64 },
65 { catalog: apps.map((a) => ({ ref: a.repo, readable: true, bytes: 0, forgeJsonBytes: 0 })), briefs: [], subscriptions: [] },
66 );
67 if (!planned.ok) return err(planned.error);
68 const p = planned.value;
69 return ok({
70 apps,
71 ...(p.budgetUsd === null ? {} : { budgetUsd: p.budgetUsd }),
72 ...(p.admin === undefined ? {} : { admin: p.admin }),
73 ...(p.domain === undefined ? {} : { domain: p.domain }),
74 });
75 }
76
77 const fileOf = (dataDir: string, personId: string): string => join(dataDir, "recipes", `${personId}.json`);
78
79 export function listRecipes(dataDir: string, personId: string): Recipe[] {
80 if (!PERSON.test(personId)) return [];
81 let v: unknown;
82 try {
83 v = JSON.parse(readFileSync(fileOf(dataDir, personId), "utf8"));
84 } catch {
85 return [];
86 }
87 if (!Array.isArray(v)) return [];
88 const out: Recipe[] = [];
89 for (const r of v as { name?: unknown; config?: unknown }[]) {
90 const config = parseConfig(r?.config);
91 if (typeof r?.name === "string" && RECIPE_NAME.test(r.name) && config.ok) out.push({ name: r.name, config: config.value });
92 }
93 return out;
94 }
95
96 export const recipeNamed = (dataDir: string, personId: string, name: string): Recipe | undefined =>
97 listRecipes(dataDir, personId).find((r) => r.name === name);
98
99 function write(dataDir: string, personId: string, recipes: readonly Recipe[]): void {
100 mkdirSync(join(dataDir, "recipes"), { recursive: true });
101 writePrivate(fileOf(dataDir, personId), JSON.stringify(recipes));
102 }
103
104 /**
105 * Save (or replace) a recipe under a name. The read, the change and the write (a rename into
106 * place, `writePrivate`) are one synchronous run with no await between them, so two saves in this
107 * one process cannot interleave and lose one.
108 */
109 export function saveRecipe(
110 dataDir: string,
111 personId: string,
112 name: unknown,
113 config: unknown,
114 ): Result<Recipe, { field: string; reason: string }> {
115 if (!PERSON.test(personId)) return err({ field: "recipe", reason: "sign in to save a recipe" });
116 if (typeof name !== "string" || !RECIPE_NAME.test(name.trim()))
117 return err({ field: "recipe", reason: "a recipe name is 1-40 characters of letters, digits, spaces, dots, dashes and underscores" });
118 const parsed = parseConfig(config);
119 if (!parsed.ok) return parsed;
120 const recipe: Recipe = { name: name.trim(), config: parsed.value };
121 const kept = listRecipes(dataDir, personId).filter((r) => r.name !== recipe.name);
122 if (kept.length >= MAX_RECIPES) return err({ field: "recipe", reason: `at most ${MAX_RECIPES} recipes; delete one first` });
123 write(dataDir, personId, [...kept, recipe].sort((a, b) => (a.name < b.name ? -1 : 1)));
124 return ok(recipe);
125 }
126
127 /** Forget a recipe; false when there was none. */
128 export function deleteRecipe(dataDir: string, personId: string, name: string): boolean {
129 const all = listRecipes(dataDir, personId);
130 const kept = all.filter((r) => r.name !== name);
131 if (kept.length === all.length) return false;
132 if (kept.length === 0) {
133 try {
134 unlinkSync(fileOf(dataDir, personId));
135 } catch {
136 /* already gone */
137 }
138 } else write(dataDir, personId, kept);
139 return true;
140 }
src/tui/screens/newforge.ts +34 −5
@@ -15,6 +15,7 @@ import { quotaFull } from "../../spawn/quota.ts";
1515 import { FOLLOW_LINE, FOLLOW_WORDS } from "../../spawn/follow_words.ts";
1616 import { isFollowMode } from "../../spawn/chain.ts";
1717 import { MAX_BUDGET_USD, MIN_BUDGET_USD } from "../../spawn/plan.ts";
18 import { listRecipes, saveRecipe } from "../../spawn/recipes.ts";
1819 import type { Ctx, Screen } from "../app/app.ts";
1920 import { binding } from "../app/keys.ts";
2021 import { style } from "../term/style.ts";
@@ -42,7 +43,7 @@ const SPECS: readonly Spec[] = [
4243 { key: "name", label: "Name", hint: "Lowercase letters, digits and dashes." },
4344 { key: "for", label: "For whom", hint: "A person or client, for your list of forges sent. Optional." },
4445 { key: "direction", label: "What it is for", hint: "The crew's first direction. Optional." },
45 { key: "apps", label: "Apps to fork", hint: "owner/name, comma-separated. Optional." },
46 { key: "apps", label: "Apps to fork", hint: "owner/name, comma-separated; owner/name:autonomous or :migration to have the crew work it. Optional." },
4647 { key: "fresh", label: "Or a fresh app", hint: "One line on what it is. Optional." },
4748 { key: "modelKey", label: "AI account key", hint: "Sealed in the new forge, never shown again. Optional.", secret: true },
4849 { key: "modelEndpoint", label: "API base URL", hint: "Omit /v1: https://openrouter.ai/api. Empty = your AI's own service." },
@@ -51,8 +52,11 @@ const SPECS: readonly Spec[] = [
5152 { key: "size", label: "Size", hint: "small (default), medium or large: left and right choose, or type it.", choices: SIZE_CHOICES },
5253 { key: "template", label: "Template", hint: TEMPLATE_HINT, choices: TEMPLATE_CHOICES },
5354 { key: "migration", label: "Mode of the forked apps", hint: "own (default) or migration: the crew works to run each app natively there with parity to its copy here.", choices: ["own", "migration"] },
55 { key: "saveAs", label: "Save as recipe", hint: "A name to keep the apps and budget under, saved with the plan. Optional." },
5456 ];
5557
58 const RECIPE_SPEC: Spec = { key: "recipe", label: "Spawn from recipe", hint: "Left and right choose one of yours; its apps and budget replace the fields above.", choices: [""] };
59
5660 /** The chosen template's own sentence; a typed id that is no template keeps the general hint. */
5761 function templateHint(id: string): string {
5862 const t = TEMPLATES.find((x) => x.id === id);
@@ -72,7 +76,12 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
7276 const repoTemplates = listReposVisibleTo(f.app.db, f.user, { templatesOnly: true, limit: 50 }).map(
7377 (r) => `${r.ownerName}/${r.name}`,
7478 );
75 const specs = SPECS.map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s));
79 // Your saved recipes, by name: only a signed-in person has any.
80 const recipes = f.user === undefined ? [] : listRecipes(f.app.config.dataDir, f.user.id).map((r) => r.name);
81 const specs = [
82 ...SPECS.map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s)),
83 ...(recipes.length === 0 ? [] : [{ ...RECIPE_SPEC, choices: ["", ...recipes] }]),
84 ];
7685 const values: Record<string, string> = { ...initial };
7786 let focus = 0;
7887 let errorKey: string | undefined;
@@ -85,18 +94,24 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
8594
8695 const val = (k: string): string => (values[k] ?? "").trim();
8796
97 /** `owner/name` or `owner/name:mode`, as the door's `apps` entries. */
98 const appsOf = (): (string | { repo: string; mode: string })[] =>
99 val("apps").split(",").map((a) => a.trim()).filter((a) => a !== "").map((a) => {
100 const at = a.indexOf(":");
101 return at < 0 ? a : { repo: a.slice(0, at), mode: a.slice(at + 1) };
102 });
103
88104 const request = (dryRun: boolean): Record<string, unknown> => {
89 const apps = val("apps").split(",").map((a) => a.trim()).filter((a) => a !== "");
90105 return {
91106 name: val("name"),
92 apps,
107 ...(val("recipe") === "" ? { apps: appsOf() } : { recipe: val("recipe") }),
93108 ...(val("fresh") === "" ? {} : { fresh: val("fresh") }),
94109 followMode: val("followMode") === "" ? "take-updates" : val("followMode"),
95110 ...(val("for") === "" ? {} : { for: val("for") }),
96111 ...(val("direction") === "" ? {} : { direction: val("direction") }),
97112 ...(val("modelKey") === "" ? {} : { modelKey: val("modelKey") }),
98113 ...(val("modelEndpoint") === "" ? {} : { modelEndpoint: val("modelEndpoint") }),
99 ...(val("budgetUsd") === "" ? {} : { budgetUsd: Number(val("budgetUsd")) }),
114 ...(val("budgetUsd") === "" || val("recipe") !== "" ? {} : { budgetUsd: Number(val("budgetUsd")) }),
100115 ...(val("migration") === "migration" ? { migration: true } : {}),
101116 // Small is the default: it is not recorded, as on the page.
102117 ...(val("size") === "" || val("size") === DEFAULT_SIZE ? {} : { size: val("size") }),
@@ -116,6 +131,19 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
116131 auth: { user: f.user, scope: undefined, via: "none" as const },
117132 theme: undefined,
118133 };
134 // A name under "Save as recipe" keeps the config before the plan or the spawn; a refusal
135 // makes nothing, as on the page.
136 if (val("saveAs") !== "" && val("recipe") === "") {
137 const kept =
138 f.user === undefined
139 ? undefined
140 : saveRecipe(f.app.config.dataDir, f.user.id, val("saveAs"), {
141 apps: appsOf().map((a) => (typeof a === "string" ? { repo: a, mode: "fork" } : a)),
142 ...(val("budgetUsd") === "" ? {} : { budgetUsd: Number(val("budgetUsd")) }),
143 });
144 if (kept === undefined || !kept.ok)
145 return { status: 422, body: { error: "invalid", message: `saveAs: ${kept === undefined ? "sign in to save a recipe" : kept.error.reason}` } };
146 }
119147 return spawnDoor(hctx, f.user, request(dryRun));
120148 };
121149
@@ -156,6 +184,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
156184 `A forge at ${childUrlOf(f.app, val("name"))}.`,
157185 `It follows this forge's code as ${mode}${isFollowMode(mode) ? `: it ${FOLLOW_WORDS[mode]}` : "."}`,
158186 "Whoever opens the link becomes its admin.",
187 ...(val("saveAs") === "" || val("recipe") !== "" ? [] : [`Saved as the recipe ${val("saveAs")}.`]),
159188 ...(budget === null ? [] : [`Its crew runs on your key, up to $${budget} for the key's whole life.`]),
160189 "Copied into it:",
161190 ...copied.map((c) => ` ${c}`),
src/web/pages/new-forge.ts +131 −7
@@ -19,7 +19,10 @@ import { giftOf, REDEEM_WORDS } from "../../actions/codes.ts";
1919 import { limitValue } from "../../settings/limits.ts";
2020 import { quotaFull } from "../../spawn/quota.ts";
2121 import { childHost, childUrlOf, noRoom, spawnDoor, type Door } from "../../spawn/door.ts";
22 import { listRecipes, saveRecipe, type ForgeConfig, type Recipe } from "../../spawn/recipes.ts";
2223 import {
24 APP_MODES,
25 type AppMode,
2326 LEFT_BEHIND,
2427 MAX_FOR_CHARS,
2528 MAX_FRESH_CHARS,
@@ -45,6 +48,10 @@ interface Values {
4548 readonly forWhom: string;
4649 readonly direction: string;
4750 readonly apps: readonly string[];
51 /** How each chosen app goes in (`mode:<owner/name>` fields): absent means a fork. */
52 readonly modes: Readonly<Record<string, string>>;
53 /** The name a config is saved under; empty saves nothing. */
54 readonly saveAs: string;
4855 readonly crew: readonly string[];
4956 readonly fresh: string;
5057 readonly followMode: string;
@@ -65,6 +72,8 @@ const EMPTY: Values = {
6572 forWhom: "",
6673 direction: "",
6774 apps: [],
75 modes: {},
76 saveAs: "",
6877 crew: [],
6978 fresh: "",
7079 followMode: "take-updates",
@@ -109,11 +118,13 @@ interface Reads {
109118 /** Repositories marked as templates that the viewer can read (`full_name`), listed in the
110119 * Template select. */
111120 readonly templates: readonly string[];
121 /** The signed-in person's saved recipes (`spawn/recipes.ts`). */
122 readonly recipes: readonly Recipe[];
112123 }
113124
114125 function readsFor(ctx: Ctx, user: User | undefined): Reads {
115126 const full = timePhase(ctx.request, "room", () => noRoom(ctx.app));
116 if (full) return { full, quota: undefined, repos: [], crew: [], templates: [] };
127 if (full) return { full, quota: undefined, repos: [], crew: [], templates: [], recipes: [] };
117128 const quota = quotaFull(ctx.app.config.dataDir);
118129 // Each repository once, as its source, and public only; a stranger sees
119130 // none and no crew: nothing private travels to a child they have not claimed.
@@ -127,7 +138,8 @@ function readsFor(ctx: Ctx, user: User | undefined): Reads {
127138 const templates = timePhase(ctx.request, "templates", () =>
128139 listReposVisibleTo(ctx.app.db, user, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`),
129140 );
130 return { full, quota, repos, crew, templates };
141 const recipes = user === undefined ? [] : listRecipes(ctx.app.config.dataDir, user.id);
142 return { full, quota, repos, crew, templates, recipes };
131143 }
132144
133145 /** The three sizes, the one asked for chosen (small when the value is not one of them). */
@@ -208,7 +220,7 @@ function formView(
208220 plan: Html | null,
209221 reads: Reads,
210222 ): Html {
211 const { full, quota, repos, crew, templates } = reads;
223 const { full, quota, repos, crew, templates, recipes } = reads;
212224 if (full)
213225 return html`<div class="narrow-wide" data-forges>
214226 ${pageHead("New forge")}
@@ -235,6 +247,7 @@ function formView(
235247 ? html`<p class="error mb" role="alert">${errors["form"]}</p>`
236248 : null}
237249 ${plan}
250 ${recipesView(recipes, errors)}
238251 <section class="settings-block">
239252 <h2>Its name and apps</h2>
240253 <form method="post" action="/forges/new" class="stack" id="new-forge">
@@ -287,6 +300,7 @@ function formView(
287300 // With no picker to show it, an error about the apps is said here.
288301 ...(freshErr ? { error: freshErr } : {}),
289302 })}
303 ${modeRows(values, errors["modes"])}
290304 <details class="disclosure" ${Object.keys(errors).some((k) => MORE_FIELDS.includes(k)) ? html`open` : null}>
291305 <summary>More options</summary>
292306 <fieldset class="field" ${errors["followMode"] ? html`data-invalid` : null}>
@@ -400,6 +414,18 @@ function formView(
400414 </p>
401415 </details>
402416 ${codeField(values.code, errors["code"])}
417 ${anon
418 ? null
419 : html`<details class="field"${values.saveAs !== "" || errors["recipe"] ? html` open` : null}>
420 <summary>Keep this setup as a recipe</summary>
421 ${formField({
422 label: "Recipe name",
423 name: "saveAs",
424 value: values.saveAs,
425 hint: "Saved with the plan or the spawn, to spawn again. Not the name, the key or the brief.",
426 ...(errors["recipe"] ? { error: errors["recipe"] } : {}),
427 })}
428 </details>`}
403429 <div class="form-actions" data-stick>
404430 <button class="btn" type="submit" name="do" value="plan">
405431 See the plan
@@ -413,6 +439,75 @@ function formView(
413439 </div>`;
414440 }
415441
442 const MODE_LABELS: Readonly<Record<AppMode, string>> = {
443 fork: "Fork: a copy it follows, with its history",
444 autonomous: "Autonomous: the crew works it on its own",
445 migration: "Migration: the crew migrates it into the forge's shape",
446 };
447
448 const modeOf = (values: Values, ref: string): AppMode => {
449 const m = values.modes[ref];
450 return (APP_MODES as readonly string[]).includes(m ?? "") ? (m as AppMode) : "fork";
451 };
452
453 /** One mode per chosen app. A fork is the default. */
454 function modeRows(values: Values, error: string | undefined): Html | null {
455 if (values.apps.length === 0) return null;
456 return html`<fieldset class="field" id="app-how" ${error ? html`data-invalid` : null}>
457 <legend>How each app goes in</legend>
458 ${values.apps.map(
459 (ref, i) => html`<div class="field">
460 <label for="mode-${i}">${ref}</label>
461 <select class="input" id="mode-${i}" name="mode:${ref}">
462 ${APP_MODES.map((m) => html`<option value="${m}" ${modeOf(values, ref) === m ? html`selected` : null}>${MODE_LABELS[m]}</option>`)}
463 </select>
464 </div>`,
465 )}
466 ${error ? html`<span class="error">${error}</span>` : null}
467 </fieldset>`;
468 }
469
470 /** The config the form describes, as `spawn/recipes.ts` stores it. */
471 function configOf(values: Values): Record<string, unknown> {
472 return {
473 apps: values.apps.map((repo) => ({ repo, mode: values.modes[repo] ?? "fork" })),
474 ...(values.budgetUsd === "" ? {} : { budgetUsd: Number(values.budgetUsd) }),
475 };
476 }
477
478 const sayConfig = (c: ForgeConfig): string =>
479 [
480 `${c.apps.length} ${c.apps.length === 1 ? "app" : "apps"}${c.apps.some((a) => a.mode !== "fork") ? ` (${c.apps.map((a) => `${a.repo.split("/")[1]} ${a.mode}`).join(", ")})` : ""}`,
481 c.budgetUsd === undefined ? null : `$${c.budgetUsd} budget`,
482 ]
483 .filter((x) => x !== null)
484 .join(", ");
485
486 /**
487 * Saved recipes: a name for the new forge, Spawn. A budget needs its key again, as a key is never
488 * kept.
489 */
490 function recipesView(recipes: readonly Recipe[], errors: Errors): Html | null {
491 if (recipes.length === 0) return null;
492 return html`<section class="settings-block" id="recipes">
493 <h2>Your recipes</h2>
494 ${recipes.map(
495 (r, i) => html`<form method="post" action="/forges/new" class="stack mb" data-recipe>
496 <input type="hidden" name="recipe" value="${r.name}" />
497 <p><b>${r.name}</b> <span class="muted small">${sayConfig(r.config)}</span></p>
498 ${formField({ label: "Name for the new forge", name: "name", id: `recipe-${i}-name`, required: true, ...(errors["recipe"] ? { error: errors["recipe"] } : {}) })}
499 ${r.config.budgetUsd === undefined
500 ? null
501 : formField({ label: "AI account key", name: "modelKey", id: `recipe-${i}-key`, type: "password", autocomplete: "off", required: true, hint: `For its $${r.config.budgetUsd} budget; sealed in the new forge, never shown again.` })}
502 <div class="form-actions">
503 <button class="btn" type="submit" name="do" value="plan">See the plan</button>
504 ${btn("Spawn", { variant: "primary" })}
505 </div>
506 </form>`,
507 )}
508 </section>`;
509 }
510
416511 /**
417512 * The dry run, as the page shows it above the form: what the person gets
418513 * (where, as whom, with whom still there, on what budget), then what is
@@ -549,6 +644,10 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
549644 forWhom: field(form, "for").trim(),
550645 direction: field(form, "direction"),
551646 apps: all(form, "apps"),
647 modes: Object.fromEntries(
648 [...form.keys()].filter((k) => k.startsWith("mode:")).map((k) => [k.slice(5), field(form, k).trim()] as const),
649 ),
650 saveAs: field(form, "saveAs").trim(),
552651 crew: all(form, "crew"),
553652 fresh: field(form, "fresh").trim(),
554653 followMode: field(form, "followMode").trim() || "take-updates",
@@ -563,9 +662,27 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
563662 };
564663 const key = field(form, "modelKey").trim();
565664 const planOnly = field(form, "do") === "plan";
665 // A name under "Keep this setup as a recipe" saves the form's config before the plan or the
666 // spawn; a refusal shows the form again and makes nothing.
667 let saved: string | undefined;
668 if (values.saveAs !== "" && field(form, "recipe").trim() === "") {
669 const kept = user === undefined ? undefined : saveRecipe(ctx.app.config.dataDir, user.id, values.saveAs, configOf(values));
670 if (kept === undefined || !kept.ok) {
671 const refusal = kept === undefined ? { field: "recipe", reason: "sign in to save a recipe" } : kept.error;
672 const errors: Errors = { [refusal.field === "apps" ? "modes" : refusal.field]: plainError(refusal.reason) };
673 return page({ ctx, title: "New forge", body: formView(ctx, user, values, errors, null, readsFor(ctx, user)) }, 422);
674 }
675 saved = kept.value.name;
676 }
677 const recipe = field(form, "recipe").trim();
566678 const door = await spawnDoor(ctx, user, {
567679 name: values.name,
568 apps: values.apps,
680 // A recipe carries its own apps, modes and budget; the form's are not mixed in.
681 ...(recipe !== ""
682 ? { recipe }
683 : {
684 apps: values.apps.map((repo) => ({ repo, mode: values.modes[repo] ?? "fork" })),
685 }),
569686 crew: values.crew,
570687 keepAccess: values.keepAccess,
571688 ...(values.migration ? { migration: true } : {}),
@@ -575,7 +692,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
575692 ...(values.direction.trim() === "" ? {} : { direction: values.direction }),
576693 ...(key === "" ? {} : { modelKey: key }),
577694 ...(values.modelEndpoint === "" ? {} : { modelEndpoint: values.modelEndpoint }),
578 ...(values.budgetUsd === "" ? {} : { budgetUsd: Number(values.budgetUsd) }),
695 ...(values.budgetUsd === "" || recipe !== "" ? {} : { budgetUsd: Number(values.budgetUsd) }),
579696 // Small is the default: it is not recorded, so the plan stays as it was.
580697 ...(values.size === DEFAULT_SIZE ? {} : { size: values.size }),
581698 ...(values.template === DEFAULT_TEMPLATE ? {} : { template: values.template }),
@@ -597,7 +714,14 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
597714 ctx,
598715 title: "New forge",
599716 keyboardResizes: true,
600 body: formView(ctx, user, values, {}, planView(ctx, user, values, door.body), readsFor(ctx, user)),
717 body: formView(
718 ctx,
719 user,
720 values,
721 {},
722 html`${saved === undefined ? null : html`<p class="small" role="status" id="saved">Saved as <b>${saved}</b>.</p>`}${planView(ctx, user, values, door.body)}`,
723 readsFor(ctx, user),
724 ),
601725 });
602726 noteForgeMade(ctx);
603727 const link = door.body["claimUrl"];
@@ -608,7 +732,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
608732 typeof link !== "string"
609733 ? existedView(name)
610734 : user === undefined
611 ? madeBody({ name, link: link.replace(/\/claim#/, "/welcome#"), own: true })
735 ? madeBody({ name, link: link.replace(/\/[a-z]+#/, "/welcome#"), own: true })
612736 : madeBody({
613737 name,
614738 link,
test/keys-people-list.test.ts +2 −1
@@ -78,7 +78,8 @@ test("the empty page has no data-nav: nobody listed, nothing to traverse", async
7878 const text = await res.text();
7979 expect(res.status).toBe(200);
8080 expect(text).toContain("Nobody here.");
81 // The settings sidebar has its own data-nav links; the people block is what follows its heading.
81 // The settings sidebar has its own data-nav links; the people block is what follows its
82 // heading.
8283 const at = text.indexOf("data-people-filters");
8384 expect(at).toBeGreaterThan(-1);
8485 const block = text.slice(at);
test/spawn-config.test.ts added +273
@@ -0,0 +1,273 @@
1 /**
2 * A forge from a declarative config (#649): apps each as fork, autonomous or
3 * migration, a budget, an admin, a domain; saved as a recipe and spawned again.
4 */
5
6 import { Database } from "bun:sqlite";
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { childDirOf, MIGRATION_DIRECTION } from "../src/actions/spawn.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { commitFiles } from "../src/git/write.ts";
16 import { repoDir } from "../src/git/repos.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { planSpawn } from "../src/spawn/plan.ts";
19 import { parseConfig } from "../src/spawn/recipes.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 const PASSWORD = "a-long-spawn-config-passphrase";
25 const source = {
26 catalog: ["alice/a", "alice/b"].map((ref) => ({ ref, readable: true, bytes: 1, forgeJsonBytes: 0 })),
27 briefs: [],
28 subscriptions: [],
29 };
30 const plan = (extra: Record<string, unknown>) =>
31 planSpawn({ name: "x", org: "x", carryBriefs: false, carrySubscriptions: false, apps: [], ...extra }, source);
32
33 describe("config validation", () => {
34 test("a fork is not named in the plan; the other modes are", () => {
35 const p = plan({ apps: ["alice/a", { repo: "alice/b", mode: "migration" }] });
36 expect(p.ok && p.value.apps).toMatchObject([{ ref: "alice/a" }, { ref: "alice/b", mode: "migration" }]);
37 expect(p.ok && "mode" in p.value.apps[0]!).toBe(false);
38 const q = plan({ apps: [{ repo: "alice/a", mode: "fork" }] });
39 expect(q.ok && "mode" in q.value.apps[0]!).toBe(false);
40 });
41
42 test("a bad mode, domain, admin or budget is refused at the boundary, by field", () => {
43 const refused = (extra: Record<string, unknown>) => {
44 const p = plan({ apps: [{ repo: "alice/a", mode: "fork" }], ...extra });
45 return p.ok ? undefined : p.error.field;
46 };
47 expect(plan({ apps: [{ repo: "alice/a", mode: "wild" }] }).ok).toBe(false);
48 expect(plan({ apps: [{ repo: "alice/a", mode: 3 }] }).ok).toBe(false);
49 expect(plan({ apps: [{ mode: "fork" }] }).ok).toBe(false);
50 expect(refused({ domain: "not a host" })).toBe("domain");
51 expect(refused({ domain: "localhost" })).toBe("domain");
52 expect(refused({ admin: "Bad Name!" })).toBe("admin");
53 expect(refused({ budgetUsd: 0 })).toBe("budgetUsd");
54 expect(refused({ domain: "clients.example.com", admin: "maria", budgetUsd: 20 })).toBeUndefined();
55 });
56
57 test("a config keeps only its four fields", () => {
58 const c = parseConfig({ apps: [{ repo: "alice/a", mode: "autonomous" }], budgetUsd: 5, modelKey: "sk-ant-api-secret", domain: "Clients.Example.com" });
59 expect(c.ok && c.value).toEqual({ apps: [{ repo: "alice/a", mode: "autonomous" }], budgetUsd: 5, domain: "clients.example.com" });
60 expect(parseConfig("x").ok).toBe(false);
61 expect(parseConfig({ apps: "alice/a" }).ok).toBe(false);
62 });
63 });
64
65 describe("a forge from a config, each mode, and a recipe", () => {
66 let dir = "";
67 let app: App;
68 let servers: Servers;
69 let cookie = "";
70 let token = "";
71
72 const post = (form: [string, string][]) =>
73 fetch(`${servers.url}/forges/new`, {
74 method: "POST",
75 headers: { cookie, origin: "https://forge.test" },
76 body: new URLSearchParams(form),
77 redirect: "manual",
78 });
79 const api = (method: string, path: string, body?: unknown) =>
80 fetch(`${servers.url}/api/v1/forges${path}`, {
81 method,
82 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
83 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
84 });
85 const mcp = async (name: string, args: unknown) => {
86 const res = await fetch(`${servers.url}/mcp`, {
87 method: "POST",
88 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
89 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
90 });
91 const r = ((await res.json()) as any).result;
92 const text = r.content[0].text as string;
93 return { error: r.isError === true, body: (r.isError === true ? {} : JSON.parse(text)) as any };
94 };
95
96 beforeAll(async () => {
97 dir = await mkdtemp(join(tmpdir(), "forge-spawn-config-"));
98 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
99 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: PASSWORD, isAdmin: true });
100 if (!a.ok) throw new Error("user");
101 for (const name of ["bakery", "shop", "old"]) {
102 const r = await createRepo(app, a.value, { name });
103 if (!r.ok) throw new Error("repo");
104 const c = await commitFiles(repoDir(app.reposRoot, "alice", name), {
105 branch: "main",
106 message: name,
107 files: [{ path: "README.md", content: `# ${name}\n` }],
108 author: { name: "a", email: "[email protected]" },
109 });
110 if (!c.ok) throw new Error("commit");
111 }
112 servers = await serve(app);
113 const res = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: PASSWORD }), redirect: "manual" });
114 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
115 const { createToken } = await import("../src/core/tokens.ts");
116 token = createToken(app.db, a.value.id, "rw", "rw").token;
117 }, 30_000);
118
119 afterAll(async () => {
120 servers.stop();
121 app.close();
122 await rm(dir, { recursive: true, force: true });
123 });
124
125 const reposOf = async (name: string) => {
126 const ledger = await Bun.file(join(dir, "spawn", `${name}.json`)).json();
127 const db = new Database(join(childDirOf(app, ledger.bodyId), "forge.db"), { readonly: true });
128 try {
129 return Object.fromEntries(
130 (db.query("SELECT name, autonomy, autonomy_direction AS direction, plans_need_nod AS nod, decisions_by AS by FROM repo").all() as { name: string; autonomy: string; direction: string; nod: number; by: string }[]).map((r) => [r.name, r]),
131 );
132 } finally {
133 db.close();
134 }
135 };
136
137 test("each mode lands: a fork is left as it is, the others are worked by the crew", async () => {
138 const res = await post([
139 ["name", "kai"],
140 ["apps", "alice/bakery"],
141 ["apps", "alice/shop"],
142 ["apps", "alice/old"],
143 ["mode:alice/bakery", "fork"],
144 ["mode:alice/shop", "autonomous"],
145 ["mode:alice/old", "migration"],
146 ["do", "spawn"],
147 ]);
148 expect(res.status).toBe(201);
149 const repos = await reposOf("kai");
150 expect(repos["bakery"]!.by).toBe("me");
151 expect([repos["shop"]!.autonomy, repos["shop"]!.nod, repos["shop"]!.by]).toEqual(["autonomous", 0, "decider"]);
152 expect([repos["old"]!.autonomy, repos["old"]!.nod, repos["old"]!.by]).toEqual(["autonomous", 0, "decider"]);
153 expect(repos["old"]!.direction).toBe(MIGRATION_DIRECTION);
154 expect(repos["shop"]!.direction).not.toContain("Migrate");
155 }, 60_000);
156
157 test("the page refuses a bad mode and a bad domain beside their fields", async () => {
158 const bad = await post([["name", "zed"], ["apps", "alice/shop"], ["mode:alice/shop", "wild"], ["do", "plan"]]);
159 expect(bad.status).toBe(422);
160 expect(await bad.text()).toContain("mode must be fork, autonomous or migration");
161 const form = await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text();
162 // Admin and domain are recorded only, so the page does not ask for them.
163 expect(form).not.toContain('name="admin"');
164 expect(form).not.toContain('name="domain"');
165 expect(form).not.toContain('value="save"');
166 expect(form).toContain("Keep this setup as a recipe");
167 // A guest sees no recipes and is not offered saving one.
168 const guest = await (await fetch(`${servers.url}/forges/new`)).text();
169 expect(guest).not.toContain("Keep this setup as a recipe");
170 expect(guest).not.toContain("Your recipes");
171 });
172
173 test("save as recipe, list it, and spawn it again in one action", async () => {
174 const saved = await post([
175 ["name", "ignored"],
176 ["apps", "alice/shop"],
177 ["apps", "alice/old"],
178 ["mode:alice/shop", "autonomous"],
179 ["mode:alice/old", "migration"],
180 ["saveAs", "client kit"],
181 ["do", "plan"],
182 ]);
183 expect(saved.status).toBe(200);
184 const text = await saved.text();
185 expect(text).toContain("Saved as");
186 expect(text).toContain("The plan");
187 expect(text).toContain('name="recipe" value="client kit"');
188
189 const listed = (await (await api("GET", "/recipes")).json()) as any;
190 expect(listed.items).toEqual([
191 { name: "client kit", config: { apps: [{ repo: "alice/shop", mode: "autonomous" }, { repo: "alice/old", mode: "migration" }] } },
192 ]);
193 await api("PUT", "/recipes/with-admin", { config: { apps: [], admin: "maria" } });
194
195 const dry = (await (await api("POST", "", { name: "lou", recipe: "client kit" })).json()) as any;
196 expect(dry.dryRun).toBe(true);
197 const withAdmin = (await (await api("POST", "", { name: "lou", recipe: "with-admin" })).json()) as any;
198 expect(withAdmin.plan.admin).toBe("maria");
199 await api("DELETE", "/recipes/with-admin");
200 expect(dry.plan.apps.map((a: any) => [a.ref, a.mode])).toEqual([["alice/old", "migration"], ["alice/shop", "autonomous"]]);
201
202 const made = await post([["recipe", "client kit"], ["name", "lou"], ["do", "spawn"]]);
203 expect(made.status).toBe(201);
204 const repos = await reposOf("lou");
205 expect([repos["old"]!.autonomy, repos["old"]!.nod, repos["old"]!.by]).toEqual(["autonomous", 0, "decider"]);
206 expect([repos["shop"]!.autonomy, repos["shop"]!.nod, repos["shop"]!.by]).toEqual(["autonomous", 0, "decider"]);
207 }, 60_000);
208
209 test("a recipe is the person's own, refused when unknown, and can be deleted", async () => {
210 const unknown = await api("POST", "", { name: "nope", recipe: "none" });
211 expect(unknown.status).toBe(422);
212 const bad = await api("PUT", "/recipes/x", { config: { apps: [{ repo: "alice/shop", mode: "wild" }] } });
213 expect(bad.status).toBe(422);
214 expect((await api("DELETE", "/recipes/client%20kit")).status).toBe(200);
215 expect((await api("DELETE", "/recipes/client%20kit")).status).toBe(404);
216 });
217
218 test("a stranger cannot start an app as autonomous or migration; a fork is still theirs", async () => {
219 const anon = (body: unknown) =>
220 fetch(`${servers.url}/api/v1/forges`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
221 for (const apps of [[{ repo: "alice/shop", mode: "autonomous" }], [{ repo: "alice/shop", mode: "migration" }]]) {
222 const refused = await anon({ name: "stranger", apps });
223 expect(refused.status).toBe(422);
224 expect(((await refused.json()) as any).message).toContain("sign in");
225 }
226 expect((await anon({ name: "stranger", config: { apps: [{ repo: "alice/shop", mode: "migration" }] } })).status).toBe(422);
227 // A fork is not refused for its mode (this repository is private, so it is refused as unknown).
228 const fork = await anon({ name: "stranger", apps: [{ repo: "alice/shop", mode: "fork" }] });
229 expect(JSON.stringify(await fork.json())).not.toContain("sign in to start");
230 const page = await fetch(`${servers.url}/forges/new`, {
231 method: "POST",
232 headers: { origin: "https://forge.test" },
233 body: new URLSearchParams([["name", "stranger"], ["apps", "alice/shop"], ["mode:alice/shop", "migration"], ["do", "plan"]]),
234 });
235 expect(page.status).toBe(422);
236 expect(await page.text()).toContain("sign in");
237 });
238
239 test("a malformed or padded recipe name is refused, not a 500; concurrent saves keep both", async () => {
240 const config = { apps: [{ repo: "alice/shop", mode: "fork" }] };
241 // A literal % in a name once threw in a second decode of what the router had decoded.
242 expect((await api("PUT", "/recipes/a%25b", { config })).status).toBe(422);
243 expect((await api("DELETE", "/recipes/a%25b")).status).toBe(404);
244 expect((await api("PUT", "/recipes/%E0%A4%A", { config })).status).toBeLessThan(500);
245 expect((await api("DELETE", "/recipes/%E0%A4%A")).status).toBeLessThan(500);
246 await api("PUT", "/recipes/padded", { config });
247 expect((await api("DELETE", "/recipes/%20padded%20")).status).toBe(200);
248 const names = ["c1", "c2", "c3", "c4", "c5", "c6"];
249 await Promise.all(names.map((n) => api("PUT", `/recipes/${n}`, { config })));
250 const listed = ((await (await api("GET", "/recipes")).json()) as any).items.map((r: any) => r.name);
251 for (const n of names) expect(listed).toContain(n);
252 await Promise.all(names.map((n) => api("DELETE", `/recipes/${n}`)));
253 });
254
255 test("the MCP spawn takes a config, plans it, and takes a recipe too", async () => {
256 const config = { apps: [{ repo: "alice/shop", mode: "migration" }], domain: "a.example.org" };
257 const one = await mcp("spawn", { name: "mcp-kid", config });
258 expect(one.error).toBe(false);
259 expect(one.body.dryRun).toBe(true);
260 expect(one.body.plan.apps[0].mode).toBe("migration");
261 expect(one.body.plan.domain).toBe("a.example.org");
262 expect((await mcp("spawn", { name: "mcp-kid", config: { apps: [{ repo: "alice/shop", mode: "x" }] } })).error).toBe(true);
263 await api("PUT", "/recipes/mine", { config });
264 const two = await mcp("spawn", { name: "mcp-kid", recipe: "mine" });
265 expect(two.body.plan.apps[0].mode).toBe("migration");
266 });
267
268 test("a config's budget waits for a key and says so", async () => {
269 const dry = (await (await api("POST", "", { name: "bud", config: { apps: [], budgetUsd: 20 } })).json()) as any;
270 expect(dry.plan.budgetUsd).toBeNull();
271 expect(dry.budgetNote).toContain("$20");
272 });
273 });
test/tui-newforge-recipes.test.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * The terminal's New forge screen has the page's recipes (#649): apps with a mode, Save as recipe,
3 * and Spawn from recipe, through the same door.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createUser, type User } from "../src/core/users.ts";
11 import { usePlacement, useProbe } from "../src/spawn/door.ts";
12 import { hostedPlacement } from "../src/spawn/placement.ts";
13 import { listRecipes } from "../src/spawn/recipes.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { newForgeScreen } from "../src/tui/screens/newforge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 quietLogs();
21
22 let dir: string;
23 let app: App;
24 let admin: User;
25
26 beforeAll(async () => {
27 dir = await mkdtemp(join(tmpdir(), "forge-tui-newforge-recipes-"));
28 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
29 const r = await createUser(app.db, {
30 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
31 password: "a-good-passphrase", isAdmin: true,
32 });
33 if (!r.ok) throw new Error(r.error);
34 admin = r.value;
35 useProbe(app, () => async () => true);
36 usePlacement(app, hostedPlacement({ host: "forge.test" }));
37 });
38 afterAll(async () => {
39 app.db.close();
40 await rm(dir, { recursive: true, force: true });
41 });
42
43 const TAB = "\t";
44 /**
45 * Fields in order: name, for, direction, apps, fresh, key, endpoint, budget, follow, size,
46 * template, save.
47 */
48 async function open(keys: string): Promise<string> {
49 const terminal = headlessTerminal(120, 40);
50 const { app: tui, session } = createForgeApp(
51 app,
52 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin },
53 { terminal, exitHooks: false },
54 );
55 tui.start();
56 tui.ctx.push(newForgeScreen(session, tui.ctx));
57 try {
58 await settleApp(tui);
59 terminal.feed(keys);
60 await settleApp(tui);
61 return tui.screen.toText();
62 } finally {
63 tui.stop?.();
64 }
65 }
66
67 test("Save as recipe keeps the apps with their modes and the budget, with the plan", async () => {
68 const keys =
69 "zed" + TAB.repeat(3) + "alice/shop:autonomous, alice/old:migration" + TAB.repeat(4) + "20" + TAB.repeat(5) + "client kit" + "\x10";
70 const screen = await open(keys);
71 // Kept before the plan is asked for; the plan itself may refuse apps this forge does not have.
72 expect(listRecipes(dir, admin.id).map((r) => r.name)).toEqual(["client kit"]);
73 expect(listRecipes(dir, admin.id)[0]!.config).toEqual({
74 apps: [{ repo: "alice/shop", mode: "autonomous" }, { repo: "alice/old", mode: "migration" }],
75 budgetUsd: 20,
76 });
77 expect(screen).toContain("New forge");
78 });
79
80 test("a bad recipe name is refused beside its field and nothing is kept", async () => {
81 const screen = await open("zed" + TAB.repeat(12) + "no/slash!" + "\x10");
82 expect(screen).toContain("recipe name is 1-40 characters");
83 expect(listRecipes(dir, admin.id).map((r) => r.name)).toEqual(["client kit"]);
84 });
85
86 test("Spawn from recipe is offered once there is one", async () => {
87 const screen = await open(TAB.repeat(13));
88 expect(screen).toContain("Spawn from recipe");
89 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs