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