Skip to content
540 linesCodeBlameRaw
1/**
2 * One reply: an agent answering a message in chat, in this Worker, with no
3 * sandbox.
4 *
5 * 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.
11 *
12 * 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.
15 *
16 * 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).
19 */
20import { type AgentDelivery, type ServiceBinding, identityClient, newId } from "@g1t/contracts";
21
22import { CHAT_MAX_HOPS } from "../../../packages/contracts/src/chat.ts";
23import type { Tokens } from "./budget.ts";
24import { handOffPort } from "./handoff.ts";
25import { HISTORY_LIMIT, fixedHello, helloAsk, systemPrompt, turns } from "./prompt.ts";
26import { loadShelf, skillsSection, teamSlugs } from "./skills.ts";
27import { readVersion } from "./skill-library.ts";
28import { type Specialist, orchestratorInstructions, orchestratorTier, rosterLines } from "./orchestrator.ts";
29import { type MeterEnv, metered } from "./meter.ts";
30import { type RecallPlace, memorySection, recall } from "./memory.ts";
31import { recallQuery, recallSection } from "./recall.ts";
32import { REPLY_TIER, allowedProviders, effortOf, effortPlan, replyModel } from "./routing.ts";
33import { type SessionEnv, type SessionRow, actionPorts, sessionRow, startSession, steer } from "./sessions.ts";
34import { type Row, definitionOf, periods, selectAgents, toAgent } from "./store.ts";
35import { type SurfaceMessage, surfaceFor } from "./surface.ts";
36import { Audience } from "./audience.ts";
37import { audiencePorts, loadTeams, teamsOfAgents, toolPorts } from "./ports.ts";
38import { type ToolCall, type ToolPorts, ToolBox } from "./tools.ts";
39import type { Surface } from "./surface.ts";
40import type { Desk } from "./desk.ts";
41import { type ModelMessage, type Send, NO_TOKENS, addTokens, runTurn } from "./turn.ts";
42import type { AgentRouting as Policy } from "../../runner/src/model-env.ts";
43import { dollars } from "./money.ts";
44import { teamsSection } from "./teammates.ts";
45import { personalRefusal } from "./access.ts";
46
47export { billingRepo } from "./meter.ts";
48
49export type ReplyEnv = MeterEnv & {
50 DB: D1Database;
51 CHAT: ServiceBinding;
52 /** People and their access, for the audience; members and teams for the roster. */
53 IDENTITY: ServiceBinding;
54 /** Code, for read tools. */
55 REPOS: ServiceBinding;
56 /** Issues and pull requests, for read tools and filing issues. */
57 WORK: ServiceBinding;
58 /** Code search, for read tools. */
59 SEARCH: ServiceBinding;
60 /** Notifications: a session waiting for more budget. */
61 NOTIFY?: ServiceBinding;
62 /** Every agent's desk: sessions are worked on their agent's. */
63 DESKS: DurableObjectNamespace<Desk>;
64};
65
66/** A notice that the agent cannot reply is posted once per conversation in this long. */
67const NOTICE_QUIET_MS = 6 * 60 * 60 * 1000;
68/** Sessions one reply may start. */
69const MAX_SPIN_OFFS = 2;
70
71const APOLOGY = "Sorry, something went wrong on my side and I couldn't answer that. Try again in a moment.";
72
73/** Who asked, from the message that woke the agent (or their latest one). */
74function askerIn(history: SurfaceMessage[], delivery: AgentDelivery): SurfaceMessage["author"] | null {
75 const woken = history.find((m) => m.id === delivery.message_id);
76 if (woken) return woken.author;
77 return [...history].reverse().find((m) => m.author.kind === "user" && m.author.id === delivery.asked_by)?.author ?? null;
78}
79
80/**
81 * An agent's colleagues: every agent of the workspace but itself that is
82 * not archived (docs.g1t.sh/guides/agents/, "Agents know each other").
83 */
84async function team(db: D1Database, workspaceId: string, selfId: string, now: Date, teamsOf: Promise<Map<string, string[]>>): Promise<Specialist[]> {
85 const [rows, onTeams] = await Promise.all([
86 db
87 // Personal agents are their members' own: no colleague of anyone.
88 .prepare(`${selectAgents("a.workspace_id = ?3 AND a.archived_at IS NULL AND a.id <> ?4 AND a.scope = 'workspace'")} ORDER BY a.builtin DESC, a.handle LIMIT 50`)
89 .bind(...periods(now), workspaceId, selfId)
90 .all<Row>(),
91 teamsOf,
92 ]);
93 return rows.results.map((row) => {
94 const agent = toAgent(row, now);
95 return {
96 handle: agent.handle,
97 display_name: agent.display_name,
98 role: agent.role,
99 title: agent.title,
100 teams: onTeams.get(agent.id) ?? [],
101 responsibilities: agent.responsibilities,
102 status: agent.status,
103 spent_month_micros: agent.spent_month_micros,
104 monthly_micros: agent.budget.monthly_micros,
105 };
106 });
107}
108
109/** The agent's latest sessions in this conversation, one line each. */
110async function sessionsHere(db: D1Database, agentId: string, channelId: string): Promise<string | null> {
111 const rows = await db
112 .prepare(
113 "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",
114 )
115 .bind(agentId, channelId)
116 .all<{ id: string; title: string; status: string; summary: string | null; created_at: string }>();
117 if (!rows.results.length) return null;
118 return rows.results
119 .map((s) => `- "${s.title}" (${s.status}, ${s.created_at.slice(0, 10)})${s.summary ? `: ${s.summary.replace(/\s+/g, " ").slice(0, 300)}` : ""}`)
120 .join("\n");
121}
122
123/**
124 * Consulting a colleague:
125 * the colleague answers in a nested turn that posts nothing, with the same
126 * audience (so it can read no more than the conversation may), the same
127 * asker, one hop further, its own routing limits, on the same model
128 * session, billed to this reply. A compact card in the thread says who
129 * asked whom. Consults don't nest: the colleague can't consult in turn.
130 */
131function consulting(input: {
132 db: D1Database;
133 row: Row;
134 delivery: DeskWork;
135 send: Send;
136 policy: Policy;
137 ownModel: boolean;
138 sessionModel: string | null;
139 own: string | null;
140 ports: (consult: ToolPorts["consult"]) => ToolPorts;
141 hops: number;
142 now: Date;
143 surface: Surface;
144 asker: { name: string; display_name: string | null; access: NonNullable<AgentDelivery["asker"]> | null };
145 spent: { tokens: Tokens; cost: number };
146}): { ask: ToolPorts["consult"]; attach(box: ToolBox): void } {
147 let parent: ToolBox | null = null;
148 const noNesting: ToolPorts["consult"] = async () => ({ ok: false, message: "Consults don't nest: answer with what you have." });
149 const ask: ToolPorts["consult"] = async (handle, question) => {
150 const { row, delivery } = input;
151 const colleague = await input.db
152 .prepare("SELECT * FROM agents WHERE workspace_id = ? AND handle = ? AND archived_at IS NULL AND scope = 'workspace'")
153 .bind(row.workspace_id, handle)
154 .first<Row>();
155 if (!colleague || colleague.id === row.id) return { ok: false, message: `There is no other agent called @${handle} here.` };
156 // No ping-pong: never back to the agent that sent this work.
157 if ((delivery.chain ?? []).at(-1) === colleague.id) return { ok: false, message: `@${handle} sent you this work; answer with what you have.` };
158 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." };
159 const definition = definitionOf(colleague);
160 const allowed = allowedProviders(definition.routing, input.own);
161 if (input.ownModel ? !allowed.own : !allowed.hosted) return { ok: false, message: `@${handle} can't use the model this conversation runs on.` };
162 const model = replyModel(
163 input.policy,
164 { ...definition.routing, pinned: input.ownModel ? definition.routing.pinned : null },
165 { named: input.ownModel ? input.sessionModel : null },
166 );
167 const tools = parent
168 ? parent.forColleague(input.ports(noNesting), { agentId: colleague.id, notConsult: [colleague.handle, row.handle], hops: input.hops + 1, maxHops: input.hops + 1 })
169 : null;
170 const system = systemPrompt({
171 agent: { ...definition, id: colleague.id },
172 workspace: delivery.workspace,
173 channel: { kind: delivery.channel_kind, name: delivery.channel_name },
174 asker: input.asker,
175 today: input.now,
176 tools: tools ? { code: tools.definitions().some((tool) => tool.name === "read_file") } : null,
177 consultedBy: row.handle,
178 });
179 const result = await runTurn(input.send, {
180 model: model.model,
181 system,
182 messages: [{ role: "user", content: `@${row.handle} (agent) asks you: ${question}` }],
183 tools,
184 price: input.ownModel ? null : model.price,
185 });
186 input.spent.tokens = addTokens(input.spent.tokens, result.tokens);
187 input.spent.cost += input.ownModel ? 0 : result.cost;
188 const answer = result.text || "(no answer)";
189 const exchange = `Q: ${question}\nA: ${answer}`;
190 // The exchange, collapsed, in the thread. No @ in its text: it wakes nobody.
191 await input.surface
192 .post(`${row.display_name} asked ${colleague.display_name}`, {
193 kind: "consult",
194 title: `${row.display_name} asked ${colleague.display_name}`,
195 detail: exchange.length > 1000 ? `${exchange.slice(0, 1000)}…` : exchange,
196 state: null,
197 href: null,
198 })
199 .catch((error: unknown) => console.error("agents: a consult card was not posted", String(error)));
200 return { ok: true, colleague: colleague.handle, answer };
201 };
202 return {
203 ask,
204 attach(box) {
205 parent = box;
206 },
207 };
208}
209
210type Outcome = {
211 status: "replied" | "steered" | "blocked" | "skipped" | "failed";
212 error?: string | null;
213 reply_id?: string | null;
214 model?: string | null;
215 tier?: string | null;
216 tokens?: Tokens;
217 cost?: number;
218 charged?: number;
219 /** The effort level it ran at. */
220 effort?: string | null;
221};
222
223/**
224 * What a desk is handed: a message to answer, or (`hello`) the agent's
225 * first message to the person who made it, in the DM that just opened.
226 */
227export type DeskWork = AgentDelivery & { hello?: boolean };
228
229/** How a limit's refusal reads in chat, in the agent's voice. */
230function noticeFor(reason: string, message: string): string {
231 if (reason.startsWith("budget_") || reason === "workspace_agent_budget" || message.startsWith("My settings") || message.startsWith("I ")) return message;
232 if (reason === "no_model") return `I can't reply yet: ${message}`;
233 return `I can't reply right now: ${message}`;
234}
235
236/** The session a message in this thread is for: a reply under one of this agent's session cards. */
237async function steeredSession(db: D1Database, agentId: string, threadRoot: string | null): Promise<SessionRow | null> {
238 if (!threadRoot) return null;
239 const found = await db.prepare("SELECT id FROM agent_sessions WHERE agent_id = ? AND card_message_id = ?").bind(agentId, threadRoot).first<{ id: string }>();
240 return found ? sessionRow(db, found.id) : null;
241}
242
243/**
244 * Answers `delivery` as its agent. Never throws: every way it ends is
245 * recorded on the reply's row. A message handed over twice is answered
246 * once.
247 */
248export async function reply(env: ReplyEnv, delivery: DeskWork, now = new Date()): Promise<void> {
249 const db = env.DB;
250 const row = await db.prepare("SELECT * FROM agents WHERE id = ?").bind(delivery.agent_id).first<Row>();
251 if (!row || row.archived_at || row.workspace_id !== delivery.workspace_id) return;
252 const id = newId("arp", now.getTime());
253 const claimed = await db
254 .prepare(
255 `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)
256 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'working', ?)
257 ON CONFLICT (agent_id, message_id) DO NOTHING RETURNING id`,
258 )
259 .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())
260 .first<{ id: string }>();
261 if (!claimed) return;
262
263 const surface = surfaceFor(env.CHAT, delivery);
264 // 👀 as soon as the desk has it, while everything else goes on.
265 const acknowledging = surface.acknowledge();
266 const slug = delivery.workspace.toLowerCase();
267
268 // What the answer used, once there is one: counted however the reply ends.
269 let usage: Partial<Outcome> = {};
270 // What the tools did, for the audit table, and who the audience was.
271 let toolCalls: ToolCall[] = [];
272 let audienceHash: string | null = null;
273
274 const finish = async (outcome: Outcome) => {
275 const statements = [
276 db
277 .prepare(
278 `UPDATE agent_replies SET status = ?, error = ?, reply_id = ?, model = ?, tier = ?, input_tokens = ?, output_tokens = ?,
279 cost_micros = ?, charged_micros = ?, tool_count = ?, finished_at = ?, effort = ? WHERE id = ?`,
280 )
281 .bind(
282 outcome.status,
283 outcome.error?.slice(0, 1000) ?? null,
284 outcome.reply_id ?? null,
285 outcome.model ?? null,
286 outcome.tier ?? null,
287 (outcome.tokens?.input ?? 0) + (outcome.tokens?.cacheRead ?? 0) + (outcome.tokens?.cacheWrite ?? 0),
288 outcome.tokens?.output ?? 0,
289 outcome.cost ?? 0,
290 outcome.charged ?? 0,
291 toolCalls.length,
292 new Date().toISOString(),
293 outcome.effort ?? null,
294 id,
295 ),
296 // Every tool call: what was asked, for whom, and whether it was read or withheld.
297 ...toolCalls.map((call, n) =>
298 db
299 .prepare(
300 `INSERT INTO agent_tool_calls (id, reply_id, agent_id, workspace_id, asked_by, tool, args, audience_hash, outcome, bytes, created_at)
301 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
302 )
303 .bind(`${id}_${n}`, id, row.id, row.workspace_id, delivery.asked_by, call.tool, call.args, audienceHash ?? "", call.outcome, call.bytes, now.toISOString()),
304 ),
305 ];
306 await db.batch(statements);
307 // ✅ when it answered; 👀 taken back after a notice, an apology or nothing.
308 await acknowledging;
309 await surface.settle(outcome.status === "replied" || outcome.status === "steered" ? "done" : "withdrawn");
310 };
311
312 /** Says once, in this conversation, why the agent cannot answer; a repeat within hours is kept back. */
313 const notice = async (message: string, reason: string) => {
314 // An agent's first words are never an excuse: without a model, a fixed hello.
315 if (delivery.hello) {
316 const posted = await surface.post(fixedHello(row, delivery.asker?.username ?? null)).catch(() => null);
317 return await finish({ status: "blocked", error: reason, reply_id: posted });
318 }
319 const since = new Date(now.getTime() - NOTICE_QUIET_MS).toISOString();
320 const recent = await db
321 .prepare(
322 `SELECT 1 FROM agent_replies WHERE agent_id = ? AND channel_id = ? AND status = 'blocked' AND error = ?
323 AND reply_id IS NOT NULL AND created_at > ? AND id <> ? LIMIT 1`,
324 )
325 .bind(row.id, delivery.channel_id, reason, since, id)
326 .first();
327 const posted = recent ? null : await surface.post(message).catch(() => null);
328 await finish({ status: "blocked", error: reason, reply_id: posted });
329 };
330
331 try {
332 // A reply under one of its session cards steers that session; nothing is answered here.
333 const steered = delivery.hello ? null : await steeredSession(db, row.id, delivery.thread_root);
334 if (steered) {
335 const history = await surface.history(HISTORY_LIMIT).catch(() => [] as SurfaceMessage[]);
336 const message = history.find((m) => m.id === delivery.message_id);
337 if (message?.body.trim()) {
338 await steer(env as unknown as SessionEnv, steered, message.author.name, message.body);
339 return await finish({ status: "steered" });
340 }
341 }
342
343 // Read the conversation while showing that the agent is on it.
344 // A hello has no conversation yet: it is asked to introduce itself.
345 // And who is here: said every turn, so the agent knows who reads it and who doesn't.
346 // And its teams, from their pages: who leads, who owns what, who is around.
347 const [, history, conversationHere, teamsHere] = await Promise.all([
348 surface.typing(),
349 delivery.hello ? Promise.resolve([]) : surface.history(HISTORY_LIMIT),
350 delivery.hello ? Promise.resolve(null) : surface.conversation(),
351 loadTeams(env, slug, row.workspace_id, { id: row.id }).catch(() => null),
352 ]);
353 // A personal agent answers only its member, in the DM of the two of them (access.ts).
354 const refused = personalRefusal(row, {
355 asked_by: delivery.asked_by,
356 channel_kind: delivery.channel_kind,
357 members: conversationHere ? conversationHere.people + conversationHere.agents : null,
358 });
359 if (refused) return await notice(refused, "personal_agent");
360 const conversation = delivery.hello ? [{ role: "user" as const, content: helloAsk(delivery.asker?.username ?? null) }] : turns(history, row.id);
361 if (!conversation.length) return await finish({ status: "skipped", error: "nothing to answer" });
362 const author = askerIn(history, delivery);
363 const askerName = delivery.asker?.username ?? author?.name ?? null;
364 // Every agent knows its colleagues; @g1t also steps up a tier to decide
365 // who gets the work in a long thread.
366 const specialists = await team(db, row.workspace_id, row.id, now, teamsOfAgents(env, slug));
367 const definition = definitionOf(row);
368 // Its effort setting decides where the reply starts and how hard the model reasons.
369 const plan = effortPlan(effortOf(definition.routing), row.builtin ? orchestratorTier(history.length, specialists.filter((a) => a.handle !== "g1t").length) : REPLY_TIER);
370 const hops = Math.max(0, Math.floor(delivery.hops || 0));
371 const chain = delivery.chain ?? [];
372 const sender = chain.length ? await db.prepare("SELECT handle FROM agents WHERE id = ?").bind(chain[chain.length - 1]).first<{ handle: string }>() : null;
373 const asker = { name: askerName ?? "someone", display_name: author?.display_name ?? null, access: delivery.asker ?? null };
374 let posted: string | null = null;
375 let spinOffs = 0;
376
377 const done = await metered(env, { row, payer: row, slug, task: "reply", start: plan.start, effort: plan.level, askerName, person: delivery.asker?.username ?? null, teams: teamsHere }, async (model) => {
378 // What colleagues consulted along the way used: billed to this reply.
379 const consulted = { tokens: NO_TOKENS, cost: 0 };
380 let toolbox: ToolBox | null = null;
381 let place: RecallPlace = { channel_id: delivery.channel_id, kind: delivery.channel_kind === "dm" ? "dm" : "private", people: [delivery.asked_by] };
382 if (!delivery.hello) {
383 try {
384 const audience = await Audience.build(slug, delivery.asked_by, audiencePorts(env, slug, delivery.channel_id));
385 place = { channel_id: delivery.channel_id, kind: audience.kind, people: audience.shared ? [delivery.asked_by] : audience.members.map((m) => m.id) };
386 const ports = (consult: ToolPorts["consult"]) => toolPorts(env, slug, row.workspace_id, delivery.channel_id, consult, row.id);
387 audienceHash = audience.hash;
388 const consult = consulting({
389 db,
390 row,
391 delivery,
392 send: model.send,
393 policy: model.policy,
394 ownModel: model.ownModel,
395 sessionModel: model.sessionModel,
396 own: model.own,
397 ports,
398 hops,
399 now,
400 surface,
401 asker,
402 spent: consulted,
403 });
404 const where = delivery.channel_kind === "dm" ? "a direct message" : `#${delivery.channel_name ?? "a channel"}`;
405 const actions = actionPorts(env as unknown as SessionEnv, {
406 agent: row,
407 place,
408 source: { kind: "message", ref: delivery.message_id, label: askerName ? `@${askerName} in ${where}` : where, channel_id: delivery.channel_id },
409 asker: { id: delivery.asked_by, username: askerName },
410 workspace: slug,
411 postCard: (card) => surface.post("", card).catch(() => null),
412 // Real work becomes a session, with its card in this conversation.
413 spinOff: async (title, goal) => {
414 if (spinOffs >= MAX_SPIN_OFFS) return { ok: false, message: "You've started enough sessions from this message." };
415 spinOffs++;
416 const session = await startSession(env as unknown as SessionEnv, {
417 agent: row,
418 kind: "chat",
419 title,
420 goal: `${askerName ? `@${askerName}` : "Someone"} asked in ${where}:\n\n${goal}`,
421 workspace: slug,
422 channel_id: delivery.channel_id,
423 channel_kind: delivery.channel_kind,
424 channel_name: delivery.channel_name,
425 thread_root: delivery.thread_root,
426 message_id: delivery.message_id,
427 asked_by: delivery.asked_by,
428 asked_by_username: askerName,
429 asker: delivery.asker ?? null,
430 chain: [...chain],
431 hops,
432 });
433 const cap = session.cap_micros ? ` with a cap of ${dollars(session.cap_micros)}` : "";
434 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.` };
435 },
436 });
437 // Work handed to a colleague: the only way an agent gets another working (handoff.ts).
438 const viewer = audience.asker;
439 actions.handOff = handOffPort({
440 self: { id: row.id, handle: row.handle },
441 chain,
442 asker: delivery.asker ?? null,
443 agent: async (handle) => {
444 const found = await db
445 .prepare(selectAgents("a.workspace_id = ?3 AND a.handle = ?4 AND a.archived_at IS NULL AND a.scope = 'workspace'"))
446 .bind(...periods(now), row.workspace_id, handle)
447 .first<Row>();
448 if (!found) return null;
449 const agent = toAgent(found, now);
450 return { id: agent.id, handle: agent.handle, display_name: agent.display_name, builtin: !!found.builtin, status: agent.status };
451 },
452 person: async (handle) => {
453 if (!viewer) return false;
454 const members = await identityClient(env.IDENTITY).listMembers(slug, viewer);
455 return members.ok && members.value.some((m) => m.username.toLowerCase() === handle);
456 },
457 handOff: (colleagueId, brief) => surface.handOff(colleagueId, brief),
458 });
459 toolbox = new ToolBox(
460 audience,
461 ports(consult.ask),
462 { agentId: row.id, notConsult: [row.handle, ...(sender ? [sender.handle] : [])], hops, maxHops: CHAT_MAX_HOPS },
463 [],
464 actions,
465 );
466 consult.attach(toolbox);
467 } catch (error) {
468 // Without an audience nothing may be read: the reply goes on with this conversation only.
469 console.error("agents: no audience for a reply, so no tools", row.id, String(error));
470 }
471 }
472 // What people said last, for recalling what the workspace's artifacts say about it.
473 const said = [...history].reverse().filter((m) => m.author.kind === "user").slice(0, 3).map((m) => m.body);
474 const [facts, recent, passages, shelf] = delivery.hello
475 ? [[], null, [], []]
476 : await Promise.all([
477 recall(db, row.id, place).catch(() => []),
478 sessionsHere(db, row.id, delivery.channel_id).catch(() => null),
479 toolbox ? toolbox.recall(recallQuery(said), definition.reading ?? []) : Promise.resolve([]),
480 // Its skills: named in the prompt, read with use_skill (skills.ts).
481 toolbox ? loadShelf(db, row.workspace_id, { id: row.id, skills_off: definition.skills_off }, teamSlugs(teamsHere)) : Promise.resolve([]),
482 ]);
483 toolbox?.useShelf(shelf, (skillId, version) => readVersion(db, skillId, version));
484 const system = [
485 systemPrompt({
486 agent: {
487 ...definition,
488 id: row.id,
489 teams: teamsHere?.teams.map((t) => t.name) ?? [],
490 // @g1t's job is fixed; what the workspace wrote is added to it.
491 instructions: row.builtin ? orchestratorInstructions(specialists.filter((a) => a.handle !== "g1t"), definition.instructions) : definition.instructions,
492 },
493 workspace: delivery.workspace,
494 channel: { kind: delivery.channel_kind, name: delivery.channel_name },
495 asker,
496 today: now,
497 tools: toolbox ? { code: toolbox.definitions().some((tool) => tool.name === "read_file") } : null,
498 // @g1t's team is in its job; everyone else is told who their colleagues are.
499 colleagues: row.builtin ? null : rosterLines(specialists),
500 recentSessions: recent,
501 conversation: conversationHere,
502 teams: teamsSection(row.id, teamsHere, now),
503 canHandOff: !!toolbox?.definitions().some((tool) => tool.name === "hand_off"),
504 handedOffBy: sender?.handle ?? null,
505 skills: skillsSection(shelf, toolbox?.definitions().map((tool) => tool.name) ?? []),
506 }),
507 memorySection(facts),
508 recallSection(passages),
509 ]
510 .filter(Boolean)
511 .join("\n\n");
512 toolCalls = toolbox?.calls ?? [];
513 const answer = await runTurn(model.send, { model: model.model.model, system, messages: conversation as ModelMessage[], tools: toolbox, price: model.ownModel ? null : model.model.price, effort: model.effort });
514 // Post as soon as there is an answer; the bill is settled after.
515 // It wakes nobody, @mentions or not: colleagues get work only through hand_off.
516 if (answer.text) posted = await surface.post(answer.text);
517 return {
518 text: answer.text,
519 tokens: addTokens(answer.tokens, consulted.tokens),
520 cost: (model.ownModel ? 0 : answer.cost) + consulted.cost,
521 rounds: answer.rounds,
522 };
523 });
524
525 if (!done.ok) return await notice(noticeFor(done.reason, done.message), done.reason);
526 usage = { model: done.model, tier: done.tier, tokens: done.tokens, cost: done.cost, charged: done.charged, effort: plan.level };
527 if (!done.value.text) {
528 const apology = await surface.post(APOLOGY).catch(() => null);
529 return await finish({ status: "failed", error: "the model gave no text", reply_id: apology, ...usage });
530 }
531 await finish({ status: "replied", reply_id: posted, ...usage });
532 } catch (error) {
533 const message = error instanceof Error ? error.message : String(error);
534 console.error("agents: a reply failed", row.id, delivery.message_id, message);
535 const posted = await surface.post(APOLOGY).catch(() => null);
536 await finish({ status: "failed", error: message, reply_id: posted, ...usage }).catch((failure: unknown) =>
537 console.error("agents: a failed reply was not recorded", id, String(failure)),
538 );
539 }
540}