Skip to content
206 linesCodeBlameRaw
1/**
2 * Agents as stored in D1, and their spend. Shared by the RPC methods and
3 * the desk.
4 */
5import type { SubagentDef, WorkspaceAgent } from "@g1t/contracts";
6
7import { agentStatus, budgetBlock, dayKey, monthKey } from "./budget.ts";
8import { type Definition, DEFAULT_AUTONOMY, DEFAULT_BUDGET, DEFAULT_ROUTING, PRESETS, readJson } from "./definition.ts";
9
10export type Row = {
11 id: string;
12 workspace_id: string;
13 handle: string;
14 display_name: string;
15 avatar: string | null;
16 role: string;
17 instructions: string;
18 personality_preset: string;
19 personality: string;
20 routing: string;
21 budget: string;
22 autonomy: string;
23 capacity: number;
24 template: string | null;
25 avatar_seed: string | null;
26 title: string | null;
27 team: string | null;
28 department: string | null;
29 responsibilities: string | null;
30 subagents: string | null;
31 faces: string | null;
32 version: number;
33 /** 1 for the workspace's built-in @g1t. */
34 builtin: number;
35 busy_until: string | null;
36 created_by: string;
37 created_at: string;
38 updated_at: string;
39 archived_at: string | null;
40 /** Joined from agent_spend: this month and today. */
41 spent_month?: number | null;
42 spent_day?: number | null;
43};
44
45/**
46 * Agents with this month's and today's spend: `where` filters `agents`
47 * (aliased `a`); its parameters follow the two periods.
48 */
49export function selectAgents(where: string): string {
50 return `SELECT a.*, m.micros AS spent_month, d.micros AS spent_day FROM agents a
51 LEFT JOIN agent_spend m ON m.agent_id = a.id AND m.period = ?1
52 LEFT JOIN agent_spend d ON d.agent_id = a.id AND d.period = ?2
53 WHERE ${where}`;
54}
55
56export function periods(now: Date): [string, string] {
57 return [monthKey(now), dayKey(now)];
58}
59
60export function definitionOf(row: Row): Definition {
61 return {
62 handle: row.handle,
63 display_name: row.display_name,
64 role: row.role,
65 instructions: row.instructions,
66 personality_preset: PRESETS.includes(row.personality_preset as Definition["personality_preset"])
67 ? (row.personality_preset as Definition["personality_preset"])
68 : "crisp",
69 personality: row.personality,
70 routing: readJson(row.routing, DEFAULT_ROUTING),
71 budget: readJson(row.budget, DEFAULT_BUDGET),
72 autonomy: readJson(row.autonomy, DEFAULT_AUTONOMY),
73 capacity: row.capacity,
74 template: row.template,
75 avatar_seed: row.avatar_seed || row.handle,
76 title: row.title ?? "",
77 team: row.team ?? null,
78 department: row.department ?? "",
79 responsibilities: readList<string>(row.responsibilities),
80 subagents: readList<SubagentDef>(row.subagents),
81 faces: "internal",
82 };
83}
84
85export function toAgent(row: Row, now: Date): WorkspaceAgent {
86 const definition = definitionOf(row);
87 const spent = { month: row.spent_month ?? 0, day: row.spent_day ?? 0 };
88 return {
89 id: row.id,
90 workspace_id: row.workspace_id,
91 avatar: row.avatar,
92 ...definition,
93 builtin: !!row.builtin,
94 version: row.version,
95 status: row.archived_at ? "paused" : agentStatus({ busyUntil: row.busy_until, now, blocked: budgetBlock(definition.budget, spent, now) !== null }),
96 spent_month_micros: spent.month,
97 created_by: row.created_by,
98 created_at: row.created_at,
99 updated_at: row.updated_at,
100 archived_at: row.archived_at,
101 };
102}
103
104/**
105 * Adds a charge to the paying agent's month and day: a reply's, or a
106 * session step's (`task`), counted as one of each.
107 */
108export function spendStatements(db: D1Database, agentId: string, micros: number, now: Date, task: "reply" | "session" = "reply"): D1PreparedStatement[] {
109 const [replies, sessions] = task === "reply" ? [1, 0] : [0, 1];
110 return periods(now).map((period) =>
111 db
112 .prepare(
113 `INSERT INTO agent_spend (agent_id, period, micros, replies, sessions) VALUES (?1, ?2, ?3, ?4, ?5)
114 ON CONFLICT (agent_id, period) DO UPDATE SET micros = micros + ?3, replies = replies + ?4, sessions = sessions + ?5`,
115 )
116 .bind(agentId, period, Math.max(0, Math.ceil(micros)), replies, sessions),
117 );
118}
119
120/** A stored JSON list, read defensively: anything else is empty. */
121function readList<T>(raw: string | null): T[] {
122 if (!raw) return [];
123 try {
124 const parsed = JSON.parse(raw) as unknown;
125 return Array.isArray(parsed) ? (parsed as T[]) : [];
126 } catch {
127 return [];
128 }
129}
130
131/**
132 * The agents table's definition columns, in the order `definitionColumns`
133 * gives their values. Statements are built from this one list, so a new
134 * field is added in one place.
135 */
136export const DEFINITION_COLUMNS = [
137 "handle",
138 "display_name",
139 "role",
140 "instructions",
141 "personality_preset",
142 "personality",
143 "routing",
144 "budget",
145 "autonomy",
146 "capacity",
147 "template",
148 "avatar_seed",
149 "title",
150 "team",
151 "department",
152 "responsibilities",
153 "subagents",
154 "faces",
155] as const;
156
157/** A definition's values, in `DEFINITION_COLUMNS` order. */
158export function definitionColumns(d: Definition): (string | number | null)[] {
159 return [
160 d.handle,
161 d.display_name,
162 d.role,
163 d.instructions,
164 d.personality_preset,
165 d.personality,
166 JSON.stringify(d.routing),
167 JSON.stringify(d.budget),
168 JSON.stringify(d.autonomy),
169 d.capacity,
170 d.template,
171 d.avatar_seed,
172 d.title,
173 d.team,
174 d.department,
175 JSON.stringify(d.responsibilities),
176 JSON.stringify(d.subagents),
177 d.faces,
178 ];
179}
180
181/**
182 * A new agent row: `id`, `workspace_id`, the definition, then `extra`
183 * columns (version, builtin, who made it, when), all bound in order.
184 */
185export function insertAgent(db: D1Database, id: string, workspaceId: string, d: Definition, extra: Record<string, string | number>, orIgnore = false): D1PreparedStatement {
186 const names = ["id", "workspace_id", ...DEFINITION_COLUMNS, ...Object.keys(extra)];
187 const values = [id, workspaceId, ...definitionColumns(d), ...Object.values(extra)];
188 return db
189 .prepare(`INSERT ${orIgnore ? "OR IGNORE " : ""}INTO agents (${names.join(", ")}) VALUES (${names.map(() => "?").join(", ")})`)
190 .bind(...values);
191}
192
193/** Sets a row's definition, from the version read only, with `extra` columns. */
194export function updateAgent(db: D1Database, id: string, readVersion: number, d: Definition, extra: Record<string, string | number>): D1PreparedStatement {
195 const names = [...DEFINITION_COLUMNS, ...Object.keys(extra)];
196 return db
197 .prepare(`UPDATE agents SET ${names.map((name) => `${name} = ?`).join(", ")} WHERE id = ? AND version = ?`)
198 .bind(...definitionColumns(d), ...Object.values(extra), id, readVersion);
199}
200
201/** A version of a definition, as saved. */
202export function versionStatement(db: D1Database, agentId: string, version: number, d: Definition, by: string, at: string): D1PreparedStatement {
203 return db
204 .prepare("INSERT INTO agent_versions (agent_id, version, definition, changed_by, created_at) VALUES (?, ?, ?, ?, ?)")
205 .bind(agentId, version, JSON.stringify(d), by, at);
206}