Merge origin/master and renumber additive Speko migrations

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-09 15:45:59 -05:00
commit bf1ead3772
65 files changed
+5336 -56682

No files matched your search

@@ -2,6 +2,9 @@ import { connectionIntentService } from "../services/connection-intents.js";
import { connectionIntentDeliveryService } from "../services/connection-intent-delivery.js";
import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";
import { localAiLoginService } from "../services/local-ai-login.js";
// Background plan observations have their own provider-fixture coverage. Runtime
// auth tests must not send the selected fixture credentials to a real provider.
vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn().mockResolvedValue(undefined) }));
import * as localCredentials from "../services/local-ai-credentials.js";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { createHash, randomUUID } from "node:crypto";
@@ -1407,6 +1410,9 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
try {
expect(child.identity).toBe(parent.identity);
expect(child.attribution.grantId).toBe(account.grantId);
expect(parent.attribution.subscriptionId).toEqual(expect.any(String));
expect(child.attribution.subscriptionId).toBe(parent.attribution.subscriptionId);
expect(child.config.managedAiConnection).toMatchObject({ subscriptionId: parent.attribution.subscriptionId });
} finally {
await Promise.all([parent.cleanup(), child.cleanup()]);
}
@@ -537,6 +537,7 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
cachedInputTokens: 10,
outputTokens: 200_000_000,
costCents: 2_000_000_000,
costStatus: "estimated",
occurredAt: new Date("2026-04-11T00:00:00.000Z"),
},
]);
@@ -555,6 +556,11 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
expect(byAgentRow?.inputTokens).toBe(3_999_999_990);
expect(byAgentRow!.inputTokens + byAgentRow!.cachedInputTokens).toBe(4_000_000_000);
expect(byProjectRow?.costCents).toBe(4_000_000_000);
expect(byProjectRow).toMatchObject({ eventCount: 2, estimatedEventCount: 1 });
const [firstDayProject] = await costs.byProject(companyId, {
...range, to: new Date("2026-04-10T23:59:59.999Z"),
});
expect(firstDayProject).toMatchObject({ eventCount: 1, estimatedEventCount: 0 });
expect(byAgentModelRow?.costCents).toBe(4_000_000_000);
});
@@ -128,3 +128,31 @@ it("does not trust editable agent metadata as an invitation ownership receipt",
expect(await service.resume(f.companyId, f.userId)).toBeNull();
expect((await service.create(f.companyId, f.userId)).agent.id).not.toBe(spoof!.id);
});
it("reports connection setup authority separately from compatibility status", async () => {
const f = await fixture();
const invite = await dotInvitationService(db).create(f.companyId, f.userId);
const app = express();
app.use((req, _res, next) => {
req.actor = { type: "board", source: "session", userId: f.userId, companyIds: [f.companyId],
memberships: [{ companyId: f.companyId, membershipRole: "owner", status: "active" }] };
next();
});
app.use(dotRunnerRoutes(db, "https://paperclip.example/mcp/runner"));
const path = `/companies/${f.companyId}/agents/${invite.agent.id}/dot-binding`;
const cases = [
{ lifecycleState: "preparing", status: "paused", allowed: true },
{ lifecycleState: "verifying", status: "paused", allowed: true },
{ lifecycleState: "ready", status: "idle", allowed: true },
{ lifecycleState: "paused", status: "paused", allowed: false },
{ lifecycleState: "pending_approval", status: "pending_approval", allowed: false },
{ lifecycleState: "terminated", status: "terminated", allowed: false },
] as const;
for (const state of cases) {
await db.update(agents).set({ lifecycleState: state.lifecycleState, status: state.status }).where(eq(agents.id, invite.agent.id));
const result = await request(app).get(path);
expect(result.status).toBe(200);
expect(result.body).toMatchObject({ agentStatus: state.status, agentLifecycleState: state.lifecycleState,
canConfigureConnection: state.allowed });
}
});
@@ -0,0 +1,81 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { refreshCompanySubscriptions, refreshSubscriptionConnection } from "../services/subscription-refresh.js";
import type { SubscriptionConnection } from "../services/subscriptions.js";
const mocks = vi.hoisted(() => ({ accounts: vi.fn(), credential: vi.fn(), register: vi.fn(), probe: vi.fn() }));
vi.mock("../services/ai-connections.js", () => ({ aiConnectionService: () => ({ subscriptionAccounts: mocks.accounts, credential: mocks.credential }) }));
vi.mock("../services/subscriptions.js", () => ({ subscriptionService: () => ({ register: mocks.register }) }));
vi.mock("../services/subscription-identity.js", () => ({ probeSubscriptionIdentity: mocks.probe }));
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>(done => { resolve = done; });
return { promise, resolve };
}
function database() {
return {
update: () => ({ set: () => ({ where: () => ({ returning: async () => [{ id: "claimed" }] }) }) }),
select: () => ({ from: () => ({ where: async () => [{ credentialKey: "fixture-key" }] }) }),
} as unknown as Db;
}
const input = (id: string): SubscriptionConnection => ({ companyId: id, connectionId: id, grantId: id, provider: "openai", name: id, ownerUserId: "alice", credential: "fixture" });
beforeEach(() => {
vi.resetAllMocks();
mocks.credential.mockResolvedValue("fixture");
mocks.register.mockImplementation(async (connection: SubscriptionConnection) => connection.grantId);
});
describe("subscription discovery capacity", () => {
it.each([false, true])("waits for a provider slot without dropping accepted discovery (provider fails: %s)", async (fails) => {
const db = database();
const gates = Array.from({ length: 5 }, () => deferred<void>());
let started = 0, active = 0, peak = 0;
mocks.probe.mockImplementation(async () => {
const index = started++;
peak = Math.max(peak, ++active);
await gates[index].promise;
active--;
if (index === 0 && fails) throw new Error("fixture provider failure");
return { credentialKey: "fixture-key" };
});
mocks.accounts.mockResolvedValue([{ summary: { status: "connected", provider: "openai" },
connection: { id: "fifth", name: "Fifth account" }, grant: { id: "fifth", subjectUserId: "alice" } }]);
const running = Array.from({ length: 4 }, (_, i) => refreshSubscriptionConnection(db, input(`busy-${i}`), `busy-${i}`));
let discovery: Promise<void> | undefined;
try {
await vi.waitFor(() => expect(started).toBe(4));
let completed = false;
discovery = refreshCompanySubscriptions(db, "fifth", "alice").then(() => { completed = true; });
await vi.waitFor(() => expect(mocks.register).toHaveBeenCalledWith(expect.objectContaining({ grantId: "fifth" })));
expect(started).toBe(4);
expect(completed).toBe(false);
gates[0].resolve();
await vi.waitFor(() => expect(started).toBe(5));
expect(peak).toBe(4);
gates[4].resolve();
await discovery;
expect(mocks.register).toHaveBeenCalledWith(expect.objectContaining({ grantId: "fifth" }), { credentialKey: "fixture-key" });
} finally {
gates.forEach(gate => gate.resolve());
await Promise.all([...running, discovery]);
}
});
it("rejects excess discovery with a retryable error, deduplicates accepted work, and releases capacity", async () => {
const db = database(), gate = deferred<[]>();
mocks.accounts.mockReturnValue(gate.promise);
const accepted = Array.from({ length: 20 }, (_, i) => refreshCompanySubscriptions(db, "company", `user-${i}`));
try {
expect(refreshCompanySubscriptions(db, "company", "user-0")).toBe(accepted[0]);
expect(mocks.accounts).toHaveBeenCalledTimes(20);
expect(() => refreshCompanySubscriptions(db, "company", "overflow")).toThrow(expect.objectContaining({ status: 429 }));
} finally {
gate.resolve([]);
await Promise.all(accepted);
}
await refreshCompanySubscriptions(db, "company", "overflow");
expect(mocks.accounts).toHaveBeenCalledTimes(21);
});
});
@@ -0,0 +1,66 @@
import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { costRoutes } from "../routes/costs.js";
import { errorHandler } from "../middleware/error-handler.js";
import { tooManyRequests } from "../errors.js";
const mocks = vi.hoisted(() => ({ report: vi.fn(), refresh: vi.fn(), updatePrice: vi.fn(), merge: vi.fn(), decide: vi.fn() }));
vi.mock("../services/subscription-report.js", () => ({ subscriptionCostReport: mocks.report }));
vi.mock("../services/subscription-refresh.js", () => ({ refreshCompanySubscriptions: mocks.refresh }));
vi.mock("../services/subscriptions.js", () => ({ subscriptionService: () => mocks }));
vi.mock("../routes/ai-connections.js", () => ({ canManageAiConnections: async () => false }));
vi.mock("../services/index.js", () => ({
heartbeatService: () => ({}), costService: () => ({}), financeService: () => ({}), budgetService: () => ({}),
companyService: () => ({}), agentService: () => ({}), issueService: () => ({}), accessService: () => ({ decide: mocks.decide }),
}));
vi.mock("../services/accounting-integrity.js", () => ({ accountingIntegrityService: () => ({}) }));
vi.mock("../services/billing-reconciliation.js", () => ({ billingReconciliationService: () => ({}) }));
const companyId = "11111111-1111-4111-8111-111111111111";
const accountId = "22222222-2222-4222-8222-222222222222";
function app(type: "board" | "agent" = "board", role = "member") {
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = type === "board" ? { type: "board", source: "session", userId: "alice", companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: role }] } as typeof req.actor : { type: "agent", agentId: "agent", companyId } as typeof req.actor; next(); });
app.use("/api", costRoutes({} as Db)); app.use(errorHandler); return app;
}
beforeEach(() => { vi.clearAllMocks(); mocks.decide.mockResolvedValue({ allowed: true }); mocks.report.mockResolvedValue({ accounts: [] }); mocks.refresh.mockResolvedValue(undefined); mocks.updatePrice.mockResolvedValue({ id: accountId }); });
describe("subscription reporting authorization", () => {
it("allows company cost reads but rejects agents, other companies and invalid dates", async () => {
const path = `/api/companies/${companyId}/costs/subscriptions`;
expect((await request(app()).get(path)).status).toBe(200);
expect((await request(app("agent")).get(path)).status).toBe(403);
expect((await request(app()).get("/api/companies/other/costs/subscriptions")).status).toBe(403);
expect((await request(app()).get(`${path}?from=not-a-date`)).status).toBe(400);
expect((await request(app()).get(`${path}?period=all`)).status).toBe(200);
expect(mocks.report).toHaveBeenLastCalledWith(expect.anything(), companyId, expect.anything(), { allTime: true });
mocks.decide.mockResolvedValue({ allowed: false });
expect((await request(app()).get(path)).status).toBe(403);
});
it("returns immediately while authorized discovery runs and denies viewers", async () => {
mocks.refresh.mockReturnValue(new Promise(() => {}));
const path = `/api/companies/${companyId}/costs/subscriptions/refresh`;
expect((await request(app()).post(path)).status).toBe(202);
expect(mocks.refresh).toHaveBeenCalledWith(expect.anything(), companyId, "alice");
expect((await request(app("board", "viewer")).post(path)).status).toBe(403);
});
it("validates edits and passes ownership and optimistic concurrency to the service", async () => {
const path = `/api/companies/${companyId}/costs/subscriptions/${accountId}`;
const data = { expectedRevision: 3, plan: "Pro", amountCents: "2000", currency: "USD", cadence: "month", status: "active" };
expect((await request(app()).patch(path).send(data)).status).toBe(200);
expect(mocks.updatePrice).toHaveBeenCalledWith(companyId, accountId, expect.objectContaining({ expectedRevision: 3, amountCents: "2000.0000000" }), { userId: "alice", canManage: false, readOnly: false });
expect((await request(app()).patch(path).send({ ...data, amountCents: "-1" })).status).toBe(400);
expect((await request(app()).patch(path).send({ ...data, ownerUserId: "bob" })).status).toBe(400);
expect((await request(app("agent")).patch(path).send(data)).status).toBe(403);
mocks.decide.mockResolvedValue({ allowed: false });
expect((await request(app()).patch(path).send(data)).status).toBe(403);
expect((await request(app()).post(`${path}/link`).send({ targetId: accountId, expectedRevision: 3, targetRevision: 3 })).status).toBe(403);
});
it("returns a retryable error instead of accepting discovery beyond capacity", async () => {
mocks.refresh.mockImplementationOnce(() => { throw tooManyRequests("Subscription account checks are busy. Try again shortly."); });
const response = await request(app()).post(`/api/companies/${companyId}/costs/subscriptions/refresh`);
expect(response.status).toBe(429);
expect(response.body.error).toContain("Try again shortly");
});
});
+492
View File
@@ -0,0 +1,492 @@
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { and, eq, sql } from "drizzle-orm";
import { createDb, companies, agents, heartbeatRuns, costEvents, activityLog, aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections, toolApplications, toolConnections, connectionGrants, connectionGrantMembers } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
import { monthlySubscriptionCents, subscriptionPlan, subscriptionPriceSchema } from "@paperclipai/shared";
import { subscriptionService, type SubscriptionConnection } from "../services/subscriptions.js";
import { subscriptionCostReport } from "../services/subscription-report.js";
import { refreshSubscriptionConnection } from "../services/subscription-refresh.js";
import { subscriptionCredentialIdentity, probeSubscriptionIdentity } from "../services/subscription-identity.js";
import { costService } from "../services/costs.js";
import { toolAccessService } from "../services/tool-access.js";
import * as liveEvents from "../services/live-events.js";
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
const owner = { userId: "alice", canManage: false };
const other = { userId: "bob", canManage: true };
const jwt = (body: unknown) => `header.${Buffer.from(JSON.stringify(body)).toString("base64url")}.signature`;
const token = (workspace = "workspace", seat = "alice", plan = "plus", generation = "1") => JSON.stringify({ tokens: {
account_id: workspace, access_token: jwt({ sub: seat, generation,
"https://api.openai.com/auth": { chatgpt_account_id: workspace, chatgpt_user_id: seat } }),
id_token: jwt({ sub: seat, "https://api.openai.com/auth": { chatgpt_plan_type: plan, chatgpt_user_id: seat } }),
} });
const fixtureRequest = (body: unknown) => vi.fn<typeof fetch>().mockImplementation(async () => Response.json(body));
const usage = (plan = "plus") => ({ plan_type: plan, rate_limit: { primary_window: { used_percent: 1, reset_at: 1800000000, limit_window_seconds: 18000 } } });
async function verifiedConnection(input: SubscriptionConnection) {
const observed = await probeSubscriptionIdentity(input.companyId, input.provider, input.credential, fixtureRequest(usage()));
return subscriptionService(db).register(input, observed);
}
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-subscriptions-"); db = createDb(database.connectionString); }, 90000);
afterAll(async () => { await database?.cleanup(); });
async function company() {
const id = randomUUID();
await db.insert(companies).values({ id, name: "Subscription fixture", issuePrefix: `S${id.replaceAll("-", "").slice(0, 7).toUpperCase()}` });
return id;
}
async function connection(companyId: string, credential = token(), provider: SubscriptionConnection["provider"] = "openai", userId: string | null = "alice") {
const applicationId = randomUUID(), connectionId = randomUUID(), grantId = randomUUID();
await db.insert(toolApplications).values({ id: applicationId, companyId, name: applicationId, type: "custom" });
await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "My subscription", uid: connectionId,
connectionPurpose: "ai", transport: "runtime_auth", status: "active", enabled: true, config: { ai: { provider, method: "subscription" } } });
await db.insert(connectionGrants).values({ id: grantId, companyId, connectionId, kind: userId ? "user" : "organization", subjectUserId: userId });
return { companyId, connectionId, grantId, credential, provider, name: "My subscription", ownerUserId: userId };
}
async function price(companyId: string, id: string, amountCents: string | null = "10000", extra: Record<string, unknown> = {}, actor = owner) {
const [account] = await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, id));
return subscriptionService(db).updatePrice(companyId, id, { expectedRevision: account.revision, plan: "My plan", amountCents, currency: "USD", cadence: "month", status: "active", ...extra }, actor);
}
async function event(companyId: string, subscriptionId: string | null, billingType: "metered_api" | "subscription_included" | "subscription_overage" | "credits" | "fixed" | "unknown", amount = "0", occurredAt = new Date("2026-10-08T00:00:00Z")) {
const agentId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId, name: "Agent", role: "engineer", adapterType: "codex_local" });
await db.insert(costEvents).values({ companyId, agentId, subscriptionId, provider: "openai", biller: "openai", billingType, model: "fixture",
costCents: Number(amount), inputTokens: 100, cachedInputTokens: 40, outputTokens: 10, receiptHash: "normalized", occurredAt });
return agentId;
}
describe("subscription identity and price rules", () => {
it("requires provider authentication, a seat and a workspace, and never persists a credential or email", async () => {
const observed = (companyId: string, credential: string) => probeSubscriptionIdentity(companyId, "openai", credential, fixtureRequest(usage()));
const a = await observed("company", token());
expect(a.verified).toBe(true);
expect(a.accountKey).toBe((await observed("company", token("workspace", "alice", "plus", "2"))).accountKey);
expect(a.accountKey).not.toBe((await observed("company", token("workspace", "bob"))).accountKey);
expect(a.accountKey).not.toBe((await observed("other-company", token())).accountKey);
expect(JSON.stringify(a)).not.toMatch(/workspace|alice|access-1|signature/);
expect(subscriptionCredentialIdentity("company", "openai", token()).verified).toBe(false);
expect(subscriptionCredentialIdentity("company", "openai", '{"tokens":{"account_id":"workspace"}}').verified).toBe(false);
await expect(probeSubscriptionIdentity("company", "openai", token(), async () => new Response(null, { status: 401 }))).rejects.toThrow();
const opaque = JSON.parse(token()); opaque.tokens.access_token = "opaque-bearer";
expect((await observed("company", JSON.stringify(opaque))).verified).toBe(false);
const wrongWorkspace = JSON.parse(token()); wrongWorkspace.tokens.account_id = "another-workspace";
expect((await observed("company", JSON.stringify(wrongWorkspace))).verified).toBe(false);
});
it("keeps ambiguous tiers unknown and uses exact monthly equivalents", () => {
expect(subscriptionPlan("openai", "pro")).toBeNull();
expect(subscriptionPlan("anthropic", "max")).toBeNull();
expect(subscriptionPlan("openai", "business")).toBeNull();
expect(subscriptionPlan("openai", "unrecognized")).toBeNull();
expect(monthlySubscriptionCents("20000", "year")).toBe("1666.6666667");
expect(monthlySubscriptionCents("1", "year")).toBe("0.0833333");
expect(monthlySubscriptionCents("0", "month")).toBe("0.0000000");
expect(subscriptionPriceSchema.safeParse({ expectedRevision: 0, plan: "Max", amountCents: "-1", currency: "USD", cadence: "month", status: "active" }).success).toBe(false);
});
it("uses a Claude account and organization profile, never infers a Max tier from token usage", async () => {
const request = fixtureRequest({ account: { uuid: "person" }, organization: { uuid: "org", organization_type: "claude_max", rate_limit_tier: "default_claude_max_20x" } });
const observed = await probeSubscriptionIdentity("company", "anthropic", "selected-secret", request);
expect(observed.plan).toBe("max_20x");
expect(observed.verified).toBe(true);
expect(JSON.stringify(observed)).not.toContain("selected-secret");
expect(request).toHaveBeenCalledWith("https://api.anthropic.com/api/oauth/profile", expect.objectContaining({ redirect: "error", headers: expect.objectContaining({ Authorization: "Bearer selected-secret" }) }));
await expect(probeSubscriptionIdentity("company", "anthropic", "selected-secret", fixtureRequest({}))).rejects.toThrow();
});
});
describe("durable subscription reporting", () => {
it("can replay the migration and retains fees after connection deletion", async () => {
const migration = await readFile(new URL("../../../packages/db/src/migrations/0322_reflective_kree.sql", import.meta.url), "utf8");
for (const statement of migration.split("--> statement-breakpoint")) await db.execute(sql.raw(statement));
const c = await company(), input = await connection(c);
await verifiedConnection(input);
await db.delete(connectionGrants).where(eq(connectionGrants.id, input.grantId));
await db.delete(toolConnections).where(eq(toolConnections.id, input.connectionId));
expect(await db.select().from(aiSubscriptionConnections).where(eq(aiSubscriptionConnections.companyId, c))).toHaveLength(0);
expect((await subscriptionCostReport(db, c, owner)).monthlyTotals[0].amountCents).toBe("2000.0000000");
await db.delete(toolApplications).where(eq(toolApplications.companyId, c));
await db.delete(activityLog).where(eq(activityLog.companyId, c));
await db.delete(companies).where(eq(companies.id, c));
expect(await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.companyId, c))).toHaveLength(0);
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.companyId, c))).toHaveLength(0);
});
it("rejects a different provider, revoked grant, or foreign company before discovery", async () => {
const c = await company(), input = await connection(c), service = subscriptionService(db);
await expect(service.register({ ...input, provider: "anthropic" })).rejects.toMatchObject({ status: 404 });
await expect(service.register({ ...input, companyId: await company() })).rejects.toMatchObject({ status: 404 });
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, input.grantId));
await expect(service.register(input)).rejects.toMatchObject({ status: 404 });
expect(await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.companyId, c))).toHaveLength(0);
});
it.each([401, 200])("cannot acquire another owner's billing rights with forged ID claims (provider status %s)", async (status) => {
const c = await company(), service = subscriptionService(db);
const victim = await verifiedConnection(await connection(c));
const forged = JSON.parse(token("workspace", "attacker"));
forged.tokens.id_token = JSON.parse(token()).tokens.id_token;
const attacker = await connection(c, JSON.stringify(forged), "openai", "bob");
const provisional = await service.register(attacker);
expect(provisional).not.toBe(victim);
await expect(price(c, victim, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
await refreshSubscriptionConnection(db, attacker, provisional, status === 200 ? fixtureRequest(usage()) : async () => new Response(null, { status }));
await expect(price(c, victim, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
const report = await subscriptionCostReport(db, c, other);
expect(report.accounts.find(row => row.id === victim)).toBeUndefined();
const [account] = await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, victim));
expect(account.ownerUserIds).toEqual(["alice"]);
});
it("keeps unverified credentials grant-scoped even when two members submit identical bytes", async () => {
const c = await company(), service = subscriptionService(db);
const personal = await connection(c, "unverified", "anthropic");
const id = await service.register(personal);
await price(c, id, "10000");
const otherId = await service.register(await connection(c, "unverified", "anthropic", "bob"));
expect(otherId).not.toBe(id);
await expect(price(c, id, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
expect(await service.register(personal)).toBe(id);
});
it("requires fresh provider proof before an identical credential grants a new personal editor", async () => {
const c = await company(), service = subscriptionService(db);
const id = await verifiedConnection(await connection(c));
const second = await connection(c, token(), "openai", "bob");
const provisional = await service.register(second);
expect(provisional).not.toBe(id);
await refreshSubscriptionConnection(db, second, provisional, async () => new Response(null, { status: 401 }));
await expect(price(c, id, "0", { status: "excluded" }, other)).rejects.toMatchObject({ status: 403 });
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, provisional));
await refreshSubscriptionConnection(db, second, provisional, fixtureRequest(usage()));
await price(c, id, "1900", {}, other);
await price(c, id, "1800", {}, owner);
const report = await subscriptionCostReport(db, c, other);
expect(report.accounts).toHaveLength(1);
expect(report.monthlyTotals[0].amountCents).toBe("1800.0000000");
});
it("deduplicates concurrent connections and rotations, while separating seats and companies", async () => {
const c = await company(), service = subscriptionService(db);
const a = await connection(c), b = await connection(c, token("workspace", "alice", "plus", "rotated"));
const [first, second] = await Promise.all([verifiedConnection(a), verifiedConnection(b)]);
expect(first).toBe(second);
expect(await verifiedConnection(await connection(c, token("workspace", "bob"), "openai", "bob"))).not.toBe(first);
expect(await verifiedConnection(await connection(await company()))).not.toBe(first);
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
expect(report.activeCount).toBe(1);
expect(report.monthlyTotals).toEqual([{ currency: "USD", amountCents: "2000.0000000", estimatedCount: 1 }]);
expect((await subscriptionCostReport(db, c, other)).activeCount).toBe(1);
expect(report.accounts.find(row => row.id === second)?.price.revision).toBe(0);
});
it("does not multiply automatic fees when a plan has no stable account identity", async () => {
const c = await company(), service = subscriptionService(db);
const credential = JSON.parse(token());
delete credential.tokens.account_id;
for (const generation of ["first", "rotated"]) {
credential.tokens.access_token = generation;
await service.register(await connection(c, JSON.stringify(credential)));
}
const report = await subscriptionCostReport(db, c, owner);
expect(report.monthlyTotals).toEqual([]);
expect(report.unknownPriceCount).toBe(2);
expect(report.unidentifiedAccountCount).toBe(2);
expect(report.accounts.every(account => account.detectedPlan === "plus")).toBe(true);
});
it("keeps fixed fees through zero-use periods and disconnection; preserves price history and currency", async () => {
const c = await company(), input = await connection(c), service = subscriptionService(db);
const id = await service.register(input);
await price(c, id, "20000", { cadence: "year", currency: "EUR" });
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, input.grantId));
const report = await subscriptionCostReport(db, c, owner, { from: new Date("2020-01-01"), to: new Date("2020-01-07") });
expect(report.monthlyTotals).toEqual([{ currency: "EUR", amountCents: "1666.6666667", estimatedCount: 0 }]);
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id))).toHaveLength(2);
expect(report.accounts[0]).not.toHaveProperty("history");
expect(report.accounts[0].usage.eventCount).toBe(0);
expect((await db.select().from(costEvents).where(eq(costEvents.companyId, c)))).toHaveLength(0);
const [state] = await db.select().from(companies).where(eq(companies.id, c));
expect(state.spentMonthlyCents).toBe(0);
await price(c, id, "20000", { status: "ended" });
expect((await subscriptionCostReport(db, c, owner)).activeCount).toBe(0);
});
it("deduplicates profile observations, preserves manual prices, and reuses promoted credentials", async () => {
const c = await company(), service = subscriptionService(db);
const first = await connection(c, "claude-first", "anthropic");
const second = await connection(c, "claude-second", "anthropic");
const firstId = await service.register(first), secondId = await service.register(second);
await price(c, secondId, "9500");
await event(c, firstId, "subscription_included"); await event(c, secondId, "subscription_included");
const profile = fixtureRequest({ account: { uuid: "seat" }, organization: { uuid: "workspace", organization_type: "claude_max", rate_limit_tier: "default_claude_max_5x" } });
await refreshSubscriptionConnection(db, first, firstId, profile);
await refreshSubscriptionConnection(db, second, secondId, profile);
const third = await connection(c, "claude-second", "anthropic"), thirdId = await service.register(third);
expect(thirdId).not.toBe(firstId);
await refreshSubscriptionConnection(db, third, thirdId, profile);
expect(await service.register(third)).toBe(firstId);
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
expect(report.accounts).toHaveLength(1);
expect(report.monthlyTotals).toEqual([{ currency: "USD", amountCents: "9500.0000000", estimatedCount: 0 }]);
expect(report.accounts[0]).toMatchObject({ identityVerified: true, usage: { eventCount: 2 }, price: { source: "user" } });
});
it("records detected plan changes without rewriting earlier prices or treating an unknown tier as zero", async () => {
const c = await company(), input = await connection(c), id = await verifiedConnection(input);
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
await refreshSubscriptionConnection(db, input, id, fixtureRequest(usage("pro")));
const report = await subscriptionCostReport(db, c, owner);
expect((await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id)).orderBy(aiSubscriptionPrices.revision)).map(price => price.amountCents)).toEqual(["2000.0000000", null]);
expect(report.monthlyTotals).toEqual([]);
expect(report.unknownPriceCount).toBe(1);
const observedAt = report.accounts[0].observedAt;
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
await refreshSubscriptionConnection(db, input, id, fixtureRequest({ ...usage(), plan_type: null }));
const after = (await subscriptionCostReport(db, c, owner)).accounts[0];
expect(after.observedAt).toBe(observedAt);
expect(after.detectedPlan).toBe("pro");
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id))).toHaveLength(2);
expect(after.refreshStatus).toBe("unavailable");
});
it("keeps shared subscription permissions and currencies separate", async () => {
const c = await company(), service = subscriptionService(db);
await verifiedConnection(await connection(c));
const shared = await service.register(await connection(c, token("shared"), "openai", null));
await expect(price(c, shared)).rejects.toMatchObject({ status: 403 });
await price(c, shared, "2100", { currency: "EUR" }, other);
const report = await subscriptionCostReport(db, c, owner);
expect(report.monthlyTotals).toEqual([
{ currency: "EUR", amountCents: "2100.0000000", estimatedCount: 0 },
{ currency: "USD", amountCents: "2000.0000000", estimatedCount: 1 },
]);
});
it.each([true, false])("preserves personal and shared editors regardless of discovery order (shared first: %s)", async (sharedFirst) => {
const c = await company(), service = subscriptionService(db);
const personal = await connection(c), shared = await connection(c, token(), "openai", null);
const first = await verifiedConnection(sharedFirst ? shared : personal);
expect(await verifiedConnection(sharedFirst ? personal : shared)).toBe(first);
await price(c, first, "1900", {}, owner);
await price(c, first, "1800", {}, other);
for (const actor of [owner, other]) {
const report = await subscriptionCostReport(db, c, actor);
expect(report.accounts).toHaveLength(1);
expect(report.accounts[0]).toMatchObject({ canEdit: true, ownerUserId: null });
expect(report.monthlyTotals[0].amountCents).toBe("1800.0000000");
}
await expect(price(c, first, "1700", {}, { ...other, canManage: false })).rejects.toMatchObject({ status: 403 });
await expect(price(c, first, "1700", {}, { ...owner, readOnly: true })).rejects.toMatchObject({ status: 403 });
// Removing authentication connections must not remove the ability to end
// a fee that can still be billed by the provider.
await db.delete(connectionGrants).where(eq(connectionGrants.companyId, c));
await price(c, first, "1700", {}, owner);
await price(c, first, "1700", { status: "ended" }, other);
expect((await subscriptionCostReport(db, c, owner)).activeCount).toBe(0);
});
it.each([true, false])("combines editors when verified profiles link accounts (shared first: %s)", async (sharedFirst) => {
const c = await company(), service = subscriptionService(db);
const personal = await connection(c, "claude-personal", "anthropic");
const shared = await connection(c, "claude-shared", "anthropic", null);
const personalId = await service.register(personal), sharedId = await service.register(shared);
const profile = fixtureRequest({ account: { uuid: "seat" }, organization: { uuid: "org", rate_limit_tier: "default_claude_max_5x" } });
const order = sharedFirst ? [[shared, sharedId], [personal, personalId]] as const : [[personal, personalId], [shared, sharedId]] as const;
for (const [input, id] of order) await refreshSubscriptionConnection(db, input, id, profile);
const report = await subscriptionCostReport(db, c, owner);
expect(report.accounts).toHaveLength(1);
const id = report.accounts[0].id;
await price(c, id, "9500", {}, owner);
await price(c, id, "9000", {}, other);
expect((await subscriptionCostReport(db, c, other)).accounts[0].canEdit).toBe(true);
expect((await subscriptionCostReport(db, c, owner)).monthlyTotals[0].amountCents).toBe("9000.0000000");
});
it("retains every personal owner without granting managers access to a personal-only fee", async () => {
const c = await company(), service = subscriptionService(db);
const id = await verifiedConnection(await connection(c));
expect(await verifiedConnection(await connection(c, token(), "openai", "carol"))).toBe(id);
await price(c, id, "1800", {}, { userId: "carol", canManage: false });
await price(c, id, "1900", {}, owner);
await expect(price(c, id, "2000", {}, other)).rejects.toMatchObject({ status: 403 });
expect((await subscriptionCostReport(db, c, other)).accounts).toEqual([]);
expect((await subscriptionCostReport(db, c, owner)).accounts[0]).toMatchObject({ canEdit: true, shared: false, ownerUserId: null });
});
it.each([false, true])("keeps another member's personal fees private from cost readers (manager: %s)", async (canManage) => {
const c = await company(), input = await connection(c), id = await verifiedConnection(input);
await price(c, id, "1234", { plan: "Private negotiated plan" });
await event(c, id, "subscription_included");
const hidden = await subscriptionCostReport(db, c, { userId: "bob", canManage }, { allTime: true });
expect(hidden.accounts).toEqual([]);
expect(hidden.monthlyTotals).toEqual([]);
expect(hidden.activeCount).toBe(0);
expect(hidden.unknownPriceCount).toBe(0);
expect(hidden.subscription.eventCount).toBe(1);
expect(hidden.unattributedSubscription.eventCount).toBe(0);
expect(JSON.stringify(hidden)).not.toMatch(/Private negotiated plan|alice|1234/);
const visible = await subscriptionCostReport(db, c, { ...owner, readOnly: true });
expect(visible.accounts[0]).toMatchObject({ id, canEdit: false, price: { amountCents: "1234.0000000" } });
});
it("respects shared connection audiences while retaining managers' access after disconnection", async () => {
const c = await company(), input = await connection(c, token(), "openai", null), id = await verifiedConnection(input);
await db.insert(connectionGrantMembers).values({ companyId: c, grantId: input.grantId, subjectType: "user", subjectId: "bob" });
expect((await subscriptionCostReport(db, c, owner)).accounts).toEqual([]);
expect((await subscriptionCostReport(db, c, { ...other, canManage: false })).accounts[0]).toMatchObject({ id, shared: true, canEdit: false });
expect((await subscriptionCostReport(db, c, { ...owner, canManage: true })).accounts[0]).toMatchObject({ id, canEdit: true });
await db.delete(connectionGrants).where(eq(connectionGrants.id, input.grantId));
expect((await subscriptionCostReport(db, c, { ...other, canManage: false })).accounts).toEqual([]);
expect((await subscriptionCostReport(db, c, { ...owner, canManage: true })).accounts[0].id).toBe(id);
});
it.each([false, true])("revokes shared fee visibility through the public revoke service (restricted audience: %s)", async (restricted) => {
const c = await company(), input = await connection(c, token(), "openai", null), id = await verifiedConnection(input);
expect(await verifiedConnection(await connection(c))).toBe(id);
if (restricted) await db.insert(connectionGrantMembers).values({ companyId: c, grantId: input.grantId, subjectType: "user", subjectId: "bob" });
await event(c, id, "subscription_included");
const reader = { userId: "bob", canManage: false };
expect((await subscriptionCostReport(db, c, reader, { allTime: true })).accounts[0]).toMatchObject({ id, usage: { eventCount: 1 } });
await toolAccessService(db).revokeConnectionGrant(input.connectionId, input.grantId, { actorType: "user", actorId: "alice" });
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, input.grantId));
expect(grant.status).toBe("revoked");
expect(await db.select().from(connectionGrantMembers).where(eq(connectionGrantMembers.grantId, input.grantId))).toHaveLength(restricted ? 1 : 0);
const hidden = await subscriptionCostReport(db, c, reader, { allTime: true });
expect(hidden.accounts).toEqual([]);
expect(hidden.monthlyTotals).toEqual([]);
expect(hidden.activeCount).toBe(0);
expect(hidden.subscription.eventCount).toBe(1);
expect(hidden.unattributedSubscription.eventCount).toBe(0);
expect(JSON.stringify(hidden)).not.toContain(id);
for (const editor of [owner, { userId: "carol", canManage: true }]) {
const report = await subscriptionCostReport(db, c, editor);
expect(report.accounts[0]).toMatchObject({ id, canEdit: true });
expect(report.monthlyTotals[0].amountCents).toBe("2000.0000000");
}
// A different active shared grant can independently authorize the reader.
expect(await verifiedConnection(await connection(c, token(), "openai", null))).toBe(id);
expect((await subscriptionCostReport(db, c, reader)).accounts[0].id).toBe(id);
});
it("keeps private linked-account usage out of details without calling it unattributed", async () => {
const c = await company(), service = subscriptionService(db);
const a = await service.register(await connection(c, "private-a", "anthropic"));
const b = await service.register(await connection(c, "private-b", "anthropic"));
await event(c, a, "subscription_included"); await event(c, b, "subscription_included");
await event(c, null, "subscription_included");
await service.merge(c, a, b, 0, 0, owner);
const hidden = await subscriptionCostReport(db, c, other, { allTime: true });
expect(hidden.accounts).toEqual([]);
expect(hidden.subscription.eventCount).toBe(3);
expect(hidden.unattributedSubscription.eventCount).toBe(1);
expect(JSON.stringify(hidden)).not.toContain(a);
expect(JSON.stringify(hidden)).not.toContain(b);
});
it("reports only current prices while preserving accumulated revisions for auditing", async () => {
const c = await company(), service = subscriptionService(db);
const id = await service.register(await connection(c));
await db.insert(aiSubscriptionPrices).values(Array.from({ length: 500 }, (_, i) => ({
companyId: c, subscriptionId: id, revision: i + 1, plan: `Historic plan ${i}`, amountCents: "1000", source: "user" as const,
})));
await db.update(aiSubscriptions).set({ revision: 500 }).where(eq(aiSubscriptions.id, id));
const report = await subscriptionCostReport(db, c, owner);
expect(report.accounts[0].price).toMatchObject({ revision: 500, plan: "Historic plan 499" });
expect(report.accounts[0]).not.toHaveProperty("history");
expect(JSON.stringify(report)).not.toContain("Historic plan 498");
expect(await db.select().from(aiSubscriptionPrices).where(eq(aiSubscriptionPrices.subscriptionId, id))).toHaveLength(501);
});
it("never lets an admin overwrite another user's personal price or cross a company boundary", async () => {
const c = await company(), id = await subscriptionService(db).register(await connection(c));
await expect(price(c, id, "10000", {}, other)).rejects.toMatchObject({ status: 403 });
await expect(price(await company(), id)).rejects.toMatchObject({ status: 404 });
await expect(price(c, id, "10000", {}, { ...owner, readOnly: true })).rejects.toMatchObject({ status: 403 });
const input = { expectedRevision: 0, plan: "Plus", amountCents: "1234", currency: "USD" as const, cadence: "month" as const, status: "active" as const };
const results = await Promise.allSettled([subscriptionService(db).updatePrice(c, id, input, owner), subscriptionService(db).updatePrice(c, id, { ...input, amountCents: "5678" }, owner)]);
expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1);
expect(results.filter(result => result.status === "rejected")).toHaveLength(1);
});
it("commits the price and audit record even if live notification fails", async () => {
const c = await company(), id = await subscriptionService(db).register(await connection(c));
const publish = vi.spyOn(liveEvents, "publishLiveEvent").mockImplementationOnce(() => { throw new Error("fixture subscriber unavailable"); });
try {
await expect(price(c, id, "1900")).resolves.toMatchObject({ revision: 1 });
expect((await subscriptionCostReport(db, c, owner)).accounts[0].price.amountCents).toBe("1900.0000000");
expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, c), eq(activityLog.action, "subscription.price_updated")))).toHaveLength(1);
} finally { publish.mockRestore(); }
});
it("merges duplicate usage once and retains the selected price", async () => {
const c = await company(), service = subscriptionService(db);
const a = await service.register(await connection(c, "claude-token-a", "anthropic"));
const b = await service.register(await connection(c, "claude-token-b", "anthropic"));
await price(c, a, "10000"); await price(c, b, "20000");
await event(c, a, "subscription_included"); await event(c, b, "subscription_overage", "200");
await service.merge(c, a, b, 1, 1, owner);
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
expect(report.activeCount).toBe(1);
expect(report.monthlyTotals[0].amountCents).toBe("20000.0000000");
expect(report.accounts[0].usage).toMatchObject({ eventCount: 2, inputTokens: 200, cachedInputTokens: 80, outputTokens: 20, costCents: "200.0000000" });
expect(report.accounts[0].agents).toHaveLength(2);
await expect(service.merge(c, b, a, 1, 2, owner)).rejects.toMatchObject({ status: 409 });
const different = await service.register(await connection(c));
await expect(service.merge(c, b, different, 1, 0, owner)).rejects.toMatchObject({ status: 409 });
});
it("separates API, subscriptions, overages and other billing with exclusive cache counters", async () => {
const c = await company(), id = await verifiedConnection(await connection(c));
await event(c, null, "metered_api", "123"); await event(c, id, "subscription_included");
await event(c, id, "subscription_overage", "456"); await event(c, null, "unknown", "789");
await event(c, null, "credits", "100"); await event(c, null, "fixed", "200");
await event(c, null, "subscription_included"); await event(c, id, "subscription_included", "0", new Date("2026-09-01"));
const report = await subscriptionCostReport(db, c, owner, { from: new Date("2026-10-01"), to: new Date("2026-11-01") });
expect(report.api.costCents).toBe("123.0000000");
expect(report.subscription.costCents).toBe("456.0000000");
expect(report.subscription.inputTokens + report.subscription.cachedInputTokens + report.subscription.outputTokens).toBe(450);
expect(report.unknown.costCents).toBe("1089.0000000");
expect(report.unknown.eventCount).toBe(3);
expect(report.unknown.inputTokens + report.unknown.cachedInputTokens + report.unknown.outputTokens).toBe(450);
expect(report.unattributedSubscription.eventCount).toBe(1);
expect(report.accounts[0].usage.eventCount).toBe(2);
expect(report.monthlyTotals[0].amountCents).toBe("2000.0000000");
});
it("snapshots account attribution, rejects forged attribution, and preserves receipt replay", async () => {
const c = await company(), input = await connection(c), service = subscriptionService(db);
const original = await service.register(input);
const agentId = randomUUID(), runId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId: c, name: "Codie", role: "engineer", adapterType: "codex_local" });
await db.insert(heartbeatRuns).values({ id: runId, companyId: c, agentId, invocationSource: "on_demand", status: "succeeded", contextSnapshot: { aiConnection: { subscriptionId: original, provider: "openai" } } });
const replacement = await service.register({ ...input, credential: token("other-workspace") });
expect(replacement).not.toBe(original);
const receipt = { agentId, heartbeatRunId: runId, idempotencyKey: "subscription-test", provider: "openai", billingType: "subscription_included" as const, model: "fixture", inputTokens: 10, costCents: "0", occurredAt: new Date() };
const saved = await costService(db).createEvent(c, { ...receipt, subscriptionId: replacement });
expect(saved.subscriptionId).toBe(original);
expect((await costService(db).createEvent(c, receipt)).id).toBe(saved.id);
const report = await subscriptionCostReport(db, c, owner, { allTime: true });
expect(report.accounts.find(row => row.id === original)?.usage.eventCount).toBe(1);
expect(report.accounts.find(row => row.id === replacement)?.usage.eventCount).toBe(0);
// Legacy or foreign context must not make a valid receipt fail or leak an account.
const foreign = await service.register(await connection(await company()));
for (const subscriptionId of ["malformed-legacy-id", foreign]) {
await db.update(heartbeatRuns).set({ contextSnapshot: { aiConnection: { subscriptionId, provider: "openai" } } }).where(eq(heartbeatRuns.id, runId));
const unlinked = await costService(db).createEvent(c, { ...receipt, idempotencyKey: subscriptionId });
expect(unlinked.subscriptionId).toBeNull();
}
});
it("preserves successful observations and manual prices through provider failures", async () => {
const c = await company(), input = await connection(c), service = subscriptionService(db), id = await service.register(input);
const request = fixtureRequest(usage());
await Promise.all([refreshSubscriptionConnection(db, input, id, request), refreshSubscriptionConnection(db, input, id, request)]);
expect(request).toHaveBeenCalledTimes(1);
await refreshSubscriptionConnection(db, input, id, request);
expect(request).toHaveBeenCalledTimes(1);
await price(c, id, "1750");
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
await refreshSubscriptionConnection(db, input, id, vi.fn<typeof fetch>().mockRejectedValue(new Error("SECRET raw provider failure")));
const report = await subscriptionCostReport(db, c, owner);
expect(report.accounts[0]).toMatchObject({ detectedPlan: "plus", refreshStatus: "unavailable", price: { amountCents: "1750.0000000" } });
expect(report.accounts[0].observedAt).not.toBeNull();
expect(JSON.stringify(report)).not.toContain("SECRET");
await db.update(aiSubscriptions).set({ lastCheckedAt: new Date(0) }).where(eq(aiSubscriptions.id, id));
await refreshSubscriptionConnection(db, input, id, fixtureRequest(usage("pro")));
expect((await subscriptionCostReport(db, c, owner)).accounts[0].price.amountCents).toBe("1750.0000000");
});
it("ignores a delayed provider observation after reconnecting another account", async () => {
const c = await company(), input = await connection(c), service = subscriptionService(db), id = await service.register(input);
let finish!: (response: Response) => void;
let started!: () => void;
const ready = new Promise<void>(resolve => { started = resolve; });
const request = vi.fn<typeof fetch>().mockImplementation(() => { started(); return new Promise<Response>(resolve => { finish = resolve; }); });
const pending = refreshSubscriptionConnection(db, input, id, request);
await ready;
const next = await service.register({ ...input, credential: token("new-workspace") });
finish(Response.json(usage("pro"))); await pending;
const [binding] = await db.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, c), eq(aiSubscriptionConnections.grantId, input.grantId)));
expect(binding.subscriptionId).toBe(next);
expect((await db.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, next)))[0].detectedPlan).toBe("plus");
});
});
+43
View File
@@ -1,4 +1,9 @@
import { importProviderDailyCosts } from "../services/provider-billing-import.js";
import { subscriptionPriceSchema, mergeSubscriptionsSchema } from "@paperclipai/shared";
import { subscriptionService } from "../services/subscriptions.js";
import { subscriptionCostReport } from "../services/subscription-report.js";
import { refreshCompanySubscriptions } from "../services/subscription-refresh.js";
import { canManageAiConnections } from "./ai-connections.js";
import { importProviderCostsSchema } from "@paperclipai/shared";
import { accountingIntegrityService } from "../services/accounting-integrity.js";
import { billingReconciliationService } from "../services/billing-reconciliation.js";
@@ -79,6 +84,44 @@ export function costRoutes(
const issues = issueService(db);
const access = accessService(db);
async function subscriptionActor(req: Parameters<typeof assertCompanyAccess>[0], companyId: string) {
assertBoard(req);
assertCompanyAccess(req, companyId);
return { userId: getActorInfo(req).actorId, canManage: await canManageAiConnections(db, req, companyId),
readOnly: req.actor.memberships?.some(member => member.companyId === companyId && member.membershipRole === "viewer") ?? false };
}
router.get("/companies/:companyId/costs/subscriptions", async (req, res) => {
const companyId = req.params.companyId as string;
const actor = await subscriptionActor(req, companyId);
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
res.json(await subscriptionCostReport(db, companyId, actor, parseCostDateRange(req.query)));
});
router.post("/companies/:companyId/costs/subscriptions/refresh", async (req, res) => {
const companyId = req.params.companyId as string;
const actor = await subscriptionActor(req, companyId);
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
if (actor.readOnly) throw forbidden("Viewers cannot refresh subscription accounts");
void refreshCompanySubscriptions(db, companyId, actor.userId);
res.status(202).json({ status: "accepted" });
});
router.patch("/companies/:companyId/costs/subscriptions/:subscriptionId", validate(subscriptionPriceSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const actor = await subscriptionActor(req, companyId);
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
const id = z.string().uuid().safeParse(req.params.subscriptionId);
if (!id.success) throw badRequest("Invalid subscription ID");
res.json(await subscriptionService(db).updatePrice(companyId, id.data, req.body, actor));
});
router.post("/companies/:companyId/costs/subscriptions/:subscriptionId/link", validate(mergeSubscriptionsSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const actor = await subscriptionActor(req, companyId);
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
const id = z.string().uuid().safeParse(req.params.subscriptionId);
if (!id.success) throw badRequest("Invalid subscription ID");
res.json(await subscriptionService(db).merge(companyId, id.data, req.body.targetId, req.body.expectedRevision, req.body.targetRevision, actor));
});
async function resolveIssueByRef(rawId: string) {
const identifier = normalizeIssueIdentifier(rawId);
if (identifier) {
+9 -1
View File
@@ -9,6 +9,7 @@ import { agentService } from "../services/agents.js";
import { notFound } from "../errors.js";
import { accessService } from "../services/access.js";
import { dotRunnerBroker } from "../services/dot-runner-broker.js";
import { canConfigureAgentConnection } from "../modules/agent-lifecycle/index.js";
export function dotRunnerRoutes(db: Db, resourceUrl?: string) {
const router = Router();
@@ -48,7 +49,14 @@ export function dotRunnerRoutes(db: Db, resourceUrl?: string) {
const agent = await agentService(db).getById(input.agentId);
if (!agent || agent.companyId !== input.companyId) throw notFound("Agent not found");
const config = resourceUrl ? null : publicMcpConfig(process.env);
res.json({ agentStatus: agent.status, enabled: await broker.enabled(), resourceUrl: resourceUrl ?? (config ? config.origin + "/mcp/runner" : null), binding: await broker.bindingForAgent(input.companyId, input.agentId) });
res.json({
agentStatus: agent.status,
agentLifecycleState: agent.lifecycleState,
canConfigureConnection: canConfigureAgentConnection(agent),
enabled: await broker.enabled(),
resourceUrl: resourceUrl ?? (config ? config.origin + "/mcp/runner" : null),
binding: await broker.bindingForAgent(input.companyId, input.agentId),
});
});
router.post(path, async (req, res) => {
const input = scope(req, true);
+22
View File
@@ -5,6 +5,7 @@ import {
experimentalApiQueries,
} from "./experimental-api-paths.js";
import { Router } from "express";
import { subscriptionPriceSchema, mergeSubscriptionsSchema } from "@paperclipai/shared";
import { z } from "zod";
import {
createAiConnectionSchema,
@@ -5567,6 +5568,7 @@ const costSummaryPaths = [
"finance-events",
"window-spend",
"quota-windows",
"subscriptions",
] as const;
for (const segment of costSummaryPaths) {
@@ -5585,6 +5587,26 @@ for (const segment of costSummaryPaths) {
});
}
registry.registerPath({ method: "post", path: "/api/companies/{companyId}/costs/subscriptions/refresh", tags: ["costs"],
summary: "Refresh connected subscription estimates in the background",
description: "Board members only. Probes only credentials the caller can use. Successful observations are cached for six hours; provider failures retain prior estimates. No inference requests, invoices, or budget charges are created.",
request: { params: z.object({ companyId: z.string() }) },
responses: { 202: { description: "Background refresh accepted" }, 401: r.unauthorized, 403: r.forbidden,
429: { description: "Discovery capacity is full; retry the request later" } },
});
registry.registerPath({ method: "patch", path: "/api/companies/{companyId}/costs/subscriptions/{subscriptionId}", tags: ["costs"],
summary: "Set a subscription price or end tracking",
description: "Owner only for personal subscriptions; connection managers for shared subscriptions. Appends price history from now. Expected revision prevents lost updates. Ending tracking does not cancel provider billing. Monthly estimates never change recorded charges or agent budgets.",
request: { params: z.object({ companyId: z.string(), subscriptionId: z.string().uuid() }), body: jsonBody(subscriptionPriceSchema) },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
});
registry.registerPath({ method: "post", path: "/api/companies/{companyId}/costs/subscriptions/{subscriptionId}/link", tags: ["costs"],
summary: "Link duplicate subscription accounts",
description: "Requires editing permission on both accounts in this company. Combines their usage, counts the fee once, and keeps the target price. Historical run IDs and price history are preserved.",
request: { params: z.object({ companyId: z.string(), subscriptionId: z.string().uuid() }), body: jsonBody(mergeSubscriptionsSchema) },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
});
registry.registerPath({
method: "post",
path: "/api/companies/{companyId}/cost-events",
+14 -2
View File
@@ -12,6 +12,8 @@ import {
} from "@paperclipai/shared";
import { managedProviderRouting } from "./ai-provider-routing.js";
import { aiConnectionService } from "./ai-connections.js";
import { subscriptionService } from "./subscriptions.js";
import { refreshSubscriptionConnection } from "./subscription-refresh.js";
import { secretService } from "./secrets.js";
import { decideCodexAuthMerge, withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
import { WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from "@paperclipai/adapter-utils/workspace-restore-merge";
@@ -354,6 +356,16 @@ export async function prepareManagedAiRuntime(
if (projected.hermesConfig) await writeFile(path.join(providerHome, "config.yaml"), projected.hermesConfig, { mode: 0o600 });
if (projected.codexConfig) await writeFile(path.join(providerHome, "config.toml"), 'cli_auth_credentials_store = "file"\n' + projected.codexConfig, { mode: 0o600 });
}
const attribution = { ...selection.attribution } as typeof selection.attribution & { subscriptionId?: string };
if (attribution.method === "subscription") {
const subscription = {
companyId: input.companyId, connectionId: selection.connection.id, grantId: selection.grant.id,
provider: selection.attribution.provider, name: selection.connection.name,
ownerUserId: selection.grant.subjectUserId, credential: value,
};
attribution.subscriptionId = await subscriptionService(db).register(subscription);
void refreshSubscriptionConnection(db, subscription, attribution.subscriptionId);
}
const generation = createHash("sha256")
.update(value)
.digest("hex")
@@ -367,9 +379,9 @@ export async function prepareManagedAiRuntime(
...projected?.config,
...(routing ? { managedAiRouting: routing } : {}),
env,
managedAiConnection: { ...selection.attribution, identity, sessionIdentity },
managedAiConnection: { ...attribution, identity, sessionIdentity },
},
attribution: selection.attribution,
attribution,
accountName: selection.connection.name,
accountOwnerUserId: selection.grant.subjectUserId,
identity,
+1 -1
View File
@@ -63,7 +63,7 @@ class ProbeFailure extends Error {
constructor(readonly code: NonNullable<AiConnectionUsage["errorCode"]>) { super(code); }
}
async function readUsage(url: string, headers: Record<string, string>, request: typeof fetch): Promise<ObjectValue> {
export async function readUsage(url: string, headers: Record<string, string>, request: typeof fetch): Promise<ObjectValue> {
// Fixed origins, no redirects, and a deadline covering headers AND response bytes.
const response = await request(url, {
headers, redirect: "error", signal: AbortSignal.timeout(15000),
+3 -3
View File
@@ -1084,15 +1084,15 @@ export function aiConnectionService(db: Db) {
}
// A quota read uses the same credential audience as execution. Operator status
// alone never grants access to another member's personal subscription.
async function quotaAccounts(companyId: string, userId: string) {
async function quotaAccounts(companyId: string, userId: string, includeOtherProviders = false) {
if (!(await membership(companyId, userId))) return [];
const visible = await list(companyId, userId);
const accounts = await rows(companyId);
return accounts.flatMap(row => {
const summary = visible.find(item => item.id === row.connection.id && item.grantId === row.grant.id);
if (!summary || summary.method !== "subscription" || !["openai", "anthropic"].includes(summary.provider)) return [];
if (!summary || summary.method !== "subscription" || !(includeOtherProviders ? ["openai", "anthropic", "xai"] : ["openai", "anthropic"]).includes(summary.provider)) return [];
return [{ ...row, summary }];
});
}
return { list, selectDecision, quotaAccounts, refreshQuotaCredential, select, credential, runtimeCredential, probeUsage, save, setDefault, membership, markAuthenticationFailed };
return { list, selectDecision, quotaAccounts, subscriptionAccounts: (companyId: string, userId: string) => quotaAccounts(companyId, userId, true), refreshQuotaCredential, select, credential, runtimeCredential, probeUsage, save, setDefault, membership, markAuthenticationFailed };
}
+15 -5
View File
@@ -1,9 +1,9 @@
import { receiptFingerprint } from "./receipt-fingerprint.js";
import { agentAvatarUrl, resolveAgentAppearance, createCostEventSchema, createServiceCostEventSchema, normalizeCents, type MoneyInput, type CostByUserReport } from "@paperclipai/shared";
import { agentAvatarUrl, resolveAgentAppearance, createCostEventSchema, createServiceCostEventSchema, normalizeCents, isUuidLike, type MoneyInput, type CostByUserReport } from "@paperclipai/shared";
import { and, desc, eq, gte, inArray, isNotNull, isNull, lt, lte, ne, sql } from "drizzle-orm";
import { alias } from "drizzle-orm/pg-core";
import type { Db } from "@paperclipai/db";
import { activityLog, agents, agentRuntimeState, authUsers, companies, companyMemberships, costEvents, heartbeatRuns, issues, projects, goals } from "@paperclipai/db";
import { activityLog, agents, agentRuntimeState, authUsers, companies, companyMemberships, costEvents, heartbeatRuns, issues, projects, goals, aiSubscriptions } from "@paperclipai/db";
import { notFound, unprocessable, conflict } from "../errors.js";
import { budgetService, budgetServiceInTransaction, type BudgetServiceHooks } from "./budgets.js";
import { logActivity, type LogActivityInput, type ActivityPublication } from "./activity-log.js";
@@ -20,7 +20,7 @@ const SUBSCRIPTION_BILLING_TYPES = ["subscription_included", "subscription_overa
// provider-qualified model IDs and already excluded cache reads. Normalize each
// historical row before aggregation so mixed old/new groups share the current
// exclusive-input contract. Preserve the original ledger and monetary amounts.
const ordinaryInputTokens = sql<number>`case
export const ordinaryInputTokens = sql<number>`case
when ${costEvents.receiptHash} is null and ${costEvents.provider} = 'openai'
and ${costEvents.model} not like 'openai/_%'
then greatest(0, ${costEvents.inputTokens} - ${costEvents.cachedInputTokens})
@@ -124,11 +124,19 @@ export async function createCostEventInTransaction(db: Db, companyId: string, da
if (!row) throw notFound(`${label} not found`);
if (row.companyId !== companyId) throw unprocessable(`${label} does not belong to company`);
}
let subscriptionId: string | null = null;
if (values.heartbeatRunId) {
const [run] = await db.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(eq(heartbeatRuns.id, values.heartbeatRunId));
const [run] = await db.select({ agentId: heartbeatRuns.agentId, context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns).where(eq(heartbeatRuns.id, values.heartbeatRunId));
if (run.agentId !== values.agentId) throw unprocessable("Heartbeat run does not belong to agent");
const attribution = run.context?.aiConnection as { subscriptionId?: unknown; provider?: unknown } | undefined;
if (SUBSCRIPTION_BILLING_TYPES.includes(values.billingType as typeof SUBSCRIPTION_BILLING_TYPES[number]) && attribution?.provider === values.provider && typeof attribution.subscriptionId === "string" && isUuidLike(attribution.subscriptionId)) {
const [account] = await db.select({ id: aiSubscriptions.id }).from(aiSubscriptions).where(and(eq(aiSubscriptions.id, attribution.subscriptionId), eq(aiSubscriptions.companyId, companyId), eq(aiSubscriptions.provider, values.provider)));
subscriptionId = account?.id ?? null;
}
}
const [event] = await db.insert(costEvents).values({ ...values, costCents: sql`${values.costCents}::numeric`, reportedCostCents: values.costCents, id: data.id, companyId, receiptHash }).returning();
// Server-derived attribution stays outside the immutable receipt fingerprint;
// replaying a receipt must not depend on later account metadata changes.
const [event] = await db.insert(costEvents).values({ ...values, subscriptionId, costCents: sql`${values.costCents}::numeric`, reportedCostCents: values.costCents, id: data.id, companyId, receiptHash }).returning();
await updateMonthlySpendProjections(db, companyId, event.agentId, values.costCents, event.occurredAt);
// Separately reported charges linked to an already-accounted run contribute
// to lifetime totals too. Before acknowledgement, accountRunCost includes
@@ -676,6 +684,8 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
.select({
projectId: projects.id,
projectName: projects.name,
eventCount: sql<number>`count(*)::int`,
estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,
costCents: costCentsExpr,
costCentsExact: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,
inputTokens: sumAsNumber(ordinaryInputTokens),
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,284 @@
import { randomUUID } from "node:crypto";
import type { Db } from "@paperclipai/db";
import {
agents, agentSessionGoalActions, agentTaskSessions, companies, createDb,
EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues,
} from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { conflict } from "../../errors.js";
import { createHeartbeatRunPreparation } from "./run-preparation.js";
import { createHeartbeatRunState } from "./run-state.js";
import { createHeartbeatScheduling, type HeartbeatSchedulingDependencies } from "./scheduling.js";
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
type Run = typeof heartbeatRuns.$inferSelect;
const now = new Date("2026-10-09T12:00:00.000Z");
const dueAt = new Date(now.getTime() - 60_000);
const admitted = { id: "admitted-run" } as Run;
const timerPolicy = {
enabled: false, intervalSec: 60, wakeOnDemand: true, maxConcurrentRuns: 1,
skipTimerWhenNoActionableWork: false, maxDailyRuns: null, maxDailyCostCents: null,
};
function callbacks(db: Db) {
const state = createHeartbeatRunState(db);
const preparation = createHeartbeatRunPreparation(db);
return {
getAgent: state.getAgent,
getRun: state.getRun,
toAgentOrgRow: preparation.toAgentOrgRow,
groupAgentOrgRowsByCompany: preparation.groupAgentOrgRowsByCompany,
issuesSvc: {
listReviewAttention: vi.fn<HeartbeatSchedulingDependencies["issuesSvc"]["listReviewAttention"]>(async () => new Map()),
create: vi.fn<HeartbeatSchedulingDependencies["issuesSvc"]["create"]>(),
},
enqueueWakeup: vi.fn<HeartbeatSchedulingDependencies["enqueueWakeup"]>(async () => admitted),
scheduleBoundedRetryForRun: vi.fn<HeartbeatSchedulingDependencies["scheduleBoundedRetryForRun"]>(),
getSchedulingSuppression: vi.fn(async () => ({ suppressed: false })),
getWorktreeExecutionCutoff: vi.fn<HeartbeatSchedulingDependencies["getWorktreeExecutionCutoff"]>(async () => null),
parseHeartbeatPolicy: vi.fn<HeartbeatSchedulingDependencies["parseHeartbeatPolicy"]>(() => timerPolicy),
claimDueTimerHeartbeat: vi.fn<HeartbeatSchedulingDependencies["claimDueTimerHeartbeat"]>(async () => ({ wasFirstHeartbeat: true })),
} satisfies HeartbeatSchedulingDependencies;
}
describe("heartbeat scheduling module boundary", () => {
function guardedDatabase() {
const access = vi.fn(() => { throw new Error("Unexpected scheduling database access"); });
return { db: new Proxy({}, { get: access }) as Db, access };
}
it("constructs without querying, admitting work, or starting timers", () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
createHeartbeatScheduling(database.db, deps);
expect(database.access).not.toHaveBeenCalled();
for (const callback of Object.values(deps)) if (vi.isMockFunction(callback)) expect(callback).not.toHaveBeenCalled();
});
it.each(["tickTimers", "recoverActiveSessionGoals", "recoverPendingSessionGoalActions"] as const)(
"honors suppression before %s reads or admits work", async (operation) => {
const database = guardedDatabase();
const deps = callbacks(database.db);
deps.getSchedulingSuppression.mockResolvedValue({ suppressed: true });
const result = await createHeartbeatScheduling(database.db, deps)[operation]();
expect(Object.values(result).every(value => value === 0)).toBe(true);
expect(database.access).not.toHaveBeenCalled();
expect(deps.enqueueWakeup).not.toHaveBeenCalled();
expect(deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
},
);
});
const postgres = await getEmbeddedPostgresTestSupport();
describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-scheduling-module");
db = createDb(database.connectionString);
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterAll(async () => {
await db?.$client.end();
await database?.cleanup();
});
beforeEach(async () => {
await db.execute(sql`truncate table companies restart identity cascade`);
});
async function fixture() {
const [company] = await db.insert(companies).values({ name: "Scheduling", issuePrefix: "SCH" }).returning();
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Scheduled agent", adapterType: "paperclip_runner", createdAt: dueAt }).returning();
const [issue] = await db.insert(issues).values({
companyId: company.id, title: "Check deployment", status: "in_progress", assigneeAgentId: agent.id,
monitorNextCheckAt: dueAt, monitorAttemptCount: 0, createdAt: dueAt,
executionPolicy: { mode: "normal", commentRequired: true, stages: [], monitor: { nextCheckAt: dueAt.toISOString() } },
}).returning();
const deps = callbacks(db);
return { company, agent, issue, deps, scheduler: createHeartbeatScheduling(db, deps) };
}
async function readIssue(id: string) {
return db.select().from(issues).where(eq(issues.id, id)).then(rows => rows[0]!);
}
async function session(f: Awaited<ReturnType<typeof fixture>>, patch: Partial<typeof agentTaskSessions.$inferInsert> = {}) {
return db.insert(agentTaskSessions).values({
companyId: f.company.id, agentId: f.agent.id, adapterType: f.agent.adapterType, taskKey: f.issue.id,
goalDesiredState: "active", goalStatus: "active", goalRevision: 7, ...patch,
}).returning().then(rows => rows[0]!);
}
function enableTimer(deps: ReturnType<typeof callbacks>) {
deps.parseHeartbeatPolicy.mockReturnValue({ ...timerPolicy, enabled: true });
deps.parseHeartbeatPolicy.mockClear();
}
it("shares database monitor claims across scheduler instances", async () => {
const f = await fixture();
let release!: () => void;
let entered!: () => void;
const started = new Promise<void>(resolve => { entered = resolve; });
const hold = new Promise<void>(resolve => { release = resolve; });
f.deps.enqueueWakeup.mockImplementationOnce(async () => { entered(); await hold; return admitted; });
const first = f.scheduler.tickTimers(now);
try {
await started;
const second = createHeartbeatScheduling(db, f.deps);
expect(await second.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 });
await expect(second.triggerIssueMonitor(f.issue.id, { now })).rejects.toThrow("already in progress");
} finally {
release();
await first;
}
expect(f.deps.enqueueWakeup).toHaveBeenCalledTimes(1);
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: null, monitorAttemptCount: 1 });
});
it("preserves a replacement schedule written during wake admission", async () => {
const f = await fixture();
const replacement = new Date(now.getTime() + 60_000);
f.deps.enqueueWakeup.mockImplementationOnce(async () => {
await db.update(issues).set({ monitorNextCheckAt: replacement, monitorWakeRequestedAt: null }).where(eq(issues.id, f.issue.id));
return admitted;
});
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 });
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: replacement, monitorAttemptCount: 0 });
});
it("retains a deferred monitor and releases its claim for a later tick", async () => {
const f = await fixture();
f.deps.enqueueWakeup.mockResolvedValueOnce(null);
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 });
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null, monitorAttemptCount: 0 });
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
const calls = f.deps.enqueueWakeup.mock.calls;
expect(calls[0]![1]!.idempotencyKey).toBe(calls[1]![1]!.idempotencyKey);
expect(calls[0]![1]!.issueStateGuard).toMatchObject({
assigneeAgentId: f.agent.id, statuses: ["in_progress"], monitorNextCheckAt: dueAt.toISOString(), monitorWakeRequestedAt: now.toISOString(),
});
});
it("keeps manual error recovery distinct from scheduled client-error handling", async () => {
const f = await fixture();
f.deps.enqueueWakeup.mockRejectedValue(conflict("Agent is paused"));
await expect(f.scheduler.triggerIssueMonitor(f.issue.id, { now, actorType: "user", actorId: "board-user" })).rejects.toThrow("Agent is paused");
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null });
expect(f.deps.enqueueWakeup).toHaveBeenLastCalledWith(f.agent.id, expect.objectContaining({
source: "on_demand", requestedByActorType: "user", requestedByActorId: "board-user",
}));
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 });
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: null });
});
it("retains monitors after transient admission failures", async () => {
const f = await fixture();
f.deps.enqueueWakeup.mockRejectedValueOnce(new Error("Temporary admission failure"));
await f.scheduler.tickTimers(now);
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null });
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
});
it("leaves monitors alone while a native run owns the issue", async () => {
const f = await fixture();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, nativeIssueId: f.issue.id, runtimeMode: "native", status: "running", contextSnapshot: { issueId: f.issue.id } }).returning();
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 });
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run!.id));
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
});
it("skips archived companies for both timers and monitors", async () => {
const f = await fixture();
enableTimer(f.deps);
await db.update(companies).set({ status: "archived" }).where(eq(companies.id, f.company.id));
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 });
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt });
});
it("combines timer and monitor counts and passes the timer claim receipt to admission", async () => {
const f = await fixture();
enableTimer(f.deps);
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 2, enqueued: 2, skipped: 0 });
expect(f.deps.claimDueTimerHeartbeat).toHaveBeenCalledWith(expect.objectContaining({ id: f.agent.id }), now, 60);
expect(f.deps.enqueueWakeup).toHaveBeenCalledWith(f.agent.id, expect.objectContaining({
source: "timer", reason: "heartbeat_timer", contextSnapshot: expect.objectContaining({ timerClaimWasFirstHeartbeat: true }),
}));
});
it("does not enqueue a timer after losing its due claim", async () => {
const f = await fixture();
enableTimer(f.deps);
await db.update(issues).set({ monitorNextCheckAt: null }).where(eq(issues.id, f.issue.id));
f.deps.claimDueTimerHeartbeat.mockResolvedValue(null);
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 0 });
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
});
it("enforces worktree cutoffs and agent invokability before timer claims", async () => {
const f = await fixture();
enableTimer(f.deps);
await db.update(issues).set({ monitorNextCheckAt: null }).where(eq(issues.id, f.issue.id));
f.deps.getWorktreeExecutionCutoff.mockResolvedValue(now);
await f.scheduler.tickTimers(now);
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
await db.update(issues).set({ createdAt: now }).where(eq(issues.id, f.issue.id));
await db.update(agents).set({ status: "paused" }).where(eq(agents.id, f.agent.id));
await f.scheduler.tickTimers(now);
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
await db.update(agents).set({ status: "idle" }).where(eq(agents.id, f.agent.id));
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
});
it("recovers active goals with stable revision-based admission keys", async () => {
const f = await fixture();
const active = await session(f);
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 1, enqueued: 1 });
expect(f.deps.enqueueWakeup).toHaveBeenCalledWith(f.agent.id, expect.objectContaining({
idempotencyKey: `goal_recovery:${active.id}:7`, contextSnapshot: { issueId: f.issue.id, taskKey: f.issue.id, resumeSessionGoalHeartbeat: true, skipIssueComment: true },
}));
f.deps.enqueueWakeup.mockResolvedValueOnce(null);
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 1, enqueued: 0 });
expect(f.deps.enqueueWakeup.mock.calls[1]![1]!.idempotencyKey).toBe(f.deps.enqueueWakeup.mock.calls[0]![1]!.idempotencyKey);
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issue.id));
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 0, enqueued: 0 });
});
it("excludes goals after reassignment or with a mismatched company binding", async () => {
const f = await fixture();
const [other] = await db.insert(companies).values({ name: "Other company", issuePrefix: "OTH" }).returning();
const active = await session(f, { companyId: other!.id });
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 0, enqueued: 0 });
await db.update(agentTaskSessions).set({ companyId: f.company.id }).where(eq(agentTaskSessions.id, active.id));
await db.update(issues).set({ assigneeAgentId: null }).where(eq(issues.id, f.issue.id));
expect(await f.scheduler.recoverActiveSessionGoals()).toEqual({ scanned: 0, enqueued: 0 });
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
});
it.each(["queued", "scheduled_retry", "running"])("deduplicates a pending goal action against a %s run", async status => {
const f = await fixture();
const active = await session(f);
const requestId = randomUUID();
const [action] = await db.insert(agentSessionGoalActions).values({ companyId: f.company.id, sessionId: active.id, requestId, action: "pause", payloadJson: { requestId, action: "pause" } }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status, contextSnapshot: { goalControlRequestId: requestId } }).returning();
expect(await f.scheduler.recoverPendingSessionGoalActions()).toEqual({ scanned: 1, enqueued: 0, alreadyQueued: 1, invalid: 0 });
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, run!.id));
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issue.id));
expect(await f.scheduler.recoverPendingSessionGoalActions()).toEqual({ scanned: 1, enqueued: 1, alreadyQueued: 0, invalid: 0 });
expect(f.deps.enqueueWakeup).toHaveBeenCalledWith(f.agent.id, expect.objectContaining({
idempotencyKey: `goal_control_recovery:${action!.id}`, contextSnapshot: expect.objectContaining({ resumeIntent: true, goalControlRequestId: requestId, runnerGoalControl: { requestId, action: "pause" } }),
}));
});
it("persists invalid goal actions as failures without wake admission", async () => {
const f = await fixture();
const active = await session(f);
const [action] = await db.insert(agentSessionGoalActions).values({ companyId: f.company.id, sessionId: active.id, requestId: "expected", action: "pause", payloadJson: { requestId: "different", action: "pause" } }).returning();
expect(await f.scheduler.recoverPendingSessionGoalActions()).toEqual({ scanned: 1, enqueued: 0, alreadyQueued: 0, invalid: 1 });
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
const failed = await db.select().from(agentSessionGoalActions).where(eq(agentSessionGoalActions.id, action!.id));
expect(failed[0]).toMatchObject({ status: "failed", error: "session_goal_control_payload_invalid" });
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,78 @@
import { createHash } from "node:crypto";
import { probeAiConnectionUsage, readUsage } from "./ai-connection-usage.js";
import type { AiProvider } from "@paperclipai/shared";
const object = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
const string = (value: unknown): string | null => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : null;
function json(value: string): Record<string, unknown> { try { return object(JSON.parse(value)); } catch { return {}; } }
function claims(value: unknown) {
if (typeof value !== "string" || value.length > 32768) return {};
return json(Buffer.from(value.split(".")[1] ?? "", "base64url").toString());
}
export function subscriptionIdentityKey(companyId: string, provider: string, parts: string[]): string {
return createHash("sha256").update(JSON.stringify([companyId, provider, ...parts])).digest("hex");
}
export interface SubscriptionIdentity {
credentialKey: string;
accountKey: string;
verified: boolean;
plan: string | null;
}
/** Credential-local hints cannot authenticate a provider account. In particular,
* a user may edit an ID token independently of the bearer token sent upstream.
* No ambient host credentials, emails, raw account IDs, or tokens leave this helper. */
export function subscriptionCredentialIdentity(companyId: string, provider: string, credential: string): SubscriptionIdentity {
const credentialKey = subscriptionIdentityKey(companyId, provider, ["credential", credential]);
const auth = json(credential);
let plan: string | null = null;
if (provider === "openai") {
const tokens = object(auth.tokens);
const token = claims(tokens.id_token);
const account = object(token["https://api.openai.com/auth"]);
plan = string(account.chatgpt_plan_type);
}
// Other credential formats do not yet prove a stable billing identity. Use a
// credential-scoped record until a profile observation or manual link proves it.
return { credentialKey, accountKey: credentialKey, verified: false, plan };
}
export async function probeSubscriptionIdentity(companyId: string, provider: AiProvider, credential: string, request: typeof fetch = fetch) {
const identity = subscriptionCredentialIdentity(companyId, provider, credential);
if (provider === "anthropic") {
// Same account-scoped OAuth profile used by Claude Code / CodexBar. A
// setup-token may lack user:profile; failure must preserve the prior record.
const profile = await readUsage("https://api.anthropic.com/api/oauth/profile", {
Authorization: `Bearer ${credential}`, "anthropic-beta": "oauth-2025-04-20",
}, request);
const account = object(profile.account), organization = object(profile.organization);
const seat = string(account.uuid), workspace = string(organization.uuid);
const type = string(organization.organization_type);
const tier = string(organization.rate_limit_tier);
const plan = type === "claude_max" && tier === "default_claude_max_5x" ? "max_5x"
: type === "claude_max" && tier === "default_claude_max_20x" ? "max_20x"
: ({ claude_pro: "pro", claude_max: "max", claude_team: "team", claude_enterprise: "enterprise" } as Record<string, string>)[type ?? ""] ?? null;
if (!seat || !workspace) throw new Error("Subscription profile unavailable");
return { ...identity, accountKey: subscriptionIdentityKey(companyId, provider, ["account", workspace, seat]), verified: true, plan };
}
const usage = await probeAiConnectionUsage({ provider, method: "subscription" }, credential, { request });
if (usage.status !== "ok") throw new Error("Subscription profile unavailable");
if (provider === "openai") {
// The usage request authenticated this exact bearer token with OpenAI.
// Only its claims may identify a seat; the separate ID token and editable
// account-id field cannot grant billing access. An opaque bearer or a
// selected workspace that differs from its claims stays unconfirmed.
const auth = json(credential), tokens = object(auth.tokens);
const token = claims(tokens.access_token ?? auth.accessToken);
const account = object(token["https://api.openai.com/auth"]);
const workspace = string(account.chatgpt_account_id);
const selectedWorkspace = string(tokens.account_id ?? auth.accountId);
const seat = string(account.chatgpt_user_id) ?? string(token.sub);
if (workspace && seat && (!selectedWorkspace || selectedWorkspace === workspace)) {
return { ...identity, accountKey: subscriptionIdentityKey(companyId, provider, ["account", workspace, seat]), verified: true, plan: string(usage.planType) };
}
}
return { ...identity, plan: string(usage.planType) };
}
@@ -0,0 +1,81 @@
import { and, eq, lt, or, isNull } from "drizzle-orm";
import { aiSubscriptions, aiSubscriptionConnections, type Db } from "@paperclipai/db";
import { aiConnectionService } from "./ai-connections.js";
import { subscriptionService, type SubscriptionConnection } from "./subscriptions.js";
import { probeSubscriptionIdentity } from "./subscription-identity.js";
import { logger } from "../middleware/logger.js";
import { tooManyRequests } from "../errors.js";
const jobs = new WeakMap<Db, Map<string, Promise<void>>>();
const discovery = new WeakMap<Db, Map<string, Promise<void>>>();
const REFRESH_MS = 6 * 60 * 60 * 1000;
/** Cached metadata refresh only. Never exchanges tokens or blocks a run/page on a provider. */
export function refreshSubscriptionConnection(db: Db, input: SubscriptionConnection, id: string, request: typeof fetch = fetch): Promise<void> {
let active = jobs.get(db);
if (!active) jobs.set(db, active = new Map());
const existing = active.get(id);
if (existing) return existing;
// Bound provider concurrency across all companies on this instance. Dashboard
// discovery waits below; opportunistic run observations remain due when busy.
if (active.size >= 4) return Promise.resolve();
const task = (async () => {
const [claimed] = await db.update(aiSubscriptions).set({ lastCheckedAt: new Date() }).where(and(
eq(aiSubscriptions.companyId, input.companyId), eq(aiSubscriptions.id, id),
or(isNull(aiSubscriptions.lastCheckedAt), lt(aiSubscriptions.lastCheckedAt, new Date(Date.now() - REFRESH_MS))),
)).returning({ id: aiSubscriptions.id });
if (!claimed) return;
try {
const observation = await probeSubscriptionIdentity(input.companyId, input.provider, input.credential, request);
// A later execution/reconnect may now use another account. Never replace
// that binding with a slow response for the previous credential.
const [binding] = await db.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, input.companyId), eq(aiSubscriptionConnections.grantId, input.grantId)));
if (binding?.credentialKey !== observation.credentialKey) return;
await subscriptionService(db).register(input, observation);
} catch {
await db.update(aiSubscriptions).set({ refreshStatus: "unavailable" }).where(and(eq(aiSubscriptions.companyId, input.companyId), eq(aiSubscriptions.id, id)));
}
})().catch(() => {
// No raw provider/credential errors are logged or returned to a user.
logger.warn({ companyId: input.companyId, subscriptionId: id }, "Subscription observation could not be saved");
}).finally(() => active!.delete(id));
active.set(id, task);
return task;
}
export function refreshCompanySubscriptions(db: Db, companyId: string, userId: string): Promise<void> {
let active = discovery.get(db);
if (!active) discovery.set(db, active = new Map());
const key = `${companyId}:${userId}`;
const existing = active.get(key);
if (existing) return existing;
if (active.size >= 20) throw tooManyRequests("Subscription account checks are busy. Try again shortly.");
const task = (async () => {
const service = aiConnectionService(db);
// Uses the existing credential audience. Being a company admin does not
// authorize probing another member's personal credentials.
for (const row of await service.subscriptionAccounts(companyId, userId)) {
if (row.summary.status !== "connected") continue;
try {
const credential = await service.credential(row);
const input: SubscriptionConnection = { companyId, connectionId: row.connection.id, grantId: row.grant.id,
provider: row.summary.provider, name: row.connection.name, ownerUserId: row.grant.subjectUserId, credential };
const id = await subscriptionService(db).register(input);
// Accepted discovery must not silently skip an account. At most twenty
// discovery tasks can wait here; never create an unbounded provider queue.
// Recheck after each completion because another discovery may take a slot.
let providers = jobs.get(db);
while (providers && providers.size >= 4 && !providers.has(id)) {
await Promise.race(providers.values());
providers = jobs.get(db);
}
await refreshSubscriptionConnection(db, input, id);
} catch {
logger.warn({ companyId, connectionId: row.connection.id }, "Subscription discovery unavailable for a connection");
}
}
})().catch(() => logger.warn({ companyId }, "Subscription discovery unavailable"))
.finally(() => active!.delete(key));
active.set(key, task);
return task;
}
+114
View File
@@ -0,0 +1,114 @@
import { and, eq, exists, gte, isNull, lte, notExists, or, sql } from "drizzle-orm";
import { aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections, connectionGrants, connectionGrantMembers, agents, authUsers, companyMemberships, costEvents, type Db } from "@paperclipai/db";
import { addCents, monthlySubscriptionCents, type SubscriptionCostReport, type SubscriptionPrice, type SubscriptionUsage } from "@paperclipai/shared";
import { withAccountingReadSnapshot } from "./accounting-transaction.js";
import { ordinaryInputTokens } from "./costs.js";
import { resolveCostDateRange, type CostDateRange } from "./cost-date-range.js";
import { canEditSubscription, canonicalSubscriptionId, type SubscriptionActor } from "./subscriptions.js";
export function emptySubscriptionUsage(): SubscriptionUsage {
return { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, costCents: "0.0000000", eventCount: 0, estimatedEventCount: 0, unpricedEventCount: 0 };
}
function addUsage(target: SubscriptionUsage, source: SubscriptionUsage) {
target.costCents = addCents(target.costCents, source.costCents);
for (const key of ["inputTokens", "cachedInputTokens", "outputTokens", "eventCount", "estimatedEventCount", "unpricedEventCount"] as const) target[key] += Number(source[key]);
}
function priceDto(price: typeof aiSubscriptionPrices.$inferSelect): SubscriptionPrice {
return { revision: price.revision, plan: price.plan, amountCents: price.amountCents,
monthlyCents: price.amountCents == null ? null : monthlySubscriptionCents(price.amountCents, price.cadence),
currency: price.currency, cadence: price.cadence, status: price.status, source: price.source,
sourceUrl: price.sourceUrl, effectiveAt: price.effectiveAt.toISOString() };
}
export async function subscriptionCostReport(db: Db, companyId: string, actor: SubscriptionActor, range?: CostDateRange): Promise<SubscriptionCostReport> {
return withAccountingReadSnapshot(db, companyId, async tx => {
const period = resolveCostDateRange(range);
const conditions = [eq(costEvents.companyId, companyId)];
if (period?.from) conditions.push(gte(costEvents.occurredAt, period.from));
if (period?.to) conditions.push(lte(costEvents.occurredAt, period.to));
// Company cost-read permission covers aggregate run usage, not another
// member's private subscription fee. Billing editors retain visibility
// after disconnection; other readers need an authorized shared audience.
const audience = and(eq(connectionGrantMembers.companyId, companyId), eq(connectionGrantMembers.grantId, connectionGrants.id));
const visible = or(
sql`${actor.userId} = any(${aiSubscriptions.ownerUserIds})`,
actor.canManage ? eq(aiSubscriptions.shared, true) : undefined,
exists(tx.select({ id: aiSubscriptionConnections.id }).from(aiSubscriptionConnections)
.innerJoin(connectionGrants, and(eq(connectionGrants.id, aiSubscriptionConnections.grantId), eq(connectionGrants.companyId, companyId)))
.where(and(eq(aiSubscriptionConnections.companyId, companyId), eq(aiSubscriptionConnections.subscriptionId, aiSubscriptions.id),
eq(connectionGrants.kind, "organization"), eq(connectionGrants.status, "active"), or(
notExists(tx.select({ id: connectionGrantMembers.id }).from(connectionGrantMembers).where(audience)),
exists(tx.select({ id: connectionGrantMembers.id }).from(connectionGrantMembers).where(and(audience,
eq(connectionGrantMembers.subjectType, "user"), eq(connectionGrantMembers.subjectId, actor.userId)))),
)))),
);
const visibleCurrent = and(eq(aiSubscriptions.companyId, companyId), isNull(aiSubscriptions.mergedIntoId), visible);
const [accounts, links, prices, owners, groups] = await Promise.all([
tx.select().from(aiSubscriptions).where(visibleCurrent),
// Historical aliases are needed to distinguish hidden accounts from
// truly unattributed runs. Do not load their private metadata or prices.
tx.select({ id: aiSubscriptions.id, mergedIntoId: aiSubscriptions.mergedIntoId }).from(aiSubscriptions).where(eq(aiSubscriptions.companyId, companyId)),
tx.select({ price: aiSubscriptionPrices }).from(aiSubscriptions).innerJoin(aiSubscriptionPrices, and(
eq(aiSubscriptionPrices.companyId, aiSubscriptions.companyId), eq(aiSubscriptionPrices.subscriptionId, aiSubscriptions.id),
eq(aiSubscriptionPrices.revision, aiSubscriptions.revision),
)).where(visibleCurrent),
tx.select({ id: authUsers.id, name: authUsers.name }).from(authUsers).innerJoin(companyMemberships, and(
eq(companyMemberships.principalId, authUsers.id), eq(companyMemberships.companyId, companyId), eq(companyMemberships.principalType, "user"))),
tx.select({ subscriptionId: costEvents.subscriptionId, billingType: costEvents.billingType,
agentId: costEvents.agentId, agentName: agents.name,
inputTokens: sql<number>`coalesce(sum(${ordinaryInputTokens}), 0)::double precision`,
cachedInputTokens: sql<number>`coalesce(sum(${costEvents.cachedInputTokens}), 0)::double precision`,
outputTokens: sql<number>`coalesce(sum(${costEvents.outputTokens}), 0)::double precision`,
costCents: sql<string>`coalesce(sum(${costEvents.costCents}), 0)::text`,
eventCount: sql<number>`count(*)::int`,
estimatedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'estimated')::int`,
unpricedEventCount: sql<number>`count(*) filter (where ${costEvents.costStatus} = 'unpriced' and ${costEvents.billingType} <> 'subscription_included')::int`,
}).from(costEvents).leftJoin(agents, and(eq(agents.id, costEvents.agentId), eq(agents.companyId, companyId)))
.where(and(...conditions)).groupBy(costEvents.subscriptionId, costEvents.billingType, costEvents.agentId, agents.name),
]);
const report: SubscriptionCostReport = { canRefresh: !actor.readOnly, asOf: new Date().toISOString(), accounts: [], monthlyTotals: [],
activeCount: 0, unknownPriceCount: 0, unidentifiedAccountCount: 0,
api: emptySubscriptionUsage(), subscription: emptySubscriptionUsage(), unknown: emptySubscriptionUsage(), unattributedSubscription: emptySubscriptionUsage() };
const currentPrices = new Map(prices.map(({ price }) => [price.subscriptionId, priceDto(price)]));
const ownerNames = new Map(owners.map(owner => [owner.id, owner.name]));
for (const account of accounts) {
const price = currentPrices.get(account.id);
if (!price) throw new Error("Subscription price history is incomplete");
const ownerUserId = !account.shared && account.ownerUserIds.length === 1 ? account.ownerUserIds[0] : null;
report.accounts.push({ id: account.id, provider: account.provider,
name: account.ownerUserIds.length > 0 && (account.shared || !account.ownerUserIds.includes(actor.userId)) ? `${account.provider} subscription` : account.name,
ownerUserId, ownerName: ownerNames.get(ownerUserId ?? "") ?? null, shared: account.shared,
identityVerified: account.identityVerified, detectedPlan: account.detectedPlan,
observedAt: account.observedAt?.toISOString() ?? null, lastCheckedAt: account.lastCheckedAt?.toISOString() ?? null,
refreshStatus: account.refreshStatus, canEdit: canEditSubscription(account, actor), price,
usage: emptySubscriptionUsage(), agents: [] });
if (price.status !== "active") continue;
report.activeCount++;
if (!account.identityVerified) report.unidentifiedAccountCount++;
if (price.monthlyCents == null) { report.unknownPriceCount++; continue; }
let total = report.monthlyTotals.find(row => row.currency === price.currency);
if (!total) report.monthlyTotals.push(total = { currency: price.currency, amountCents: "0.0000000", estimatedCount: 0 });
total.amountCents = addCents(total.amountCents, price.monthlyCents);
if (price.source !== "user") total.estimatedCount++;
}
const byId = new Map(report.accounts.map(account => [account.id, account]));
const aliases = new Map(links.map(account => [account.id, account.mergedIntoId]));
const canonicalIds = new Map(links.map(account => [account.id, canonicalSubscriptionId(account.id, aliases)]));
for (const group of groups) {
const isSubscription = group.billingType === "subscription_included" || group.billingType === "subscription_overage";
addUsage(group.billingType === "metered_api" ? report.api : isSubscription ? report.subscription : report.unknown, group);
if (!isSubscription) continue;
const canonicalId = group.subscriptionId ? canonicalIds.get(group.subscriptionId) : undefined;
const account = canonicalId ? byId.get(canonicalId) : undefined;
if (canonicalId && !account) continue; // Known private account; not missing attribution.
if (!account) { addUsage(report.unattributedSubscription, group); continue; }
addUsage(account.usage, group);
if (group.agentId && !account.agents.some(agent => agent.id === group.agentId)) account.agents.push({ id: group.agentId, name: group.agentName ?? "Agent" });
}
report.accounts.sort((a, b) => (a.ownerName ?? "Shared").localeCompare(b.ownerName ?? "Shared") || a.name.localeCompare(b.name));
report.monthlyTotals.sort((a, b) => a.currency.localeCompare(b.currency));
return report;
});
}
+198
View File
@@ -0,0 +1,198 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import { aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections, connectionGrants, toolConnections, type Db } from "@paperclipai/db";
import { aiConnectionMetadataSchema, normalizeCents, subscriptionPlan, type AiProvider, type UpdateSubscriptionPrice } from "@paperclipai/shared";
import { conflict, forbidden, notFound } from "../errors.js";
import { logActivity, type ActivityPublication } from "./activity-log.js";
import { publishAccountingActivities } from "./accounting-transaction.js";
import { subscriptionCredentialIdentity, subscriptionIdentityKey, type SubscriptionIdentity } from "./subscription-identity.js";
type Account = typeof aiSubscriptions.$inferSelect;
type Price = typeof aiSubscriptionPrices.$inferInsert;
export interface SubscriptionActor { userId: string; canManage: boolean; readOnly?: boolean }
export interface SubscriptionConnection {
companyId: string; connectionId: string; grantId: string; provider: AiProvider;
name: string; ownerUserId: string | null; credential: string;
}
export function canonicalSubscriptionId(id: string, accounts: Pick<Account, "id" | "mergedIntoId">[] | Map<string, string | null>): string {
const map = accounts instanceof Map ? accounts : new Map(accounts.map(row => [row.id, row.mergedIntoId]));
const seen = new Set<string>();
while (map.get(id)) {
if (seen.has(id)) throw new Error("Subscription link cycle");
seen.add(id); id = map.get(id)!;
}
return id;
}
function detectedPrice(companyId: string, subscriptionId: string, plan: string | null, revision: number): Price {
return { companyId, subscriptionId, revision, plan: plan ?? "Plan unknown", amountCents: null, source: "unknown" };
}
function autoPrice(account: Pick<Account, "id" | "companyId" | "provider" | "identityVerified">, plan: string | null, revision: number): Price {
// A plan hint alone cannot prove whether two rotated credentials are one paid
// seat. Require a stable identity before adding an automatic fee to totals.
const catalog = account.identityVerified ? subscriptionPlan(account.provider, plan) : null;
return { ...detectedPrice(account.companyId, account.id, plan, revision),
...(catalog ? { plan: catalog.name, amountCents: normalizeCents(catalog.monthlyCents), currency: catalog.currency, source: "catalog" as const, sourceUrl: catalog.sourceUrl } : {}),
};
}
async function lock(db: Db, companyId: string) {
// A separate, short lock; no provider requests or credential rotation under it.
await db.execute(sql`select pg_advisory_xact_lock(hashtext('subscription_costs'), hashtext(${companyId}))`);
}
async function withSubscriptionTransaction<T>(db: Db, companyId: string, work: (tx: Db, publications: ActivityPublication[]) => Promise<T>) {
const publications: ActivityPublication[] = [];
const result = await db.transaction(async transaction => {
const tx = transaction as unknown as Db;
await lock(tx, companyId);
return work(tx, publications);
});
publishAccountingActivities(companyId, publications);
return result;
}
type Ownership = Pick<Account, "ownerUserIds" | "shared">;
function combineOwnership(a: Ownership, b: Ownership): Ownership {
return { ownerUserIds: [...new Set([...a.ownerUserIds, ...b.ownerUserIds])].sort(), shared: a.shared || b.shared };
}
export function canEditSubscription(account: Ownership, actor: SubscriptionActor) {
return !actor.readOnly && (account.ownerUserIds.includes(actor.userId) || (account.shared && actor.canManage));
}
async function mergeInTransaction(db: Db, companyId: string, source: Account, target: Account, automatic: boolean) {
if (source.id === target.id) throw conflict("Choose a different subscription to link");
if (source.provider !== target.provider || source.mergedIntoId || target.mergedIntoId) throw conflict("Choose two current accounts from the same provider");
await db.update(aiSubscriptions).set(combineOwnership(source, target)).where(and(eq(aiSubscriptions.id, target.id), eq(aiSubscriptions.companyId, companyId)));
const prices = await db.select().from(aiSubscriptionPrices).where(and(eq(aiSubscriptionPrices.companyId, companyId), inArray(aiSubscriptionPrices.subscriptionId, [source.id, target.id])));
const sourcePrice = prices.find(row => row.subscriptionId === source.id && row.revision === source.revision)!;
const targetPrice = prices.find(row => row.subscriptionId === target.id && row.revision === target.revision)!;
if (automatic && sourcePrice.source === "user") {
if (targetPrice.source === "user" && ["amountCents", "currency", "cadence", "status"].some(key => sourcePrice[key as keyof typeof sourcePrice] !== targetPrice[key as keyof typeof targetPrice])) {
throw conflict("These accounts have different saved prices. Link them after choosing the price to keep.");
}
if (targetPrice.source !== "user") {
await db.insert(aiSubscriptionPrices).values({ ...sourcePrice, id: undefined, subscriptionId: target.id, revision: target.revision + 1, effectiveAt: new Date() });
await db.update(aiSubscriptions).set({ revision: target.revision + 1 }).where(eq(aiSubscriptions.id, target.id));
}
}
await db.update(aiSubscriptions).set({ mergedIntoId: target.id, revision: source.revision + 1 }).where(and(eq(aiSubscriptions.id, source.id), eq(aiSubscriptions.companyId, companyId)));
// Preserve each old ID for historical run attribution. Flatten existing links.
await db.update(aiSubscriptions).set({ mergedIntoId: target.id }).where(and(eq(aiSubscriptions.companyId, companyId), eq(aiSubscriptions.mergedIntoId, source.id)));
await db.update(aiSubscriptionConnections).set({ subscriptionId: target.id }).where(and(eq(aiSubscriptionConnections.companyId, companyId), eq(aiSubscriptionConnections.subscriptionId, source.id)));
return target.id;
}
export function subscriptionService(db: Db) {
async function register(input: SubscriptionConnection, observed?: SubscriptionIdentity) {
const identity = { ...(observed ?? subscriptionCredentialIdentity(input.companyId, input.provider, input.credential)) };
// Only a successful provider observation may match another grant's billing
// identity or add its editors. Provisional rows are grant-scoped, even when
// two callers supply the same unverified credential or forged ID claims.
if (!observed?.verified) identity.accountKey = subscriptionIdentityKey(input.companyId, input.provider, ["grant", input.grantId, identity.credentialKey]);
if (!observed) {
const [cached] = await db.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, input.companyId), eq(aiSubscriptionConnections.grantId, input.grantId)));
if (cached?.credentialKey === identity.credentialKey && cached.connectionId === input.connectionId) return cached.subscriptionId;
}
return withSubscriptionTransaction(db, input.companyId, async (tx, publications) => {
// Company and grant identity are authoritative, even for internal callers.
const [grant] = await tx.select({ grant: connectionGrants, connection: toolConnections }).from(connectionGrants)
.innerJoin(toolConnections, and(eq(toolConnections.id, connectionGrants.connectionId), eq(toolConnections.companyId, connectionGrants.companyId)))
.where(and(eq(connectionGrants.companyId, input.companyId), eq(connectionGrants.id, input.grantId), eq(toolConnections.id, input.connectionId)));
const metadata = aiConnectionMetadataSchema.safeParse(grant?.connection.config.ai);
if (!grant || grant.grant.status !== "active" || grant.connection.connectionPurpose !== "ai"
|| !grant.connection.enabled || grant.connection.status !== "active"
|| !metadata.success || metadata.data.method !== "subscription" || metadata.data.provider !== input.provider) {
throw notFound("Subscription connection not found");
}
const [binding] = await tx.select().from(aiSubscriptionConnections).where(and(eq(aiSubscriptionConnections.companyId, input.companyId), eq(aiSubscriptionConnections.grantId, input.grantId)));
const accounts = await tx.select().from(aiSubscriptions).where(eq(aiSubscriptions.companyId, input.companyId));
if (observed && binding && binding.credentialKey !== identity.credentialKey) return canonicalSubscriptionId(binding.subscriptionId, accounts);
// A fresh credential-local hint cannot override a verified profile binding.
if (!observed && binding?.credentialKey === identity.credentialKey) return canonicalSubscriptionId(binding.subscriptionId, accounts);
const known = accounts.find(row => row.provider === input.provider && row.accountKey === identity.accountKey);
let account = known ? accounts.find(row => row.id === canonicalSubscriptionId(known.id, accounts))! : undefined;
const previous = binding?.credentialKey === identity.credentialKey ? accounts.find(row => row.id === canonicalSubscriptionId(binding.subscriptionId, accounts)) : undefined;
if (!account && previous && observed && !previous.identityVerified && !previous.mergedIntoId) {
[account] = await tx.update(aiSubscriptions).set({ accountKey: identity.accountKey, identityVerified: identity.verified }).where(eq(aiSubscriptions.id, previous.id)).returning();
}
if (!account) {
[account] = await tx.insert(aiSubscriptions).values({ companyId: input.companyId, provider: input.provider,
accountKey: identity.accountKey, identityVerified: identity.verified, name: grant.connection.name,
ownerUserIds: grant.grant.subjectUserId ? [grant.grant.subjectUserId] : [], shared: grant.grant.kind === "organization", detectedPlan: identity.plan,
}).returning();
await tx.insert(aiSubscriptionPrices).values(autoPrice(account, identity.plan, 0));
await logActivity(tx, { companyId: input.companyId, actorType: "system", actorId: "subscription_reporting",
action: "subscription.discovered", entityType: "ai_subscription", entityId: account.id, details: { provider: input.provider } }, publications);
}
// The union is independent of discovery order. Credential sharing does
// not transfer personal ownership, and personal reuse does not remove
// managers' authority over a fee already connected to the company.
const ownership = combineOwnership(account, {
ownerUserIds: grant.grant.subjectUserId ? [grant.grant.subjectUserId] : [], shared: grant.grant.kind === "organization",
});
if (ownership.shared !== account.shared || ownership.ownerUserIds.join() !== account.ownerUserIds.join()) {
[account] = await tx.update(aiSubscriptions).set(ownership).where(eq(aiSubscriptions.id, account.id)).returning();
await logActivity(tx, { companyId: input.companyId, actorType: "system", actorId: "subscription_reporting",
action: "subscription.ownership_updated", entityType: "ai_subscription", entityId: account.id,
details: { shared: ownership.shared, ownerCount: ownership.ownerUserIds.length } }, publications);
}
if (observed && previous && previous.id !== account.id && !previous.identityVerified) {
await mergeInTransaction(tx, input.companyId, previous, account, true);
await logActivity(tx, { companyId: input.companyId, actorType: "system", actorId: "subscription_reporting",
action: "subscription.linked", entityType: "ai_subscription", entityId: previous.id, details: { targetId: account.id, automatic: true } }, publications);
// Merging can adopt a user price and advance the revision.
[account] = await tx.select().from(aiSubscriptions).where(eq(aiSubscriptions.id, account.id));
}
if (observed) {
if (identity.plan) {
const [price] = await tx.select().from(aiSubscriptionPrices).where(and(eq(aiSubscriptionPrices.subscriptionId, account.id), eq(aiSubscriptionPrices.revision, account.revision)));
const next = autoPrice(account, identity.plan, account.revision + 1);
if (price?.source !== "user" && (price?.plan !== next.plan || price?.amountCents !== (next.amountCents ?? null) || price?.source !== next.source)) {
account.revision++;
await tx.insert(aiSubscriptionPrices).values(next);
}
}
await tx.update(aiSubscriptions).set({ detectedPlan: identity.plan ?? account.detectedPlan, observedAt: identity.plan ? new Date() : account.observedAt,
lastCheckedAt: new Date(), refreshStatus: identity.plan ? "ok" : "unavailable", revision: account.revision }).where(eq(aiSubscriptions.id, account.id));
}
await tx.insert(aiSubscriptionConnections).values({ companyId: input.companyId, connectionId: input.connectionId, grantId: input.grantId,
credentialKey: identity.credentialKey, subscriptionId: account.id }).onConflictDoUpdate({ target: [aiSubscriptionConnections.companyId, aiSubscriptionConnections.grantId],
set: { credentialKey: identity.credentialKey, subscriptionId: account.id } });
return account.id;
});
}
async function updatePrice(companyId: string, id: string, input: UpdateSubscriptionPrice, actor: SubscriptionActor) {
return withSubscriptionTransaction(db, companyId, async (tx, publications) => {
const [account] = await tx.select().from(aiSubscriptions).where(and(eq(aiSubscriptions.companyId, companyId), eq(aiSubscriptions.id, id)));
if (!account) throw notFound("Subscription not found");
if (!canEditSubscription(account, actor)) throw forbidden("Only subscription owners or managers of shared accounts can edit prices");
if (account.mergedIntoId || account.revision !== input.expectedRevision) throw conflict("This subscription changed. Reload it before saving.");
const revision = account.revision + 1;
await tx.insert(aiSubscriptionPrices).values({ companyId, subscriptionId: id, revision, plan: input.plan,
amountCents: input.amountCents == null ? null : normalizeCents(input.amountCents), currency: input.currency,
cadence: input.cadence, status: input.status, source: "user" });
await tx.update(aiSubscriptions).set({ revision }).where(eq(aiSubscriptions.id, id));
await logActivity(tx, { companyId, actorType: "user", actorId: actor.userId, action: "subscription.price_updated",
entityType: "ai_subscription", entityId: id, details: { revision, status: input.status } }, publications);
return { id, revision };
});
}
async function merge(companyId: string, id: string, targetId: string, expectedRevision: number, targetRevision: number, actor: SubscriptionActor) {
return withSubscriptionTransaction(db, companyId, async (tx, publications) => {
const rows = await tx.select().from(aiSubscriptions).where(and(eq(aiSubscriptions.companyId, companyId), inArray(aiSubscriptions.id, [id, targetId])));
const source = rows.find(row => row.id === id), target = rows.find(row => row.id === targetId);
if (!source || !target) throw notFound("Subscription not found");
if (!canEditSubscription(source, actor) || !canEditSubscription(target, actor)) throw forbidden("You must be able to edit both subscriptions");
if (source.revision !== expectedRevision || target.revision !== targetRevision) throw conflict("These subscriptions changed. Reload before linking them.");
const result = await mergeInTransaction(tx, companyId, source, target, false);
await logActivity(tx, { companyId, actorType: "user", actorId: actor.userId, action: "subscription.linked", entityType: "ai_subscription", entityId: id, details: { targetId } }, publications);
return { id: result };
});
}
return { register, updatePrice, merge };
}