Skip to content
514 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 * One reply: an agent answering a message in chat, in this Worker, with no
3 * sandbox (docs/WORKSPACE.md, "Two kinds of turn").
4 *
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked5 * A reply is quick and bounded: it reads the latest messages of the
6 * conversation (never all of it), what the agent remembers for this place,
7 * and its recent sessions here. When a request needs real work, the agent
8 * spins off a session (sessions.ts) and says so; the session reports back.
9 * A message in a session's card thread is not a reply at all: it steers
10 * that session.
Chat and workspace agents: channels, DMs and named agents you talk to11 *
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked12 * A reply is metered exactly as a session step is (`metered`, meter.ts):
13 * the agent's and the workspace's agent budgets, model routing, the
14 * compute gate, a billing run, the model proxy, and the spend recorded.
Chat and workspace agents: channels, DMs and named agents you talk to15 *
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked16 * Whatever happens, the reply's row says so: replied, steered, blocked
17 * (with one short notice in the conversation, not repeated), skipped or
18 * failed (with one short apology).
Chat and workspace agents: channels, DMs and named agents you talk to19 */
Merge branch 'worktree-agent-a1398e81ad1a64c5f'20import { type AgentDelivery, type ServiceBinding, identityClient, newId } from "@g1t/contracts";
Chat and workspace agents: channels, DMs and named agents you talk to21
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)22import { CHAT_MAX_HOPS } from "../../../packages/contracts/src/chat.ts";
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked23import type { Tokens } from "./budget.ts";
Merge branch 'worktree-agent-a1398e81ad1a64c5f'24import { handOffPort } from "./handoff.ts";
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)25import { HISTORY_LIMIT, fixedHello, helloAsk, systemPrompt, turns } from "./prompt.ts";
Merge branch 'worktree-agent-a1398e81ad1a64c5f'26import { type Specialist, orchestratorInstructions, orchestratorTier, rosterLines } from "./orchestrator.ts";
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked27import { type MeterEnv, metered } from "./meter.ts";
28import { type RecallPlace, memorySection, recall } from "./memory.ts";
Agents recall what Docs say before they answer or work, and each has required reading29import { recallQuery, recallSection } from "./recall.ts";
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)30import { REPLY_TIER, allowedProviders, replyModel } from "./routing.ts";
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked31import { type SessionEnv, type SessionRow, actionPorts, sessionRow, startSession, steer } from "./sessions.ts";
32import { type Row, definitionOf, periods, selectAgents, toAgent } from "./store.ts";
Chat and workspace agents: channels, DMs and named agents you talk to33import { type SurfaceMessage, surfaceFor } from "./surface.ts";
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)34import { Audience } from "./audience.ts";
35import { audiencePorts, toolPorts } from "./ports.ts";
36import { type ToolCall, type ToolPorts, ToolBox } from "./tools.ts";
37import type { Surface } from "./surface.ts";
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked38import type { Desk } from "./desk.ts";
39import { type ModelMessage, type Send, NO_TOKENS, addTokens, runTurn } from "./turn.ts";
40import type { AgentRouting as Policy } from "../../runner/src/model-env.ts";
41import { dollars } from "./money.ts";
42
43export { billingRepo } from "./meter.ts";
Chat and workspace agents: channels, DMs and named agents you talk to44
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked45export type ReplyEnv = MeterEnv & {
Chat and workspace agents: channels, DMs and named agents you talk to46 DB: D1Database;
47 CHAT: ServiceBinding;
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)48 /** People and their access, for the audience; members and teams for the roster. */
49 IDENTITY: ServiceBinding;
50 /** Code, for read tools. */
51 REPOS: ServiceBinding;
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked52 /** Issues and pull requests, for read tools and filing issues. */
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)53 WORK: ServiceBinding;
54 /** Code search, for read tools. */
55 SEARCH: ServiceBinding;
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked56 /** Notifications: a session waiting for more budget. */
57 NOTIFY?: ServiceBinding;
58 /** Every agent's desk: sessions are worked on their agent's. */
59 DESKS: DurableObjectNamespace<Desk>;
Chat and workspace agents: channels, DMs and named agents you talk to60};
61
62/** A notice that the agent cannot reply is posted once per conversation in this long. */
63const NOTICE_QUIET_MS = 6 * 60 * 60 * 1000;
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked64/** Sessions one reply may start. */
65const MAX_SPIN_OFFS = 2;
Chat and workspace agents: channels, DMs and named agents you talk to66
67const APOLOGY = "Sorry, something went wrong on my side and I couldn't answer that. Try again in a moment.";
68
69/** Who asked, from the message that woke the agent (or their latest one). */
70function askerIn(history: SurfaceMessage[], delivery: AgentDelivery): SurfaceMessage["author"] | null {
71 const woken = history.find((m) => m.id === delivery.message_id);
72 if (woken) return woken.author;
73 return [...history].reverse().find((m) => m.author.kind === "user" && m.author.id === delivery.asked_by)?.author ?? null;
74}
75
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)76/**
77 * An agent's colleagues: every agent of the workspace but itself that is
78 * not archived (docs/WORKSPACE.md, "Agents know each other").
79 */
80async function team(db: D1Database, workspaceId: string, selfId: string, now: Date): Promise<Specialist[]> {
81 const rows = await db
82 .prepare(`${selectAgents("a.workspace_id = ?3 AND a.archived_at IS NULL AND a.id <> ?4")} ORDER BY a.builtin DESC, a.handle LIMIT 50`)
83 .bind(...periods(now), workspaceId, selfId)
84 .all<Row>();
85 return rows.results.map((row) => {
86 const agent = toAgent(row, now);
87 return {
88 handle: agent.handle,
89 display_name: agent.display_name,
90 role: agent.role,
91 title: agent.title,
92 team: agent.team,
93 department: agent.department,
94 responsibilities: agent.responsibilities,
95 status: agent.status,
96 spent_month_micros: agent.spent_month_micros,
97 monthly_micros: agent.budget.monthly_micros,
98 };
99 });
100}
101
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked102/** The agent's latest sessions in this conversation, one line each. */
103async function sessionsHere(db: D1Database, agentId: string, channelId: string): Promise<string | null> {
104 const rows = await db
105 .prepare(
106 "SELECT id, title, status, summary, created_at FROM agent_sessions WHERE agent_id = ? AND channel_id = ? AND parent_id IS NULL ORDER BY created_at DESC LIMIT 5",
107 )
108 .bind(agentId, channelId)
109 .all<{ id: string; title: string; status: string; summary: string | null; created_at: string }>();
110 if (!rows.results.length) return null;
111 return rows.results
112 .map((s) => `- "${s.title}" (${s.status}, ${s.created_at.slice(0, 10)})${s.summary ? `: ${s.summary.replace(/\s+/g, " ").slice(0, 300)}` : ""}`)
113 .join("\n");
114}
115
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)116/**
117 * Consulting a colleague (docs/WORKSPACE.md, "Agents know each other"):
118 * the colleague answers in a nested turn that posts nothing, with the same
119 * audience (so it can read no more than the conversation may), the same
120 * asker, one hop further, its own routing limits, on the same model
121 * session, billed to this reply. A compact card in the thread says who
122 * asked whom. Consults don't nest: the colleague can't consult in turn.
123 */
124function consulting(input: {
125 db: D1Database;
126 row: Row;
127 delivery: DeskWork;
128 send: Send;
129 policy: Policy;
130 ownModel: boolean;
131 sessionModel: string | null;
132 own: string | null;
133 ports: (consult: ToolPorts["consult"]) => ToolPorts;
134 hops: number;
135 now: Date;
136 surface: Surface;
137 asker: { name: string; display_name: string | null; access: NonNullable<AgentDelivery["asker"]> | null };
138 spent: { tokens: Tokens; cost: number };
139}): { ask: ToolPorts["consult"]; attach(box: ToolBox): void } {
140 let parent: ToolBox | null = null;
141 const noNesting: ToolPorts["consult"] = async () => ({ ok: false, message: "Consults don't nest: answer with what you have." });
142 const ask: ToolPorts["consult"] = async (handle, question) => {
143 const { row, delivery } = input;
144 const colleague = await input.db
145 .prepare("SELECT * FROM agents WHERE workspace_id = ? AND handle = ? AND archived_at IS NULL")
146 .bind(row.workspace_id, handle)
147 .first<Row>();
148 if (!colleague || colleague.id === row.id) return { ok: false, message: `There is no other agent called @${handle} here.` };
149 // No ping-pong: never back to the agent that sent this work.
150 if ((delivery.chain ?? []).at(-1) === colleague.id) return { ok: false, message: `@${handle} sent you this work; answer with what you have.` };
151 if (input.hops + 1 > CHAT_MAX_HOPS) return { ok: false, message: "This request has been passed along too many times; answer with what you have." };
152 const definition = definitionOf(colleague);
153 const allowed = allowedProviders(definition.routing, input.own);
154 if (input.ownModel ? !allowed.own : !allowed.hosted) return { ok: false, message: `@${handle} can't use the model this conversation runs on.` };
155 const model = replyModel(
156 input.policy,
157 { ...definition.routing, pinned: input.ownModel ? definition.routing.pinned : null },
158 { named: input.ownModel ? input.sessionModel : null },
159 );
160 const tools = parent
161 ? parent.forColleague(input.ports(noNesting), { agentId: colleague.id, notConsult: [colleague.handle, row.handle], hops: input.hops + 1, maxHops: input.hops + 1 })
162 : null;
163 const system = systemPrompt({
164 agent: { ...definition, id: colleague.id },
165 workspace: delivery.workspace,
166 channel: { kind: delivery.channel_kind, name: delivery.channel_name },
167 asker: input.asker,
168 today: input.now,
169 tools: tools ? { code: tools.definitions().some((tool) => tool.name === "read_file") } : null,
170 consultedBy: row.handle,
171 });
172 const result = await runTurn(input.send, {
173 model: model.model,
174 system,
175 messages: [{ role: "user", content: `@${row.handle} (agent) asks you: ${question}` }],
176 tools,
177 price: input.ownModel ? null : model.price,
178 });
179 input.spent.tokens = addTokens(input.spent.tokens, result.tokens);
180 input.spent.cost += input.ownModel ? 0 : result.cost;
181 const answer = result.text || "(no answer)";
182 const exchange = `Q: ${question}\nA: ${answer}`;
183 // The exchange, collapsed, in the thread. No @ in its text: it wakes nobody.
184 await input.surface
185 .post(`${row.display_name} asked ${colleague.display_name}`, {
186 kind: "consult",
187 title: `${row.display_name} asked ${colleague.display_name}`,
188 detail: exchange.length > 1000 ? `${exchange.slice(0, 1000)}…` : exchange,
189 state: null,
190 href: null,
191 })
192 .catch((error: unknown) => console.error("agents: a consult card was not posted", String(error)));
193 return { ok: true, colleague: colleague.handle, answer };
194 };
195 return {
196 ask,
197 attach(box) {
198 parent = box;
199 },
200 };
201}
202
Chat and workspace agents: channels, DMs and named agents you talk to203type Outcome = {
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked204 status: "replied" | "steered" | "blocked" | "skipped" | "failed";
Chat and workspace agents: channels, DMs and named agents you talk to205 error?: string | null;
206 reply_id?: string | null;
207 model?: string | null;
208 tier?: string | null;
209 tokens?: Tokens;
210 cost?: number;
211 charged?: number;
212};
213
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)214/**
215 * What a desk is handed: a message to answer, or (`hello`) the agent's
216 * first message to the person who made it, in the DM that just opened.
217 */
218export type DeskWork = AgentDelivery & { hello?: boolean };
219
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked220/** How a limit's refusal reads in chat, in the agent's voice. */
221function noticeFor(reason: string, message: string): string {
222 if (reason.startsWith("budget_") || reason === "workspace_agent_budget" || message.startsWith("My settings") || message.startsWith("I ")) return message;
223 if (reason === "no_model") return `I can't reply yet: ${message}`;
224 return `I can't reply right now: ${message}`;
225}
226
227/** The session a message in this thread is for: a reply under one of this agent's session cards. */
228async function steeredSession(db: D1Database, agentId: string, threadRoot: string | null): Promise<SessionRow | null> {
229 if (!threadRoot) return null;
230 const found = await db.prepare("SELECT id FROM agent_sessions WHERE agent_id = ? AND card_message_id = ?").bind(agentId, threadRoot).first<{ id: string }>();
231 return found ? sessionRow(db, found.id) : null;
232}
233
234/**
235 * Answers `delivery` as its agent. Never throws: every way it ends is
236 * recorded on the reply's row. A message handed over twice is answered
237 * once.
238 */
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)239export async function reply(env: ReplyEnv, delivery: DeskWork, now = new Date()): Promise<void> {
Chat and workspace agents: channels, DMs and named agents you talk to240 const db = env.DB;
241 const row = await db.prepare("SELECT * FROM agents WHERE id = ?").bind(delivery.agent_id).first<Row>();
242 if (!row || row.archived_at || row.workspace_id !== delivery.workspace_id) return;
243 const id = newId("arp", now.getTime());
244 const claimed = await db
245 .prepare(
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked246 `INSERT INTO agent_replies (id, agent_id, workspace_id, channel_id, message_id, asked_by, asked_by_username, channel_name, agent_version, status, created_at)
247 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'working', ?)
Chat and workspace agents: channels, DMs and named agents you talk to248 ON CONFLICT (agent_id, message_id) DO NOTHING RETURNING id`,
249 )
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked250 .bind(id, row.id, row.workspace_id, delivery.channel_id, delivery.message_id, delivery.asked_by, delivery.asker?.username ?? null, delivery.channel_name, row.version, now.toISOString())
Chat and workspace agents: channels, DMs and named agents you talk to251 .first<{ id: string }>();
252 if (!claimed) return;
253
254 const surface = surfaceFor(env.CHAT, delivery);
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)255 // 👀 as soon as the desk has it, while everything else goes on.
256 const acknowledging = surface.acknowledge();
Chat and workspace agents: channels, DMs and named agents you talk to257 const slug = delivery.workspace.toLowerCase();
258
259 // What the answer used, once there is one: counted however the reply ends.
260 let usage: Partial<Outcome> = {};
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked261 // What the tools did, for the audit table, and who the audience was.
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)262 let toolCalls: ToolCall[] = [];
263 let audienceHash: string | null = null;
Chat and workspace agents: channels, DMs and named agents you talk to264
265 const finish = async (outcome: Outcome) => {
266 const statements = [
267 db
268 .prepare(
269 `UPDATE agent_replies SET status = ?, error = ?, reply_id = ?, model = ?, tier = ?, input_tokens = ?, output_tokens = ?,
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked270 cost_micros = ?, charged_micros = ?, tool_count = ?, finished_at = ? WHERE id = ?`,
Chat and workspace agents: channels, DMs and named agents you talk to271 )
272 .bind(
273 outcome.status,
274 outcome.error?.slice(0, 1000) ?? null,
275 outcome.reply_id ?? null,
276 outcome.model ?? null,
277 outcome.tier ?? null,
278 (outcome.tokens?.input ?? 0) + (outcome.tokens?.cacheRead ?? 0) + (outcome.tokens?.cacheWrite ?? 0),
279 outcome.tokens?.output ?? 0,
280 outcome.cost ?? 0,
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked281 outcome.charged ?? 0,
282 toolCalls.length,
Chat and workspace agents: channels, DMs and named agents you talk to283 new Date().toISOString(),
284 id,
285 ),
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)286 // Every tool call: what was asked, for whom, and whether it was read or withheld.
287 ...toolCalls.map((call, n) =>
288 db
289 .prepare(
290 `INSERT INTO agent_tool_calls (id, reply_id, agent_id, workspace_id, asked_by, tool, args, audience_hash, outcome, bytes, created_at)
291 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
292 )
293 .bind(`${id}_${n}`, id, row.id, row.workspace_id, delivery.asked_by, call.tool, call.args, audienceHash ?? "", call.outcome, call.bytes, now.toISOString()),
294 ),
Chat and workspace agents: channels, DMs and named agents you talk to295 ];
296 await db.batch(statements);
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)297 // ✅ when it answered; 👀 taken back after a notice, an apology or nothing.
298 await acknowledging;
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked299 await surface.settle(outcome.status === "replied" || outcome.status === "steered" ? "done" : "withdrawn");
Chat and workspace agents: channels, DMs and named agents you talk to300 };
301
302 /** Says once, in this conversation, why the agent cannot answer; a repeat within hours is kept back. */
303 const notice = async (message: string, reason: 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)304 // An agent's first words are never an excuse: without a model, a fixed hello.
305 if (delivery.hello) {
306 const posted = await surface.post(fixedHello(row, delivery.asker?.username ?? null)).catch(() => null);
307 return await finish({ status: "blocked", error: reason, reply_id: posted });
308 }
Chat and workspace agents: channels, DMs and named agents you talk to309 const since = new Date(now.getTime() - NOTICE_QUIET_MS).toISOString();
310 const recent = await db
311 .prepare(
312 `SELECT 1 FROM agent_replies WHERE agent_id = ? AND channel_id = ? AND status = 'blocked' AND error = ?
313 AND reply_id IS NOT NULL AND created_at > ? AND id <> ? LIMIT 1`,
314 )
315 .bind(row.id, delivery.channel_id, reason, since, id)
316 .first();
317 const posted = recent ? null : await surface.post(message).catch(() => null);
318 await finish({ status: "blocked", error: reason, reply_id: posted });
319 };
320
321 try {
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked322 // A reply under one of its session cards steers that session; nothing is answered here.
323 const steered = delivery.hello ? null : await steeredSession(db, row.id, delivery.thread_root);
324 if (steered) {
325 const history = await surface.history(HISTORY_LIMIT).catch(() => [] as SurfaceMessage[]);
326 const message = history.find((m) => m.id === delivery.message_id);
327 if (message?.body.trim()) {
328 await steer(env as unknown as SessionEnv, steered, message.author.name, message.body);
329 return await finish({ status: "steered" });
330 }
Chat and workspace agents: channels, DMs and named agents you talk to331 }
332
333 // Read the conversation while showing that the agent is on it.
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)334 // A hello has no conversation yet: it is asked to introduce itself.
Merge branch 'worktree-agent-a1398e81ad1a64c5f'335 // And who is here: said every turn, so the agent knows who reads it and who doesn't.
336 const [, history, conversationHere] = await Promise.all([
337 surface.typing(),
338 delivery.hello ? Promise.resolve([]) : surface.history(HISTORY_LIMIT),
339 delivery.hello ? Promise.resolve(null) : surface.conversation(),
340 ]);
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)341 const conversation = delivery.hello ? [{ role: "user" as const, content: helloAsk(delivery.asker?.username ?? null) }] : turns(history, row.id);
Chat and workspace agents: channels, DMs and named agents you talk to342 if (!conversation.length) return await finish({ status: "skipped", error: "nothing to answer" });
343 const author = askerIn(history, delivery);
344 const askerName = delivery.asker?.username ?? author?.name ?? 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)345 // Every agent knows its colleagues; @g1t also steps up a tier to decide
346 // who gets the work in a long thread.
347 const specialists = await team(db, row.workspace_id, row.id, now);
348 const start = row.builtin ? orchestratorTier(history.length, specialists.filter((a) => a.handle !== "g1t").length) : REPLY_TIER;
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked349 const definition = definitionOf(row);
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)350 const hops = Math.max(0, Math.floor(delivery.hops || 0));
351 const chain = delivery.chain ?? [];
352 const sender = chain.length ? await db.prepare("SELECT handle FROM agents WHERE id = ?").bind(chain[chain.length - 1]).first<{ handle: string }>() : null;
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked353 const asker = { name: askerName ?? "someone", display_name: author?.display_name ?? null, access: delivery.asker ?? null };
354 let posted: string | null = null;
355 let spinOffs = 0;
356
357 const done = await metered(env, { row, payer: row, slug, task: "reply", start, askerName }, async (model) => {
358 // What colleagues consulted along the way used: billed to this reply.
359 const consulted = { tokens: NO_TOKENS, cost: 0 };
360 let toolbox: ToolBox | null = null;
361 let place: RecallPlace = { channel_id: delivery.channel_id, kind: delivery.channel_kind === "dm" ? "dm" : "private", people: [delivery.asked_by] };
362 if (!delivery.hello) {
363 try {
364 const audience = await Audience.build(slug, delivery.asked_by, audiencePorts(env, slug, delivery.channel_id));
365 place = { channel_id: delivery.channel_id, kind: audience.kind, people: audience.shared ? [delivery.asked_by] : audience.members.map((m) => m.id) };
Docs: a workspace knowledge base people and agents write together366 const ports = (consult: ToolPorts["consult"]) => toolPorts(env, slug, row.workspace_id, delivery.channel_id, consult, row.id);
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked367 audienceHash = audience.hash;
368 const consult = consulting({
369 db,
370 row,
371 delivery,
372 send: model.send,
373 policy: model.policy,
374 ownModel: model.ownModel,
375 sessionModel: model.sessionModel,
376 own: model.own,
377 ports,
378 hops,
379 now,
380 surface,
381 asker,
382 spent: consulted,
383 });
384 const where = delivery.channel_kind === "dm" ? "a direct message" : `#${delivery.channel_name ?? "a channel"}`;
385 const actions = actionPorts(env as unknown as SessionEnv, {
386 agent: row,
387 place,
388 source: { kind: "message", ref: delivery.message_id, label: askerName ? `@${askerName} in ${where}` : where, channel_id: delivery.channel_id },
389 asker: { id: delivery.asked_by, username: askerName },
390 workspace: slug,
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar391 postCard: (card) => surface.post("", card).catch(() => null),
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked392 // Real work becomes a session, with its card in this conversation.
393 spinOff: async (title, goal) => {
394 if (spinOffs >= MAX_SPIN_OFFS) return { ok: false, message: "You've started enough sessions from this message." };
395 spinOffs++;
396 const session = await startSession(env as unknown as SessionEnv, {
397 agent: row,
398 kind: "chat",
399 title,
400 goal: `${askerName ? `@${askerName}` : "Someone"} asked in ${where}:\n\n${goal}`,
401 workspace: slug,
402 channel_id: delivery.channel_id,
403 channel_kind: delivery.channel_kind,
404 channel_name: delivery.channel_name,
405 thread_root: delivery.thread_root,
406 message_id: delivery.message_id,
407 asked_by: delivery.asked_by,
408 asked_by_username: askerName,
409 asker: delivery.asker ?? null,
410 chain: [...chain],
411 hops,
412 });
413 const cap = session.cap_micros ? ` with a cap of ${dollars(session.cap_micros)}` : "";
414 return { ok: true, message: `Started the session "${session.title}"${cap}. Its card is in the conversation and it reports back there. Tell them in a sentence; don't do the work here.` };
415 },
416 });
Merge branch 'worktree-agent-a1398e81ad1a64c5f'417 // Work handed to a colleague: the only way an agent gets another working (handoff.ts).
418 const viewer = audience.asker;
419 actions.handOff = handOffPort({
420 self: { id: row.id, handle: row.handle },
421 chain,
422 asker: delivery.asker ?? null,
423 agent: async (handle) => {
424 const found = await db
425 .prepare(selectAgents("a.workspace_id = ?3 AND a.handle = ?4 AND a.archived_at IS NULL"))
426 .bind(...periods(now), row.workspace_id, handle)
427 .first<Row>();
428 if (!found) return null;
429 const agent = toAgent(found, now);
430 return { id: agent.id, handle: agent.handle, display_name: agent.display_name, builtin: !!found.builtin, status: agent.status };
431 },
432 person: async (handle) => {
433 if (!viewer) return false;
434 const members = await identityClient(env.IDENTITY).listMembers(slug, viewer);
435 return members.ok && members.value.some((m) => m.username.toLowerCase() === handle);
436 },
437 handOff: (colleagueId, brief) => surface.handOff(colleagueId, brief),
438 });
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked439 toolbox = new ToolBox(
440 audience,
441 ports(consult.ask),
442 { agentId: row.id, notConsult: [row.handle, ...(sender ? [sender.handle] : [])], hops, maxHops: CHAT_MAX_HOPS },
443 [],
444 actions,
445 );
446 consult.attach(toolbox);
447 } catch (error) {
448 // Without an audience nothing may be read: the reply goes on with this conversation only.
449 console.error("agents: no audience for a reply, so no tools", row.id, String(error));
450 }
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)451 }
Workspace agents find, read, write and share the workspace's artifacts with search_artifacts, read_artifact, create_artifact (docs for now), edit_artifact, stale_artifacts, share_artifact and list_spaces, and their recall reads artifacts and projects' docs through the folio RPCs instead of Docs' pages.452 // What people said last, for recalling what the workspace's artifacts say about it.
Agents recall what Docs say before they answer or work, and each has required reading453 const said = [...history].reverse().filter((m) => m.author.kind === "user").slice(0, 3).map((m) => m.body);
454 const [facts, recent, passages] = delivery.hello
455 ? [[], null, []]
456 : await Promise.all([
457 recall(db, row.id, place).catch(() => []),
458 sessionsHere(db, row.id, delivery.channel_id).catch(() => null),
459 toolbox ? toolbox.recall(recallQuery(said), definition.reading ?? []) : Promise.resolve([]),
460 ]);
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked461 const system = [
462 systemPrompt({
463 agent: {
464 ...definition,
465 id: row.id,
466 // @g1t's job is fixed; what the workspace wrote is added to it.
467 instructions: row.builtin ? orchestratorInstructions(specialists.filter((a) => a.handle !== "g1t"), definition.instructions) : definition.instructions,
468 },
469 workspace: delivery.workspace,
470 channel: { kind: delivery.channel_kind, name: delivery.channel_name },
471 asker,
472 today: now,
473 tools: toolbox ? { code: toolbox.definitions().some((tool) => tool.name === "read_file") } : null,
474 // @g1t's team is in its job; everyone else is told who their colleagues are.
475 colleagues: row.builtin ? null : rosterLines(specialists),
476 recentSessions: recent,
Merge branch 'worktree-agent-a1398e81ad1a64c5f'477 conversation: conversationHere,
478 canHandOff: !!toolbox?.definitions().some((tool) => tool.name === "hand_off"),
479 handedOffBy: sender?.handle ?? null,
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked480 }),
481 memorySection(facts),
Agents recall what Docs say before they answer or work, and each has required reading482 recallSection(passages),
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked483 ]
484 .filter(Boolean)
485 .join("\n\n");
486 toolCalls = toolbox?.calls ?? [];
487 const answer = await runTurn(model.send, { model: model.model.model, system, messages: conversation as ModelMessage[], tools: toolbox, price: model.ownModel ? null : model.model.price });
488 // Post as soon as there is an answer; the bill is settled after.
Merge branch 'worktree-agent-a1398e81ad1a64c5f'489 // It wakes nobody, @mentions or not: colleagues get work only through hand_off.
490 if (answer.text) posted = await surface.post(answer.text);
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked491 return {
492 text: answer.text,
493 tokens: addTokens(answer.tokens, consulted.tokens),
494 cost: (model.ownModel ? 0 : answer.cost) + consulted.cost,
495 rounds: answer.rounds,
496 };
Chat and workspace agents: channels, DMs and named agents you talk to497 });
498
Agents work in sessions: bounded, visible, steerable work spun off from chat, with subagents and colleagues in a tree paid by its root; memory with sources and scopes; routines; a workspace budget for every agent; agents file issues for whoever asked499 if (!done.ok) return await notice(noticeFor(done.reason, done.message), done.reason);
500 usage = { model: done.model, tier: done.tier, tokens: done.tokens, cost: done.cost, charged: done.charged };
501 if (!done.value.text) {
502 const apology = await surface.post(APOLOGY).catch(() => null);
503 return await finish({ status: "failed", error: "the model gave no text", reply_id: apology, ...usage });
Chat and workspace agents: channels, DMs and named agents you talk to504 }
505 await finish({ status: "replied", reply_id: posted, ...usage });
506 } catch (error) {
507 const message = error instanceof Error ? error.message : String(error);
508 console.error("agents: a reply failed", row.id, delivery.message_id, message);
509 const posted = await surface.post(APOLOGY).catch(() => null);
510 await finish({ status: "failed", error: message, reply_id: posted, ...usage }).catch((failure: unknown) =>
511 console.error("agents: a failed reply was not recorded", id, String(failure)),
512 );
513 }
514}

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