Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 29 additions & 14 deletions apps/api/src/agent-connection-cap-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
24 changes: 23 additions & 1 deletion apps/api/src/agent-spend-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -81,6 +89,8 @@ interface Ledger {
reserve(month: string, key: string, cents: number): Promise<AgentSpendOutcome>;
/** Lists a connection without a cap in Settings, where its limit is set (#2785). */
noteWithoutCap?(): Promise<void>;
/** Gives a connection never seen before its default cap; true when it did. */
adoptDefault?(): Promise<boolean>;
release(month: string, key: string, cents: number): Promise<void>;
}

Expand All @@ -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,
Expand All @@ -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);
Expand Down Expand Up @@ -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(
Expand Down
18 changes: 10 additions & 8 deletions docs/reference/agent-channel.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -560,15 +560,17 @@ its own client. The API treats that token as an **agent grant**:
`draftloop:<scope>`, 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.
Expand Down
28 changes: 13 additions & 15 deletions docs/reference/connect-an-assistant.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
18 changes: 17 additions & 1 deletion packages/storage-postgres/src/agent-connection-caps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand All @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions packages/storage/src/agent-connection-caps-conformance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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(
(
Expand Down
22 changes: 20 additions & 2 deletions packages/storage/src/agent-connection-caps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
/**
* 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<boolean>;
get(workspaceId: string, clientId: string): Promise<AgentConnectionCap | undefined>;
/** A workspace's caps, by client id. */
list(workspaceId: string): Promise<readonly AgentConnectionCap[]>;
/** 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<boolean>;
/**
* Reserves `cents` against the connection's cap for `month`, once per `key`. Atomic, so two
Expand Down Expand Up @@ -124,15 +132,25 @@ 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()]
.filter((cap) => cap.workspaceId === workspaceId)
.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);
Expand Down
Loading