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