Skip to content
706 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`). Plan: docs/WORKSPACE.md,
6 * "g1t, the orchestrator".
7 *
8 * Wire shapes are snake_case end to end.
9 */
10import type { ServiceBinding } from "./clients";
11import type { Role, User } from "./identity";
12import type { Result } from "./result";
13import type { CardActionResult } from "./chat";
14
15// Model tiers (`ModelTier`, `MODEL_TIERS`) are integrations.ts's, the
16// same ones runs are routed between.
17import type { ModelTier } from "./integrations";
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 (docs/WORKSPACE.md, "Roles, not
83 * tasks"): a title, a team, and broad 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/WORKSPACE.md, "Back office and front
139 * 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
225 * (docs/WORKSPACE.md, "The whole company"). Absent from an older chat
226 * service: the agent then treats the asker as unable 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 (docs/WORKSPACE.md, "Working from another chat
239 * app"). The agent reads and replies through that surface; its
240 * definition, budget and replies are the same everywhere. 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 (docs/WORKSPACE.md,
283 * "Sessions"). A conversation with an agent is not a session: talking stays
284 * cheap and quick, and when a request needs real work the agent spins off a
285 * 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 /** At list price, what it counts against budgets. */
352 charged_micros: number;
353 /** The most it may spend before someone approves more. */
354 cap_micros: number | null;
355 model: string | null;
356 /** What it produced: issues filed, sessions started. */
357 outputs: SessionOutput[];
358 created_at: string;
359 updated_at: string;
360 finished_at: string | null;
361 /**
362 * False when the viewer is not among the people of the conversation it
363 * came from: they see that it ran and what it cost, never its title,
364 * goal, report or transcript.
365 */
366 visible: boolean;
367};
368
369export type SessionOutput =
370 | { kind: "issue"; repo: string; number: number; title: string }
371 | { kind: "session"; id: string; agent_handle: string; title: string }
372 | { kind: "memory"; id: string; body: string };
373
374/** One entry of a session's transcript, as its page shows it. */
375export type SessionEvent = {
376 seq: number;
377 kind: "goal" | "text" | "tool" | "steer" | "update" | "child" | "result" | "note";
378 /** Who: the agent's handle, a person's username (steering), or null for g1t's notes. */
379 by: string | null;
380 body: string;
381 /** For `tool`: the tool, and whether it read, was withheld, refused or failed. */
382 tool: string | null;
383 outcome: string | null;
384 created_at: string;
385};
386
387export type AgentSessionDetail = {
388 session: AgentSession;
389 events: SessionEvent[];
390 /** Every session in its tree, root first. */
391 tree: AgentSession[];
392 /** Whether the viewer may stop it, steer it, or approve more spend. */
393 can_stop: boolean;
394 can_steer: boolean;
395 can_approve: boolean;
396};
397
398/**
399 * What an agent remembers (docs/WORKSPACE.md, "What an agent can and can't
400 * know"). Every fact carries where it came from, and its scope decides, in
401 * code, where it may be recalled and who may see it:
402 *
403 * - `workspace`: anywhere in the workspace. Owners write these, or an agent
404 * from a public channel, which every member can read already.
405 * - `channel`: only in that channel and its threads.
406 * - `person`: only in a direct message with that one person.
407 */
408export type AgentMemoryScope = "workspace" | "channel" | "person";
409
410export type AgentMemory = {
411 id: string;
412 agent_id: string;
413 scope: AgentMemoryScope;
414 /** The channel's id or the person's user id; empty for `workspace`. */
415 scope_ref: string;
416 /** The channel's name or the person's username, for display. */
417 scope_label: string | null;
418 body: string;
419 source_kind: "message" | "session" | "person";
420 /** A message id, a session id, or the username of who wrote it. */
421 source_ref: string | null;
422 source_label: string | null;
423 /** The channel the source is in, for a link. */
424 source_channel_id: string | null;
425 created_by: string;
426 created_by_kind: "agent" | "user";
427 pinned: boolean;
428 created_at: string;
429 updated_at: string;
430};
431
432/** When a routine runs, in UTC. */
433export type RoutineSchedule = {
434 every: "hour" | "day" | "weekday" | "week";
435 /** Minute of the hour, 0 to 59. */
436 minute: number;
437 /** Hour of the day (UTC), 0 to 23; not used for `hour`. */
438 hour: number;
439 /** Day of the week for `week`, 0 (Sunday) to 6. */
440 weekday: number;
441};
442
443/**
444 * Things that happen in the workspace a routine can run on
445 * (docs/WORKSPACE.md, "Routines"). Each run is one session about the one
446 * thing that happened, in a repository its sponsor can read.
447 */
448export const ROUTINE_EVENTS = [
449 { key: "pull_ready", label: "A pull request is ready for review", hint: "Opened ready, or moved out of draft." },
450 { key: "pull_merged", label: "A pull request is merged", hint: "On any branch it targets." },
451 { key: "checks_failed", label: "Checks fail on a pull request", hint: "Its required checks failed or errored." },
452 { key: "issue_opened", label: "An issue is opened", hint: "By a person or an agent." },
453 { key: "deploy_failed", label: "A deploy fails", hint: "A production or preview deploy." },
454] as const;
455
456export type RoutineEvent = (typeof ROUTINE_EVENTS)[number]["key"];
457
458/**
459 * A routine: work an agent does on a schedule or when something happens, such as Izzy's Monday digest
460 * of support themes. Each run is a session posted in the routine's channel,
461 * paid from the agent's budget, and run with the access of the person who
462 * set it up (its sponsor), never more.
463 */
464export type AgentRoutine = {
465 id: string;
466 agent_id: string;
467 name: string;
468 instructions: string;
469 /** When it runs on a clock; null when it runs only on events. */
470 schedule: RoutineSchedule | null;
471 /** What it runs on; empty when it runs only on its schedule. */
472 events: RoutineEvent[];
473 /** Which repositories its events come from, by `workspace/name`; empty: every one its sponsor can read. */
474 repos: string[];
475 channel_id: string;
476 channel_name: string | null;
477 sponsor: string;
478 sponsor_username: string | null;
479 enabled: boolean;
480 /** Why g1t paused it, when it did. */
481 paused_note: string | null;
482 next_run_at: string | null;
483 last_run_at: string | null;
484 last_session_id: string | null;
485 runs: number;
486 created_at: string;
487 updated_at: string;
488};
489
490/** A routine suggested from an agent's responsibilities, for an owner to add in one step. */
491export type RoutineSuggestion = { responsibility: string; routine: Omit<NewRoutine, "channel_id"> };
492
493export type NewRoutine = {
494 name: string;
495 instructions: string;
496 /** A schedule, events, or both; at least one. */
497 schedule: RoutineSchedule | null;
498 events?: RoutineEvent[];
499 repos?: string[];
500 /** A channel the agent is in, by id. */
501 channel_id: string;
502 enabled?: boolean;
503};
504
505/**
506 * The workspace's say over all its agents together, set by owners: one
507 * monthly budget across every agent, the budget a new agent starts with,
508 * and the cap a session starts with. The workspace's spend limit and AI
509 * credit (billing) sit above all of it.
510 */
511export type AgentPolicy = {
512 /** Every agent's spend together in a month. Null: only the workspace's spend limit. */
513 monthly_micros: number | null;
514 /** The monthly budget a new agent gets. Null: none. */
515 default_agent_monthly_micros: number | null;
516 /** The cap one session starts with, unless its agent's per-task cap is lower. */
517 default_session_micros: number;
518};
519
520export type SpendSlice = { key: string; label: string; micros: number; count: number };
521
522/** Where an agent's (or every agent's) month went. */
523export type AgentSpendBreakdown = {
524 period: string;
525 total_micros: number;
526 /** Chat replies, sessions, routines, helping colleagues. */
527 by_kind: SpendSlice[];
528 by_model: SpendSlice[];
529 /** Who asked: the work done for each person. */
530 by_person: SpendSlice[];
531 by_agent: SpendSlice[];
532 by_team: SpendSlice[];
533 /** The costliest sessions this month. */
534 top_sessions: AgentSession[];
535 /** Spend by day this month. */
536 days: { day: string; micros: number }[];
537};
538
539/** Agents mode's front page. */
540export type AgentsOverview = {
541 policy: AgentPolicy;
542 /** Every agent's spend this month, against the policy's budget. */
543 spent_month_micros: number;
544 /** The highest alert this month: 75, 90 or 100 (% of the workspace's agent budget). */
545 alert: number | null;
546 agents: WorkspaceAgent[];
547 /** Live sessions, counted by agent id, for the roster. */
548 live_by_agent: Record<string, number>;
549 /** Sessions live now that the viewer can see. */
550 live: AgentSession[];
551 /** Sessions waiting on the viewer: spend they may approve. */
552 waiting_on_you: AgentSession[];
553 /** Recently finished sessions the viewer can see. */
554 recent: AgentSession[];
555 /** The next routines to run on a schedule. */
556 upcoming: (AgentRoutine & { agent_handle: string; agent_name: string })[];
557 spend: AgentSpendBreakdown;
558 can_manage: boolean;
559};
560
561/** One thing an agent did, for its Activity tab. */
562export type AgentActivity = {
563 id: string;
564 kind: "reply" | "session";
565 status: string;
566 channel_id: string;
567 channel_name: string | null;
568 /** The session's title; null for a reply or one the viewer can't see. */
569 title: string | null;
570 asked_by_username: string | null;
571 model: string | null;
572 tools: number;
573 charged_micros: number;
574 created_at: string;
575 visible: boolean;
576 /** For a reply, the message it posted; for a session, its id. */
577 ref: string | null;
578};
579
580export type AgentVersion = { version: number; changed_by: string; created_at: string; definition: Partial<NewWorkspaceAgent> };
581
582/** A card action, as chat hands it to agents. */
583export type AgentCardAction = {
584 workspace: string;
585 channel_id: string;
586 message_id: string;
587 viewer: User;
588 card: { kind: string; ref: string | null };
589 action_id: string;
590 input: string | null;
591};
592
593export type WorkspaceAgentsApi = {
594 list(workspace: string, viewer: User): Promise<Result<WorkspaceAgent[]>>;
595 get(workspace: string, handle: string, viewer: User): Promise<Result<WorkspaceAgent>>;
596 /** Internal: by id, for the chat service resolving members. */
597 byIds(ids: string[]): Promise<WorkspaceAgent[]>;
598 create(workspace: string, viewer: User, input: NewWorkspaceAgent): Promise<Result<WorkspaceAgent>>;
599 update(
600 workspace: string,
601 handle: string,
602 viewer: User,
603 changes: Partial<NewWorkspaceAgent>,
604 ): Promise<Result<WorkspaceAgent>>;
605 archive(workspace: string, handle: string, viewer: User): Promise<Result<null>>;
606 templates(): Promise<AgentTemplate[]>;
607 /**
608 * Internal: the workspace's built-in `@g1t` agent, made if it does not
609 * exist yet. The chat service asks for it when someone mentions @g1t in
610 * a channel it is not in yet.
611 */
612 builtin(workspace: string, workspaceId: string): Promise<Result<WorkspaceAgent>>;
613 /** The chat service hands over a message for an agent to answer. Returns at once. */
614 deliver(delivery: AgentDelivery): Promise<Result<null>>;
615 overview(workspace: string, viewer: User): Promise<Result<AgentsOverview>>;
616 sessions(
617 workspace: string,
618 viewer: User,
619 filter?: { handle?: string | null; status?: "live" | "done" | null; limit?: number | null },
620 ): Promise<Result<AgentSession[]>>;
621 session(workspace: string, id: string, viewer: User): Promise<Result<AgentSessionDetail>>;
622 /** Stops a session and every session under it. */
623 stopSession(workspace: string, id: string, viewer: User): Promise<Result<AgentSession>>;
624 /** Raises a stopped session's cap and lets it go on. Owners only. */
625 approveSession(workspace: string, id: string, viewer: User, capMicros: number): Promise<Result<AgentSession>>;
626 /** A person's message to a session, running or finished: it reads it and goes on. */
627 steerSession(workspace: string, id: string, viewer: User, body: string): Promise<Result<AgentSession>>;
628 memories(workspace: string, handle: string, viewer: User): Promise<Result<AgentMemory[]>>;
629 remember(
630 workspace: string,
631 handle: string,
632 viewer: User,
633 input: { body: string; scope: AgentMemoryScope; scope_ref?: string | null },
634 ): Promise<Result<AgentMemory>>;
635 updateMemory(
636 workspace: string,
637 handle: string,
638 viewer: User,
639 id: string,
640 changes: { body?: string; pinned?: boolean },
641 ): Promise<Result<AgentMemory>>;
642 forget(workspace: string, handle: string, viewer: User, id: string): Promise<Result<null>>;
643 routines(workspace: string, handle: string, viewer: User): Promise<Result<{ routines: AgentRoutine[]; suggestions: RoutineSuggestion[] }>>;
644 saveRoutine(workspace: string, handle: string, viewer: User, input: NewRoutine, id?: string | null): Promise<Result<AgentRoutine>>;
645 deleteRoutine(workspace: string, handle: string, viewer: User, id: string): Promise<Result<null>>;
646 /** Runs a routine now, as a session. */
647 runRoutine(workspace: string, handle: string, viewer: User, id: string): Promise<Result<AgentSession>>;
648 /** Where the month went: one agent's, or every agent's. */
649 spend(workspace: string, viewer: User, handle?: string | null): Promise<Result<AgentSpendBreakdown>>;
650 activity(workspace: string, handle: string, viewer: User): Promise<Result<AgentActivity[]>>;
651 versions(workspace: string, handle: string, viewer: User): Promise<Result<AgentVersion[]>>;
652 /**
653 * Internal, from chat: a person pressed an action on one of agents'
654 * cards. Agents checks they may, acts, and updates the card.
655 */
656 cardAction(input: AgentCardAction): Promise<Result<CardActionResult>>;
657 policy(workspace: string, viewer: User): Promise<Result<AgentPolicy>>;
658 setPolicy(workspace: string, viewer: User, policy: Partial<AgentPolicy>): Promise<Result<AgentPolicy>>;
659};
660
661async function rpc<T>(service: ServiceBinding, method: string, args: object): Promise<T> {
662 const response = await service.fetch(`https://service/rpc/${method}`, {
663 method: "POST",
664 headers: { "content-type": "application/json" },
665 body: JSON.stringify(args),
666 });
667 if (!response.ok) {
668 throw new Error(`${method} failed with status ${response.status}`);
669 }
670 return (await response.json()) as T;
671}
672
673export function workspaceAgentsClient(service: ServiceBinding): WorkspaceAgentsApi {
674 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
675 return {
676 list: (workspace, viewer) => call("list", { workspace, viewer }),
677 get: (workspace, handle, viewer) => call("get", { workspace, handle, viewer }),
678 byIds: (ids) => call("by_ids", { ids }),
679 create: (workspace, viewer, input) => call("create", { workspace, viewer, input }),
680 update: (workspace, handle, viewer, changes) => call("update", { workspace, handle, viewer, changes }),
681 archive: (workspace, handle, viewer) => call("archive", { workspace, handle, viewer }),
682 templates: () => call("templates", {}),
683 builtin: (workspace, workspaceId) => call("builtin", { workspace, workspace_id: workspaceId }),
684 deliver: (delivery) => call("deliver", delivery),
685 overview: (workspace, viewer) => call("overview", { workspace, viewer }),
686 sessions: (workspace, viewer, filter) => call("sessions", { workspace, viewer, ...(filter ?? {}) }),
687 session: (workspace, id, viewer) => call("session", { workspace, id, viewer }),
688 stopSession: (workspace, id, viewer) => call("stop_session", { workspace, id, viewer }),
689 approveSession: (workspace, id, viewer, capMicros) => call("approve_session", { workspace, id, viewer, cap_micros: capMicros }),
690 steerSession: (workspace, id, viewer, body) => call("steer_session", { workspace, id, viewer, body }),
691 memories: (workspace, handle, viewer) => call("memories", { workspace, handle, viewer }),
692 remember: (workspace, handle, viewer, input) => call("remember", { workspace, handle, viewer, input }),
693 updateMemory: (workspace, handle, viewer, id, changes) => call("update_memory", { workspace, handle, viewer, id, changes }),
694 forget: (workspace, handle, viewer, id) => call("forget", { workspace, handle, viewer, id }),
695 routines: (workspace, handle, viewer) => call("routines", { workspace, handle, viewer }),
696 saveRoutine: (workspace, handle, viewer, input, id) => call("save_routine", { workspace, handle, viewer, input, id: id ?? null }),
697 deleteRoutine: (workspace, handle, viewer, id) => call("delete_routine", { workspace, handle, viewer, id }),
698 runRoutine: (workspace, handle, viewer, id) => call("run_routine", { workspace, handle, viewer, id }),
699 spend: (workspace, viewer, handle) => call("spend", { workspace, viewer, handle: handle ?? null }),
700 activity: (workspace, handle, viewer) => call("activity", { workspace, handle, viewer }),
701 versions: (workspace, handle, viewer) => call("versions", { workspace, handle, viewer }),
702 cardAction: (input) => call("card_action", input),
703 policy: (workspace, viewer) => call("policy", { workspace, viewer }),
704 setPolicy: (workspace, viewer, policy) => call("set_policy", { workspace, viewer, policy }),
705 };
706}