Skip to content
351 linesCodeBlameRaw
1/**
2 * An agent's definition: what a new one gets by default, what a change may
3 * set, and how a stored row reads. Pure, so it is tested on its own.
4 */
5import type {
6 AgentAutonomy,
7 AgentBudget,
8 AgentRouting,
9 NewWorkspaceAgent,
10 PersonalityPreset,
11 AgentFaces,
12 SubagentDef,
13} from "@g1t/contracts";
14import { FOUNDATIONAL_SKILL_IDS } from "../../../packages/contracts/src/skills.ts";
15
16import { checkHandle } from "./handle.ts";
17import { isEffort, isTier, limitsAgree } from "./routing.ts";
18
19export const PRESETS: PersonalityPreset[] = ["crisp", "friendly", "socratic", "terse"];
20
21export const DEFAULT_ROUTING: AgentRouting = { floor: null, ceiling: null, providers: [], pinned: null, effort: "auto" };
22export const DEFAULT_BUDGET: AgentBudget = { monthly_micros: null, daily_micros: null, task_micros: null };
23/** What an agent may do alone until someone says otherwise: open pull requests; the rest asks. */
24export const DEFAULT_AUTONOMY: AgentAutonomy = {
25 open_pull_requests: "alone",
26 merge: "approval",
27 deploy_production: "approval",
28 edit_docs: "suggest",
29};
30/** Tasks at once. */
31export const DEFAULT_CAPACITY = 3;
32export const MAX_CAPACITY = 10;
33
34const LIMITS = { displayName: 64, role: 120, title: 60, department: 40, duty: 160, instructions: 8000, personality: 1000, providers: 10, pinned: 200 };
35/** $100,000 in millionths: a cap above this is a typo. */
36const MAX_MICROS = 100_000_000_000;
37
38/** Everything a definition holds, complete: what is stored and versioned. */
39export type Definition = {
40 handle: string;
41 display_name: string;
42 role: string;
43 instructions: string;
44 personality_preset: PersonalityPreset;
45 personality: string;
46 routing: AgentRouting;
47 budget: AgentBudget;
48 autonomy: AgentAutonomy;
49 capacity: number;
50 template: string | null;
51 /** What its generated avatar is drawn from. */
52 avatar_seed: string;
53 title: string;
54 team: string | null;
55 department: string;
56 responsibilities: string[];
57 subagents: SubagentDef[];
58 faces: AgentFaces;
59 /** Spaces whose artifacts it reads first. */
60 reading: string[];
61 /** Foundational skills turned off for it, by id (@g1t/contracts skills.ts). */
62 skills_off: string[];
63};
64
65/** The one-line role a title and team (or department) make: "QA Engineer on the qa team". */
66export function roleOf(d: Pick<Definition, "title" | "team" | "department">): string {
67 const title = d.title.trim();
68 if (!title) return "";
69 if (d.team) return `${title} on the ${d.team} team`;
70 return d.department.trim() ? `${title}, ${d.department.trim()}` : title;
71}
72
73export const MAX_SUBAGENTS = 8;
74
75export type Checked<T> = { ok: true; value: T } | { ok: false; message: string };
76
77const bad = (message: string): { ok: false; message: string } => ({ ok: false, message });
78
79function text(value: unknown, what: string, max: number, required: boolean): Checked<string> {
80 if (value === undefined || value === null) return required ? bad(`${what} is required.`) : { ok: true, value: "" };
81 if (typeof value !== "string") return bad(`${what} is text.`);
82 const trimmed = value.trim();
83 if (required && !trimmed) return bad(`${what} is required.`);
84 if (trimmed.length > max) return bad(`${what} is at most ${max} characters.`);
85 return { ok: true, value: trimmed };
86}
87
88function routingOf(base: AgentRouting, given: unknown): Checked<AgentRouting> {
89 if (given === undefined || given === null) return { ok: true, value: base };
90 if (typeof given !== "object") return bad("Routing is an object.");
91 const g = given as Partial<AgentRouting>;
92 const next: AgentRouting = { ...base };
93 for (const key of ["floor", "ceiling"] as const) {
94 if (g[key] === undefined) continue;
95 if (g[key] !== null && !isTier(g[key])) return bad(`The ${key} is small, large, frontier or none.`);
96 next[key] = g[key] ?? null;
97 }
98 if (!limitsAgree(next.floor, next.ceiling)) return bad("The floor is above the ceiling: lower the floor or raise the ceiling.");
99 if (g.providers !== undefined) {
100 if (!Array.isArray(g.providers) || g.providers.some((p) => typeof p !== "string" || !p.trim())) return bad("Providers is a list of names.");
101 const providers = [...new Set(g.providers.map((p) => p.trim()))];
102 if (providers.length > LIMITS.providers) return bad(`An agent names at most ${LIMITS.providers} providers.`);
103 next.providers = providers;
104 }
105 if (g.effort !== undefined) {
106 if (g.effort !== null && !isEffort(g.effort)) return bad("Effort is auto, low, medium, high or max.");
107 next.effort = g.effort ?? "auto";
108 }
109 if (g.pinned !== undefined) {
110 if (g.pinned === null || g.pinned === "") next.pinned = null;
111 else if (typeof g.pinned !== "string" || g.pinned.trim().length > LIMITS.pinned || !/^[^/\s]+\/\S+$/.test(g.pinned.trim())) {
112 return bad("A pinned model is written provider/model.");
113 } else next.pinned = g.pinned.trim();
114 }
115 return { ok: true, value: next };
116}
117
118function budgetOf(base: AgentBudget, given: unknown): Checked<AgentBudget> {
119 if (given === undefined || given === null) return { ok: true, value: base };
120 if (typeof given !== "object") return bad("Budget is an object.");
121 const g = given as Partial<AgentBudget>;
122 const next: AgentBudget = { ...base };
123 for (const key of ["monthly_micros", "daily_micros", "task_micros"] as const) {
124 const value = g[key];
125 if (value === undefined) continue;
126 if (value === null) next[key] = null;
127 else if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > MAX_MICROS) {
128 return bad("A budget is a whole number of millionths of a dollar, or none.");
129 } else next[key] = value;
130 }
131 return { ok: true, value: next };
132}
133
134const AUTONOMY_CHOICES: { [K in keyof AgentAutonomy]: AgentAutonomy[K][] } = {
135 open_pull_requests: ["alone", "approval"],
136 merge: ["alone", "approval", "never"],
137 deploy_production: ["approval", "never"],
138 edit_docs: ["alone", "suggest"],
139};
140
141function autonomyOf(base: AgentAutonomy, given: unknown): Checked<AgentAutonomy> {
142 if (given === undefined || given === null) return { ok: true, value: base };
143 if (typeof given !== "object") return bad("Autonomy is an object.");
144 const next = { ...base } as Record<string, string>;
145 for (const [key, choices] of Object.entries(AUTONOMY_CHOICES) as [string, string[]][]) {
146 const value = (given as Record<string, unknown>)[key];
147 if (value === undefined) continue;
148 if (typeof value !== "string" || !choices.includes(value)) return bad(`${key} is one of ${choices.join(", ")}.`);
149 next[key] = value;
150 }
151 return { ok: true, value: next as AgentAutonomy };
152}
153
154function responsibilitiesOf(given: unknown): Checked<string[]> {
155 if (!Array.isArray(given) || given.some((d) => typeof d !== "string")) return bad("Responsibilities are a list of short duties.");
156 const duties = [...new Set((given as string[]).map((d) => d.trim()).filter(Boolean))];
157 if (duties.length && (duties.length < 2 || duties.length > 8)) return bad("Give 2 to 8 responsibilities, or none yet.");
158 if (duties.some((d) => d.length > LIMITS.duty)) return bad(`Each responsibility is at most ${LIMITS.duty} characters.`);
159 return { ok: true, value: duties };
160}
161
162const ORDER = ["small", "large", "frontier"] as const;
163
164/** A subagent's limits held within its agent's: never a lower floor, never a higher ceiling. */
165export function withinParent(
166 sub: { floor: AgentRouting["floor"]; ceiling: AgentRouting["ceiling"] },
167 parent: Pick<AgentRouting, "floor" | "ceiling">,
168): { floor: AgentRouting["floor"]; ceiling: AgentRouting["ceiling"] } {
169 const at = (tier: AgentRouting["floor"]) => (tier ? ORDER.indexOf(tier) : -1);
170 let floor = sub.floor;
171 let ceiling = sub.ceiling;
172 if (parent.floor && at(floor) < at(parent.floor)) floor = parent.floor;
173 if (parent.ceiling && (!ceiling || at(ceiling) > at(parent.ceiling))) ceiling = parent.ceiling;
174 // Held inside, a floor can end above the ceiling: the ceiling, the spending rail, wins.
175 if (floor && ceiling && at(floor) > at(ceiling)) floor = ceiling;
176 return { floor, ceiling };
177}
178
179function subagentsOf(given: unknown): Checked<SubagentDef[]> {
180 if (!Array.isArray(given)) return bad("Subagents are a list.");
181 if (given.length > MAX_SUBAGENTS) return bad(`An agent keeps at most ${MAX_SUBAGENTS} subagents.`);
182 const out: SubagentDef[] = [];
183 for (const raw of given as Partial<SubagentDef>[]) {
184 if (!raw || typeof raw !== "object") return bad("Each subagent has a name, a description and instructions.");
185 const name = typeof raw.name === "string" ? raw.name.trim().toLowerCase() : "";
186 if (!/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){1,31}$/.test(name)) return bad("A subagent's name is 2 to 32 lowercase letters, digits and single hyphens.");
187 if (out.some((sub) => sub.name === name)) return bad(`Two subagents are called ${name}.`);
188 const description = text(raw.description, `${name}'s description`, 200, true);
189 if (!description.ok) return description;
190 const instructions = text(raw.instructions, `${name}'s instructions`, 4000, true);
191 if (!instructions.ok) return instructions;
192 const routing = raw.routing ?? { floor: null, ceiling: null };
193 for (const tier of [routing.floor, routing.ceiling]) {
194 if (tier !== null && tier !== undefined && !isTier(tier)) return bad(`${name}'s limits are small, large, frontier or none.`);
195 }
196 if (!limitsAgree(routing.floor ?? null, routing.ceiling ?? null)) return bad(`${name}'s floor is above its ceiling.`);
197 const parallel = raw.max_parallel ?? 2;
198 if (typeof parallel !== "number" || !Number.isInteger(parallel) || parallel < 1 || parallel > 8) return bad(`${name} runs 1 to 8 at once.`);
199 out.push({
200 name,
201 description: description.value,
202 instructions: instructions.value,
203 routing: { floor: routing.floor ?? null, ceiling: routing.ceiling ?? null },
204 max_parallel: parallel,
205 });
206 }
207 return { ok: true, value: out };
208}
209
210/**
211 * `changes` applied to `base` (a new agent's defaults, or its current
212 * definition), checked. `templates` are the template ids an agent may name.
213 */
214export function applyChanges(
215 base: Definition | null,
216 changes: Partial<NewWorkspaceAgent>,
217 templates: string[],
218 options: { builtin?: boolean } = {},
219): Checked<Definition> {
220 if (!changes || typeof changes !== "object") return bad("Send the agent's fields.");
221 const creating = base === null;
222 const from: Definition = base ?? {
223 handle: "",
224 display_name: "",
225 role: "",
226 instructions: "",
227 personality_preset: "crisp",
228 personality: "",
229 routing: DEFAULT_ROUTING,
230 budget: DEFAULT_BUDGET,
231 autonomy: DEFAULT_AUTONOMY,
232 capacity: DEFAULT_CAPACITY,
233 template: null,
234 avatar_seed: "",
235 title: "",
236 team: null,
237 department: "",
238 responsibilities: [],
239 subagents: [],
240 faces: "internal",
241 reading: [],
242 skills_off: [],
243 };
244 const next: Definition = { ...from, skills_off: from.skills_off ?? [] };
245 // Whether the role was made from the title and team, so it follows them.
246 const roleDerived = !from.role || from.role === roleOf(from);
247 if (creating || changes.handle !== undefined) {
248 const handle = checkHandle(changes.handle);
249 if (!handle.ok) return bad(handle.message);
250 next.handle = handle.handle;
251 }
252 const fields = [
253 ["display_name", "A display name", LIMITS.displayName, true],
254 ["role", "The role", LIMITS.role, false],
255 ["title", "The title", LIMITS.title, false],
256 ["department", "The department", LIMITS.department, false],
257 // The built-in agent's instructions are added to its fixed job, and may be empty.
258 ["instructions", "The instructions", LIMITS.instructions, !options.builtin],
259 ["personality", "The personality", LIMITS.personality, false],
260 ] as const;
261 for (const [key, what, max, required] of fields) {
262 if (!creating && changes[key] === undefined) continue;
263 const value = text(changes[key], what, max, required);
264 if (!value.ok) return value;
265 next[key] = value.value;
266 }
267 if (changes.team !== undefined) {
268 if (changes.team === null || changes.team === "") next.team = null;
269 else if (typeof changes.team !== "string" || !/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(changes.team.trim().toLowerCase())) {
270 return bad("A team is named by its slug.");
271 } else next.team = changes.team.trim().toLowerCase();
272 }
273 if (changes.responsibilities !== undefined) {
274 const duties = responsibilitiesOf(changes.responsibilities);
275 if (!duties.ok) return duties;
276 next.responsibilities = duties.value;
277 }
278 // A role left empty, or made from the title and team before, follows them.
279 if (!next.role || (changes.role === undefined && roleDerived)) next.role = roleOf(next);
280 if (!next.role) return bad("Give the agent a title or a one-line role.");
281 if (changes.avatar_seed !== undefined) {
282 const seed = text(changes.avatar_seed, "The avatar seed", 64, false);
283 if (!seed.ok) return seed;
284 next.avatar_seed = seed.value;
285 }
286 // A new face from the handle, unless one was chosen; renaming keeps the face.
287 if (!next.avatar_seed) next.avatar_seed = next.handle;
288 if (changes.personality_preset !== undefined) {
289 if (!PRESETS.includes(changes.personality_preset)) return bad(`The personality preset is one of ${PRESETS.join(", ")}.`);
290 next.personality_preset = changes.personality_preset;
291 }
292 const routing = routingOf(next.routing, changes.routing);
293 if (!routing.ok) return routing;
294 next.routing = routing.value;
295 const budget = budgetOf(next.budget, changes.budget);
296 if (!budget.ok) return budget;
297 next.budget = budget.value;
298 const autonomy = autonomyOf(next.autonomy, changes.autonomy);
299 if (!autonomy.ok) return autonomy;
300 next.autonomy = autonomy.value;
301 if (changes.capacity !== undefined) {
302 const capacity = changes.capacity;
303 if (typeof capacity !== "number" || !Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) {
304 return bad(`Capacity is 1 to ${MAX_CAPACITY} tasks at once.`);
305 }
306 next.capacity = capacity;
307 }
308 if (changes.template !== undefined) {
309 if (changes.template !== null && !templates.includes(changes.template)) return bad("There is no such template.");
310 next.template = changes.template;
311 }
312 if (changes.subagents !== undefined) {
313 const subagents = subagentsOf(changes.subagents);
314 if (!subagents.ok) return subagents;
315 next.subagents = subagents.value;
316 }
317 if (changes.reading !== undefined) {
318 if (!Array.isArray(changes.reading)) return bad("Required reading is a list of spaces.");
319 const ids = [...new Set(changes.reading.filter((id): id is string => typeof id === "string").map((id) => id.trim()).filter(Boolean))];
320 if (ids.length > 10) return bad("An agent has at most 10 spaces of required reading.");
321 if (ids.some((id) => !/^[A-Za-z0-9_-]{1,80}$/.test(id))) return bad("That isn't a space.");
322 next.reading = ids;
323 }
324 if (changes.skills_off !== undefined) {
325 if (!Array.isArray(changes.skills_off)) return bad("Skills turned off are a list of skills.");
326 const ids = new Set(changes.skills_off.filter((id): id is string => typeof id === "string").map((id) => id.trim()).filter(Boolean));
327 const unknown = [...ids].find((id) => !FOUNDATIONAL_SKILL_IDS.includes(id));
328 if (unknown) return bad(`There is no skill called ${unknown.slice(0, 40)}.`);
329 // In the skills' own order, so the same choice always reads the same.
330 next.skills_off = FOUNDATIONAL_SKILL_IDS.filter((id) => ids.has(id));
331 }
332 if (changes.faces !== undefined) {
333 if (changes.faces === "customers") return bad("Customer-facing agents aren't available yet.");
334 if (changes.faces !== "internal") return bad("An agent faces internal: the workspace's own people.");
335 next.faces = "internal";
336 }
337 // Never wider than their agent, whichever of the two changed.
338 next.subagents = next.subagents.map((sub) => ({ ...sub, routing: withinParent(sub.routing, next.routing) }));
339 return { ok: true, value: next };
340}
341
342/** A stored JSON column, read defensively: a bad value is the default. */
343export function readJson<T extends object>(raw: unknown, fallback: T): T {
344 if (typeof raw !== "string") return fallback;
345 try {
346 const parsed = JSON.parse(raw) as unknown;
347 return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? { ...fallback, ...(parsed as T) } : fallback;
348 } catch {
349 return fallback;
350 }
351}