mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 20:09:10 +01:00
feat: add company decision models with permission and cost controls (#15473)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Optional product features need small, typed model decisions. > - Each company needs to choose which shared API connection pays for those decisions. > - Calls must retain user and task permissions, budget limits, and cost attribution. > - This pull request adds a managed decision service, setup UI, and request history. > - Features can check availability cheaply and keep their existing behavior when decisions are unavailable. ## Linked Issues or Issue Description **Subsystem affected** Server services, shared contracts, database accounting, Company Settings, and Costs. **Problem or motivation** Paperclip has no common decision-model service. Adding provider calls within each feature would duplicate credential access, permission checks, and billing rules. **Proposed solution** Let a connection manager configure one company decision model. Support OpenAI Decisions and Jev through OpenRouter. Provide a fixed setup test and metadata-only history. Default company-sponsored background decisions to on during setup, and preserve a saved off setting. **Alternatives considered** Per-feature credentials would duplicate existing connection management. Personal overrides and provider fallback chains add permission and billing complexity; they remain deferred. **Roadmap alignment** Reviewed ROADMAP.md and searched open PRs. This extends existing connection access and budget accounting. Product features that call the service remain outside this change. No matching decision-model service PR was found. ## What Changed - Add company settings, an internal `decisionModelService`, local availability checks, and trusted human, agent/run, and system contexts. - Pin Vercel AI SDK provider dependencies and adapt boolean, choice, and ordered-score decisions for both providers. Bound requests and time; disable paid retries. - Add durable invocation metadata and agentless decision ledger charges. Preserve fractional cents, pricing evidence, dispatch identity, and unresolved billing holds. - Share the company accounting lock and apply company, agent, and project budgets. Settle charges once, retain unknown holds, and recover interrupted calls without resubmission. - Reuse connection setup and management UI. Add a Decisions view under Costs, production-component Storybook coverage, database migration, and service documentation. ## Verification - Passed 166 current-code tests covering the decision service/provider, setup component, Costs, OpenAPI, and every failure from the earlier broad run. Coverage includes native SDK wire formats, refusals, billed malformed responses, permission and secret-rotation races, identity changes, concurrent budget admission, unresolved holds, agent/task deletion, and stale setup feedback. - Passed 170 existing connection, cost, budget, heartbeat-accounting, and profile regression tests. - Passed repository typecheck, production build, and design token gates after integrating master. Verified the generated migration on a fresh test database and upgraded the populated preview database from the branch's earlier migration without losing settings or usage. - Ran the required full `pnpm test:run`: its general phase completed with 16,354 passed and 10 failures across five files while this branch was still being updated. Every reported failure passes in the current-code rerun; the serialized phase did not run after that failure. The full GitHub CI suite passed on `b1b856a88`: general and serialized tests, browser shards, runner checks, typecheck, production build, packaging/canary, and policy gates. [CI evidence](https://github.com/paperclipai/paperclip/actions/runs/37673106360). - Passed the full-shell Storybook setup-to-history interaction test again after integrating master. Greptile rates the final revision 5/5 with zero unresolved threads. - Walked through the running app: empty setup, add each provider, save, reload, run all three sample questions, inspect fractional charges in history, switch provider while sponsorship is off, disable, and reconnect. Checked mobile settings. These tests used the actual UI, vault, server, SDKs, and database with simulated upstream responses. - Live paid setup tests remain unverified: this environment has no authorized OpenAI/OpenRouter credentials available. No mocked test is presented as live provider evidence. Reviewer journey: Company Settings → General → Decision model. Add/select a shared API connection, save, run the billed sample, open View usage, then disable decisions and verify Run test is disabled after reload. ## Risks - The SDK decision interface is experimental. Pinned versions and wire-format tests limit upgrade drift. - The migration allows agentless service charges and reservations. Existing agent cost-reporting APIs still require an agent, and decision receipts stay separate from run reconciliation. - Timeouts can have unknown provider charges. Holds remain until an audited accounting correction resolves them. - OpenAI prices use a versioned Decisions rate snapshot; OpenRouter costs use provider receipts. Unknown pricing is retained as unknown. - A configured company authorizes background spending by default. Setup explains this, and managers can turn it off. - Live provider account/model availability still needs the two credentialed acceptance checks. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository inspection, code execution, and browser tools. The exact serving revision and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
f1c44b7b56
commit
a7a244ab33
51 files changed
+4017
-68
No files matched your search
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DECISION_MODELS, DECISION_TEST_REQUEST, decisionProviderForConnection } from "@paperclipai/shared";
|
||||
import { decisionReceipt, runDecisionProvider } from "../services/decision-model-provider.js";
|
||||
|
||||
function openaiResponse() {
|
||||
return { model: "gpt-6-luna", usage: { input_tokens: 123, output_tokens: 0 }, answers: [
|
||||
{ type: "predicate", name: "billing", probability: 0.99 },
|
||||
{ type: "choice", name: "team", choice: "billing", confidence: 0.9, probabilities: [{ value: "billing", probability: 0.9 }, { value: "technical", probability: 0.1 }] },
|
||||
{ type: "score", name: "severity", score: 0.1, probabilities: [{ value: 0, probability: 0.9 }, { value: 1, probability: 0.1 }, { value: 2, probability: 0 }] },
|
||||
] };
|
||||
}
|
||||
function openrouterResponse() {
|
||||
return { id: "decision-fixture", model: "typesafe/jev-1.13", usage: { input_tokens: 123, output_tokens: 0, cost: 0.000005166 }, answers: {
|
||||
billing: { type: "noul", noul: 0.99 }, team: { type: "choice", choice: "billing", confidence: 0.85, probabilities: { billing: 0.9, technical: 0.1 } },
|
||||
severity: { type: "score", score: 0.1, probabilities: { "0": 0.9, "1": 0.1, "2": 0 } },
|
||||
} };
|
||||
}
|
||||
describe("decision provider contract", () => {
|
||||
it.each(["openai", "openrouter"] as const)("uses native %s decisions with the selected credential and preserves answers and fractional costs", async provider => {
|
||||
const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json(provider === "openai" ? openaiResponse() : openrouterResponse()));
|
||||
const result = await runDecisionProvider({ provider, model: DECISION_MODELS[provider].id, apiKey: "selected-credential", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: transport });
|
||||
expect(transport).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = transport.mock.calls[0];
|
||||
expect(String(url)).toBe(provider === "openai" ? "https://api.openai.com/v1/decisions" : "https://openrouter.ai/api/alpha/decisions");
|
||||
expect(new Headers(options?.headers).get("authorization")).toBe("Bearer selected-credential");
|
||||
expect(result.answers).toMatchObject({ billing: { type: "boolean", probability: 0.99 }, team: { type: "choice", choice: "billing", confidence: provider === "openai" ? 0.9 : 0.85 }, severity: { type: "score", score: 0.1 } });
|
||||
expect(result.receipt.costCents).toBe(provider === "openai" ? "0.0012300" : "0.0005166");
|
||||
expect(JSON.stringify(result.receipt)).not.toContain("customer");
|
||||
expect(JSON.parse(String(options?.body)).model).toBe(DECISION_MODELS[provider].id);
|
||||
});
|
||||
it("keeps usage for a charged refusal and never treats it as an answer", async () => {
|
||||
const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ ...openaiResponse(), answers: [{ type: "refusal", name: null }] }));
|
||||
const result = await runDecisionProvider({ provider: "openai", model: "gpt-6-luna", apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: transport });
|
||||
expect(result.answers).toBeUndefined(); expect(result.errorCode).toBe("refused"); expect(result.receipt.inputTokens).toBe(123);
|
||||
});
|
||||
it.each([401, 429, 500])("does not retry HTTP %i or retain its response body", async status => {
|
||||
const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ error: { message: "PRIVATE STATE AND KEY", type: "server_error" } }, { status }));
|
||||
const result = await runDecisionProvider({ provider: "openai", model: "gpt-6-luna", apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: transport });
|
||||
expect(transport).toHaveBeenCalledTimes(1); expect(result.receipt.costStatus).toBe(status === 500 ? "unpriced" : "estimated"); expect(result.noProviderWork).toBe(status !== 500); expect(JSON.stringify(result)).not.toContain("PRIVATE");
|
||||
});
|
||||
it("preserves usage when answer validation fails", async () => {
|
||||
const response = openrouterResponse(); response.answers.team.choice = "invented";
|
||||
const result = await runDecisionProvider({ provider: "openrouter", model: "typesafe/jev-1.13", apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: async () => Response.json(response) });
|
||||
expect(result.answers).toBeUndefined(); expect(result.receipt.costStatus).toBe("reported");
|
||||
});
|
||||
it.each(["openai", "openrouter"] as const)("retains the %s receipt when the SDK rejects malformed wire answers", async provider => {
|
||||
const wire = provider === "openai" ? { ...openaiResponse(), answers: [{ type: "predicate", name: "billing", probability: 2 }] }
|
||||
: { ...openrouterResponse(), answers: { billing: { type: "noul", noul: "not-a-probability" } } };
|
||||
const result = await runDecisionProvider({ provider, model: DECISION_MODELS[provider].id, apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: async () => Response.json(wire) });
|
||||
expect(result.answers).toBeUndefined(); expect(result.receipt.inputTokens).toBe(123);
|
||||
expect(result.receipt.costStatus).toBe(provider === "openai" ? "estimated" : "reported");
|
||||
});
|
||||
it("fails closed on an OpenRouter refusal while retaining any reported charge", async () => {
|
||||
const result = await runDecisionProvider({ provider: "openrouter", model: DECISION_MODELS.openrouter.id, apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal },
|
||||
{ fetch: async () => Response.json({ ...openrouterResponse(), answers: { billing: { type: "refusal" } } }) });
|
||||
expect(result.answers).toBeUndefined(); expect(result.errorCode).toBe("refused"); expect(result.receipt.costStatus).toBe("reported");
|
||||
});
|
||||
it("does not invent prices when usage or a supported rate is missing", () => {
|
||||
expect(decisionReceipt("openai", {}).costCents).toBeNull();
|
||||
expect(decisionReceipt("openai", { usage: { inputTokens: 100_000 } }).costStatus).toBe("unpriced");
|
||||
expect(decisionReceipt("openrouter", { usage: { inputTokens: 1 } }).costCents).toBeNull();
|
||||
expect(decisionReceipt("openrouter", { providerMetadata: { openrouter: { usage: { cost: 0 } } } }).costStatus).toBe("reported");
|
||||
});
|
||||
it("rejects subscription, personal endpoint routing and other provider capabilities", () => {
|
||||
expect(decisionProviderForConnection({ provider: "openai", method: "subscription" })).toBeNull();
|
||||
expect(decisionProviderForConnection({ provider: "openai", method: "api_key", routing: { kind: "gateway", baseUrl: "https://example.com" } })).toBeNull();
|
||||
expect(decisionProviderForConnection({ provider: "anthropic", method: "api_key" })).toBeNull();
|
||||
expect(decisionProviderForConnection({ provider: "openrouter", method: "api_key", routing: { kind: "openrouter" } })).toBe("openrouter");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,291 @@
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, realpath, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import {
|
||||
createDb, companies, agents, companyMemberships, companyDecisionModels, costEvents, decisionInvocations,
|
||||
connectionGrants, connectionGrantMembers, toolConnectionInstalls, budgetPolicies, budgetReservations,
|
||||
heartbeatRuns, issues, projects, runIdentityContexts, secretAccessEvents, companySecrets,
|
||||
} from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
|
||||
import { DECISION_TEST_REQUEST, updateDecisionModelSchema, createCostEventSchema } from "@paperclipai/shared";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { agentService } from "../services/agents.js";
|
||||
import { decisionModelService, settingsDecisionTest, defineDecisionFeature, type DecisionContext } from "../services/decision-models.js";
|
||||
import { decisionReceipt, type DecisionProviderOutcome } from "../services/decision-model-provider.js";
|
||||
import { costService } from "../services/costs.js";
|
||||
import { billingReconciliationService } from "../services/billing-reconciliation.js";
|
||||
import { withAccountingTransaction } from "../services/accounting-transaction.js";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { decisionModelRoutes } from "../routes/decision-models.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let home: string;
|
||||
const backgroundFeature = defineDecisionFeature("test.background", { background: true });
|
||||
const outcome: DecisionProviderOutcome = { answers: { billing: { type: "boolean", probability: 0.9 } }, receipt: decisionReceipt("openai", { usage: { inputTokens: 100, outputTokens: 0 } }) };
|
||||
beforeAll(async () => {
|
||||
home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-decisions-")));
|
||||
vi.stubEnv("PAPERCLIP_HOME", home);
|
||||
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "decisions-fixture");
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-decisions-db-");
|
||||
db = createDb(database.connectionString);
|
||||
}, 90000);
|
||||
afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });
|
||||
let sequence = 0;
|
||||
async function fixture() {
|
||||
const companyId = randomUUID(), agentId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Decision tests", issuePrefix: `DC${++sequence}` });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Test agent", adapterType: "codex_local" });
|
||||
await db.insert(companyMemberships).values(["alice", "bob"].map(principalId => ({ companyId, principalId, principalType: "user", status: "active", membershipRole: "owner" })));
|
||||
const connections = aiConnectionService(db);
|
||||
const binding = await connections.save(companyId, "alice", { provider: "openai", method: "api_key", name: "Decision key", ownership: "shared", apiKey: "fixture-key", agentIds: [], allAgents: true }, "fixture-key");
|
||||
const provider = vi.fn().mockResolvedValue(structuredClone(outcome));
|
||||
const service = decisionModelService(db, { provider });
|
||||
const context: DecisionContext = { companyId, feature: settingsDecisionTest,
|
||||
actor: { type: "board", userId: "alice", source: "session", companyIds: [companyId], memberships: [{ companyId, membershipRole: "owner", status: "active" }] } };
|
||||
const config = { ...binding, enabled: true, allowBackground: true };
|
||||
await service.configure(companyId, "alice", config);
|
||||
return { companyId, agentId, binding, provider, service, context, config, connections };
|
||||
}
|
||||
describe("company decision service", () => {
|
||||
it("starts unconfigured with background sponsorship on and makes availability free", async () => {
|
||||
const f = await fixture();
|
||||
await db.delete(companyDecisionModels).where(eq(companyDecisionModels.companyId, f.companyId));
|
||||
expect(await f.service.settings(f.companyId)).toMatchObject({ enabled: false, allowBackground: true, connectionId: null });
|
||||
expect(await f.service.availability(f.context)).toEqual({ available: false, reason: "not_configured" });
|
||||
await f.service.configure(f.companyId, "alice", updateDecisionModelSchema.parse({ ...f.binding, enabled: true }));
|
||||
const before = await db.select().from(secretAccessEvents).where(eq(secretAccessEvents.companyId, f.companyId));
|
||||
const memo = f.service.availabilityForRequest();
|
||||
expect(memo(f.context)).toBe(memo(f.context));
|
||||
expect(await memo(f.context)).toEqual({ available: true });
|
||||
expect(await db.select().from(secretAccessEvents).where(eq(secretAccessEvents.companyId, f.companyId))).toHaveLength(before.length);
|
||||
expect(f.provider).not.toHaveBeenCalled();
|
||||
});
|
||||
it("records a human service charge without an agent, exact cost and no input or answer content", async () => {
|
||||
const f = await fixture();
|
||||
const result = await f.service.decide(f.context, { ...DECISION_TEST_REQUEST, state: "PRIVATE PAYLOAD" });
|
||||
expect(result.status).toBe("succeeded");
|
||||
expect(f.provider.mock.calls[0][0].apiKey).toBe("fixture-key");
|
||||
const [event] = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
|
||||
expect(event).toMatchObject({ agentId: null, responsibleUserId: "alice", usageKind: "decision", costCents: 0.001, costStatus: "estimated", heartbeatRunId: null });
|
||||
const rows = await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId));
|
||||
expect(rows[0]).toMatchObject({ status: "succeeded", actorType: "user", responsibleUserId: "alice", costEventId: event.id });
|
||||
expect(JSON.stringify(rows)).not.toContain("PRIVATE PAYLOAD"); expect(JSON.stringify(rows)).not.toContain("probability");
|
||||
expect((await costService(db).byUser(f.companyId)).rows.find(r => r.userId === "alice")?.costCentsExact).toBe("0.0010000");
|
||||
expect((await costService(db).byAgent(f.companyId))[0].agentId).toBeNull();
|
||||
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("settled");
|
||||
});
|
||||
it("allows real background use, preserves explicit off, and never sponsors a denied human", async () => {
|
||||
const f = await fixture();
|
||||
const context: DecisionContext = { companyId: f.companyId, feature: backgroundFeature, actor: { type: "system" } };
|
||||
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("succeeded");
|
||||
expect((await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId)))[0]).toMatchObject({ actorType: "system", responsibleUserId: null });
|
||||
await f.service.configure(f.companyId, "alice", { ...f.config, allowBackground: false });
|
||||
expect(await f.service.availability(context)).toEqual({ available: false, reason: "background_disabled" });
|
||||
const second = await f.connections.save(f.companyId, "alice", { provider: "openrouter", method: "api_key", name: "Other key", ownership: "shared", apiKey: "other", agentIds: [], allAgents: true }, "other");
|
||||
await f.service.configure(f.companyId, "alice", { ...second, enabled: true, allowBackground: false });
|
||||
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
|
||||
await f.service.configure(f.companyId, "alice", f.config);
|
||||
await db.insert(connectionGrantMembers).values({ companyId: f.companyId, grantId: f.binding.grantId, subjectType: "user", subjectId: "bob" });
|
||||
expect(await f.service.decide({ ...f.context, feature: backgroundFeature }, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "access_denied" });
|
||||
expect(f.provider).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("retains the charge and dispatch snapshot when the task is deleted during provider work", async () => {
|
||||
const f = await fixture(), issueId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Temporary task" });
|
||||
f.provider.mockImplementationOnce(async () => {
|
||||
await db.delete(issues).where(eq(issues.id, issueId));
|
||||
return structuredClone(outcome);
|
||||
});
|
||||
expect((await f.service.decide({ ...f.context, issueId }, DECISION_TEST_REQUEST)).status).toBe("succeeded");
|
||||
const [event] = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
|
||||
expect(event).toMatchObject({ issueId: null, costCents: 0.001 });
|
||||
const [invocation] = await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId));
|
||||
expect(invocation).toMatchObject({ issueId, status: "succeeded", costEventId: event.id });
|
||||
});
|
||||
it("rechecks revoked grants after availability, and can disable a revoked connection", async () => {
|
||||
const f = await fixture(); expect(await f.service.availability(f.context)).toEqual({ available: true });
|
||||
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, f.binding.grantId));
|
||||
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "connection_unavailable" });
|
||||
await f.service.configure(f.companyId, "alice", { ...f.config, enabled: false });
|
||||
expect(await f.service.availability(f.context)).toEqual({ available: false, reason: "disabled" }); expect(f.provider).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["disabled", "rotated"])("rejects a secret %s while admission waits for accounting", async change => {
|
||||
const f = await fixture();
|
||||
const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.companyId, f.companyId));
|
||||
let release!: () => void, locked!: (pid: number) => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const acquired = new Promise<number>(resolve => { locked = resolve; });
|
||||
const holding = withAccountingTransaction(db, f.companyId, async tx => {
|
||||
const [row] = await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`);
|
||||
locked(row.pid); await gate;
|
||||
});
|
||||
const pid = await acquired;
|
||||
const pending = f.service.decide(f.context, DECISION_TEST_REQUEST);
|
||||
try {
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity where ${pid} = any(pg_blocking_pids(pid))`);
|
||||
expect(row.count).toBeGreaterThan(0);
|
||||
}, { timeout: 5000 });
|
||||
await db.update(companySecrets).set(change === "disabled" ? { status: "disabled" } : { latestVersion: secret.latestVersion + 1 }).where(eq(companySecrets.id, secret.id));
|
||||
} finally { release(); await holding; }
|
||||
expect(await pending).toMatchObject({ status: "unavailable", reason: "connection_unavailable" });
|
||||
expect(f.provider).not.toHaveBeenCalled();
|
||||
expect(await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId))).toHaveLength(0);
|
||||
});
|
||||
it("preserves sponsorship off when a deleted grant is replaced", async () => {
|
||||
const f = await fixture();
|
||||
await f.service.configure(f.companyId, "alice", { ...f.config, allowBackground: false });
|
||||
await db.delete(connectionGrants).where(eq(connectionGrants.id, f.binding.grantId));
|
||||
expect(await f.service.availability(f.context)).toMatchObject({ available: false, reason: "connection_unavailable" });
|
||||
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
|
||||
const next = await f.connections.save(f.companyId, "alice", { provider: "openrouter", method: "api_key", name: "Replacement", ownership: "shared", apiKey: "other", agentIds: [], allAgents: true }, "other");
|
||||
await f.service.configure(f.companyId, "alice", { ...next, enabled: true });
|
||||
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
|
||||
expect(f.provider).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects foreign-company credentials, membership loss, and invented feature handles", async () => {
|
||||
const f = await fixture(), other = await fixture();
|
||||
await expect(f.service.configure(f.companyId, "alice", { ...other.config })).rejects.toThrow();
|
||||
await db.update(companyMemberships).set({ status: "inactive" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "alice")));
|
||||
expect(await f.service.availability(f.context)).toMatchObject({ available: false, reason: "access_denied" });
|
||||
expect(await f.service.decide({ ...f.context, feature: { id: "settings.test", background: true }, actor: { type: "system" } }, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "access_denied" });
|
||||
});
|
||||
it("captures the active run identity and checks both human and agent access", async () => {
|
||||
const f = await fixture(), issueId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Decision task", status: "in_progress", assigneeAgentId: f.agentId });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", invocationSource: "on_demand", responsibleUserId: "alice", contextSnapshot: { issueId } });
|
||||
const [identity] = await db.insert(runIdentityContexts).values({ companyId: f.companyId, runId, revision: 1, responsibleUserId: "bob", cause: "steering", correlationId: "test", acceptedAt: new Date() }).returning();
|
||||
await db.update(heartbeatRuns).set({ responsibleUserId: "bob", activeIdentityContextId: identity.id }).where(eq(heartbeatRuns.id, runId));
|
||||
const context: DecisionContext = { companyId: f.companyId, feature: settingsDecisionTest, actor: { type: "agent", agentId: f.agentId, runId, companyId: f.companyId, source: "agent_jwt", onBehalfOfUserId: "alice" } };
|
||||
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("succeeded");
|
||||
expect((await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId)))[0]).toMatchObject({ responsibleUserId: "bob", runId, issueId, identityContextId: identity.id });
|
||||
await db.delete(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.binding.connectionId));
|
||||
expect(await f.service.availability(context)).toMatchObject({ available: false, reason: "access_denied" });
|
||||
await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, runId));
|
||||
expect(await f.service.availability(context)).toMatchObject({ available: false, reason: "responsible_user_missing" });
|
||||
});
|
||||
it("serializes budget admission against concurrent requests", async () => {
|
||||
const f = await fixture();
|
||||
await db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType: "company", scopeId: f.companyId, windowKind: "calendar_month_utc", amount: 1, reservationCents: "1", notifyEnabled: false });
|
||||
let release!: () => void; const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
let entered!: () => void; const started = new Promise<void>(resolve => { entered = resolve; });
|
||||
f.provider.mockImplementationOnce(async () => { entered(); await gate; return structuredClone(outcome); });
|
||||
const first = f.service.decide(f.context, DECISION_TEST_REQUEST);
|
||||
await started;
|
||||
try { expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "budget_blocked" }); }
|
||||
finally { release(); }
|
||||
expect((await first).status).toBe("succeeded"); expect(f.provider).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("blocks agent deletion while an in-flight or unknown decision retains a budget hold", async () => {
|
||||
const f = await fixture(), runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", invocationSource: "on_demand", responsibleUserId: "alice" });
|
||||
await db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType: "company", scopeId: f.companyId, windowKind: "calendar_month_utc", amount: 1, reservationCents: "1", notifyEnabled: false });
|
||||
const context: DecisionContext = { companyId: f.companyId, feature: settingsDecisionTest,
|
||||
actor: { type: "agent", agentId: f.agentId, runId, companyId: f.companyId, source: "agent_jwt" } };
|
||||
const remove = () => agentService(db).remove(f.agentId);
|
||||
f.provider.mockImplementationOnce(async () => {
|
||||
await expect(remove()).rejects.toMatchObject({ status: 409, details: { code: "agent_decision_accounting_pending" } });
|
||||
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "budget_blocked" });
|
||||
return { errorCode: "timeout", receipt: decisionReceipt("openai", null) };
|
||||
});
|
||||
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("failed");
|
||||
await expect(remove()).rejects.toMatchObject({ status: 409, details: { code: "agent_decision_accounting_pending" } });
|
||||
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0]).toMatchObject({ state: "held", amountCents: "1.0000000" });
|
||||
});
|
||||
it("holds unknown billing until an audited correction, without rerunning the provider", async () => {
|
||||
const f = await fixture(); f.provider.mockResolvedValue({ errorCode: "timeout", receipt: decisionReceipt("openai", null) });
|
||||
expect((await f.service.decide(f.context, DECISION_TEST_REQUEST)).status).toBe("failed");
|
||||
const [event] = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
|
||||
expect(event.costStatus).toBe("unpriced");
|
||||
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("held");
|
||||
await billingReconciliationService(db).adjust(f.companyId, event.id, { idempotencyKey: "correction", expectedCents: "0", correctedCents: "0.002", reason: "Verified provider invoice", pricing: { source: "operator" } }, "alice");
|
||||
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("settled");
|
||||
expect(f.provider).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("recovers an interrupted dispatch once without paying for a retry", async () => {
|
||||
const f = await fixture();
|
||||
const [invocation] = await db.insert(decisionInvocations).values({ companyId: f.companyId, feature: "test.background", actorType: "system", actorId: "paperclip-decisions",
|
||||
...f.binding, provider: "openai", model: "gpt-6-luna", questionTypes: ["boolean"], startedAt: new Date(Date.now() - 180_000) }).returning();
|
||||
await db.insert(budgetReservations).values({ companyId: f.companyId, decisionInvocationId: invocation.id, amountCents: "0.01", providerStartedAt: invocation.startedAt });
|
||||
await Promise.all([f.service.recoverInterrupted(), f.service.recoverInterrupted()]);
|
||||
const events = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
|
||||
expect(events).toHaveLength(1); expect(events[0].costStatus).toBe("unpriced"); expect(f.provider).not.toHaveBeenCalled();
|
||||
});
|
||||
it("keeps public cost reporting agent-scoped and bounds decision input before payment", async () => {
|
||||
expect(createCostEventSchema.safeParse({ agentId: null, provider: "openai", model: "gpt-6-luna", costCents: 1, occurredAt: new Date().toISOString() }).success).toBe(false);
|
||||
const f = await fixture(); await expect(f.service.decide(f.context, { ...DECISION_TEST_REQUEST, state: "x".repeat(32_001) })).rejects.toThrow(); expect(f.provider).not.toHaveBeenCalled();
|
||||
});
|
||||
it("preserves an explicit sponsorship opt-out when a subsequent edit omits the field", async () => {
|
||||
const f = await fixture();
|
||||
await f.service.configure(f.companyId, "alice", { ...f.config, allowBackground: false });
|
||||
const second = await f.connections.save(f.companyId, "alice", { provider: "openrouter", method: "api_key", name: "Other", ownership: "shared", apiKey: "other", agentIds: [], allAgents: true }, "other");
|
||||
await f.service.configure(f.companyId, "alice", { ...second, enabled: true });
|
||||
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
|
||||
});
|
||||
it("rejects revoked secrets without provider work and returns usage on successful calls", async () => {
|
||||
const f = await fixture();
|
||||
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "succeeded", usage: { costCents: "0.0010000", costStatus: "estimated", inputTokens: 100 } });
|
||||
await db.update(companySecrets).set({ status: "revoked" }).where(eq(companySecrets.companyId, f.companyId));
|
||||
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable" });
|
||||
expect(f.provider).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it.each(["agent", "project"] as const)("reserves and enforces applicable %s budgets", async scopeType => {
|
||||
const f = await fixture(), projectId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(projects).values({ id: projectId, companyId: f.companyId, name: "Decisions project" });
|
||||
await db.insert(issues).values({ id: issueId, companyId: f.companyId, projectId, title: "Budgeted task", assigneeAgentId: f.agentId });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", invocationSource: "on_demand", responsibleUserId: "alice", contextSnapshot: { issueId } });
|
||||
const context: DecisionContext = { companyId: f.companyId, feature: settingsDecisionTest, actor: { type: "agent", agentId: f.agentId, runId, companyId: f.companyId, source: "agent_jwt" } };
|
||||
const [policy] = await db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType, scopeId: scopeType === "agent" ? f.agentId : projectId, windowKind: "calendar_month_utc", amount: 1, reservationCents: "2", notifyEnabled: false }).returning();
|
||||
expect(await f.service.availability(context)).toEqual({ available: true });
|
||||
expect(await f.service.decide(context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "budget_blocked" });
|
||||
expect(f.provider).not.toHaveBeenCalled();
|
||||
await db.update(budgetPolicies).set({ amount: 5 }).where(eq(budgetPolicies.id, policy.id));
|
||||
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("succeeded");
|
||||
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0]).toMatchObject({ agentId: f.agentId, projectId, amountCents: "2.0000000", state: "settled" });
|
||||
});
|
||||
it("releases reservations when the provider rejects a request before model work", async () => {
|
||||
const f = await fixture();
|
||||
f.provider.mockResolvedValue({ noProviderWork: true, errorCode: "provider_auth_failed", receipt: { ...outcome.receipt, inputTokens: 0, costCents: "0", pricingProvenance: { source: "unknown", evidence: "HTTP 401" } } });
|
||||
expect((await f.service.decide(f.context, DECISION_TEST_REQUEST)).status).toBe("failed");
|
||||
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("released");
|
||||
expect((await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId)))[0].costCents).toBe(0);
|
||||
});
|
||||
it("enforces manager-only configuration and tests, company isolation, and fixed sample execution", async () => {
|
||||
const f = await fixture(), other = await fixture();
|
||||
const app = express(); app.use(express.json());
|
||||
let actor = f.context.actor;
|
||||
app.use((req, _res, next) => { req.actor = actor as typeof req.actor; next(); });
|
||||
app.use("/api", decisionModelRoutes(db)); app.use(errorHandler);
|
||||
const url = `/api/companies/${f.companyId}/decision-model`;
|
||||
expect((await request(app).get(url)).body.canManage).toBe(true);
|
||||
expect((await request(app).get(`/api/companies/${other.companyId}/decision-model`)).status).toBe(403);
|
||||
actor = { type: "board", userId: "alice", source: "session", companyIds: [f.companyId], memberships: [{ companyId: f.companyId, status: "active", membershipRole: "viewer" }] };
|
||||
expect((await request(app).get(url)).body).toEqual({ canManage: false, settings: null, choices: [] });
|
||||
expect((await request(app).put(url).send(f.config)).status).toBe(403);
|
||||
expect((await request(app).post(`${url}/test`).send({ actor: { type: "system" } })).status).toBe(403);
|
||||
actor = f.context.actor;
|
||||
await f.service.configure(f.companyId, "alice", { ...f.config, enabled: false });
|
||||
expect((await request(app).post(`${url}/test`).send({ state: "untrusted", actor: { type: "system" }, model: "untrusted" })).body).toEqual({ status: "unavailable", reason: "disabled" });
|
||||
expect((await request(app).post(`${url}/decide`).send(DECISION_TEST_REQUEST)).status).toBe(404);
|
||||
expect((await request(app).get(`${url}/history?limit=501`)).status).toBe(400);
|
||||
expect((await request(app).get(`${url}/history?from=2026-10-01T00:00:00.000Z&to=2026-10-31T23:59:59.000Z`)).status).toBe(200);
|
||||
});
|
||||
it("keeps private task links out of company cost history for unauthorized readers", async () => {
|
||||
const f = await fixture(), projectId = randomUUID(), issueId = randomUUID();
|
||||
await db.insert(projects).values({ id: projectId, companyId: f.companyId, name: "Private project", visibility: "private", privacyOwnerUserId: "bob" });
|
||||
await db.insert(issues).values({ id: issueId, companyId: f.companyId, projectId, title: "PRIVATE TITLE", identifier: "SECRET-1" });
|
||||
await f.service.decide({ companyId: f.companyId, feature: backgroundFeature, actor: { type: "system" }, issueId }, DECISION_TEST_REQUEST);
|
||||
await db.update(companyMemberships).set({ membershipRole: "member" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "alice")));
|
||||
const actor = { type: "board" as const, userId: "alice", source: "session" as const, companyIds: [f.companyId], memberships: [{ companyId: f.companyId, status: "active", membershipRole: "member" }] };
|
||||
expect(await f.service.availability({ ...f.context, actor, issueId })).toMatchObject({ available: false, reason: "access_denied" });
|
||||
const history = await f.service.history(f.companyId, actor);
|
||||
expect(history[0]).toMatchObject({ issueId: null, issueIdentifier: null, runId: null });
|
||||
expect(JSON.stringify(history)).not.toContain("SECRET");
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"agent-avatars.ts": "/api",
|
||||
"announcements.ts": "/api",
|
||||
"ai-connections.ts": "/api",
|
||||
"decision-models.ts": "/api",
|
||||
"attention.ts": "/api",
|
||||
"approvals.ts": "/api",
|
||||
"assets.ts": "/api",
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createMcpApiDispatch, createPublicMcpExecutor } from "./services/public
|
||||
import { createPublicMcpEvents, type PublicMcpEvents } from "./services/public-mcp/events.js";
|
||||
import { publicMcpIngressRoutes, publicMcpManagementRoutes } from "./routes/public-mcp.js";
|
||||
import { agentAvatarRoutes } from "./routes/agent-avatars.js";
|
||||
import { decisionModelRoutes } from "./routes/decision-models.js";
|
||||
import { aiConnectionRoutes } from "./routes/ai-connections.js";
|
||||
import { projectToolRoutes } from "./routes/project-tools.js";
|
||||
import { emailChannelService } from "./services/email-channels.js";
|
||||
@@ -877,6 +878,7 @@ export async function createApp(
|
||||
registerAssignedMcpGateway(db, toolGateway);
|
||||
app.locals.toolActionDeliveries = toolActionDeliveries;
|
||||
app.use(mcpGatewayProtocolRoutes(toolGateway));
|
||||
api.use(decisionModelRoutes(db));
|
||||
api.use(aiConnectionRoutes(db, { deploymentMode: opts.deploymentMode, deploymentExposure: opts.deploymentExposure, trustedLocalStdioRuntimeHost }));
|
||||
api.use(
|
||||
toolAccessRoutes(db, {
|
||||
|
||||
@@ -39,7 +39,7 @@ export function responsibleUserForAiRequest(req: Request): string | null {
|
||||
: getActorInfo(req).actorId;
|
||||
}
|
||||
|
||||
async function canManageAiConnections(db: Db, req: Request, companyId: string): Promise<boolean> {
|
||||
export async function canManageAiConnections(db: Db, req: Request, companyId: string): Promise<boolean> {
|
||||
const membership = req.actor.memberships?.find((m) => m.companyId === companyId && m.status === "active");
|
||||
if (membership?.membershipRole === "viewer") return false;
|
||||
return req.actor.source === "local_implicit" || Boolean(req.actor.isInstanceAdmin)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Router } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { DECISION_TEST_REQUEST, updateDecisionModelSchema } from "@paperclipai/shared";
|
||||
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
import { canManageAiConnections } from "./ai-connections.js";
|
||||
import { forbidden } from "../errors.js";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { decisionModelService, settingsDecisionTest } from "../services/decision-models.js";
|
||||
import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { parseCostDateRange, parseCostLimit } from "./costs.js";
|
||||
|
||||
export function decisionModelRoutes(db: Db) {
|
||||
const router = Router();
|
||||
const service = decisionModelService(db, { budgetHooks: { cancelWorkForScope: heartbeatService(db).cancelBudgetScopeWork } });
|
||||
router.get("/companies/:companyId/decision-model", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId); assertBoard(req);
|
||||
const canManage = await canManageAiConnections(db, req, companyId);
|
||||
if (!canManage) { res.json({ canManage, settings: null, choices: [] }); return; }
|
||||
res.json({ canManage, settings: await service.settings(companyId), choices: await service.choices(companyId, getActorInfo(req).actorId) });
|
||||
});
|
||||
router.put("/companies/:companyId/decision-model", validate(updateDecisionModelSchema), async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId); assertBoard(req);
|
||||
if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
|
||||
res.json(await service.configure(companyId, getActorInfo(req).actorId, req.body));
|
||||
});
|
||||
router.get("/companies/:companyId/decision-model/availability", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
res.json(await service.availability({ companyId, actor: req.actor, feature: settingsDecisionTest }));
|
||||
});
|
||||
router.post("/companies/:companyId/decision-model/test", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId); assertBoard(req);
|
||||
if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
|
||||
// The client cannot supply a prompt, model, identity, or background flag.
|
||||
res.json(await service.decide({ companyId, actor: req.actor, feature: settingsDecisionTest }, DECISION_TEST_REQUEST));
|
||||
});
|
||||
router.get("/companies/:companyId/decision-model/history", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
res.json(await service.history(companyId, req.actor, { ...parseCostDateRange(req.query), limit: parseCostLimit(req.query) }));
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { Router } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
createAiConnectionSchema,
|
||||
updateDecisionModelSchema,
|
||||
aiConnectionPoolConfigSchema,
|
||||
aiConnectionLoginIntentSchema,
|
||||
localAiConnectionSchema,
|
||||
@@ -1355,6 +1356,9 @@ const browserUseOperations = [
|
||||
] as const;
|
||||
|
||||
const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"GET /api/companies/{companyId}/decision-model",
|
||||
"PUT /api/companies/{companyId}/decision-model",
|
||||
"POST /api/companies/{companyId}/decision-model/test",
|
||||
...browserUseOperations.map(([method, path]) => `${method.toUpperCase()} ${path}`),
|
||||
"GET /api/companies/{companyId}/ai-connections",
|
||||
"POST /api/companies/{companyId}/ai-connections",
|
||||
@@ -10735,6 +10739,33 @@ registerCurrentRoute({
|
||||
|
||||
// --- Tool access -------------------------------------------------------------
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "get", path: "/api/companies/{companyId}/decision-model", tags: ["decision-models"],
|
||||
summary: "Get decision settings, compatible connections, and manager capability",
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "put", path: "/api/companies/{companyId}/decision-model", tags: ["decision-models"],
|
||||
summary: "Configure the company decision model as a connection manager", body: updateDecisionModelSchema,
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 422: r.unprocessable },
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "get", path: "/api/companies/{companyId}/decision-model/availability", tags: ["decision-models"],
|
||||
summary: "Check local decision configuration and caller authorization without contacting a provider",
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "post", path: "/api/companies/{companyId}/decision-model/test", tags: ["decision-models"],
|
||||
summary: "Run the fixed billed three-question setup test as a connection manager",
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
|
||||
});
|
||||
registerCurrentRoute({
|
||||
method: "get", path: "/api/companies/{companyId}/decision-model/history", tags: ["decision-models"],
|
||||
summary: "List decision metadata and charges with authorized task links",
|
||||
query: costReportQuerySchema.extend({ limit: z.coerce.number().int().min(1).max(500).optional() }),
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden },
|
||||
});
|
||||
|
||||
registerCurrentRoute({
|
||||
method: "get",
|
||||
path: "/api/companies/{companyId}/tools/gallery",
|
||||
|
||||
@@ -111,7 +111,7 @@ export function accountingIntegrityService(db: Db, hooks: BudgetServiceHooks = {
|
||||
and result_json->'executionRecovery'->>'providerWorkStarted' is distinct from 'false' then 'waiting_for_receipt' else 'retryable' end as state,
|
||||
accounting_last_error as "lastError", accounting_attempt_count as attempts, coalesce(finished_at,created_at)::text as since, accounting_last_attempt_at::text as "lastAttemptAt"
|
||||
from heartbeat_runs where company_id = ${companyId} and cost_accounting_pending and status in ('succeeded','failed','timed_out','cancelled','interrupted') order by coalesce(finished_at,created_at),id limit 100`);
|
||||
const unpriced = await tx.execute<{ runId: string | null; costEventId: string; agentId: string; since: string }>(sql`
|
||||
const unpriced = await tx.execute<{ runId: string | null; costEventId: string; agentId: string | null; since: string }>(sql`
|
||||
select heartbeat_run_id as "runId", id as "costEventId", agent_id as "agentId", occurred_at::text as since from cost_events
|
||||
where company_id = ${companyId} and cost_status = 'unpriced' and billing_type <> 'subscription_included' order by occurred_at,id limit 100`);
|
||||
return { companyId, pendingRunCount: counts.pending, unpricedEventCount: counts.unpriced, oldestPendingAt: counts.oldest, pendingCancellationCount: counts.cancellations,
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
agentWakeupRequests,
|
||||
activityLog,
|
||||
costEvents,
|
||||
budgetReservations,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
issueExecutionDecisions,
|
||||
@@ -1098,6 +1099,13 @@ export function agentService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
|
||||
}
|
||||
|
||||
return withAccountingTransaction(db, existing.companyId, async (tx) => {
|
||||
const [decisionHold] = await tx.select({ id: budgetReservations.id }).from(budgetReservations).where(and(
|
||||
eq(budgetReservations.companyId, existing.companyId), eq(budgetReservations.agentId, id),
|
||||
eq(budgetReservations.state, "held"), sql`${budgetReservations.decisionInvocationId} is not null`,
|
||||
)).limit(1);
|
||||
if (decisionHold) throw conflict("Wait for active decisions or resolve their unknown charges in Costs before deleting this agent", {
|
||||
code: "agent_decision_accounting_pending",
|
||||
});
|
||||
await tx
|
||||
.select({ id: agents.id })
|
||||
.from(agents)
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
AI_CONNECTION_CAPABILITIES,
|
||||
decisionProviderForConnection,
|
||||
aiConnectionCatalogSlug,
|
||||
getAppStoreDefinition,
|
||||
aiConnectionMetadataSchema,
|
||||
@@ -407,7 +408,41 @@ export function aiConnectionService(db: Db) {
|
||||
} satisfies AiConnectionAttribution,
|
||||
};
|
||||
}
|
||||
async function credential(row: Pick<Awaited<ReturnType<typeof select>>, "connection" | "grant">, retry = 0): Promise<string> {
|
||||
/** Internal decision use has its own capability check, never a pretend CLI harness. */
|
||||
async function selectDecision(input: {
|
||||
companyId: string; connectionId: string; grantId: string;
|
||||
userId: string | null; agentId?: string | null; sponsoredBackground?: boolean;
|
||||
}) {
|
||||
const [row] = await db.select({ connection: toolConnections, grant: connectionGrants })
|
||||
.from(toolConnections).innerJoin(connectionGrants, and(
|
||||
eq(connectionGrants.connectionId, toolConnections.id), eq(connectionGrants.companyId, toolConnections.companyId),
|
||||
)).where(and(eq(toolConnections.companyId, input.companyId), eq(toolConnections.id, input.connectionId),
|
||||
eq(connectionGrants.id, input.grantId), eq(toolConnections.connectionPurpose, "ai"))).limit(1);
|
||||
if (!row || row.grant.kind !== "organization") throw unprocessable("Shared AI connection unavailable", { code: "connection_unavailable" });
|
||||
const metadata = aiConnectionMetadataSchema.safeParse(row.connection.config.ai);
|
||||
const provider = metadata.success ? decisionProviderForConnection(metadata.data) : null;
|
||||
if (!provider) throw unprocessable("Connection does not support decisions", { code: "incompatible_connection" });
|
||||
if (row.grant.status !== "active" || !row.connection.enabled || row.connection.status !== "active" || row.connection.healthStatus !== "ok")
|
||||
throw unprocessable("Reconnect or enable this connection", { code: "connection_unavailable" });
|
||||
// Only the decision service may sponsor background use; ordinary AI selection never bypasses an audience.
|
||||
if (!input.sponsoredBackground) {
|
||||
if (!(await membership(input.companyId, input.userId))) throw forbidden("Active responsible user required");
|
||||
const audience = await db.select().from(connectionGrantMembers).where(and(
|
||||
eq(connectionGrantMembers.companyId, input.companyId), eq(connectionGrantMembers.grantId, input.grantId),
|
||||
));
|
||||
if (!canUseCredential(row.grant, input.userId, audience)) throw forbidden("Connection is not shared with this user");
|
||||
} else if (input.userId || input.agentId) throw forbidden("Background sponsorship cannot replace caller permissions");
|
||||
if (input.agentId) {
|
||||
const [install] = await db.select({ id: toolConnectionInstalls.id }).from(toolConnectionInstalls).where(and(
|
||||
eq(toolConnectionInstalls.companyId, input.companyId), eq(toolConnectionInstalls.connectionId, input.connectionId),
|
||||
or(and(eq(toolConnectionInstalls.targetType, "company"), eq(toolConnectionInstalls.targetId, input.companyId)),
|
||||
and(eq(toolConnectionInstalls.targetType, "agent"), eq(toolConnectionInstalls.targetId, input.agentId))),
|
||||
)).limit(1);
|
||||
if (!install) throw forbidden("Connection is not permitted for this agent");
|
||||
}
|
||||
return { ...row, provider };
|
||||
}
|
||||
async function credential(row: Pick<Awaited<ReturnType<typeof select>>, "connection" | "grant">, retry = 0, audit?: { responsibleUserId: string | null; actorType: "user" | "agent" | "system"; actorId: string; issueId?: string | null; heartbeatRunId?: string | null }): Promise<string> {
|
||||
const metadata = aiConnectionMetadataSchema.parse(row.connection.config.ai);
|
||||
if (metadata.routing?.auth === "none") return "";
|
||||
const ref = row.grant.credentialSecretRefs.find(
|
||||
@@ -432,12 +467,14 @@ export function aiConnectionService(db: Db) {
|
||||
});
|
||||
if (row.grant.kind === "user" && secret.scope !== "user")
|
||||
throw forbidden("Credential ownership mismatch");
|
||||
if (row.grant.kind === "organization" && secret.scope !== "company") throw forbidden("Credential ownership mismatch");
|
||||
const context = {
|
||||
consumerType: "tool_connection" as const,
|
||||
consumerId: row.connection.id,
|
||||
configPath: ref.configPath,
|
||||
responsibleUserId: row.grant.subjectUserId,
|
||||
actorType: "system" as const,
|
||||
...audit,
|
||||
};
|
||||
let value: string;
|
||||
if (secret.scope === "user") {
|
||||
@@ -469,7 +506,7 @@ export function aiConnectionService(db: Db) {
|
||||
if (!latest || latest.status !== "active") throw unprocessable("Reconnect this AI account");
|
||||
if (latest.latestVersion !== secret.latestVersion) {
|
||||
if (retry >= 2) throw unprocessable("AI credentials are changing. Retry this execution.", { code: "ai_connection_busy" });
|
||||
return credential(row, retry + 1);
|
||||
return credential(row, retry + 1, audit);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -1070,5 +1107,5 @@ export function aiConnectionService(db: Db) {
|
||||
return [{ ...row, summary }];
|
||||
});
|
||||
}
|
||||
return { list, quotaAccounts, refreshQuotaCredential, select, credential, runtimeCredential, probeUsage, save, setDefault, membership, markAuthenticationFailed };
|
||||
return { list, selectDecision, quotaAccounts, refreshQuotaCredential, select, credential, runtimeCredential, probeUsage, save, setDefault, membership, markAuthenticationFailed };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createFinanceEventInTransaction } from "./finance.js";
|
||||
import { and, desc, eq, sql } from "drizzle-orm";
|
||||
import { agentRuntimeState, costEvents, costAdjustments, billingInvoices, billingInvoiceLines, financeEvents, heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { decisionInvocations, budgetReservations, agentRuntimeState, costEvents, costAdjustments, billingInvoices, billingInvoiceLines, financeEvents, heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { adjustCostSchema, importBillingInvoiceSchema, normalizeCents, subtractCents, type AdjustCost, type ImportBillingInvoice } from "@paperclipai/shared";
|
||||
import { conflict, notFound, unprocessable } from "../errors.js";
|
||||
import { withAccountingReadSnapshot, withAccountingTransaction } from "./accounting-transaction.js";
|
||||
@@ -147,12 +147,20 @@ export function billingReconciliationService(db: Db, hooks: BudgetServiceHooks =
|
||||
reportedCostCents: event.event.reportedCostCents ?? normalizeCents(event.exact), costStatus: input.pricing.source === "rate_card" ? "estimated" : "reported", pricingProvenance: input.pricing,
|
||||
}).where(eq(costEvents.id, eventId)).returning();
|
||||
await updateMonthlySpendProjections(tx, companyId, updated.agentId, subtractCents(input.correctedCents, input.expectedCents), updated.occurredAt);
|
||||
if (updated.heartbeatRunId) {
|
||||
if (updated.heartbeatRunId && updated.agentId) {
|
||||
const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, updated.heartbeatRunId), eq(heartbeatRuns.companyId, companyId)));
|
||||
if (run?.costAccountedAt && run.accountingProjectionVersion === "v2") await tx.update(agentRuntimeState)
|
||||
.set({ totalCostCents: sql`${agentRuntimeState.totalCostCents} + ${subtractCents(input.correctedCents, input.expectedCents)}::numeric`, updatedAt: new Date() })
|
||||
.where(and(eq(agentRuntimeState.agentId, updated.agentId), eq(agentRuntimeState.companyId, companyId)));
|
||||
}
|
||||
if (updated.usageKind === "decision") {
|
||||
const [invocation] = await tx.select({ id: decisionInvocations.id }).from(decisionInvocations).where(and(
|
||||
eq(decisionInvocations.companyId, companyId), eq(decisionInvocations.costEventId, eventId),
|
||||
));
|
||||
if (invocation) await tx.update(budgetReservations).set({ state: "settled", settledAt: new Date() }).where(and(
|
||||
eq(budgetReservations.companyId, companyId), eq(budgetReservations.decisionInvocationId, invocation.id), eq(budgetReservations.state, "held"),
|
||||
));
|
||||
}
|
||||
const budgets = budgetServiceInTransaction(tx, publications);
|
||||
await budgets.evaluateCostEvent(updated);
|
||||
await budgets.getInvocationBlock(companyId, updated.agentId, { projectId: updated.projectId });
|
||||
|
||||
@@ -160,10 +160,10 @@ async function mapBudgetReads<T, R>(rows: T[], read: (row: T) => Promise<R>): Pr
|
||||
}
|
||||
|
||||
/** Filter in PostgreSQL so one run never loads unrelated agents' policies. */
|
||||
export function budgetPoliciesForRun(companyId: string, agentId: string, projectId: string | null) {
|
||||
export function budgetPoliciesForRun(companyId: string, agentId: string | null, projectId: string | null) {
|
||||
return or(
|
||||
and(eq(budgetPolicies.scopeType, "company"), eq(budgetPolicies.scopeId, companyId)),
|
||||
and(eq(budgetPolicies.scopeType, "agent"), eq(budgetPolicies.scopeId, agentId)),
|
||||
agentId ? and(eq(budgetPolicies.scopeType, "agent"), eq(budgetPolicies.scopeId, agentId)) : undefined,
|
||||
projectId ? and(eq(budgetPolicies.scopeType, "project"), eq(budgetPolicies.scopeId, projectId)) : undefined,
|
||||
);
|
||||
}
|
||||
@@ -858,11 +858,11 @@ export function budgetServiceInTransaction(db: Db, publications: ActivityPublica
|
||||
|
||||
getInvocationBlock: async (
|
||||
companyId: string,
|
||||
agentId: string,
|
||||
agentId: string | null,
|
||||
context?: { issueId?: string | null; projectId?: string | null },
|
||||
) => {
|
||||
const scopes: Array<{ scopeType: BudgetScopeType; scopeId: string }> = [
|
||||
{ scopeType: "company", scopeId: companyId }, { scopeType: "agent", scopeId: agentId },
|
||||
{ scopeType: "company", scopeId: companyId }, ...(agentId ? [{ scopeType: "agent" as const, scopeId: agentId }] : []),
|
||||
...(context?.projectId ? [{ scopeType: "project" as const, scopeId: context.projectId }] : []),
|
||||
];
|
||||
for (const { scopeType, scopeId } of scopes) {
|
||||
@@ -1043,7 +1043,7 @@ export function budgetService(db: Db, hooks: BudgetServiceHooks = {}) {
|
||||
mutate(companyId, (service) => service.upsertPolicy(companyId, input, actorUserId)),
|
||||
evaluateCostEvent: (event: typeof costEvents.$inferSelect) =>
|
||||
mutate(event.companyId, (service) => service.evaluateCostEvent(event)),
|
||||
getInvocationBlock: (companyId: string, agentId: string, context?: { issueId?: string | null; projectId?: string | null }) =>
|
||||
getInvocationBlock: (companyId: string, agentId: string | null, context?: { issueId?: string | null; projectId?: string | null }) =>
|
||||
mutate(companyId, (service) => service.getInvocationBlock(companyId, agentId, context)),
|
||||
resolveIncident: (companyId: string, incidentId: string, input: BudgetIncidentResolutionInput, actorUserId: string) =>
|
||||
mutate(companyId, (service) => service.resolveIncident(companyId, incidentId, input, actorUserId)),
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
runIdentityContexts,
|
||||
heartbeatRunEvents,
|
||||
costEvents,
|
||||
decisionInvocations,
|
||||
financeEvents,
|
||||
budgetPolicies,
|
||||
budgetIncidents,
|
||||
@@ -563,6 +564,7 @@ export function companyService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
|
||||
// Finance can reference costs and both can reference runs. Incidents
|
||||
// reference policies and approvals; delete these dependents first.
|
||||
await tx.delete(financeEvents).where(eq(financeEvents.companyId, id));
|
||||
await tx.delete(decisionInvocations).where(eq(decisionInvocations.companyId, id));
|
||||
await tx.delete(costEvents).where(eq(costEvents.companyId, id));
|
||||
await tx.delete(budgetIncidents).where(eq(budgetIncidents.companyId, id));
|
||||
await tx.delete(budgetPolicies).where(eq(budgetPolicies.companyId, id));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { receiptFingerprint } from "./receipt-fingerprint.js";
|
||||
import { agentAvatarUrl, resolveAgentAppearance, createCostEventSchema, normalizeCents, type MoneyInput, type CostByUserReport } from "@paperclipai/shared";
|
||||
import { agentAvatarUrl, resolveAgentAppearance, createCostEventSchema, createServiceCostEventSchema, normalizeCents, 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";
|
||||
@@ -42,12 +42,13 @@ function currentUtcMonthWindow(now = new Date()) {
|
||||
/** Increment an initialized month under the company lock. On upgrade or UTC
|
||||
* rollover, initialize from the ledger in the same transaction exactly once.
|
||||
* Reports, budgets and the integrity checker continue reading the ledger. */
|
||||
export async function updateMonthlySpendProjections(db: Db, companyId: string, agentId: string, amountCents: MoneyInput, occurredAt: Date) {
|
||||
export async function updateMonthlySpendProjections(db: Db, companyId: string, agentId: string | null, amountCents: MoneyInput, occurredAt: Date) {
|
||||
const { start, end } = currentUtcMonthWindow();
|
||||
const month = start.toISOString().slice(0, 10);
|
||||
const delta = occurredAt >= start && occurredAt < end ? normalizeCents(amountCents) : "0.0000000";
|
||||
for (const table of [companies, agents] as const) {
|
||||
const id = table === companies ? companyId : agentId;
|
||||
if (!id) continue;
|
||||
const companyCondition = table === companies ? eq(companies.id, companyId) : eq(agents.companyId, companyId);
|
||||
await db.update(table).set({
|
||||
spentMonthlyCents: sql`case when ${table.spendMonthUtc} = ${month} then ${table.spentMonthlyCents} + ${delta}::numeric else (
|
||||
@@ -82,7 +83,7 @@ export async function getMonthlySpendTotal(
|
||||
}
|
||||
|
||||
export async function createCostEventInTransaction(db: Db, companyId: string, data: Omit<typeof costEvents.$inferInsert, "companyId" | "receiptHash" | "costCents"> & { costCents: MoneyInput }, publications: ActivityPublication[] = [], actor?: Pick<LogActivityInput, "actorType" | "actorId" | "agentId">) {
|
||||
const parsed = createCostEventSchema.safeParse({ ...data, occurredAt: data.occurredAt.toISOString() });
|
||||
const parsed = (data.usageKind === "decision" ? createServiceCostEventSchema : createCostEventSchema).safeParse({ ...data, occurredAt: data.occurredAt.toISOString() });
|
||||
if (!parsed.success) throw unprocessable("Invalid cost receipt", parsed.error.flatten());
|
||||
const values = {
|
||||
...parsed.data,
|
||||
@@ -132,7 +133,7 @@ export async function createCostEventInTransaction(db: Db, companyId: string, da
|
||||
// Separately reported charges linked to an already-accounted run contribute
|
||||
// to lifetime totals too. Before acknowledgement, accountRunCost includes
|
||||
// all of the run's events atomically when it initializes the projection.
|
||||
if (event.heartbeatRunId) {
|
||||
if (event.heartbeatRunId && event.agentId) {
|
||||
const [run] = await db.select({ acknowledged: heartbeatRuns.costAccountedAt, version: heartbeatRuns.accountingProjectionVersion })
|
||||
.from(heartbeatRuns).where(and(eq(heartbeatRuns.id, event.heartbeatRunId), eq(heartbeatRuns.companyId, companyId)));
|
||||
if (run.acknowledged && run.version === "v2") await db.update(agentRuntimeState).set({
|
||||
@@ -146,6 +147,7 @@ export async function createCostEventInTransaction(db: Db, companyId: string, da
|
||||
await budgetServiceInTransaction(db, publications).evaluateCostEvent(event);
|
||||
await logActivity(db, {
|
||||
companyId, actorType: actor?.actorType ?? "system", actorId: actor?.actorId ?? "cost_accounting", agentId: actor?.agentId ?? event.agentId,
|
||||
...(event.usageKind === "decision" ? { responsibleUserIdOverride: event.responsibleUserId } : {}),
|
||||
runId: event.heartbeatRunId, action: "cost.reported", entityType: "cost_event", entityId: event.id,
|
||||
details: { costCents: event.costCents, costCentsExact: values.costCents, model: event.model, costStatus: event.costStatus },
|
||||
}, publications);
|
||||
@@ -402,7 +404,7 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
|
||||
eq(companyMemberships.companyId, companyId),
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
ne(companyMemberships.principalId, "local-board"),
|
||||
eq(companyMemberships.principalId, heartbeatRuns.responsibleUserId),
|
||||
eq(companyMemberships.principalId, sql`case when ${costEvents.usageKind} = 'decision' then ${costEvents.responsibleUserId} else ${heartbeatRuns.responsibleUserId} end`),
|
||||
))
|
||||
.where(and(...conditions))
|
||||
.groupBy(companyMemberships.principalId)
|
||||
@@ -463,8 +465,8 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
|
||||
.groupBy(costEvents.agentId, agents.name, agents.appearance, agents.status)
|
||||
.orderBy(desc(sumAsNumber(costEvents.costCents)));
|
||||
return rows.map(row => {
|
||||
const appearance = resolveAgentAppearance(row.agentAppearance, row.agentId);
|
||||
return { ...row, agentAppearance: appearance, avatarUrl: agentAvatarUrl(appearance, 512) };
|
||||
const appearance = row.agentId ? resolveAgentAppearance(row.agentAppearance, row.agentId) : null;
|
||||
return { ...row, agentAppearance: appearance, avatarUrl: appearance ? agentAvatarUrl(appearance, 512) : undefined };
|
||||
});
|
||||
},
|
||||
|
||||
@@ -630,8 +632,8 @@ export function costService(db: Db, budgetHooks: BudgetServiceHooks = {}) {
|
||||
)
|
||||
.orderBy(costEvents.provider, costEvents.biller, costEvents.billingType, costEvents.model);
|
||||
return rows.map(row => {
|
||||
const appearance = resolveAgentAppearance(row.agentAppearance, row.agentId);
|
||||
return { ...row, agentAppearance: appearance, avatarUrl: agentAvatarUrl(appearance, 512) };
|
||||
const appearance = row.agentId ? resolveAgentAppearance(row.agentAppearance, row.agentId) : null;
|
||||
return { ...row, agentAppearance: appearance, avatarUrl: appearance ? agentAvatarUrl(appearance, 512) : undefined };
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { createOpenAI } from "@ai-sdk/openai";
|
||||
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
|
||||
import { experimental_decide as decide, type Experimental_DecisionModel } from "ai";
|
||||
import { centsToUnits, unitsToCents, type DecisionAnswer, type DecisionProvider, type DecisionRequest } from "@paperclipai/shared";
|
||||
|
||||
export interface DecisionProviderReceipt {
|
||||
inputTokens: number | null; outputTokens: number | null; providerRequestId: string | null;
|
||||
costCents: string | null; costStatus: "reported" | "estimated" | "unpriced";
|
||||
pricingProvenance: { source: "provider_reported" | "rate_card" | "unknown"; version?: string; evidence?: string; inputCentsPerMillion?: string };
|
||||
}
|
||||
export interface DecisionProviderOutcome { noProviderWork?: boolean; answers?: Record<string, DecisionAnswer>; errorCode?: string; receipt: DecisionProviderReceipt }
|
||||
const record = (v: unknown): Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record<string, unknown> : {};
|
||||
const tokenCount = (v: unknown) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= 2_147_483_647 ? v : null;
|
||||
function rejectedResponseData(error: unknown) {
|
||||
const value = record(error);
|
||||
if (value.data) return record(value.data);
|
||||
if (record(value.cause).value) return record(record(value.cause).value);
|
||||
// SDK schema rejection may retain only responseBody. Read a bounded body in
|
||||
// memory for accounting; never forward it to the ledger, logger, or caller.
|
||||
if (typeof value.responseBody === "string" && value.responseBody.length <= 1_000_000) {
|
||||
try { return record(JSON.parse(value.responseBody)); } catch { /* Not valid JSON. */ }
|
||||
}
|
||||
return {};
|
||||
}
|
||||
export function decisionReceipt(provider: DecisionProvider, result: unknown): DecisionProviderReceipt {
|
||||
const value = record(result), usage = record(value.usage), metadata = record(value.providerMetadata);
|
||||
const response = record(value.response);
|
||||
const headers = record(response.headers);
|
||||
const inputTokens = tokenCount(usage.inputTokens), outputTokens = tokenCount(usage.outputTokens);
|
||||
const reported = record(record(metadata.openrouter).usage).cost;
|
||||
const base = { inputTokens, outputTokens, providerRequestId: typeof response.id === "string" ? response.id.slice(0, 250) : typeof headers["x-request-id"] === "string" ? headers["x-request-id"].slice(0, 250) : null };
|
||||
if (provider === "openrouter" && typeof reported === "number" && Number.isFinite(reported) && reported >= 0) {
|
||||
return { ...base, costCents: unitsToCents(centsToUnits(reported * 100)), costStatus: "reported", pricingProvenance: { source: "provider_reported" } };
|
||||
}
|
||||
// V1 uses the official default endpoint and bounded short text requests. Decisions has its own rate, not the chat model's rate.
|
||||
if (provider === "openai" && inputTokens !== null && inputTokens <= 32_000) {
|
||||
return { ...base, costCents: unitsToCents(centsToUnits("10") * BigInt(inputTokens) / 1_000_000n), costStatus: "estimated",
|
||||
pricingProvenance: { source: "rate_card", version: "openai-decisions-2026-10-07", inputCentsPerMillion: "10.0000000" } };
|
||||
}
|
||||
return { ...base, costCents: null, costStatus: "unpriced", pricingProvenance: { source: "unknown" } };
|
||||
}
|
||||
export async function runDecisionProvider(input: {
|
||||
provider: DecisionProvider; model: string; apiKey: string; request: DecisionRequest; signal: AbortSignal;
|
||||
}, options: { fetch?: typeof fetch } = {}): Promise<DecisionProviderOutcome> {
|
||||
const native = input.provider === "openai"
|
||||
? createOpenAI({ apiKey: input.apiKey, fetch: options.fetch }).decisionModel(input.model)
|
||||
: createOpenRouter({ apiKey: input.apiKey, fetch: options.fetch }).evaluationModel(input.model);
|
||||
let receipt = decisionReceipt(input.provider, null);
|
||||
// Capture only accounting metadata before SDK answer validation/refusal errors.
|
||||
const model: Exclude<Experimental_DecisionModel, string> = {
|
||||
specificationVersion: "v4", provider: native.provider, modelId: native.modelId, supportedQuestionTypes: native.supportedQuestionTypes,
|
||||
async doDecide(args) {
|
||||
const response = await ("doDecide" in native ? native.doDecide(args) : native.doEvaluate(args));
|
||||
receipt = decisionReceipt(input.provider, response);
|
||||
return { ...response, warnings: [] };
|
||||
},
|
||||
};
|
||||
try {
|
||||
const result = await decide({ model, ...input.request, maxRetries: 0, abortSignal: input.signal,
|
||||
telemetry: { isEnabled: false, recordInputs: false, recordOutputs: false } });
|
||||
const metadata = record(result.providerMetadata);
|
||||
const answers = Object.fromEntries(Object.entries(result.answers).map(([id, answer]) => {
|
||||
const confidence = input.provider === "openai" ? record(record(metadata.openai).confidence)[id]
|
||||
: record(record(record(metadata.openrouter).answers)[id]).confidence;
|
||||
return [id, { ...answer, ...(typeof confidence === "number" && confidence >= 0 && confidence <= 1 ? { confidence } : {}) }];
|
||||
}));
|
||||
return { answers, receipt };
|
||||
} catch (error) {
|
||||
// Never expose provider error messages/bodies; they may contain inputs or credentials.
|
||||
const name = error instanceof Error ? error.name : "";
|
||||
const status = record(error).statusCode;
|
||||
// SDKs can reject refusals or malformed answers before normalized usage.
|
||||
// Keep only validated accounting fields, even in this failure path.
|
||||
const data = rejectedResponseData(error);
|
||||
const rawUsage = record(data.usage);
|
||||
if (receipt.costStatus === "unpriced") {
|
||||
receipt = decisionReceipt(input.provider, { usage: { inputTokens: rawUsage.input_tokens, outputTokens: rawUsage.output_tokens },
|
||||
providerMetadata: { openrouter: { usage: { cost: rawUsage.cost } } },
|
||||
response: { id: data.id, headers: record(error).responseHeaders } });
|
||||
}
|
||||
const rawAnswers = Array.isArray(data.answers) ? data.answers : Object.values(record(data.answers));
|
||||
const refused = name.includes("Refusal") || record(data.error).type === "refusal" || rawAnswers.some(answer => record(answer).type === "refusal");
|
||||
const errorCode = input.signal.aborted ? "timeout" : refused ? "refused"
|
||||
: status === 401 || status === 403 ? "provider_auth_failed" : status === 429 ? "provider_rate_limited" : "provider_failed";
|
||||
// An explicit authentication/validation rejection occurs before model work.
|
||||
// Server errors and network failures remain unresolved: their charge is unknown.
|
||||
const noProviderWork = receipt.costStatus === "unpriced" && [400, 401, 403, 404, 422, 429].includes(Number(status));
|
||||
if (noProviderWork) receipt = { ...receipt, inputTokens: 0, outputTokens: 0, costCents: "0.0000000", costStatus: "estimated",
|
||||
pricingProvenance: { source: "unknown", evidence: `Provider rejected request before model work (HTTP ${status})` } };
|
||||
return { errorCode, receipt, noProviderWork };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, desc, eq, gte, lt, lte, or, sql } from "drizzle-orm";
|
||||
import {
|
||||
agents, authUsers, budgetPolicies, budgetReservations, companies, companyMemberships, companyDecisionModels, costEvents,
|
||||
decisionInvocations, heartbeatRuns, issues, projects, companySecrets, type Db,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
DECISION_MODELS, decisionProviderForConnection, decisionRequestSchema, updateDecisionModelSchema,
|
||||
centsToUnits, unitsToCents, type DecisionAvailability, type DecisionConnectionChoice, type DecisionHistoryEntry,
|
||||
type DecisionModelSettings, type DecisionProvider, type DecisionRequest, type DecisionResult, type DecisionUnavailableReason, type UpdateDecisionModel,
|
||||
} from "@paperclipai/shared";
|
||||
import { HttpError, forbidden, unprocessable } from "../errors.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { accessService } from "./access.js";
|
||||
import { type AuthorizationActor } from "./authorization.js";
|
||||
import { withAccountingTransaction } from "./accounting-transaction.js";
|
||||
import { budgetPoliciesForRun, budgetService, budgetServiceInTransaction, computeObservedSpend, type BudgetServiceHooks } from "./budgets.js";
|
||||
import { createCostEventInTransaction } from "./costs.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { decisionReceipt, runDecisionProvider, type DecisionProviderOutcome } from "./decision-model-provider.js";
|
||||
|
||||
const registeredFeatures = new WeakSet<object>();
|
||||
/** Register once in a server module. Feature handles cannot be supplied over JSON/API. */
|
||||
export function defineDecisionFeature(id: string, options: { background?: boolean } = {}) {
|
||||
if (!/^[a-z][a-z0-9_.-]{0,99}$/.test(id)) throw new Error("Invalid decision feature identifier");
|
||||
const feature = Object.freeze({ id, background: options.background === true });
|
||||
registeredFeatures.add(feature);
|
||||
return feature;
|
||||
}
|
||||
export const settingsDecisionTest = defineDecisionFeature("settings.test");
|
||||
export interface DecisionContext {
|
||||
companyId: string;
|
||||
feature: ReturnType<typeof defineDecisionFeature>;
|
||||
actor: AuthorizationActor | { type: "system" };
|
||||
issueId?: string;
|
||||
projectId?: string;
|
||||
}
|
||||
class DecisionUnavailable extends Error {
|
||||
constructor(readonly reason: DecisionUnavailableReason) { super(reason); }
|
||||
}
|
||||
function unavailableReason(error: unknown): DecisionUnavailableReason | null {
|
||||
if (error instanceof DecisionUnavailable) return error.reason;
|
||||
if (error instanceof HttpError) {
|
||||
if (error.status === 403 || error.status === 404) return "access_denied";
|
||||
if (error.status === 422) {
|
||||
return (error.details as { code?: string } | undefined)?.code === "incompatible_connection" ? "incompatible_connection" : "connection_unavailable";
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function decisionModelService(db: Db, options: { provider?: typeof runDecisionProvider; budgetHooks?: BudgetServiceHooks } = {}) {
|
||||
const providerCall = options.provider ?? runDecisionProvider;
|
||||
async function settings(companyId: string): Promise<DecisionModelSettings> {
|
||||
const [row] = await db.select().from(companyDecisionModels).where(eq(companyDecisionModels.companyId, companyId));
|
||||
return row ? { ...row, provider: row.provider as DecisionProvider | null } : {
|
||||
companyId, enabled: false, allowBackground: true, connectionId: null, grantId: null, provider: null, model: null,
|
||||
};
|
||||
}
|
||||
async function choices(companyId: string, userId: string): Promise<DecisionConnectionChoice[]> {
|
||||
const connections = aiConnectionService(db);
|
||||
if (!(await connections.membership(companyId, userId))) throw forbidden();
|
||||
return (await connections.list(companyId, userId)).flatMap(row => {
|
||||
const provider = decisionProviderForConnection(row);
|
||||
return provider && row.ownership === "shared" ? [{ ...row, decisionModel: DECISION_MODELS[provider].id }] : [];
|
||||
});
|
||||
}
|
||||
async function configure(companyId: string, userId: string, input: UpdateDecisionModel) {
|
||||
const data = updateDecisionModelSchema.parse(input);
|
||||
return withAccountingTransaction(db, companyId, async (tx, publications) => {
|
||||
const [previous] = await tx.select().from(companyDecisionModels).where(eq(companyDecisionModels.companyId, companyId));
|
||||
// Managers can always turn off a broken/revoked connection without acquiring it.
|
||||
const disabling = !data.enabled && previous?.connectionId === data.connectionId && previous?.grantId === data.grantId;
|
||||
const row = !disabling && data.connectionId && data.grantId ? await aiConnectionService(tx).selectDecision({ companyId,
|
||||
userId, connectionId: data.connectionId, grantId: data.grantId }) : null;
|
||||
const provider = (disabling ? previous?.provider : row?.provider) as DecisionProvider | null | undefined;
|
||||
const values = { ...data, allowBackground: data.allowBackground ?? previous?.allowBackground ?? true, companyId, provider: provider ?? null, model: provider ? DECISION_MODELS[provider].id : null, updatedAt: new Date() };
|
||||
await tx.insert(companyDecisionModels).values(values).onConflictDoUpdate({ target: companyDecisionModels.companyId, set: values });
|
||||
await logActivity(tx, { companyId, actorType: "user", actorId: userId, action: "decision_model.configured", entityType: "company", entityId: companyId,
|
||||
details: { ...data, provider: values.provider, model: values.model } }, publications);
|
||||
return values;
|
||||
});
|
||||
}
|
||||
async function resolve(context: DecisionContext, executor = db) {
|
||||
if (!registeredFeatures.has(context.feature)) throw forbidden("A registered decision feature is required");
|
||||
const [config] = await executor.select().from(companyDecisionModels).where(eq(companyDecisionModels.companyId, context.companyId));
|
||||
if (!config?.connectionId || !config.grantId) throw new DecisionUnavailable("not_configured");
|
||||
if (!config.enabled) throw new DecisionUnavailable("disabled");
|
||||
let userId: string | null = null, agentId: string | null = null, runId: string | null = null, identityContextId: string | null = null;
|
||||
let issueId = context.issueId ?? null;
|
||||
let actor = context.actor;
|
||||
if (actor.type === "system") {
|
||||
if (!context.feature.background || !config.allowBackground) throw new DecisionUnavailable("background_disabled");
|
||||
} else if (actor.type === "agent") {
|
||||
if (!actor.agentId || !actor.runId || actor.companyId !== context.companyId) throw forbidden();
|
||||
const [run] = await executor.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, context.companyId), eq(heartbeatRuns.id, actor.runId), eq(heartbeatRuns.agentId, actor.agentId)));
|
||||
if (!run || run.status !== "running") throw forbidden("An active run is required");
|
||||
agentId = run.agentId; runId = run.id; userId = run.responsibleUserId; identityContextId = run.activeIdentityContextId;
|
||||
const runIssue = run.nativeIssueId ?? run.contextSnapshot?.issueId ?? run.contextSnapshot?.taskId;
|
||||
if (issueId && issueId !== runIssue) throw forbidden("Task does not belong to this run");
|
||||
issueId = typeof runIssue === "string" ? runIssue : null;
|
||||
const memberships = userId ? await executor.select({ companyId: companyMemberships.companyId, membershipRole: companyMemberships.membershipRole, status: companyMemberships.status })
|
||||
.from(companyMemberships).where(and(eq(companyMemberships.companyId, context.companyId), eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId))) : [];
|
||||
actor = { ...actor, onBehalfOfUserId: userId, onBehalfOfMemberships: memberships };
|
||||
} else if (actor.type === "board") userId = actor.userId ?? (actor.source === "local_implicit" ? "local-board" : null);
|
||||
else throw forbidden();
|
||||
if (actor.type !== "system" && !userId) throw new DecisionUnavailable("responsible_user_missing");
|
||||
const [issue] = issueId ? await executor.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, context.companyId))) : [];
|
||||
if (issueId && !issue) throw forbidden();
|
||||
if (issue && context.projectId && context.projectId !== issue.projectId) throw forbidden("Task project mismatch");
|
||||
const projectId = issue?.projectId ?? context.projectId ?? null;
|
||||
if (projectId) {
|
||||
const [project] = await executor.select({ id: projects.id }).from(projects).where(and(eq(projects.id, projectId), eq(projects.companyId, context.companyId)));
|
||||
if (!project) throw forbidden();
|
||||
}
|
||||
if (actor.type !== "system") {
|
||||
const access = accessService(executor);
|
||||
const accessResult = await access.decide({ actor, action: issue ? "issue:read" : projectId ? "project:read" : "company_scope:read",
|
||||
resource: issue ? { type: "issue", companyId: context.companyId, issueId: issue.id, projectId: issue.projectId, parentIssueId: issue.parentId,
|
||||
assigneeAgentId: issue.assigneeAgentId, assigneeUserId: issue.assigneeUserId, status: issue.status }
|
||||
: projectId ? { type: "project", companyId: context.companyId, projectId } : { type: "company", companyId: context.companyId } });
|
||||
if (!accessResult.allowed) throw forbidden();
|
||||
}
|
||||
const connection = await aiConnectionService(executor).selectDecision({ companyId: context.companyId,
|
||||
connectionId: config.connectionId, grantId: config.grantId, userId, agentId, sponsoredBackground: actor.type === "system" });
|
||||
if (connection.provider !== config.provider || config.model !== DECISION_MODELS[connection.provider].id) throw new DecisionUnavailable("incompatible_connection");
|
||||
return { config, connection, userId, agentId, runId, identityContextId, issueId, projectId,
|
||||
actorType: actor.type === "board" ? "user" as const : actor.type === "agent" ? "agent" as const : "system" as const,
|
||||
actorId: actor.type === "system" ? "paperclip-decisions" : agentId ?? userId! };
|
||||
}
|
||||
async function availability(context: DecisionContext): Promise<DecisionAvailability> {
|
||||
try { await resolve(context); return { available: true }; }
|
||||
catch (error) { const reason = unavailableReason(error); if (reason) return { available: false, reason }; throw error; }
|
||||
}
|
||||
/** Callers may memoize within their request; dispatch never consumes a cached authorization. */
|
||||
function availabilityForRequest() {
|
||||
const cache = new Map<DecisionContext, Promise<DecisionAvailability>>();
|
||||
return (context: DecisionContext) => { let result = cache.get(context); if (!result) { result = availability(context); cache.set(context, result); } return result; };
|
||||
}
|
||||
async function settle(invocation: typeof decisionInvocations.$inferSelect, outcome: DecisionProviderOutcome) {
|
||||
await withAccountingTransaction(db, invocation.companyId, async (tx, publications) => {
|
||||
const [current] = await tx.select().from(decisionInvocations).where(and(eq(decisionInvocations.companyId, invocation.companyId), eq(decisionInvocations.id, invocation.id))).for("update");
|
||||
if (!current || current.status !== "running") return;
|
||||
const receipt = outcome.receipt;
|
||||
// Keep dispatch identity on the invocation even if its task or agent was
|
||||
// deleted while the provider worked. Ledger foreign keys use live rows.
|
||||
const links: { agentId: string | null; issueId: string | null; projectId: string | null } = { agentId: null, issueId: null, projectId: null };
|
||||
for (const [key, table] of [["agentId", agents], ["issueId", issues], ["projectId", projects]] as const) {
|
||||
const id = invocation[key];
|
||||
if (!id) continue;
|
||||
const [row] = await tx.select({ id: table.id }).from(table).where(and(eq(table.id, id), eq(table.companyId, invocation.companyId))).for("key share");
|
||||
if (row) links[key] = row.id;
|
||||
}
|
||||
const event = await createCostEventInTransaction(tx, invocation.companyId, {
|
||||
usageKind: "decision", responsibleUserId: invocation.responsibleUserId, ...links,
|
||||
// Run attribution lives on the invocation. Run receipt reconciliation must not ingest this independent charge.
|
||||
heartbeatRunId: null, idempotencyKey: `decision:${invocation.id}`,
|
||||
provider: invocation.provider === "openrouter" ? "typesafe" : "openai", biller: invocation.provider,
|
||||
billingType: "metered_api", costStatus: receipt.costStatus, model: invocation.model,
|
||||
inputTokens: receipt.inputTokens ?? 0, outputTokens: receipt.outputTokens ?? 0, costCents: receipt.costCents ?? "0",
|
||||
providerRequestId: receipt.providerRequestId, pricingProvenance: receipt.pricingProvenance, occurredAt: invocation.startedAt,
|
||||
}, publications, { actorType: invocation.actorType as "system" | "user" | "agent", actorId: invocation.actorId, agentId: links.agentId });
|
||||
const finishedAt = new Date();
|
||||
await tx.update(decisionInvocations).set({ status: outcome.answers ? "succeeded" : receipt.costStatus === "unpriced" ? "unknown" : "failed",
|
||||
errorCode: outcome.errorCode ?? null, costEventId: event.id, providerRequestId: receipt.providerRequestId,
|
||||
inputTokens: receipt.inputTokens, outputTokens: receipt.outputTokens, finishedAt, durationMs: Math.max(0, finishedAt.getTime() - invocation.startedAt.getTime()),
|
||||
}).where(eq(decisionInvocations.id, invocation.id));
|
||||
if (receipt.costStatus !== "unpriced") await tx.update(budgetReservations).set({ state: outcome.noProviderWork ? "released" : "settled", settledAt: finishedAt }).where(and(
|
||||
eq(budgetReservations.companyId, invocation.companyId), eq(budgetReservations.decisionInvocationId, invocation.id), eq(budgetReservations.state, "held"),
|
||||
));
|
||||
});
|
||||
await budgetService(db, options.budgetHooks).deliverPendingEnforcement(invocation.companyId);
|
||||
}
|
||||
async function decide(context: DecisionContext, request: DecisionRequest, signal?: AbortSignal): Promise<DecisionResult> {
|
||||
const parsed = decisionRequestSchema.safeParse(request);
|
||||
if (!parsed.success || Buffer.byteLength(JSON.stringify(parsed.data)) > 32_000) throw unprocessable("Decisions require 1–20 valid questions and at most 32 KB of text/JSON");
|
||||
let selected: Awaited<ReturnType<typeof resolve>>;
|
||||
try { selected = await resolve(context); }
|
||||
catch (error) { const reason = unavailableReason(error); if (reason) return { status: "unavailable", reason }; throw error; }
|
||||
const secretId = selected.connection.grant.credentialSecretRefs.find(ref => ref.configPath === "ai.credential")?.secretId;
|
||||
const [credentialSnapshot] = secretId ? await db.select({ id: companySecrets.id, status: companySecrets.status, version: companySecrets.latestVersion })
|
||||
.from(companySecrets).where(and(eq(companySecrets.companyId, context.companyId), eq(companySecrets.id, secretId))) : [];
|
||||
if (!credentialSnapshot || credentialSnapshot.status !== "active") return { status: "unavailable", reason: "connection_unavailable" };
|
||||
let credential: string;
|
||||
try { credential = await aiConnectionService(db).credential(selected.connection, 0, { responsibleUserId: selected.userId,
|
||||
actorType: selected.actorType, actorId: selected.actorId, issueId: selected.issueId, heartbeatRunId: selected.runId }); }
|
||||
catch (error) { return { status: "unavailable", reason: unavailableReason(error) ?? "connection_unavailable" }; }
|
||||
const admission = await withAccountingTransaction(db, context.companyId, async (tx, publications) => {
|
||||
let current: Awaited<ReturnType<typeof resolve>>;
|
||||
try { current = await resolve(context, tx); }
|
||||
catch (error) { const reason = unavailableReason(error); if (reason) return { reason }; throw error; }
|
||||
// A different setting or steering identity requires a fresh credential acquisition.
|
||||
if (current.config.updatedAt.getTime() !== selected.config.updatedAt.getTime() || current.userId !== selected.userId || current.identityContextId !== selected.identityContextId
|
||||
|| current.connection.grant.updatedAt.getTime() !== selected.connection.grant.updatedAt.getTime()
|
||||
|| current.connection.connection.updatedAt.getTime() !== selected.connection.connection.updatedAt.getTime())
|
||||
return { reason: "connection_unavailable" as const };
|
||||
// Secret changes do not update the connection revision. Serialize against
|
||||
// rotation/revocation through admission, including time spent waiting for
|
||||
// the accounting lock after credential resolution.
|
||||
const [currentSecret] = await tx.select({ status: companySecrets.status, version: companySecrets.latestVersion }).from(companySecrets)
|
||||
.where(and(eq(companySecrets.companyId, context.companyId), eq(companySecrets.id, credentialSnapshot.id))).for("share");
|
||||
if (!currentSecret || currentSecret.status !== "active" || currentSecret.version !== credentialSnapshot.version)
|
||||
return { reason: "connection_unavailable" as const };
|
||||
const budgets = budgetServiceInTransaction(tx, publications);
|
||||
const block = await budgets.getInvocationBlock(context.companyId, current.agentId, { projectId: current.projectId });
|
||||
const [company] = await tx.select({ status: companies.status }).from(companies).where(eq(companies.id, context.companyId));
|
||||
const [agent] = current.agentId ? await tx.select({ status: agents.status }).from(agents).where(and(eq(agents.id, current.agentId), eq(agents.companyId, context.companyId))) : [];
|
||||
if (block || company.status !== "active" || (current.agentId && (!agent || agent.status === "paused" || agent.status === "terminated"))) return { reason: "budget_blocked" as const };
|
||||
const policies = await tx.select().from(budgetPolicies).where(and(eq(budgetPolicies.companyId, context.companyId), eq(budgetPolicies.isActive, true),
|
||||
eq(budgetPolicies.hardStopEnabled, true), eq(budgetPolicies.metric, "billed_cents"), sql`${budgetPolicies.amount} > 0`, budgetPoliciesForRun(context.companyId, current.agentId, current.projectId)));
|
||||
const amount = policies.reduce((max, p) => { const n = centsToUnits(p.reservationCents); return n > max ? n : max; }, 0n);
|
||||
for (const policy of policies) {
|
||||
const [held] = await tx.select({ total: sql<string>`coalesce(sum(${budgetReservations.amountCents}),0)::text` }).from(budgetReservations).where(and(
|
||||
eq(budgetReservations.companyId, context.companyId), eq(budgetReservations.state, "held"),
|
||||
policy.scopeType === "agent" ? eq(budgetReservations.agentId, current.agentId!) : undefined,
|
||||
policy.scopeType === "project" ? eq(budgetReservations.projectId, current.projectId!) : undefined,
|
||||
));
|
||||
const committed = centsToUnits((await computeObservedSpend(tx, policy)).totalExact) + centsToUnits(held.total);
|
||||
if (committed >= centsToUnits(policy.amount) || committed + amount > centsToUnits(policy.amount)) return { reason: "budget_blocked" as const };
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
const [invocation] = await tx.insert(decisionInvocations).values({ id: randomUUID(), companyId: context.companyId, feature: context.feature.id,
|
||||
actorType: current.actorType, actorId: current.actorId, responsibleUserId: current.userId, agentId: current.agentId,
|
||||
issueId: current.issueId, projectId: current.projectId, runId: current.runId, identityContextId: current.identityContextId,
|
||||
connectionId: current.connection.connection.id, grantId: current.connection.grant.id, provider: current.connection.provider, model: current.config.model!,
|
||||
questionTypes: Object.values(parsed.data.questions).map(q => q.type),
|
||||
}).returning();
|
||||
await tx.insert(budgetReservations).values({ companyId: context.companyId, decisionInvocationId: invocation.id, agentId: current.agentId,
|
||||
projectId: current.projectId, amountCents: unitsToCents(amount), providerStartedAt: invocation.startedAt });
|
||||
return { invocation };
|
||||
});
|
||||
if (admission.reason) return { status: "unavailable", reason: admission.reason };
|
||||
const invocation = admission.invocation!;
|
||||
let outcome: DecisionProviderOutcome;
|
||||
try { outcome = await providerCall({ provider: selected.connection.provider, model: invocation.model, apiKey: credential,
|
||||
request: parsed.data, signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000) }); }
|
||||
catch { outcome = { errorCode: "provider_failed", receipt: decisionReceipt(selected.connection.provider, null) }; }
|
||||
await settle(invocation, outcome);
|
||||
const { inputTokens, outputTokens, costCents, costStatus } = outcome.receipt;
|
||||
const usage = { inputTokens, outputTokens, costCents, costStatus };
|
||||
return outcome.answers ? { status: "succeeded", invocationId: invocation.id, answers: outcome.answers, usage }
|
||||
: { status: "failed", invocationId: invocation.id, errorCode: outcome.errorCode ?? "provider_failed", usage };
|
||||
}
|
||||
async function recoverInterrupted() {
|
||||
const stale = await db.select().from(decisionInvocations).where(and(eq(decisionInvocations.status, "running"), lt(decisionInvocations.startedAt, new Date(Date.now() - 120_000)))).limit(100);
|
||||
for (const invocation of stale) await settle(invocation, { errorCode: "interrupted", receipt: decisionReceipt(invocation.provider as DecisionProvider, null) });
|
||||
return stale.length;
|
||||
}
|
||||
async function history(companyId: string, actor: AuthorizationActor, range: { from?: Date; to?: Date; before?: Date; limit?: number } = {}): Promise<DecisionHistoryEntry[]> {
|
||||
const access = accessService(db);
|
||||
if (!(await access.decide({ actor, action: "company_scope:read", resource: { type: "company", companyId } })).allowed) throw forbidden();
|
||||
const rows = await db.select({ invocation: decisionInvocations, userName: authUsers.name,
|
||||
inputTokens: costEvents.inputTokens, outputTokens: costEvents.outputTokens, costStatus: costEvents.costStatus,
|
||||
costCents: sql<string | null>`${costEvents.costCents}::text`, issue: issues,
|
||||
}).from(decisionInvocations).leftJoin(costEvents, and(eq(costEvents.id, decisionInvocations.costEventId), eq(costEvents.companyId, companyId)))
|
||||
.leftJoin(authUsers, eq(authUsers.id, decisionInvocations.responsibleUserId))
|
||||
.leftJoin(issues, and(eq(issues.id, decisionInvocations.issueId), eq(issues.companyId, companyId)))
|
||||
.where(and(eq(decisionInvocations.companyId, companyId), range.from ? gte(decisionInvocations.startedAt, range.from) : undefined,
|
||||
range.to ? lte(decisionInvocations.startedAt, range.to) : undefined, range.before ? lt(decisionInvocations.startedAt, range.before) : undefined))
|
||||
.orderBy(desc(decisionInvocations.startedAt), desc(decisionInvocations.id)).limit(Math.min(range.limit ?? 100, 500));
|
||||
return Promise.all(rows.map(async ({ invocation: row, issue, ...cost }) => {
|
||||
const visible = issue && (await access.decide({ actor, action: "issue:read", resource: { type: "issue", companyId, issueId: issue.id,
|
||||
projectId: issue.projectId, parentIssueId: issue.parentId, assigneeAgentId: issue.assigneeAgentId, assigneeUserId: issue.assigneeUserId, status: issue.status } })).allowed;
|
||||
return { id: row.id, feature: row.feature, actorType: row.actorType, responsibleUserId: row.responsibleUserId, userName: cost.userName,
|
||||
issueId: visible ? issue.id : null, issueIdentifier: visible ? issue.identifier : null, agentId: row.agentId, runId: visible ? row.runId : null,
|
||||
connectionId: row.connectionId, provider: row.provider, model: row.model, status: row.status, errorCode: row.errorCode,
|
||||
startedAt: row.startedAt.toISOString(), finishedAt: row.finishedAt?.toISOString() ?? null, durationMs: row.durationMs,
|
||||
inputTokens: row.inputTokens, outputTokens: row.outputTokens,
|
||||
costCents: cost.costStatus === "unpriced" ? null : cost.costCents, costStatus: cost.costStatus };
|
||||
}));
|
||||
}
|
||||
return { settings, choices, configure, availability, availabilityForRequest, decide, recoverInterrupted, history };
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { preserveWorkspaceRestoreRecoveryMetadataSql } from "./legacy-workspace-
|
||||
import { preserveWorkspaceRestoreRecoveryMetadata } from "./workspace-restore-recovery-state.js";
|
||||
import { recordLegacyWorkspaceRestoreFailure } from "./legacy-execution-recovery.js";
|
||||
import { CONFIGURED_ENVIRONMENT_KEYS, configuredEnvironmentProjection } from "../vendor/paperclip-runner/index.js";
|
||||
import { decisionModelService } from "./decision-models.js";
|
||||
import { activeIssueInteractionCondition, TASK_QUESTION_GUIDANCE } from "./issue-question-context.js";
|
||||
import { createAgentIdentityRedactor } from "./agent-identity-redaction.js";
|
||||
import { agentIdentityService, supportsManagedAgentIdentity } from "./agent-identity.js";
|
||||
@@ -30667,7 +30668,10 @@ export function heartbeatService(
|
||||
scanSilentActiveRuns,
|
||||
|
||||
reconcileTaskWatchdogs,
|
||||
reconcileCostAccounting: createCostAccountingReconciler(db, budgetHooks),
|
||||
reconcileCostAccounting: async () => {
|
||||
await decisionModelService(db, { budgetHooks }).recoverInterrupted();
|
||||
return createCostAccountingReconciler(db, budgetHooks)();
|
||||
},
|
||||
|
||||
buildRunOutputSilence,
|
||||
|
||||
|
||||
@@ -217,3 +217,5 @@ export {
|
||||
type RemoteAgentProfileInput,
|
||||
type RemoteAgentService,
|
||||
} from "./remote-agent-profiles.js";
|
||||
|
||||
export { decisionModelService, defineDecisionFeature } from "./decision-models.js";
|
||||
Reference in new issue
Block a user