Skip to content
109 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.

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 asked1/**
2 * The workspace's say over all its agents together (docs/WORKSPACE.md,
3 * "Budgets"): one monthly budget across every agent, the budget a new
4 * agent starts with, the cap a session starts with, and alerts at 75, 90
5 * and 100% of the monthly budget. Owners set it. Pure apart from the
6 * statements it builds, so the rules are tested on their own.
7 */
8import type { AgentPolicy } from "@g1t/contracts";
9
10import { dayKey, monthKey } from "./budget.ts";
11
12/** A session's cap when nobody set one: $2. */
13export const DEFAULT_SESSION_MICROS = 2_000_000;
14/** The thresholds owners hear about, in % of the workspace's agent budget. */
15export const ALERTS = [75, 90, 100] as const;
16
17export type PolicyRow = AgentPolicy & {
18 /** Every agent's spend this month. */
19 spent: number;
20 /** The highest alert already sent this month, or 0. */
21 alerted: number;
22};
23
24export const DEFAULT_POLICY: AgentPolicy = { monthly_micros: null, default_agent_monthly_micros: null, default_session_micros: DEFAULT_SESSION_MICROS };
25
26/** The workspace's policy and this month's spend across its agents. */
27export async function readPolicy(db: D1Database, workspaceId: string, month: string): Promise<PolicyRow> {
28 const [policy, spend] = await Promise.all([
29 db
30 .prepare("SELECT monthly_micros, default_agent_monthly_micros, default_session_micros FROM agent_policies WHERE workspace_id = ?")
31 .bind(workspaceId)
32 .first<AgentPolicy>(),
33 db
34 .prepare("SELECT micros, alerted FROM workspace_agent_spend WHERE workspace_id = ? AND period = ?")
35 .bind(workspaceId, month)
36 .first<{ micros: number; alerted: number }>(),
37 ]);
38 return {
39 monthly_micros: positive(policy?.monthly_micros),
40 default_agent_monthly_micros: positive(policy?.default_agent_monthly_micros),
41 default_session_micros: positive(policy?.default_session_micros) ?? DEFAULT_SESSION_MICROS,
42 spent: spend?.micros ?? 0,
43 alerted: spend?.alerted ?? 0,
44 };
45}
46
47function positive(value: number | null | undefined): number | null {
48 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : null;
49}
50
51/** Why no agent may start more work this month, as people are told, or null. */
52export function policyBlock(policy: Pick<PolicyRow, "monthly_micros" | "spent">): string | null {
53 if (policy.monthly_micros && policy.spent >= policy.monthly_micros) {
54 return "This workspace's agents have used their budget for the month. An owner can raise it under Agents → Budget.";
55 }
56 return null;
57}
58
59/** The alert a workspace has newly crossed, or null: the highest threshold at or under its share, past what was sent. */
60export function alertDue(policy: Pick<PolicyRow, "monthly_micros" | "spent" | "alerted">): number | null {
61 if (!policy.monthly_micros) return null;
62 const share = (policy.spent * 100) / policy.monthly_micros;
63 const crossed = ALERTS.filter((level) => share >= level).at(-1) ?? null;
64 return crossed && crossed > policy.alerted ? crossed : null;
65}
66
67/** Adds a charge to the workspace's agent spend, this month and today. */
68export function workspaceSpendStatements(db: D1Database, workspaceId: string, micros: number, now: Date): D1PreparedStatement[] {
69 return [monthKey(now), dayKey(now)].map((period) =>
70 db
71 .prepare(
72 `INSERT INTO workspace_agent_spend (workspace_id, period, micros) VALUES (?1, ?2, ?3)
73 ON CONFLICT (workspace_id, period) DO UPDATE SET micros = micros + ?3`,
74 )
75 .bind(workspaceId, period, Math.max(0, Math.ceil(micros))),
76 );
77}
78
79/** Marks an alert as sent, once: true when this call is the one that sent it. */
80export async function markAlerted(db: D1Database, workspaceId: string, month: string, level: number): Promise<boolean> {
81 const changed = await db
82 .prepare("UPDATE workspace_agent_spend SET alerted = ? WHERE workspace_id = ? AND period = ? AND alerted < ?")
83 .bind(level, workspaceId, month, level)
84 .run();
85 return changed.meta.changes > 0;
86}
87
88/**
89 * A policy as owners change it, checked: budgets are whole micro-dollars
90 * or null (none); a session's default cap is between 10 cents and $500.
91 */
92export function checkPolicy(current: AgentPolicy, changes: Partial<AgentPolicy>): { ok: true; value: AgentPolicy } | { ok: false; message: string } {
93 const next = { ...current };
94 for (const key of ["monthly_micros", "default_agent_monthly_micros"] as const) {
95 if (!(key in changes)) continue;
96 const value = changes[key];
97 if (value === null || value === 0) next[key] = null;
98 else if (typeof value === "number" && Number.isFinite(value) && value > 0 && value <= 1_000_000_000_000) next[key] = Math.floor(value);
99 else return { ok: false, message: "A budget is a positive amount, or none." };
100 }
101 if ("default_session_micros" in changes) {
102 const value = changes.default_session_micros;
103 if (typeof value !== "number" || !Number.isFinite(value) || value < 100_000 || value > 500_000_000) {
104 return { ok: false, message: "A session's cap is between $0.10 and $500." };
105 }
106 next.default_session_micros = Math.floor(value);
107 }
108 return { ok: true, value: next };
109}