Skip to content
453 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Chat and workspace agents: channels, DMs and named agents you talk to1/**
2 * Chat: channels, direct messages, threads and messages, kept by the chat
3 * service (`services/chat`). People and agents are members alike. Plan:
4 * docs/WORKSPACE.md.
5 *
6 * Wire shapes are snake_case end to end, so the site, the public API and
7 * the live socket all carry the same objects.
8 */
9import type { ServiceBinding } from "./clients";
10import type { User } from "./identity";
11import type { Result } from "./result";
12import type { AskerAccess } from "./workspace-agents";
13
14/** Who is speaking: a person (by user id) or a workspace agent (by agent id). */
15export type Principal = { kind: "user" | "agent"; id: string };
16
17export function principalKey(principal: Principal): string {
18 return `${principal.kind}:${principal.id}`;
19}
20
21export function parsePrincipalKey(key: string): Principal | null {
22 const at = key.indexOf(":");
23 if (at < 0) return null;
24 const kind = key.slice(0, at);
25 const id = key.slice(at + 1);
26 if ((kind !== "user" && kind !== "agent") || !id) return null;
27 return { kind, id };
28}
29
30/** How a member shows: resolved by the chat service when it answers. */
31export type MemberProfile = Principal & {
32 /** `username` for a person, `handle` for an agent. */
33 name: string;
34 display_name: string;
35 /** Uploaded avatar hash for a person, or null for the letter avatar. */
36 avatar: string | null;
37 /** An agent's one-line role ("Release manager for g1t"). */
38 role: string | null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)39 /**
40 * An agent's title ("QA Engineer"); null for a person. Chat always sets
41 * it; optional so profiles a page makes for itself need not.
42 */
43 title?: string | null;
44 /** What an agent's pixel creature is drawn from; null for a person. Always set by chat. */
45 avatar_seed?: string | null;
Chat and workspace agents: channels, DMs and named agents you talk to46};
47
48export type ChannelKind = "channel" | "dm";
49
50export type Channel = {
51 id: string;
52 workspace_id: string;
53 kind: ChannelKind;
54 /** Lowercase, no `#`. Null for a direct message. */
55 name: string | null;
56 topic: string | null;
57 private: boolean;
58 created_by: Principal;
59 created_at: string;
60 archived_at: string | null;
61 last_message_at: string | null;
62};
63
64export type ChannelMember = {
65 channel_id: string;
66 member: MemberProfile;
67 role: "owner" | "member";
68 starred: boolean;
69 muted: boolean;
70 last_read_id: string | null;
71 joined_at: string;
72};
73
74/** A card g1t or an agent posts: an event, a task, an approval. */
75export type MessageCard = {
76 /** What it is about, e.g. `pull`, `issue`, `task`, `deploy`, `approval`. */
77 kind: string;
78 title: string;
79 /** A short line under the title: "3/3 checks · +214 −87". */
80 detail: string | null;
81 /** A status shown on the right: "Needs approval", "Merged". */
82 state: string | null;
83 /** Where clicking the card goes, relative to the site. */
84 href: string | null;
85};
86
87export type ChatMessage = {
88 /** Time-sortable (ULID-like), so ordering by id is ordering by time. */
89 id: string;
90 channel_id: string;
91 author: MemberProfile;
92 kind: "text" | "card";
93 body: string;
94 card: MessageCard | null;
95 /** The message this replies under, or null for a top-level message. */
96 thread_root: string | null;
97 reply_count: number;
98 last_reply_at: string | null;
99 created_at: string;
100 edited_at: string | null;
101 deleted_at: string | null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)102 /**
103 * Its reactions, one per emoji in the order each was first used. Chat
104 * always sets it; optional so messages a page makes for itself need not.
105 */
106 reactions?: ChatReaction[];
Chat and workspace agents: channels, DMs and named agents you talk to107};
108
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)109/**
110 * One emoji's reactions on a message. `emoji` is a Unicode emoji or
111 * `:name:` for one of the workspace's own (`CustomEmoji`).
112 */
113export type ChatReaction = {
114 emoji: string;
115 /** Everyone who reacted with it, people and agents alike. */
116 count: number;
117 /**
118 * Whether the viewer did. In live `message.*` events, which everyone in
119 * the room gets, it is always false: keep your own from what you know.
120 */
121 me: boolean;
122 /** The first ten who reacted with it, for the hover list. */
123 by: MemberProfile[];
124};
125
126/** Who may add a workspace's emoji: every member (the default), or only its owners. */
127export type EmojiUpload = "members" | "admins";
128
129/**
130 * One of a workspace's own emoji, used as `:name:`. Its image is served
131 * from the usercontent origin at `/emoji/<file>` (never from the site).
132 */
133export type CustomEmoji = {
134 name: string;
135 /** For an alias, the emoji it is another name for; it shows that one's image. */
136 alias_of: string | null;
137 /** The SHA-256 of the image's bytes. */
138 file: string;
139 content_type: "image/png" | "image/gif" | "image/webp";
140 bytes: number;
141 created_by: MemberProfile;
142 created_at: string;
143};
144
145export type EmojiList = {
146 emoji: CustomEmoji[];
147 emoji_upload: EmojiUpload;
148 /** Whether the viewer may add emoji and aliases. */
149 can_upload: boolean;
150 /** Whether the viewer is an owner: may remove any emoji and change `emoji_upload`. */
151 can_manage: boolean;
152};
153
154/** An image for a new emoji, as base64. Its type is read from its bytes, never taken from here. */
155export type EmojiFile = { data: string };
156
157/** The largest custom emoji image, in bytes, and the widest or tallest, in pixels. */
158export const MAX_EMOJI_BYTES = 256 * 1024;
159export const MAX_EMOJI_SIDE = 512;
160
Chat and workspace agents: channels, DMs and named agents you talk to161/** One row of the Chat sidebar. */
162export type ChatSidebarEntry = {
163 channel: Channel;
164 /** "g1t-core", or the other members' names for a direct message. */
165 title: string;
166 /** For a direct message: who else is in it (up to four). */
167 others: MemberProfile[];
168 starred: boolean;
169 muted: boolean;
170 unread: number;
171 mentions: number;
172};
173
174export type ChatSidebar = {
175 entries: ChatSidebarEntry[];
176 /** Public channels in the workspace the viewer has not joined. */
177 browsable: number;
178};
179
180export type MessagePage = {
181 messages: ChatMessage[];
182 /** Pass as `before` to read further back; null at the beginning. */
183 older: string | null;
184 /**
185 * Set when the page was read with `after`: pass it as `after` again for
186 * the next messages, or null when this page reached the newest.
187 */
188 newer?: string | null;
189};
190
191export type NewChannel = { name: string; topic?: string | null; private?: boolean };
192
193export type PostMessage = { body: string; thread_root?: string | null };
194
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)195/**
196 * Who will read what is said in a conversation (docs/WORKSPACE.md, "What
197 * an agent can and can't know"): a direct message's or private channel's
198 * people, or, for a public channel, the whole workspace. An agent answers
199 * there only with what every one of them may see.
200 */
201export type ChatAudience = {
202 kind: "dm" | "private" | "public";
203 /** The people in it (agents left out). For a public channel, its current members, for reference only. */
204 member_user_ids: string[];
205 member_count: number;
206};
207
208/** A message an agent found by searching, with the conversation it is in. */
209export type AgentFoundMessage = {
210 channel_id: string;
211 /** The channel's name, or null for a direct message. */
212 channel: string | null;
213 message: ChatMessage;
214};
215
Chat and workspace agents: channels, DMs and named agents you talk to216/** The most agent-to-agent hops one person's request may start (docs/WORKSPACE.md, "Hop limit"). */
217export const CHAT_MAX_HOPS = 6;
218
219/**
220 * What an agent posts. When it answers a delivery, it passes that
221 * delivery's `hops`, `asked_by` and `asker` back, so another agent it @mentions is
222 * handed the message one hop further along the same person's request, and
223 * the chain stops at `CHAT_MAX_HOPS`. Left out: a new chain (hops 0) asked
224 * by the person who created the agent.
225 */
226export type AgentPostMessage = PostMessage & {
227 card?: MessageCard | null;
228 hops?: number;
229 asked_by?: string | null;
230 /** The delivery's `asker`, handed on to agents this message wakes. Absent: none (they treat the asker as unable to change code). */
231 asker?: AskerAccess | null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)232 /**
233 * The delivery's `chain`: the agents that handled this request before
234 * the one posting, oldest first. Chat adds the poster, and never hands
235 * the message to the agent that sent the work to it (no ping-pong).
236 */
237 chain?: string[];
Chat and workspace agents: channels, DMs and named agents you talk to238};
239
240/**
241 * What the live socket sends. The site opens
242 * `wss://<site>/<workspace>/chat/live?channel=<id>`; the site checks the
243 * session and forwards the upgrade to the chat service with the viewer.
244 */
245export type ChatLiveEvent =
246 | { type: "message.created"; message: ChatMessage }
247 | { type: "message.updated"; message: ChatMessage }
248 | { type: "message.deleted"; channel_id: string; id: string }
249 | { type: "typing"; channel_id: string; member: MemberProfile; until: string }
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)250 | { type: "read"; channel_id: string; principal: Principal; last_read_id: string }
251 | { type: "reaction.added" | "reaction.removed"; channel_id: string; message_id: string; emoji: string; member: MemberProfile };
Chat and workspace agents: channels, DMs and named agents you talk to252
253/**
254 * Header the site sets on a forwarded live socket: the viewer, as JSON.
255 * The site forwards the upgrade to the chat service's
256 * `GET /live?workspace=<slug>&channel=<id>` (`workspace` may be left out,
257 * at the cost of looking up each of the viewer's workspaces).
258 */
259export const CHAT_VIEWER_HEADER = "x-g1t-chat-viewer";
260
261export type ChatApi = {
262 sidebar(workspace: string, viewer: User): Promise<Result<ChatSidebar>>;
263 channel(
264 workspace: string,
265 channelId: string,
266 viewer: User,
267 ): Promise<Result<{ channel: Channel; members: ChannelMember[] }>>;
268 /** The same, found by its name in the workspace (`#general` or `general`), as the site's URLs name channels. */
269 channelByName(
270 workspace: string,
271 name: string,
272 viewer: User,
273 ): Promise<Result<{ channel: Channel; members: ChannelMember[] }>>;
274 /** Public channels, for Browse channels. */
275 browse(workspace: string, viewer: User): Promise<Result<Channel[]>>;
276 createChannel(workspace: string, viewer: User, input: NewChannel): Promise<Result<Channel>>;
277 /**
278 * The direct message between the viewer and these members, created on
279 * first use. The same set of members always gets the same channel.
280 */
281 openDm(workspace: string, viewer: User, members: Principal[]): Promise<Result<Channel>>;
282 join(workspace: string, channelId: string, viewer: User): Promise<Result<null>>;
283 leave(workspace: string, channelId: string, viewer: User): Promise<Result<null>>;
284 /** Adds a person or an agent. An invite grants read, never write. */
285 invite(workspace: string, channelId: string, viewer: User, member: Principal): Promise<Result<null>>;
286 /**
287 * Newest first. Without `thread_root`, the channel's top-level messages;
288 * with it, that thread's replies, plus the message they reply to as the
289 * oldest once the page reaches the start of the thread (`older` null).
290 * With `after` (catching up after a reconnect): the messages after that
291 * id instead, oldest first, deleted ones included so the client can
292 * drop them; `newer` says whether there are more.
293 * Limit 50 by default, 200 at most.
294 */
295 messages(
296 workspace: string,
297 channelId: string,
298 viewer: User,
299 page?: { before?: string | null; after?: string | null; limit?: number; thread_root?: string | null },
300 ): Promise<Result<MessagePage>>;
301 post(workspace: string, channelId: string, viewer: User, message: PostMessage): Promise<Result<ChatMessage>>;
302 edit(workspace: string, channelId: string, viewer: User, id: string, body: string): Promise<Result<ChatMessage>>;
303 remove(workspace: string, channelId: string, viewer: User, id: string): Promise<Result<null>>;
304 markRead(workspace: string, channelId: string, viewer: User, id: string): Promise<Result<null>>;
305 setPreferences(
306 workspace: string,
307 channelId: string,
308 viewer: User,
309 prefs: { starred?: boolean; muted?: boolean },
310 ): Promise<Result<null>>;
311 /**
312 * Posts as an agent. Only the agents service calls this, for replies and
313 * cards; the agent must be a member of the channel.
314 */
315 postAsAgent(
316 workspace: string,
317 channelId: string,
318 agentId: string,
319 message: AgentPostMessage,
320 ): Promise<Result<ChatMessage>>;
321 /** Shows "is typing" for an agent while it works on a reply. */
322 agentTyping(workspace: string, channelId: string, agentId: string): Promise<Result<null>>;
323 /**
324 * What an agent reads before it replies, oldest first: with
325 * `thread_root`, that thread (its root, then its replies); without, the
326 * channel's or direct message's latest top-level messages. Only the
327 * agents service calls this; the agent must be a member of the channel,
328 * so it reads only what was said where it was invited. `limit` defaults
329 * to 30, at most 100.
330 */
331 historyForAgent(
332 workspace: string,
333 channelId: string,
334 agentId: string,
335 page?: { thread_root?: string | null; limit?: number },
336 ): Promise<Result<ChatMessage[]>>;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)337 /** Internal: who reads a conversation. */
338 audience(workspace: string, channelId: string): Promise<Result<ChatAudience>>;
339 /**
340 * Internal, for an agent replying in `channelId`: messages matching
341 * `query` (newest first, at most 20) from conversations every person in
342 * that conversation's audience is in, and from public channels. Never
343 * another direct message unless it has exactly the same people. The
344 * audience is worked out here from `channelId`, never taken from the
345 * caller.
346 */
347 searchForAgent(workspace: string, channelId: string, query: string, limit?: number): Promise<Result<AgentFoundMessage[]>>;
348 /**
349 * Internal, for an agent replying in `channelId`: a thread (`id`, its
350 * root or any reply) in `targetChannelId`, oldest first, under the same
351 * rule. A conversation the audience may not read is not found, exactly
352 * as one that does not exist.
353 */
354 threadForAgent(workspace: string, channelId: string, targetChannelId: string, id: string): Promise<Result<AgentFoundMessage[]>>;
355 /**
356 * Reacts to a message with `emoji` (one Unicode emoji, or `:name:` for
357 * one of the workspace's own). Once per member per emoji; at most 50
358 * different emoji on a message. Answers the message's reactions now.
359 */
360 react(workspace: string, channelId: string, viewer: User, messageId: string, emoji: string): Promise<Result<ChatReaction[]>>;
361 unreact(workspace: string, channelId: string, viewer: User, messageId: string, emoji: string): Promise<Result<ChatReaction[]>>;
362 /** Internal, for the agents service: an agent reacts (or, with `remove`, takes it back). It must be in the channel. */
363 reactAsAgent(
364 workspace: string,
365 channelId: string,
366 agentId: string,
367 messageId: string,
368 emoji: string,
369 remove?: boolean,
370 ): Promise<Result<ChatReaction[]>>;
371 /** The workspace's own emoji, by name, and who may add them. */
372 listEmoji(workspace: string, viewer: User): Promise<Result<EmojiList>>;
373 /** Adds an emoji: a PNG, GIF or WebP of at most 256 KB and 512×512. */
374 addEmoji(workspace: string, viewer: User, name: string, file: EmojiFile): Promise<Result<CustomEmoji>>;
375 /** Gives an existing emoji (`target`) another name. */
376 aliasEmoji(workspace: string, viewer: User, name: string, target: string): Promise<Result<CustomEmoji>>;
377 /** Removes an emoji, and its aliases with it. Its creator or an owner may. */
378 removeEmoji(workspace: string, viewer: User, name: string): Promise<Result<null>>;
379 /** Owners only: who may add emoji. */
380 setEmojiUpload(workspace: string, viewer: User, value: EmojiUpload): Promise<Result<EmojiUpload>>;
Chat and workspace agents: channels, DMs and named agents you talk to381};
382
383async function rpc<T>(service: ServiceBinding, method: string, args: object): Promise<T> {
384 const response = await service.fetch(`https://service/rpc/${method}`, {
385 method: "POST",
386 headers: { "content-type": "application/json" },
387 body: JSON.stringify(args),
388 });
389 if (!response.ok) {
390 throw new Error(`${method} failed with status ${response.status}`);
391 }
392 return (await response.json()) as T;
393}
394
395export function chatClient(service: ServiceBinding): ChatApi {
396 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
397 return {
398 sidebar: (workspace, viewer) => call("sidebar", { workspace, viewer }),
399 channel: (workspace, channelId, viewer) => call("channel", { workspace, channel_id: channelId, viewer }),
400 channelByName: (workspace, name, viewer) => call("channel_by_name", { workspace, name, viewer }),
401 browse: (workspace, viewer) => call("browse", { workspace, viewer }),
402 createChannel: (workspace, viewer, input) => call("create_channel", { workspace, viewer, input }),
403 openDm: (workspace, viewer, members) => call("open_dm", { workspace, viewer, members }),
404 join: (workspace, channelId, viewer) => call("join", { workspace, channel_id: channelId, viewer }),
405 leave: (workspace, channelId, viewer) => call("leave", { workspace, channel_id: channelId, viewer }),
406 invite: (workspace, channelId, viewer, member) =>
407 call("invite", { workspace, channel_id: channelId, viewer, member }),
408 messages: (workspace, channelId, viewer, page) =>
409 call("messages", {
410 workspace,
411 channel_id: channelId,
412 viewer,
413 before: page?.before ?? null,
414 after: page?.after ?? null,
415 limit: page?.limit ?? null,
416 thread_root: page?.thread_root ?? null,
417 }),
418 post: (workspace, channelId, viewer, message) => call("post", { workspace, channel_id: channelId, viewer, message }),
419 edit: (workspace, channelId, viewer, id, body) => call("edit", { workspace, channel_id: channelId, viewer, id, body }),
420 remove: (workspace, channelId, viewer, id) => call("remove", { workspace, channel_id: channelId, viewer, id }),
421 markRead: (workspace, channelId, viewer, id) => call("mark_read", { workspace, channel_id: channelId, viewer, id }),
422 setPreferences: (workspace, channelId, viewer, prefs) =>
423 call("set_preferences", { workspace, channel_id: channelId, viewer, prefs }),
424 postAsAgent: (workspace, channelId, agentId, message) =>
425 call("post_as_agent", { workspace, channel_id: channelId, agent_id: agentId, message }),
426 agentTyping: (workspace, channelId, agentId) =>
427 call("agent_typing", { workspace, channel_id: channelId, agent_id: agentId }),
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)428 audience: (workspace, channelId) => call("audience", { workspace, channel_id: channelId }),
429 searchForAgent: (workspace, channelId, query, limit) =>
430 call("search_for_agent", { workspace, channel_id: channelId, query, limit: limit ?? null }),
431 threadForAgent: (workspace, channelId, targetChannelId, id) =>
432 call("thread_for_agent", { workspace, channel_id: channelId, target_channel_id: targetChannelId, id }),
433 react: (workspace, channelId, viewer, messageId, emoji) =>
434 call("react", { workspace, channel_id: channelId, viewer, message_id: messageId, emoji }),
435 unreact: (workspace, channelId, viewer, messageId, emoji) =>
436 call("unreact", { workspace, channel_id: channelId, viewer, message_id: messageId, emoji }),
437 reactAsAgent: (workspace, channelId, agentId, messageId, emoji, remove) =>
438 call("react_as_agent", { workspace, channel_id: channelId, agent_id: agentId, message_id: messageId, emoji, remove: remove ?? false }),
439 listEmoji: (workspace, viewer) => call("list_emoji", { workspace, viewer }),
440 addEmoji: (workspace, viewer, name, file) => call("add_emoji", { workspace, viewer, name, file }),
441 aliasEmoji: (workspace, viewer, name, target) => call("alias_emoji", { workspace, viewer, name, target }),
442 removeEmoji: (workspace, viewer, name) => call("remove_emoji", { workspace, viewer, name }),
443 setEmojiUpload: (workspace, viewer, value) => call("set_emoji_upload", { workspace, viewer, value }),
Chat and workspace agents: channels, DMs and named agents you talk to444 historyForAgent: (workspace, channelId, agentId, page) =>
445 call("history_for_agent", {
446 workspace,
447 channel_id: channelId,
448 agent_id: agentId,
449 thread_root: page?.thread_root ?? null,
450 limit: page?.limit ?? null,
451 }),
452 };
453}

This file's history is long; its oldest lines are credited to the oldest commit read.