Skip to content
184 linesCodeBlameRaw
1/**
2 * `@g1t`, every workspace's built-in orchestrator (docs/WORKSPACE.md, "g1t,
3 * the orchestrator"). Pure, so it is tested on its own.
4 *
5 * It is an agent row like any other, marked builtin, so it is billed,
6 * gated, routed and audited the same way. What sets it apart is here:
7 * the fields nobody may change, the job it always has, the roster of
8 * specialists it is given, and the rails on how it delegates.
9 */
10import type { AgentStatus, ModelTier, NewWorkspaceAgent } from "@g1t/contracts";
11
12import { BUILTIN_AGENT_HANDLE, ORCHESTRATOR_TEMPLATE } from "../../../packages/contracts/src/workspace-agents.ts";
13import { type Checked, type Definition, DEFAULT_AUTONOMY, DEFAULT_BUDGET, DEFAULT_CAPACITY, DEFAULT_ROUTING } from "./definition.ts";
14
15export const BUILTIN_ROLE = "Your orchestrator: delegates to the team's agents, or does the work itself";
16
17/** What a new workspace's @g1t starts as. `instructions` are the workspace's additions, none at first. */
18export function builtinDefinition(): Definition {
19 return {
20 handle: BUILTIN_AGENT_HANDLE,
21 display_name: "g1t",
22 role: BUILTIN_ROLE,
23 instructions: "",
24 personality_preset: "friendly",
25 personality: "",
26 routing: DEFAULT_ROUTING,
27 budget: DEFAULT_BUDGET,
28 autonomy: DEFAULT_AUTONOMY,
29 capacity: DEFAULT_CAPACITY,
30 template: ORCHESTRATOR_TEMPLATE,
31 avatar_seed: BUILTIN_AGENT_HANDLE,
32 title: "Orchestrator",
33 team: null,
34 department: "",
35 responsibilities: [],
36 subagents: [],
37 faces: "internal",
38 reading: [],
39 };
40}
41
42/** What nobody may change on the built-in agent: who it is and what its job is. */
43export const PROTECTED: (keyof NewWorkspaceAgent)[] = [
44 "handle",
45 "display_name",
46 "role",
47 "title",
48 "team",
49 "department",
50 "responsibilities",
51 "subagents",
52 "template",
53 "faces",
54];
55
56/**
57 * `changes` to the built-in agent with its fixed fields taken out, whatever
58 * they say: a profile form sends every field (an empty title, no
59 * responsibilities), and only the editable ones apply.
60 */
61export function builtinChanges(_current: Definition, changes: Partial<NewWorkspaceAgent>): Checked<Partial<NewWorkspaceAgent>> {
62 if (!changes || typeof changes !== "object") return { ok: false, message: "Send the agent's fields." };
63 const rest: Partial<NewWorkspaceAgent> = { ...changes };
64 for (const key of PROTECTED) delete rest[key];
65 return { ok: true, value: rest };
66}
67
68/** One specialist as @g1t sees it. */
69export type Specialist = {
70 handle: string;
71 display_name: string;
72 role: string;
73 title?: string;
74 team?: string | null;
75 department?: string;
76 responsibilities?: string[];
77 status: AgentStatus;
78 spent_month_micros: number;
79 /** The monthly cap, or null for none. */
80 monthly_micros: number | null;
81};
82
83const STATUS_WORDS: Record<AgentStatus, string> = {
84 idle: "idle",
85 working: "working",
86 waiting: "waiting on someone",
87 out_of_budget: "out of budget",
88 paused: "paused",
89};
90
91const dollars = (micros: number) => `$${(Math.max(0, micros) / 1_000_000).toFixed(2)}`;
92
93/** Where a specialist sits: "QA Engineer on the qa team", "QA Engineer, QA", or its role. */
94function placeLine(agent: Specialist): string {
95 const title = agent.title?.trim();
96 if (!title) return agent.role.replace(/\.$/, "");
97 if (agent.team) return `${title} on the ${agent.team} team`;
98 return agent.department?.trim() ? `${title}, ${agent.department.trim()}` : title;
99}
100
101/**
102 * The roster, one line per specialist, so g1t can route "QA should look"
103 * to the right one: `- @margo (Margo): QA Engineer, QA. Does: review pull
104 * requests; write test plans. idle; $1.20 of $20.00 this month.`
105 */
106export function rosterLines(specialists: Specialist[]): string {
107 if (!specialists.length) return "There are no specialists in this workspace yet.";
108 return specialists
109 .map((agent) => {
110 const name = agent.display_name && agent.display_name.toLowerCase() !== agent.handle ? ` (${agent.display_name})` : "";
111 const spend = agent.monthly_micros ? `${dollars(agent.spent_month_micros)} of ${dollars(agent.monthly_micros)}` : `${dollars(agent.spent_month_micros)}, no cap`;
112 const duties = agent.responsibilities?.length ? ` Does: ${agent.responsibilities.map((d) => d.replace(/\.$/, "")).join("; ")}.` : "";
113 return `- @${agent.handle}${name}: ${placeLine(agent)}.${duties} ${STATUS_WORDS[agent.status] ?? agent.status}; ${spend} this month.`;
114 })
115 .join("\n");
116}
117
118/** The most specialists one of @g1t's messages may hand work to. */
119export const MAX_DELEGATES = 2;
120
121/** @g1t's job: fixed, whatever the workspace adds. */
122export function orchestratorInstructions(specialists: Specialist[], extra: string): string {
123 const available = specialists.filter((agent) => agent.status !== "out_of_budget" && agent.status !== "paused");
124 const job = [
125 "You are the workspace's orchestrator. People come to you when they don't know who should do something. You either answer, hand the work to the right specialist, or do it yourself.",
126 "",
127 "### The team",
128 "",
129 rosterLines(specialists),
130 "",
131 "### How you decide",
132 "",
133 "1. **Answer directly** when it is a question, a summary or a quick judgment you can give from this conversation.",
134 "2. **Delegate** when a specialist's role fits the work. @mention them in this thread with a crisp brief: what is wanted, why, what done looks like, and any constraint (who asked, deadlines, what not to touch). One short message; no preamble.",
135 "3. **Do it yourself, or suggest a specialist,** when nobody fits. Say so plainly, offer to take it on yourself, and if this kind of work will recur, suggest setting one up (for example: \"Want me to set up a release manager for this?\").",
136 "",
137 "### Rules for delegating",
138 "",
139 `- Mention at most ${MAX_DELEGATES} specialists in one message. Split bigger work into steps and hand off the next step when the first is done.`,
140 "- Never delegate in a loop: don't hand work back to a specialist who handed it to you, don't hand the same work to the same specialist twice in a thread, and never mention yourself.",
141 "- Don't delegate to a specialist who is out of budget or paused; say they are unavailable and why.",
142 "- Delegating is only an @mention in the thread: the person can see every hand-off, and the asker's access still limits what any agent does for them.",
143 "- When a specialist answers in a thread you delegated into, you only speak again if someone mentions you.",
144 "- When asked what everyone is working on, answer from the team list above.",
145 available.length ? "" : "\nNo specialist is available right now, so do the work yourself or suggest creating one.",
146 ].join("\n");
147 const added = extra.trim();
148 return added ? `${job}\n\n### Added by this workspace\n\n${added}` : job;
149}
150
151/** How long a thread is before @g1t's delegation call is worth a larger model. */
152export const LONG_THREAD = 6;
153
154/**
155 * Where @g1t's reply starts: the small tier, or the large one for a
156 * delegation decision in a long thread (more than `LONG_THREAD` messages,
157 * with specialists to choose from). Its floor and ceiling apply after.
158 */
159export function orchestratorTier(messages: number, specialists: number): ModelTier {
160 return messages > LONG_THREAD && specialists > 0 ? "large" : "small";
161}
162
163/**
164 * The rail behind "at most two specialists per message": past the first
165 * `max` specialists a reply @mentions, the `@` is dropped, so the chat
166 * service wakes nobody else. Names stay readable.
167 */
168export function capMentions(text: string, specialists: string[], max = MAX_DELEGATES): string {
169 const known = new Set(specialists.map((handle) => handle.toLowerCase()));
170 const kept = new Set<string>();
171 return text.replace(/(^|[^a-z0-9_.@-])@([a-z0-9](?:[a-z0-9_-]{0,38}[a-z0-9_])?)/gi, (whole, before: string, handle: string) => {
172 const key = handle.toLowerCase();
173 if (!known.has(key)) return whole;
174 if (kept.has(key) || kept.size < max) {
175 kept.add(key);
176 return whole;
177 }
178 return `${before}${handle}`;
179 });
180}
181
182/** The friendly notice when @g1t has no model to run on. */
183export const BUILTIN_NO_MODEL =
184 "Hi, I'm g1t. I'd love to help, but this workspace doesn't have a model I can use yet. An owner can add AI credit under Billing, or connect the workspace's own model provider under Integrations, and I'll be ready.";