Skip to content
248 linesCodeBlameRaw
1/**
2 * The agent form (components/agents-mode.tsx) as the agents service takes
3 * it: what each field means, and the checks made before it is sent. Pure,
4 * so it is tested on its own.
5 */
6import type { AgentEffort, ModelTier, NewWorkspaceAgent, PersonalityPreset, SubagentDef, WorkspaceAgent } from "@g1t/contracts";
7
8import { plainDollars } from "./money.ts";
9
10/** An effort setting from a form: one of the five, or null. */
11export function readEffort(value: FormDataEntryValue | null): AgentEffort | null {
12 const text = String(value ?? "");
13 return text === "auto" || text === "low" || text === "medium" || text === "high" || text === "max" ? text : null;
14}
15
16/** The tiers, cheapest first: `MODEL_TIERS` in the contracts. */
17const MODEL_TIERS: ModelTier[] = ["small", "large", "frontier"];
18
19export const PRESETS: { value: PersonalityPreset; label: string; about: string }[] = [
20 { value: "crisp", label: "Crisp", about: "Clear and to the point, with enough context to act on." },
21 { value: "friendly", label: "Friendly", about: "Warm and encouraging; explains as it goes." },
22 { value: "socratic", label: "Socratic", about: "Asks before it assumes; draws out what you mean." },
23 { value: "terse", label: "Terse operator", about: "As few words as will do. Status, then done." },
24];
25
26export const TIER_LABELS: Record<ModelTier, string> = {
27 small: "Fast: replies and triage",
28 large: "Standard: making changes, most reviews",
29 frontier: "Most capable: planning and hard work",
30};
31
32export const AUTONOMY = {
33 open_pull_requests: { label: "Open pull requests", options: [["alone", "On its own"], ["approval", "After approval"]] },
34 merge: { label: "Merge", options: [["alone", "On its own"], ["approval", "After approval"], ["never", "Never"]] },
35 deploy_production: { label: "Deploy to production", options: [["approval", "After approval"], ["never", "Never"]] },
36 edit_docs: { label: "Edit docs", options: [["alone", "Directly"], ["suggest", "As suggestions"]] },
37} as const;
38
39/** The handle as people type it: lowercase letters, digits and dashes. */
40export function cleanHandle(typed: string): string {
41 return typed
42 .trim()
43 .toLowerCase()
44 .replace(/^@/, "")
45 .replace(/[\s_]+/g, "-")
46 .replace(/[^a-z0-9-]/g, "")
47 .replace(/-{2,}/g, "-")
48 .replace(/^-|-$/g, "")
49 .slice(0, 39);
50}
51
52/** Handles the site's own addresses use, and g1t's: never an agent's. */
53const RESERVED_HANDLES = new Set(["g1t", "new", "runs", "fleet"]);
54
55function tier(value: FormDataEntryValue | null): ModelTier | null {
56 const text = String(value ?? "");
57 return (MODEL_TIERS as string[]).includes(text) ? (text as ModelTier) : null;
58}
59
60function pick<T extends string>(value: FormDataEntryValue | null, allowed: readonly (readonly [T, string])[], fallback: T): T {
61 const text = String(value ?? "");
62 return (allowed.find(([key]) => key === text)?.[0] ?? fallback) as T;
63}
64
65export type AgentFormResult = { ok: true; input: NewWorkspaceAgent } | { ok: false; errors: Record<string, string> };
66
67/** The form, checked: the agent to make or the changes to save, or what to fix, by field. */
68export function readAgentForm(form: FormData, options: { orchestrator?: boolean } = {}): AgentFormResult {
69 const errors: Record<string, string> = {};
70 const display_name = String(form.get("display_name") ?? "").trim();
71 const handle = cleanHandle(String(form.get("handle") ?? "") || display_name);
72 const title = String(form.get("title") ?? "").trim();
73 const responsibilities = form
74 .getAll("responsibility")
75 .map((value) => String(value).trim())
76 .filter(Boolean)
77 .slice(0, MAX_RESPONSIBILITIES);
78 const subagents = readSubagents(form.get("subagents"));
79 // Docs spaces it reads first; the agents service checks them.
80 const reading = [...new Set(form.getAll("reading").map((value) => String(value).trim()).filter(Boolean))].slice(0, 10);
81 const instructions = String(form.get("instructions") ?? "").trim();
82 if (!display_name) errors.display_name = "Give it a name.";
83 if (!handle) errors.handle = "Give it a handle, like @ship.";
84 else if (RESERVED_HANDLES.has(handle) && !(options.orchestrator && handle === "g1t")) errors.handle = `@${handle} is taken by g1t.`;
85 if (!title && !options.orchestrator) errors.title = "Give it a title, like QA Engineer.";
86 if (subagents == null) errors.subagents = "The subagents couldn't be read. Edit one and save again.";
87 // g1t's job is fixed; what is written here is added to it, and may be nothing.
88 if (!instructions && !options.orchestrator) errors.instructions = "Tell it what it's responsible for.";
89 const floor = tier(form.get("floor"));
90 const ceiling = tier(form.get("ceiling"));
91 if (floor && ceiling && MODEL_TIERS.indexOf(floor) > MODEL_TIERS.indexOf(ceiling)) errors.ceiling = "The ceiling can't be below the floor.";
92 const budget = {
93 monthly_micros: microsFromDollars(form.get("monthly")),
94 daily_micros: microsFromDollars(form.get("daily")),
95 task_micros: microsFromDollars(form.get("task")),
96 };
97 for (const [field, value] of [["monthly", budget.monthly_micros], ["daily", budget.daily_micros], ["task", budget.task_micros]] as const) {
98 if (value != null && Number.isNaN(value)) errors[field] = "A sum in dollars, like 25.";
99 }
100 const capacity = Number(form.get("capacity") ?? 3);
101 if (!Number.isInteger(capacity) || capacity < 1 || capacity > 20) errors.capacity = "Between 1 and 20.";
102 const providers = String(form.get("providers") ?? "any");
103 const pinned = String(form.get("pinned") ?? "").trim();
104 // How hard it works; a form without the control leaves it as it is.
105 const effort = readEffort(form.get("effort"));
106 if (pinned && !/^[\w.-]+\/[\w.:@-]+$/.test(pinned)) errors.pinned = "As provider/model.";
107 if (Object.keys(errors).length > 0) return { ok: false, errors };
108 return {
109 ok: true,
110 input: {
111 handle,
112 display_name,
113 // Its title, made by the agents service.
114 role: "",
115 title,
116 responsibilities,
117 subagents: subagents ?? [],
118 reading,
119 instructions,
120 personality_preset: pick(form.get("personality_preset"), PRESETS.map((p) => [p.value, p.label] as const), "crisp"),
121 personality: String(form.get("personality") ?? "").trim(),
122 routing: {
123 floor,
124 ceiling,
125 providers: providers === "any" ? [] : [providers],
126 pinned: pinned || null,
127 ...(effort ? { effort } : {}),
128 },
129 budget,
130 autonomy: {
131 open_pull_requests: pick(form.get("open_pull_requests"), AUTONOMY.open_pull_requests.options, "alone"),
132 merge: pick(form.get("merge"), AUTONOMY.merge.options, "approval"),
133 deploy_production: pick(form.get("deploy_production"), AUTONOMY.deploy_production.options, "approval"),
134 edit_docs: pick(form.get("edit_docs"), AUTONOMY.edit_docs.options, "suggest"),
135 },
136 capacity,
137 template: String(form.get("template") ?? "") || null,
138 // A drafted agent carries its scope, the skills it keeps off and its face.
139 ...(form.get("scope") === "personal" || form.get("scope") === "workspace" ? { scope: form.get("scope") as "personal" | "workspace" } : {}),
140 ...(form.has("skills_off") ? { skills_off: String(form.get("skills_off") ?? "").split(",").map((id) => id.trim()).filter(Boolean) } : {}),
141 ...(String(form.get("avatar_seed") ?? "").trim() ? { avatar_seed: String(form.get("avatar_seed")).trim().slice(0, 64) } : {}),
142 },
143 };
144}
145
146/** Most responsibilities an agent lists. */
147export const MAX_RESPONSIBILITIES = 8;
148
149/** The subagents, as the form sends them (JSON); null when they are not valid. */
150function readSubagents(value: FormDataEntryValue | null): SubagentDef[] | null {
151 const text = String(value ?? "").trim();
152 if (!text) return [];
153 try {
154 const parsed = JSON.parse(text) as unknown;
155 if (!Array.isArray(parsed)) return null;
156 return parsed.filter(
157 (item): item is SubagentDef =>
158 item != null && typeof item === "object" && typeof (item as SubagentDef).name === "string" && typeof (item as SubagentDef).description === "string",
159 );
160 } catch {
161 return null;
162 }
163}
164
165/** A subagent's name: lowercase letters, digits and hyphens. */
166export function cleanSubagentName(typed: string): string {
167 return cleanHandle(typed).slice(0, 40);
168}
169
170/**
171 * A subagent's routing limits, kept within its agent's: a floor below the
172 * agent's is raised to it, a ceiling above the agent's is lowered to it,
173 * and a floor above the ceiling comes down to it.
174 */
175export function clampRouting(
176 sub: { floor: ModelTier | null; ceiling: ModelTier | null },
177 agent: { floor: ModelTier | null; ceiling: ModelTier | null },
178): { floor: ModelTier | null; ceiling: ModelTier | null } {
179 const rank = (tier: ModelTier) => MODEL_TIERS.indexOf(tier);
180 let floor = sub.floor;
181 let ceiling = sub.ceiling;
182 if (agent.floor && (!floor || rank(floor) < rank(agent.floor))) floor = agent.floor;
183 if (agent.ceiling && (!ceiling || rank(ceiling) > rank(agent.ceiling))) ceiling = agent.ceiling;
184 if (floor && ceiling && rank(floor) > rank(ceiling)) floor = ceiling;
185 return { floor, ceiling };
186}
187
188/**
189 * The teams a new agent joins as it is made (the form's "Add to teams"),
190 * by slug: membership is the team's, never part of the agent.
191 */
192export function readTeams(form: FormData): string[] {
193 return [...new Set(form.getAll("teams").map((value) => String(value).trim().toLowerCase()).filter((slug) => /^[a-z0-9][a-z0-9-]{0,63}$/.test(slug)))].slice(0, 20);
194}
195
196/** What the form starts from: an agent being edited, a template, or nothing. */
197export type AgentDraft = Pick<
198 WorkspaceAgent,
199 | "handle"
200 | "display_name"
201 | "role"
202 | "title"
203 | "responsibilities"
204 | "subagents"
205 | "reading"
206 | "instructions"
207 | "personality_preset"
208 | "personality"
209 | "routing"
210 | "budget"
211 | "autonomy"
212 | "capacity"
213 | "template"
214>;
215
216export const BLANK_DRAFT: AgentDraft = {
217 handle: "",
218 display_name: "",
219 role: "",
220 title: "",
221 responsibilities: [],
222 subagents: [],
223 reading: [],
224 instructions: "",
225 personality_preset: "crisp",
226 personality: "",
227 routing: { floor: null, ceiling: null, providers: [], pinned: null, effort: "auto" },
228 budget: { monthly_micros: 50_000_000, daily_micros: null, task_micros: 5_000_000 },
229 autonomy: { open_pull_requests: "alone", merge: "approval", deploy_production: "approval", edit_docs: "suggest" },
230 capacity: 3,
231 template: null,
232};
233
234/** Dollars from micro-dollars, for a form field: empty for none, `20` for a whole sum, else to the cent. */
235export function dollarsField(micros: number | null | undefined): string {
236 if (micros == null) return "";
237 return plainDollars(micros, { whole: true });
238}
239
240/** Micro-dollars from a form field in dollars: null when empty, NaN when not a sum. */
241export function microsFromDollars(value: FormDataEntryValue | null): number | null {
242 const text = String(value ?? "").trim().replace(/^\$/, "").replaceAll(",", "");
243 if (!text) return null;
244 const dollars = Number(text);
245 if (!Number.isFinite(dollars) || dollars < 0) return Number.NaN;
246 return Math.round(dollars * 1_000_000);
247}
248