Skip to content
915 linesCodeBlameRaw
1/**
2 * A workspace's own agents: named members with a job, a personality,
3 * routing limits and a budget, kept by the agents service
4 * (`services/agents`). Every workspace also has `@g1t`, its built-in
5 * orchestrator, kept the same way (`builtin`).
6 *
7 * Wire shapes are snake_case end to end.
8 */
9import type { ServiceBinding } from "./clients";
10import type { Role, User } from "./identity";
11import type { Result } from "./result";
12import type { CardActionResult } from "./chat";
13
14// Model tiers (`ModelTier`, `MODEL_TIERS`) are integrations.ts's, the
15// same ones runs are routed between.
16import type { ModelTier } from "./integrations";
17import type { ExtensionInstall, InstallRequest, InstallRequestStatus, InstallRequests } from "./marketplace";
18
19/** The built-in orchestrator's handle; nobody else's agent may take it. */
20export const BUILTIN_AGENT_HANDLE = "g1t";
21
22/** The built-in orchestrator's template id: not one a workspace can adopt. */
23export const ORCHESTRATOR_TEMPLATE = "orchestrator";
24
25/** Voice presets; free text in `personality` refines them. */
26export type PersonalityPreset = "crisp" | "friendly" | "socratic" | "terse";
27
28export type AgentRouting = {
29 /** Never route below this tier. Null: no floor. */
30 floor: ModelTier | null;
31 /** Never route above this tier. Null: no ceiling. */
32 ceiling: ModelTier | null;
33 /**
34 * Where its model calls may go. Empty: anything the workspace allows.
35 * `g1t`: g1t's hosted models. `workspace`: the workspace's own providers
36 * (Integrations), whichever they are. Any other entry: one of the
37 * workspace's own providers by integration id. Entries combine, so
38 * `["g1t", "workspace"]` is both.
39 */
40 providers: string[];
41 /** Advanced: a fixed `provider/model`, for own endpoints. Usually null. */
42 pinned: string | null;
43};
44
45export type AgentBudget = {
46 /** Monthly cap in micro-dollars. Null: only the workspace limit applies. */
47 monthly_micros: number | null;
48 daily_micros: number | null;
49 /** Default cap for one task. */
50 task_micros: number | null;
51};
52
53export type AgentAutonomy = {
54 open_pull_requests: "alone" | "approval";
55 merge: "alone" | "approval" | "never";
56 deploy_production: "approval" | "never";
57 edit_docs: "alone" | "suggest";
58};
59
60export type AgentStatus = "idle" | "working" | "waiting" | "out_of_budget" | "paused";
61
62export type WorkspaceAgent = {
63 id: string;
64 workspace_id: string;
65 /** Lowercase, unique in the workspace, never `g1t`. Mentioned as `@handle`. */
66 handle: string;
67 display_name: string;
68 /** Uploaded avatar hash, or null for the generated mark. */
69 avatar: string | null;
70 /**
71 * What its generated avatar is drawn from: a little pixel creature, the
72 * same for the same seed everywhere. Set from the handle when it is
73 * made; changing it gives the agent a new face.
74 */
75 avatar_seed: string;
76 /**
77 * One line, as lists show it: "QA Engineer on the QA team". Made from
78 * the title and team (or department) when not written.
79 */
80 role: string;
81 /**
82 * Agents are hired into roles, not tasks: a title, a team, and broad
83 * responsibilities.
84 */
85 title: string;
86 /** The team it is on, by slug, from the workspace's teams; null for none. */
87 team: string | null;
88 /** A label for where it works when it is on no team: "QA", "Sales". */
89 department: string;
90 /** What it is responsible for: 2 to 8 short duties, or none yet. */
91 responsibilities: string[];
92 /**
93 * Specialised help it will use inside its own work. Never members, never
94 * wider than their agent. Stored now; they run with tasks and sessions.
95 */
96 subagents: SubagentDef[];
97 /**
98 * Its required reading: Docs spaces (by id) it checks first, every time
99 * it answers or works. It still reads only what the person it acts for,
100 * and everyone reading its answer, can read.
101 */
102 reading: string[];
103 /**
104 * g1t's foundational skills turned off for it, by id (./skills.ts):
105 * every one is on unless named here. Off takes the skill's playbook out of
106 * its instructions; its tools stay as they are.
107 */
108 skills_off: string[];
109 /**
110 * Who it works with: `internal`, the workspace's own people (back
111 * office), or `customers` (front office). Only `internal` for now.
112 */
113 faces: AgentFaces;
114 /** The job: what it is responsible for and how it works. */
115 instructions: string;
116 personality_preset: PersonalityPreset;
117 /** Free text refining the voice. Never changes what it may do. */
118 personality: string;
119 routing: AgentRouting;
120 budget: AgentBudget;
121 autonomy: AgentAutonomy;
122 /** Tasks it works at once; more queue on its desk. */
123 capacity: number;
124 /** The template it was made from, if any. */
125 template: string | null;
126 /**
127 * The workspace's built-in orchestrator, `@g1t`: every workspace has one,
128 * made the first time its agents are asked for. It cannot be archived,
129 * and its handle, name, role and job are fixed; its `instructions` are
130 * added to that job. Listed first.
131 */
132 builtin: boolean;
133 /**
134 * Who it belongs to (docs.g1t.sh/guides/agents/, "Personal agents"):
135 * `workspace`, the workspace's own, which owners keep; or `personal`, a
136 * member's own, which only that member talks to, in their direct message
137 * with it, and whose spend counts against that member's budget.
138 */
139 scope: WorkspaceAgentScope;
140 /** For a personal agent, the member it belongs to: their user id and username. Null for a workspace agent. */
141 personal_owner_id: string | null;
142 personal_owner: string | null;
143 version: number;
144 status: AgentStatus;
145 /** Spend this calendar month, in micro-dollars. */
146 spent_month_micros: number;
147 created_by: string;
148 created_at: string;
149 updated_at: string;
150 archived_at: string | null;
151};
152
153/**
154 * Back office or front office (docs.g1t.sh/guides/agents/, "Back office
155 * and front office"). Customer-facing agents are not available yet.
156 */
157export type AgentFaces = "internal" | "customers";
158
159/** A workspace agent, which owners keep, or a member's personal agent. */
160export type WorkspaceAgentScope = "workspace" | "personal";
161
162/** What a personal agent starts with, unless its creator gives it other caps: $20 a month and $2 a session. */
163export const PERSONAL_AGENT_BUDGET = { monthly_micros: 20_000_000, daily_micros: null, task_micros: 2_000_000 } as const;
164
165/** Most personal agents one member keeps in a workspace. */
166export const MAX_PERSONAL_AGENTS = 10;
167
168/**
169 * A subagent: help an agent keeps for its own work, such as Margo's
170 * `flake-hunter`. Its routing limits sit within its agent's: a floor below
171 * the agent's is raised to it, a ceiling above is lowered to it.
172 */
173export type SubagentDef = {
174 /** Lowercase letters, digits and hyphens: `flake-hunter`. Unique on the agent. */
175 name: string;
176 /** One line: what it is for. */
177 description: string;
178 instructions: string;
179 routing: { floor: ModelTier | null; ceiling: ModelTier | null };
180 /** How many of it may run at once inside one task, 1 to 8. */
181 max_parallel: number;
182};
183
184export type NewWorkspaceAgent = {
185 handle: string;
186 display_name: string;
187 /** Left out or empty: made from the title and team. */
188 role?: string;
189 title?: string;
190 team?: string | null;
191 department?: string;
192 responsibilities?: string[];
193 subagents?: SubagentDef[];
194 /** Docs spaces (by id) it reads first; at most 10. */
195 reading?: string[];
196 /** Foundational skills to turn off, by id (./skills.ts). */
197 skills_off?: string[];
198 /** Only `internal` for now; `customers` is refused. */
199 faces?: AgentFaces;
200 instructions: string;
201 personality_preset?: PersonalityPreset;
202 personality?: string;
203 routing?: Partial<AgentRouting>;
204 budget?: Partial<AgentBudget>;
205 autonomy?: Partial<AgentAutonomy>;
206 capacity?: number;
207 template?: string | null;
208 /** Its avatar's seed; left out, the handle. */
209 avatar_seed?: string;
210 /**
211 * When creating: `workspace` (owners only, and their default) or
212 * `personal` (any member, when the workspace lets members make them; a
213 * member's default). Ignored on a change: an owner promotes instead.
214 */
215 scope?: WorkspaceAgentScope;
216};
217
218/**
219 * What g1t drafted from a description (docs.g1t.sh/guides/agents/,
220 * "Describe it"): a whole definition to edit before anything is saved,
221 * and what the agent will want around it. Nothing here is saved until the
222 * agent is created.
223 */
224export type AgentProposal = {
225 /** A complete definition, ready to create as it is. */
226 definition: NewWorkspaceAgent & { scope: WorkspaceAgentScope };
227 /** Other names that suit it, for the shuffle. */
228 name_ideas: string[];
229 /** Foundational skills it should keep on, by id (./skills.ts); the rest are off in `definition.skills_off`. */
230 skills: string[];
231 /** Integrations the job needs, from the catalog (./connectors.ts), with why. */
232 integrations: { id: string; why: string }[];
233 /** Routines that would suit it, to set up on its Routines tab once it exists. */
234 routines: { name: string; when: string; instructions: string }[];
235 /** What drafting it cost, charged to the person who asked (micro-dollars). */
236 charged_micros: number;
237};
238
239/** One line of a Try it conversation, held by the page, never saved. */
240export type DraftTurn = { role: "user" | "assistant"; content: string };
241
242/** A Try it answer, and what it cost the person trying it. */
243export type DraftReply = { text: string; charged_micros: number };
244
245/** Changes drafted from "Tell <name> what to change", to review before they are saved as a new version. */
246export type AgentRedraft = {
247 /** The changes to save, as `update` takes them: only fields that differ. */
248 changes: Partial<NewWorkspaceAgent>;
249 /** One line on what changed. */
250 summary: string;
251 /** The version it was drafted from. */
252 from_version: number;
253 charged_micros: number;
254};
255
256/**
257 * A role to hire an agent into, by department. Agents get names, not job
258 * titles ("Margo", the QA Engineer).
259 */
260export type AgentTemplate = {
261 id: string;
262 /** The name it suggests first. */
263 display_name: string;
264 handle: string;
265 /** Other names that suit it, for the form's shuffle. Each is also a valid handle, lowercased. */
266 name_ideas: string[];
267 role: string;
268 title: string;
269 department: string;
270 responsibilities: string[];
271 subagents: SubagentDef[];
272 instructions: string;
273 personality_preset: PersonalityPreset;
274 routing: AgentRouting;
275};
276
277/** What the chat service hands an agent: a message it should answer. */
278export type AgentDelivery = {
279 workspace: string;
280 workspace_id: string;
281 channel_id: string;
282 channel_kind: "channel" | "dm";
283 channel_name: string | null;
284 agent_id: string;
285 /** The message that woke it. */
286 message_id: string;
287 thread_root: string | null;
288 /** Who asked: the person's user id. */
289 asked_by: string;
290 /** Agent-to-agent hops so far in this chain. */
291 hops: number;
292 /**
293 * What the person who asked may do, from the viewer the chat service
294 * already holds when the message is posted (`askerAccess`). An agent
295 * never does more for someone than they could do themselves. Absent
296 * from an older chat service: the agent then treats the asker as unable
297 * to change code.
298 */
299 asker?: AskerAccess | null;
300 /**
301 * The agents that handled this request before this one, by id, oldest
302 * first; the last sent the work here. An agent never hands back or
303 * consults the one that sent it work, and the hop limit counts every
304 * hand-off and consult along the chain. Absent: none (a person asked).
305 */
306 chain?: string[];
307 /**
308 * Where the conversation is: g1t's own chat, or later another chat app
309 * the workspace connected. The agent reads and replies through that
310 * surface; its definition, budget and replies are the same everywhere.
311 * Absent: `g1t`.
312 */
313 surface?: AgentSurface;
314};
315
316/** The chat surfaces an agent answers on. Only g1t's own today. */
317export type AgentSurface = "g1t";
318
319/** Who asked an agent, as far as its reply needs to know. */
320export type AskerAccess = {
321 username: string;
322 /** Their role in the workspace; `outside` for someone who is not a member. */
323 role: Role | "outside";
324 /**
325 * Whether they can change code in the workspace: Code is on for them
326 * and they hold write access (or more) on at least one of its
327 * repositories, through the base permission or a grant.
328 */
329 can_write: boolean;
330};
331
332const WRITING_ROLES = new Set(["write", "maintain", "admin"]);
333
334/**
335 * `user`'s access in `workspace`, for `AgentDelivery.asker`. Pure, with no
336 * imports, so the chat service computes it from its viewer for free.
337 */
338export function askerAccess(user: User, workspace: string): AskerAccess {
339 const slug = workspace.toLowerCase();
340 const membership = user.workspaces?.find((m) => m.slug.toLowerCase() === slug);
341 // Someone who uses only Chat, Docs and agents sees no repository at all.
342 const code = membership?.code_access !== false;
343 const base = membership ? membership.role === "owner" || WRITING_ROLES.has(membership.base_permission ?? "write") : false;
344 const granted = (user.grants ?? []).some((grant) => grant.workspace.toLowerCase() === slug && WRITING_ROLES.has(grant.role));
345 return {
346 username: user.username,
347 role: membership?.role ?? "outside",
348 can_write: code && (base || granted),
349 };
350}
351
352/**
353 * A session: one bounded piece of work an agent took on
354 * (docs.g1t.sh/guides/agent-sessions/). A conversation with an agent is
355 * not a session: talking stays cheap and quick, and when a request needs
356 * real work the agent spins off a session for it, with its own context, transcript, budget and live card in
357 * the conversation. Sessions start other sessions (one of the agent's
358 * subagents, or a colleague brought in), and everything a tree of sessions
359 * spends is charged to the agent at its root, so a chain never escapes the
360 * budget that started it.
361 */
362export type AgentSessionKind =
363 /** Spun off from a conversation: someone asked for work. */
364 | "chat"
365 /** A routine's run. */
366 | "routine"
367 /** A colleague brought in by another session. */
368 | "helper"
369 /** One of the agent's own subagents, inside another session. */
370 | "subagent";
371
372export type AgentSessionStatus =
373 | "queued"
374 | "working"
375 /** Waiting on sessions it started. */
376 | "waiting"
377 /** Stopped at its spend cap: someone who may raise it decides. */
378 | "needs_approval"
379 | "done"
380 | "failed"
381 | "stopped";
382
383/** The statuses of a session that is not over. */
384export const SESSION_LIVE: readonly AgentSessionStatus[] = ["queued", "working", "waiting", "needs_approval"];
385
386export type AgentSession = {
387 id: string;
388 workspace_id: string;
389 agent_id: string;
390 /** The agent's handle, name and face, for lists. */
391 agent_handle: string;
392 agent_name: string;
393 agent_avatar_seed: string;
394 /** The subagent running it, by name, when kind is `subagent`. */
395 subagent: string | null;
396 kind: AgentSessionKind;
397 /** The session that started it, and the root of its tree. */
398 parent_id: string | null;
399 root_id: string;
400 /** Whose budget pays for it: the agent at the root of its tree. */
401 payer_agent_id: string;
402 title: string;
403 goal: string;
404 status: AgentSessionStatus;
405 /** Why it is waiting, stopped or failed, in a line. */
406 status_note: string | null;
407 /** What it found or did, once done: its report. */
408 summary: string | null;
409 /** Where it reports: the conversation it was started from. */
410 channel_id: string;
411 channel_kind: "channel" | "dm";
412 channel_name: string | null;
413 /** Its live card in that conversation; its updates go in the card's thread. */
414 card_message_id: string | null;
415 asked_by: string | null;
416 asked_by_username: string | null;
417 routine_id: string | null;
418 steps: number;
419 tool_calls: number;
420 input_tokens: number;
421 output_tokens: number;
422 /**
423 * At list price, what it counts against budgets: the model at the
424 * provider's price with billing's model margin, plus g1t's agent rate on
425 * every token. A root session's includes everything its tree spent.
426 */
427 charged_micros: number;
428 /** What its own steps' model answers cost at the provider's price, its tree's not included. */
429 cost_micros: number;
430 /** The most it may spend before someone approves more. */
431 cap_micros: number | null;
432 model: string | null;
433 /** What it produced: issues filed, sessions started. */
434 outputs: SessionOutput[];
435 created_at: string;
436 updated_at: string;
437 finished_at: string | null;
438 /**
439 * False when the viewer is not among the people of the conversation it
440 * came from: they see that it ran and what it cost, never its title,
441 * goal, report or transcript.
442 */
443 visible: boolean;
444};
445
446export type SessionOutput =
447 | { kind: "issue"; repo: string; number: number; title: string }
448 | { kind: "session"; id: string; agent_handle: string; title: string }
449 | { kind: "memory"; id: string; body: string };
450
451/** One entry of a session's transcript, as its page shows it. */
452export type SessionEvent = {
453 seq: number;
454 kind: "goal" | "text" | "tool" | "steer" | "update" | "child" | "result" | "note";
455 /** Who: the agent's handle, a person's username (steering), or null for g1t's notes. */
456 by: string | null;
457 body: string;
458 /** For `tool`: the tool, and whether it read, was withheld, refused or failed. */
459 tool: string | null;
460 outcome: string | null;
461 created_at: string;
462};
463
464export type AgentSessionDetail = {
465 session: AgentSession;
466 events: SessionEvent[];
467 /** Every session in its tree, root first. */
468 tree: AgentSession[];
469 /** Whether the viewer may stop it, steer it, or approve more spend. */
470 can_stop: boolean;
471 can_steer: boolean;
472 can_approve: boolean;
473};
474
475/**
476 * What an agent remembers (docs.g1t.sh/guides/agent-memory/). Every fact
477 * carries where it came from, and its scope decides, in code, where it may
478 * be recalled and who may see it:
479 *
480 * - `workspace`: anywhere in the workspace. Owners write these, or an agent
481 * from a public channel, which every member can read already.
482 * - `channel`: only in that channel and its threads.
483 * - `person`: only in a direct message with that one person.
484 */
485export type AgentMemoryScope = "workspace" | "channel" | "person";
486
487export type AgentMemory = {
488 id: string;
489 agent_id: string;
490 scope: AgentMemoryScope;
491 /** The channel's id or the person's user id; empty for `workspace`. */
492 scope_ref: string;
493 /** The channel's name or the person's username, for display. */
494 scope_label: string | null;
495 body: string;
496 source_kind: "message" | "session" | "person";
497 /** A message id, a session id, or the username of who wrote it. */
498 source_ref: string | null;
499 source_label: string | null;
500 /** The channel the source is in, for a link. */
501 source_channel_id: string | null;
502 created_by: string;
503 created_by_kind: "agent" | "user";
504 pinned: boolean;
505 created_at: string;
506 updated_at: string;
507};
508
509/** When a routine runs, in UTC. */
510export type RoutineSchedule = {
511 every: "hour" | "day" | "weekday" | "week";
512 /** Minute of the hour, 0 to 59. */
513 minute: number;
514 /** Hour of the day (UTC), 0 to 23; not used for `hour`. */
515 hour: number;
516 /** Day of the week for `week`, 0 (Sunday) to 6. */
517 weekday: number;
518};
519
520/**
521 * Things that happen in the workspace a routine can run on
522 * (docs.g1t.sh/guides/agent-routines/). Each run is one session about the one
523 * thing that happened, in a repository its sponsor can read.
524 */
525export const ROUTINE_EVENTS = [
526 { key: "pull_ready", label: "A pull request is ready for review", hint: "Opened ready, or moved out of draft." },
527 { key: "pull_merged", label: "A pull request is merged", hint: "On any branch it targets." },
528 { key: "checks_failed", label: "Checks fail on a pull request", hint: "Its required checks failed or errored." },
529 { key: "issue_opened", label: "An issue is opened", hint: "By a person or an agent." },
530 { key: "deploy_failed", label: "A deploy fails", hint: "A production or preview deploy." },
531] as const;
532
533export type RoutineEvent = (typeof ROUTINE_EVENTS)[number]["key"];
534
535/**
536 * A routine: work an agent does on a schedule or when something happens, such as Sam's Monday digest
537 * of support themes. Each run is a session posted in the routine's channel,
538 * paid from the agent's budget, and run with the access of the person who
539 * set it up (its sponsor), never more.
540 */
541export type AgentRoutine = {
542 id: string;
543 agent_id: string;
544 name: string;
545 instructions: string;
546 /** When it runs on a clock; null when it runs only on events. */
547 schedule: RoutineSchedule | null;
548 /** What it runs on; empty when it runs only on its schedule. */
549 events: RoutineEvent[];
550 /** Which repositories its events come from, by `workspace/name`; empty: every one its sponsor can read. */
551 repos: string[];
552 channel_id: string;
553 channel_name: string | null;
554 sponsor: string;
555 sponsor_username: string | null;
556 enabled: boolean;
557 /** Why g1t paused it, when it did. */
558 paused_note: string | null;
559 next_run_at: string | null;
560 last_run_at: string | null;
561 last_session_id: string | null;
562 runs: number;
563 created_at: string;
564 updated_at: string;
565};
566
567/** A routine suggested from an agent's responsibilities, for an owner to add in one step. */
568export type RoutineSuggestion = { responsibility: string; routine: Omit<NewRoutine, "channel_id"> };
569
570export type NewRoutine = {
571 name: string;
572 instructions: string;
573 /** A schedule, events, or both; at least one. */
574 schedule: RoutineSchedule | null;
575 events?: RoutineEvent[];
576 repos?: string[];
577 /** A channel the agent is in, by id. */
578 channel_id: string;
579 enabled?: boolean;
580};
581
582/**
583 * The workspace's say over all its agents together, set by owners: one
584 * monthly budget across every agent, the budget a new agent starts with,
585 * and the cap a session starts with. The workspace's spend limit and AI
586 * credit (billing) sit above all of it.
587 */
588export type AgentPolicy = {
589 /** Every agent's spend together in a month. Null: only the workspace's spend limit. */
590 monthly_micros: number | null;
591 /** The monthly budget a new agent gets. Null: none. */
592 default_agent_monthly_micros: number | null;
593 /** The cap one session starts with, unless its agent's per-task cap is lower. */
594 default_session_micros: number;
595 /**
596 * What the agents working for one person (their replies and sessions,
597 * asked for by that person) may spend together in a month, unless the
598 * person has a budget of their own. Null: no budget per person.
599 */
600 person_monthly_micros: number | null;
601 /**
602 * Whether members who aren't owners may create personal agents
603 * (docs.g1t.sh/guides/agents/, "Personal agents"). On unless an owner
604 * turns it off; off, existing personal agents keep working.
605 */
606 members_create_agents: boolean;
607};
608
609/** One person's budget: what agents working for them may spend in a month, and what they have. */
610export type PersonBudget = {
611 username: string;
612 /** The budget that applies: their own, or the workspace's per-person default. Null: none. */
613 monthly_micros: number | null;
614 /** Whether it is their own, set by an owner, rather than the default. */
615 own: boolean;
616 /** What agents spent for them this month (UTC). */
617 spent_micros: number;
618};
619
620/** Budgets per person: the default, and each person who has one of their own or has spent this month. */
621export type PersonBudgets = {
622 period: string;
623 default_micros: number | null;
624 /** Owners see everyone; anyone else sees only themselves. Most spent first. */
625 people: PersonBudget[];
626};
627
628export type SpendSlice = { key: string; label: string; micros: number; count: number };
629
630/** Which days a breakdown covers: this month (the default), last month, or the last 7 or 30 days, in UTC. */
631export type SpendPeriod = "month" | "last_month" | "7d" | "30d";
632
633/** Where an agent's (or every agent's) spend went over a period. */
634export type AgentSpendBreakdown = {
635 /** `YYYY-MM` for a month; for a span of days, the month it ends in. */
636 period: string;
637 /** The span asked for, and its first and last day (`YYYY-MM-DD`, both included). */
638 span: SpendPeriod;
639 from: string;
640 until: string;
641 /** The one person it is about (work asked for by them), or null for everyone's. */
642 person: string | null;
643 total_micros: number;
644 /** Chat replies, sessions, routines, helping colleagues. */
645 by_kind: SpendSlice[];
646 by_model: SpendSlice[];
647 /** Who asked: the work done for each person. */
648 by_person: SpendSlice[];
649 by_agent: SpendSlice[];
650 by_team: SpendSlice[];
651 /**
652 * Where it was asked: a channel by id (labelled `#name`), direct
653 * messages together (`dm`), and channels the viewer can't read together
654 * (`private`).
655 */
656 by_channel: SpendSlice[];
657 /** The costliest sessions in the period. */
658 top_sessions: AgentSession[];
659 /** Spend by day in the period. */
660 days: { day: string; micros: number }[];
661};
662
663/** Agents mode's front page. */
664export type AgentsOverview = {
665 policy: AgentPolicy;
666 /** Every agent's spend this month, against the policy's budget. */
667 spent_month_micros: number;
668 /** The highest alert this month: 75, 90 or 100 (% of the workspace's agent budget). */
669 alert: number | null;
670 agents: WorkspaceAgent[];
671 /** Live sessions, counted by agent id, for the roster. */
672 live_by_agent: Record<string, number>;
673 /** Sessions live now that the viewer can see. */
674 live: AgentSession[];
675 /** Sessions waiting on the viewer: spend they may approve. */
676 waiting_on_you: AgentSession[];
677 /** Recently finished sessions the viewer can see. */
678 recent: AgentSession[];
679 /** The next routines to run on a schedule. */
680 upcoming: (AgentRoutine & { agent_handle: string; agent_name: string })[];
681 spend: AgentSpendBreakdown;
682 can_manage: boolean;
683};
684
685/** One thing an agent did, for its Activity tab. */
686export type AgentActivity = {
687 id: string;
688 kind: "reply" | "session";
689 status: string;
690 channel_id: string;
691 channel_name: string | null;
692 /** The session's title; null for a reply or one the viewer can't see. */
693 title: string | null;
694 asked_by_username: string | null;
695 model: string | null;
696 tools: number;
697 charged_micros: number;
698 created_at: string;
699 visible: boolean;
700 /** For a reply, the message it posted; for a session, its id. */
701 ref: string | null;
702};
703
704export type AgentVersion = { version: number; changed_by: string; created_at: string; definition: Partial<NewWorkspaceAgent> };
705
706/** A card action, as chat hands it to agents. */
707export type AgentCardAction = {
708 workspace: string;
709 channel_id: string;
710 message_id: string;
711 viewer: User;
712 card: { kind: string; ref: string | null };
713 action_id: string;
714 input: string | null;
715};
716
717export type WorkspaceAgentsApi = {
718 /**
719 * The workspace's agents. Personal agents are left out unless asked
720 * for: `mine`, the viewer's own; `all`, every member's for an owner (the
721 * viewer's own for anyone else).
722 */
723 list(workspace: string, viewer: User, options?: { personal?: "mine" | "all" | null }): Promise<Result<WorkspaceAgent[]>>;
724 get(workspace: string, handle: string, viewer: User): Promise<Result<WorkspaceAgent>>;
725 /** Internal: by id, for the chat service resolving members. */
726 byIds(ids: string[]): Promise<WorkspaceAgent[]>;
727 create(workspace: string, viewer: User, input: NewWorkspaceAgent): Promise<Result<WorkspaceAgent>>;
728 update(
729 workspace: string,
730 handle: string,
731 viewer: User,
732 changes: Partial<NewWorkspaceAgent>,
733 ): Promise<Result<WorkspaceAgent>>;
734 archive(workspace: string, handle: string, viewer: User): Promise<Result<null>>;
735 /**
736 * Drafts a whole agent from a description, with a fast model call charged
737 * to the viewer. Nothing is saved. Whoever may create the agent may draft it.
738 */
739 draft(workspace: string, viewer: User, input: { description: string; scope?: WorkspaceAgentScope | null }): Promise<Result<AgentProposal>>;
740 /**
741 * Try it: the unsaved definition answers the conversation so far, as it
742 * would in a direct message, without tools or memory. Charged to the
743 * viewer; nothing is saved.
744 */
745 tryDraft(workspace: string, viewer: User, input: { definition: NewWorkspaceAgent; messages: DraftTurn[] }): Promise<Result<DraftReply>>;
746 /** Drafts changes to an agent from a request in words; saved only through `update`. Whoever may change the agent may ask. */
747 redraft(workspace: string, handle: string, viewer: User, request: string): Promise<Result<AgentRedraft>>;
748 /**
749 * Owners make a member's personal agent a workspace agent: its definition
750 * and every version move to a workspace agent with the same handle, and
751 * the personal one is archived, with its memory and direct messages.
752 */
753 promote(workspace: string, handle: string, viewer: User): Promise<Result<WorkspaceAgent>>;
754 templates(): Promise<AgentTemplate[]>;
755 /**
756 * Internal: the workspace's built-in `@g1t` agent, made if it does not
757 * exist yet. The chat service asks for it when someone mentions @g1t in
758 * a channel it is not in yet.
759 */
760 builtin(workspace: string, workspaceId: string): Promise<Result<WorkspaceAgent>>;
761 /** The chat service hands over a message for an agent to answer. Returns at once. */
762 deliver(delivery: AgentDelivery): Promise<Result<null>>;
763 overview(workspace: string, viewer: User): Promise<Result<AgentsOverview>>;
764 sessions(
765 workspace: string,
766 viewer: User,
767 filter?: { handle?: string | null; status?: "live" | "done" | null; limit?: number | null },
768 ): Promise<Result<AgentSession[]>>;
769 session(workspace: string, id: string, viewer: User): Promise<Result<AgentSessionDetail>>;
770 /** Stops a session and every session under it. */
771 stopSession(workspace: string, id: string, viewer: User): Promise<Result<AgentSession>>;
772 /** Raises a stopped session's cap and lets it go on. Owners only. */
773 approveSession(workspace: string, id: string, viewer: User, capMicros: number): Promise<Result<AgentSession>>;
774 /** A person's message to a session, running or finished: it reads it and goes on. */
775 steerSession(workspace: string, id: string, viewer: User, body: string): Promise<Result<AgentSession>>;
776 memories(workspace: string, handle: string, viewer: User): Promise<Result<AgentMemory[]>>;
777 remember(
778 workspace: string,
779 handle: string,
780 viewer: User,
781 input: { body: string; scope: AgentMemoryScope; scope_ref?: string | null },
782 ): Promise<Result<AgentMemory>>;
783 updateMemory(
784 workspace: string,
785 handle: string,
786 viewer: User,
787 id: string,
788 changes: { body?: string; pinned?: boolean },
789 ): Promise<Result<AgentMemory>>;
790 forget(workspace: string, handle: string, viewer: User, id: string): Promise<Result<null>>;
791 routines(workspace: string, handle: string, viewer: User): Promise<Result<{ routines: AgentRoutine[]; suggestions: RoutineSuggestion[] }>>;
792 saveRoutine(workspace: string, handle: string, viewer: User, input: NewRoutine, id?: string | null): Promise<Result<AgentRoutine>>;
793 deleteRoutine(workspace: string, handle: string, viewer: User, id: string): Promise<Result<null>>;
794 /** Runs a routine now, as a session. */
795 runRoutine(workspace: string, handle: string, viewer: User, id: string): Promise<Result<AgentSession>>;
796 /**
797 * Where the spend went: one agent's, or every agent's; this month unless
798 * `period` says otherwise; for everyone, or only the work one `person`
799 * (by username) asked for.
800 */
801 spend(workspace: string, viewer: User, handle?: string | null, options?: { period?: SpendPeriod | null; person?: string | null }): Promise<Result<AgentSpendBreakdown>>;
802 /** Budgets per person this month: owners see everyone's, anyone else their own. */
803 personBudgets(workspace: string, viewer: User): Promise<Result<PersonBudgets>>;
804 /**
805 * Gives one person a monthly budget of their own (`monthly_micros`; 0 for
806 * no budget at all), or with null puts them back on the default. Owners only.
807 */
808 setPersonBudget(workspace: string, viewer: User, username: string, monthlyMicros: number | null): Promise<Result<PersonBudgets>>;
809 activity(workspace: string, handle: string, viewer: User): Promise<Result<AgentActivity[]>>;
810 /** What an agent is told about its teams this turn, word for word. Members only. */
811 teamContext(workspace: string, handle: string, viewer: User): Promise<Result<AgentTeamContext>>;
812 versions(workspace: string, handle: string, viewer: User): Promise<Result<AgentVersion[]>>;
813 /**
814 * Internal, from chat: a person pressed an action on one of agents'
815 * cards. Agents checks they may, acts, and updates the card.
816 */
817 cardAction(input: AgentCardAction): Promise<Result<CardActionResult>>;
818 policy(workspace: string, viewer: User): Promise<Result<AgentPolicy>>;
819 setPolicy(workspace: string, viewer: User, policy: Partial<AgentPolicy>): Promise<Result<AgentPolicy>>;
820 /**
821 * The Marketplace's install requests (./marketplace.ts): every one in the
822 * workspace for an owner, a member's own for anyone else.
823 */
824 installRequests(workspace: string, viewer: User): Promise<Result<InstallRequests>>;
825 /**
826 * A member asks the workspace's owners to add a listing
827 * (`extension:<id>` or `integration:<connector>`), and every owner is
828 * notified. Owners add
829 * things themselves, so they don't ask. Asking again while a request for
830 * the same listing is open is a conflict.
831 */
832 requestInstall(workspace: string, viewer: User, listing: string, note?: string | null): Promise<Result<InstallRequest>>;
833 /** An owner marks a request added (`done`) or turns it down (`declined`); whoever asked is told. */
834 resolveInstallRequest(workspace: string, viewer: User, id: string, status: Exclude<InstallRequestStatus, "open">): Promise<Result<InstallRequest>>;
835 /** The extensions installed in the workspace; any member sees them. */
836 extensionInstalls(workspace: string, viewer: User): Promise<Result<ExtensionInstall[]>>;
837 /** Owners install a published extension at its current version; open requests for it are answered. */
838 installExtension(workspace: string, viewer: User, extension: string): Promise<Result<ExtensionInstall>>;
839 /** Owners switch an install on or off: off is the kill switch. */
840 setExtensionEnabled(workspace: string, viewer: User, listing: string, enabled: boolean): Promise<Result<ExtensionInstall>>;
841 /** Owners cap what an install spends a month; null leaves it to the workspace's limit. */
842 setExtensionBudget(workspace: string, viewer: User, listing: string, monthlyMicros: number | null): Promise<Result<ExtensionInstall>>;
843 uninstallExtension(workspace: string, viewer: User, listing: string): Promise<Result<null>>;
844};
845
846async function rpc<T>(service: ServiceBinding, method: string, args: object): Promise<T> {
847 const response = await service.fetch(`https://service/rpc/${method}`, {
848 method: "POST",
849 headers: { "content-type": "application/json" },
850 body: JSON.stringify(args),
851 });
852 if (!response.ok) {
853 throw new Error(`${method} failed with status ${response.status}`);
854 }
855 return (await response.json()) as T;
856}
857
858/**
859 * What an agent is told about its teams every turn (docs.g1t.sh/guides/people-and-teams/,
860 * "What agents are told"): the visible teams it is on, by slug, and the text
861 * itself; null when it is on none.
862 */
863export type AgentTeamContext = { handle: string; teams: string[]; text: string | null };
864
865export function workspaceAgentsClient(service: ServiceBinding): WorkspaceAgentsApi {
866 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
867 return {
868 list: (workspace, viewer, options) => call("list", { workspace, viewer, personal: options?.personal ?? null }),
869 get: (workspace, handle, viewer) => call("get", { workspace, handle, viewer }),
870 byIds: (ids) => call("by_ids", { ids }),
871 create: (workspace, viewer, input) => call("create", { workspace, viewer, input }),
872 update: (workspace, handle, viewer, changes) => call("update", { workspace, handle, viewer, changes }),
873 archive: (workspace, handle, viewer) => call("archive", { workspace, handle, viewer }),
874 draft: (workspace, viewer, input) => call("draft", { workspace, viewer, description: input.description, scope: input.scope ?? null }),
875 tryDraft: (workspace, viewer, input) => call("try_draft", { workspace, viewer, definition: input.definition, messages: input.messages }),
876 redraft: (workspace, handle, viewer, request) => call("redraft", { workspace, handle, viewer, request }),
877 promote: (workspace, handle, viewer) => call("promote", { workspace, handle, viewer }),
878 templates: () => call("templates", {}),
879 builtin: (workspace, workspaceId) => call("builtin", { workspace, workspace_id: workspaceId }),
880 deliver: (delivery) => call("deliver", delivery),
881 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
882 sessions: (workspace, viewer, filter) => call("sessions", { workspace, viewer, ...(filter ?? {}) }),
883 session: (workspace, id, viewer) => call("session", { workspace, id, viewer }),
884 stopSession: (workspace, id, viewer) => call("stop_session", { workspace, id, viewer }),
885 approveSession: (workspace, id, viewer, capMicros) => call("approve_session", { workspace, id, viewer, cap_micros: capMicros }),
886 steerSession: (workspace, id, viewer, body) => call("steer_session", { workspace, id, viewer, body }),
887 memories: (workspace, handle, viewer) => call("memories", { workspace, handle, viewer }),
888 remember: (workspace, handle, viewer, input) => call("remember", { workspace, handle, viewer, input }),
889 updateMemory: (workspace, handle, viewer, id, changes) => call("update_memory", { workspace, handle, viewer, id, changes }),
890 forget: (workspace, handle, viewer, id) => call("forget", { workspace, handle, viewer, id }),
891 routines: (workspace, handle, viewer) => call("routines", { workspace, handle, viewer }),
892 saveRoutine: (workspace, handle, viewer, input, id) => call("save_routine", { workspace, handle, viewer, input, id: id ?? null }),
893 deleteRoutine: (workspace, handle, viewer, id) => call("delete_routine", { workspace, handle, viewer, id }),
894 runRoutine: (workspace, handle, viewer, id) => call("run_routine", { workspace, handle, viewer, id }),
895 spend: (workspace, viewer, handle, options) =>
896 call("spend", { workspace, viewer, handle: handle ?? null, period: options?.period ?? null, person: options?.person ?? null }),
897 personBudgets: (workspace, viewer) => call("person_budgets", { workspace, viewer }),
898 teamContext: (workspace, handle, viewer) => call("team_context", { workspace, handle, viewer }),
899 setPersonBudget: (workspace, viewer, username, monthlyMicros) =>
900 call("set_person_budget", { workspace, viewer, username, monthly_micros: monthlyMicros }),
901 activity: (workspace, handle, viewer) => call("activity", { workspace, handle, viewer }),
902 versions: (workspace, handle, viewer) => call("versions", { workspace, handle, viewer }),
903 cardAction: (input) => call("card_action", input),
904 policy: (workspace, viewer) => call("policy", { workspace, viewer }),
905 setPolicy: (workspace, viewer, policy) => call("set_policy", { workspace, viewer, policy }),
906 installRequests: (workspace, viewer) => call("install_requests", { workspace, viewer }),
907 requestInstall: (workspace, viewer, listing, note) => call("request_install", { workspace, viewer, listing, note: note ?? null }),
908 resolveInstallRequest: (workspace, viewer, id, status) => call("resolve_install_request", { workspace, viewer, id, status }),
909 extensionInstalls: (workspace, viewer) => call("extension_installs", { workspace, viewer }),
910 installExtension: (workspace, viewer, extension) => call("install_extension", { workspace, viewer, extension }),
911 setExtensionEnabled: (workspace, viewer, listing, enabled) => call("set_extension_enabled", { workspace, viewer, listing, enabled }),
912 setExtensionBudget: (workspace, viewer, listing, monthlyMicros) => call("set_extension_budget", { workspace, viewer, listing, monthly_micros: monthlyMicros }),
913 uninstallExtension: (workspace, viewer, listing) => call("uninstall_extension", { workspace, viewer, listing }),
914 };
915}