diff --git a/apps/api/src/agent-connection-cap-routes.test.ts b/apps/api/src/agent-connection-cap-routes.test.ts index aea74868..12772fd3 100644 --- a/apps/api/src/agent-connection-cap-routes.test.ts +++ b/apps/api/src/agent-connection-cap-routes.test.ts @@ -275,32 +275,47 @@ describe("assistant connection caps", () => { ]); }); - it("refuses a connection without a cap, and one cap never serves another assistant", async () => { + it("gives a new connection the default cap, and refuses one whose cap was removed", async () => { const api = await signInApi(createMemoryAgentConnectionCapStore()); await setCap(api, 5); + const other = await assistant("draftloop:runs:start", "another-assistant"); - const other = await start( - api, - await assistant("draftloop:runs:start", "another-assistant"), - "key-00000001", - ); - expect(other.statusCode).toBe(429); - expect(other.json().error.message).toContain("no monthly spend cap"); - expect(other.json().error.message).toContain('"another-assistant"'); - // The assistant now waits in the list, without a cap, for the person to set one (#2785). - const listed = await api.inject({ method: "GET", url: connections, headers: await person() }); + // A connection that never spent before starts within the default $5 cap (owner, 2026-12-03). + expect((await start(api, other, "key-00000001")).statusCode).toBe(201); + let listed = await api.inject({ method: "GET", url: connections, headers: await person() }); expect(listed.json().connections).toEqual([ - expect.objectContaining({ client_id: "another-assistant", spent_this_month_usd: 0 }), + expect.objectContaining({ + client_id: "another-assistant", + monthly_cap_usd: 5, + spent_this_month_usd: 2, + }), expect.objectContaining({ client_id: "assistant", monthly_cap_usd: 5 }), ]); + + // Once the person removes its cap it starts nothing, and waits in the list (#2785). + const removed = await api.inject({ + method: "DELETE", + url: `${connections}?client_id=another-assistant`, + headers: await person(), + }); + expect(removed.statusCode).toBe(204); + const refused = await start(api, other, "key-00000002"); + expect(refused.statusCode).toBe(429); + expect(refused.json().error.message).toContain("no monthly spend cap"); + expect(refused.json().error.message).toContain('"another-assistant"'); + listed = await api.inject({ method: "GET", url: connections, headers: await person() }); + expect(listed.json().connections[0]).toMatchObject({ + client_id: "another-assistant", + spent_this_month_usd: 0, + }); expect(listed.json().connections[0]).not.toHaveProperty("monthly_cap_usd"); const unscoped = await start( api, await assistant("draftloop:applications:read"), - "key-00000002", + "key-00000003", ); expect(unscoped.statusCode).toBe(403); - expect(begun).toEqual([]); + expect(begun).toHaveLength(1); }); it("tells the assistant what it may still spend in the estimate", async () => { diff --git a/apps/api/src/agent-spend-gate.ts b/apps/api/src/agent-spend-gate.ts index cbde8beb..afb96283 100644 --- a/apps/api/src/agent-spend-gate.ts +++ b/apps/api/src/agent-spend-gate.ts @@ -57,11 +57,19 @@ export interface AgentSpendGateOptions { readonly budgetCeiling: RunBudgetCeiling; /** The most one draft of application material may spend, in US dollars. */ readonly draftMaxCostUsd?: number; + /** + * The monthly cap, in US dollars, a connection gets the first time it asks to spend, so a new + * assistant works within a small limit at once; the person changes or removes it in Settings. + */ + readonly defaultConnectionCapUsd?: number; readonly now?: () => Date; } const usd = (cents: number) => cents / 100; +/** A new assistant connection's monthly cap until the person changes it (owner, 2026-12-03). */ +export const defaultAgentConnectionCapUsd = 5; + /** Dollars to whole cents, rounded up so a reservation never falls short of the limit. */ export function centsOf(amountUsd: number): number { return Math.ceil(Math.round(amountUsd * 10_000) / 100); @@ -81,6 +89,8 @@ interface Ledger { reserve(month: string, key: string, cents: number): Promise; /** Lists a connection without a cap in Settings, where its limit is set (#2785). */ noteWithoutCap?(): Promise; + /** Gives a connection never seen before its default cap; true when it did. */ + adoptDefault?(): Promise; release(month: string, key: string, cents: number): Promise; } @@ -98,6 +108,7 @@ export function registerAgentSpendGate( return centsOf(workspace.maxCostUsd ?? options.budgetCeiling.maxCostUsd); }; const draftCents = centsOf(options.draftMaxCostUsd ?? defaultApplicationMaterialMaxCostUsd); + const defaultCapCents = centsOf(options.defaultConnectionCapUsd ?? defaultAgentConnectionCapUsd); const find = async ( request: FastifyRequest, workspaceId: string, @@ -119,6 +130,13 @@ export function registerAgentSpendGate( release: (month, key, cents) => caps.releaseSpend({ workspaceId, clientId, month, key, cents }), noteWithoutCap: () => caps.note(workspaceId, clientId, now().toISOString()), + adoptDefault: () => + caps.adopt({ + workspaceId, + clientId, + monthlyCapCents: defaultCapCents, + updatedAt: now().toISOString(), + }), }; } const tokens = options.tokensFor?.(request); @@ -149,7 +167,11 @@ export function registerAgentSpendGate( const key = `${rule.charge}:${typeof idempotencyKey === "string" ? idempotencyKey : request.id}`; const cents = rule.charge === "run" ? await runCents(options.workspaceRoot(token.workspaceId)) : draftCents; - const outcome = await ledger.reserve(month, key, cents); + let outcome = await ledger.reserve(month, key, cents); + if (outcome.outcome === "no_cap" && (await ledger.adoptDefault?.()) === true) { + request.log.info({ agentTokenId: token.id }, "agent connection given the default cap"); + outcome = await ledger.reserve(month, key, cents); + } if (outcome.outcome === "reserved") { held.set(request, { id: token.id, release: () => ledger.release(month, key, cents) }); request.log.info( diff --git a/docs/reference/agent-channel.md b/docs/reference/agent-channel.md index 3df49c67..485f3131 100644 --- a/docs/reference/agent-channel.md +++ b/docs/reference/agent-channel.md @@ -493,8 +493,8 @@ sequenceDiagram `jobs:write`. `drafts:read`, `runs:start`, `evidence:write` and `profile:suggest` are granted only when the person adds them. - **Runs and drafts.** With `runs:start`, the assistant starts them within - [the connection's spend cap](#the-connections-spend-cap). Without a cap, the - tool tells the person to set one in Settings > Agents. + [the connection's spend cap](#the-connections-spend-cap): $5 a month by + default, which the person changes or removes in Settings > Agents. - **Workspace.** The tools act in the signed-in person's workspace. A person who reaches several gets the first by id; choosing one is not built. - **Token check.** Before any tool runs, the server checks the token itself: @@ -560,15 +560,17 @@ its own client. The API treats that token as an **agent grant**: `draftloop:`, such as `draftloop:applications:read`. A token of any client other than the web screen's is a grant, even with no scope. - **Spending needs a cap.** A grant with `runs:start` starts a run or a draft - only within the monthly cap its person set for that assistant in the - workspace. Without a cap it answers `429`, like a token past its cap. + only within the monthly cap that assistant has in the workspace. After the + person removes the cap it answers `429`, like a token past its cap. ### The connection's spend cap -The person sets the cap in **Settings > Agents**, on the -assistant's row of **Connected agents**. An assistant that asks to spend -without a cap is refused and listed there, waiting for a limit, so nobody -types its id. One cap holds for one workspace and one assistant client. +The first time an assistant asks to spend in a workspace, its connection +gets a $5 monthly cap, so it works at once within a small limit. The person +changes the cap in **Settings > Agents**, on the assistant's row of +**Connected agents**. After the person removes it, the assistant is refused +and stays listed there without a cap, and never gets the default again. One +cap holds for one workspace and one assistant client. The screen calls these routes from the person's own sign-in; an assistant never reaches them. diff --git a/docs/reference/connect-an-assistant.md b/docs/reference/connect-an-assistant.md index 7bbfb1c8..9d1b623b 100644 --- a/docs/reference/connect-an-assistant.md +++ b/docs/reference/connect-an-assistant.md @@ -53,15 +53,13 @@ The assistant can never do these, whatever you grant: ## Spending -Starting a CV run or a draft costs model usage on your account. An assistant -starts none until you set its monthly limit: +Starting a CV run or a draft costs model usage on your account. The first +time your assistant starts one, it gets a limit of $5 a month. To change it: -1. Ask your assistant to start something once. Without a limit it is refused, - and it then appears in Redakloop. -2. In Redakloop, open **Settings > Agents**. Under **Connected - agents**, find your assistant's row: it says "No limit yet". -3. Select **Set a limit**, type a monthly limit in US dollars and select - **Save limit**. +1. In Redakloop, open **Settings > Agents**. +2. Under **Connected agents**, find your assistant's row. +3. Change its monthly limit in US dollars and save it, or remove it. Without + a limit the assistant starts nothing, and it gets no new default. Each run counts at your workspace's cost limit per run, and each draft at its cost @@ -95,13 +93,13 @@ disconnect. ## When it fails -| The assistant says | What to do | -| -------------------------------------- | ---------------------------------------------- | -| It was not granted a permission | Connect again and add that permission | -| It has no monthly spend cap | Set its limit in Settings > Agents | -| It reached its monthly cap | Raise the limit, or wait for next month | -| The account has no Redakloop workspace | Sign up in Redakloop first, then connect again | -| It needs an export to read your CV | Approve the CV and export it in Redakloop | +| The assistant says | What to do | +| -------------------------------------- | --------------------------------------------------- | +| It was not granted a permission | Connect again and add that permission | +| It has no monthly spend cap | Set its limit in Settings > Agents (you removed it) | +| It reached its monthly cap | Raise the limit, or wait for next month | +| The account has no Redakloop workspace | Sign up in Redakloop first, then connect again | +| It needs an export to read your CV | Approve the CV and export it in Redakloop | ## Related diff --git a/packages/storage-postgres/src/agent-connection-caps.ts b/packages/storage-postgres/src/agent-connection-caps.ts index 82c0df06..7e5c6946 100644 --- a/packages/storage-postgres/src/agent-connection-caps.ts +++ b/packages/storage-postgres/src/agent-connection-caps.ts @@ -50,6 +50,17 @@ export function createAgentConnectionCapStore(client: SqlSession): AgentConnecti [workspaceId, clientId, at], ); }, + adopt: async (input) => { + const cap = requireAgentConnectionCap(input); + const rows = await client.query( + `INSERT INTO agent_connection_caps (workspace_id, client_id, monthly_cap_cents, updated_at) + VALUES ($1, $2, $3, $4) + ON CONFLICT (tenant_id, workspace_id, client_id) DO NOTHING + RETURNING 1`, + [cap.workspaceId, cap.clientId, cap.monthlyCapCents, cap.updatedAt], + ); + return rows.length > 0; + }, get: async (workspaceId, clientId) => { const [row] = await client.query( `SELECT ${columns} FROM agent_connection_caps WHERE workspace_id = $1 AND client_id = $2`, @@ -66,8 +77,13 @@ export function createAgentConnectionCapStore(client: SqlSession): AgentConnecti return rows.map(capOf); }, remove: async (workspaceId, clientId) => { + // The row stays without a cap, so the connection is still listed and gets no default. const rows = await client.query( - `DELETE FROM agent_connection_caps WHERE workspace_id = $1 AND client_id = $2 RETURNING 1`, + `UPDATE agent_connection_caps + SET monthly_cap_cents = NULL, spend_month = NULL, spent_cents = 0, + spend_keys = '{}'::jsonb + WHERE workspace_id = $1 AND client_id = $2 AND monthly_cap_cents IS NOT NULL + RETURNING 1`, [workspaceId, clientId], ); return rows.length > 0; diff --git a/packages/storage/src/agent-connection-caps-conformance.ts b/packages/storage/src/agent-connection-caps-conformance.ts index 139c6a59..3b398c7b 100644 --- a/packages/storage/src/agent-connection-caps-conformance.ts +++ b/packages/storage/src/agent-connection-caps-conformance.ts @@ -96,6 +96,10 @@ export async function expectAgentConnectionCapStore( expect(await store.reserveSpend({ ...reservation, key: "run:key-5" })).toEqual({ outcome: "no_cap", }); + // The connection stays listed without a cap, and gets no default again. + expect(await store.get("owner", "assistant-a")).toEqual({ ...assistant, updatedAt: later }); + expect(await store.adopt({ ...assistant, monthlyCapCents: 500, updatedAt: later })).toBe(false); + expect((await store.get("owner", "assistant-a"))?.monthlyCapCents).toBeUndefined(); // Setting it again starts with no spend: removal erased it. expect( (await store.set({ ...assistant, monthlyCapCents: 500, updatedAt: later })).spend, @@ -121,6 +125,26 @@ export async function expectAgentConnectionCapStore( "assistant-b", "assistant-n", ]); + // A connection never kept takes the default once; one already kept, noted or capped, does not. + expect( + await store.adopt({ + workspaceId: "owner", + clientId: "assistant-d", + monthlyCapCents: 500, + updatedAt: later, + }), + ).toBe(true); + expect((await store.get("owner", "assistant-d"))?.monthlyCapCents).toBe(500); + expect( + await store.adopt({ + workspaceId: "owner", + clientId: "assistant-n", + monthlyCapCents: 500, + updatedAt: later, + }), + ).toBe(false); + expect((await store.get("owner", "assistant-n"))?.monthlyCapCents).toBeUndefined(); + if (other !== undefined) expect(await other.get("owner", "assistant-d")).toBeUndefined(); // Its limit is then set on its row like any other. expect( ( diff --git a/packages/storage/src/agent-connection-caps.ts b/packages/storage/src/agent-connection-caps.ts index f9b42d97..7615a33c 100644 --- a/packages/storage/src/agent-connection-caps.ts +++ b/packages/storage/src/agent-connection-caps.ts @@ -46,10 +46,18 @@ export interface AgentConnectionCapStore { * list and sets its limit there; a connection already kept is left as it is. */ note(workspaceId: string, clientId: string, at: string): Promise; + /** + * Gives a connection the workspace has never kept its first cap, the default; false, changing + * nothing, when the workspace keeps it already, with a cap or after its cap was removed. + */ + adopt(cap: AgentConnectionCapInput): Promise; get(workspaceId: string, clientId: string): Promise; /** A workspace's caps, by client id. */ list(workspaceId: string): Promise; - /** Removes a cap and its spend; false when the workspace holds none for the client. */ + /** + * Removes a cap and its spend; false when the workspace holds none for the client. The + * connection stays listed without a cap, so it starts nothing and gets no default again. + */ remove(workspaceId: string, clientId: string): Promise; /** * Reserves `cents` against the connection's cap for `month`, once per `key`. Atomic, so two @@ -124,6 +132,13 @@ export function createMemoryAgentConnectionCapStore(): AgentConnectionCapStore { const id = idOf(workspaceId, clientId); if (!caps.has(id)) caps.set(id, { workspaceId, clientId, updatedAt: at }); }, + adopt: async (input) => { + const cap = requireAgentConnectionCap(input); + const id = idOf(cap.workspaceId, cap.clientId); + if (caps.has(id)) return false; + caps.set(id, cap); + return true; + }, get: async (workspaceId, clientId) => caps.get(idOf(workspaceId, clientId)), list: async (workspaceId) => [...caps.values()] @@ -131,8 +146,11 @@ export function createMemoryAgentConnectionCapStore(): AgentConnectionCapStore { .sort((a, b) => a.clientId.localeCompare(b.clientId)), remove: async (workspaceId, clientId) => { const id = idOf(workspaceId, clientId); + const cap = caps.get(id); + if (cap?.monthlyCapCents === undefined) return false; keys.delete(id); - return caps.delete(id); + caps.set(id, { workspaceId, clientId, updatedAt: cap.updatedAt }); + return true; }, reserveSpend: async ({ workspaceId, clientId, month, key, cents }) => { const id = idOf(workspaceId, clientId);